From 4a04f21d489ba8cb0f93001a28658775e11715ae Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 18:28:19 +0500 Subject: [PATCH 1/7] fix(core): skip debug-ID stamping when the runtime maps stacks (#185) With node --enable-source-maps the registration key and error frames are already original positions, so the bundle's debug-id would make the backend remap them and show a wrong line. applyDebugIds now no-ops when process.sourceMapsEnabled is true (read via a globalThis cast). Adds a real node/bun e2e through buildCrashJson. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/design/source-maps.md | 14 +++ packages/core/src/debug-id.test.ts | 89 ++++++++++++- packages/core/src/debug-id.ts | 31 ++++- packages/core/src/index.ts | 1 + .../app/sourcemaps-runtime-scenario.ts | 33 +++++ .../test/sourcemaps-runtime.e2e.ts | 118 ++++++++++++++++++ 6 files changed, 284 insertions(+), 2 deletions(-) create mode 100644 packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts create mode 100644 packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 96776315e..ab5e653d3 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -191,6 +191,20 @@ is a change to the spawn model in §4 and is tracked as OPEN-FINDINGS D3. --- +## 7.2 Runtime-mapped stacks (`node --enable-source-maps`, #185) + +With `node --enable-source-maps` (or `process.setSourceMapsEnabled(true)`) Node rewrites `Error.stack` to ORIGINAL +positions before the SDK sees it, including the stack the injected stub registers (its top frame becomes e.g. +`src/main.js:4:1`, since the appended stub has no mapping of its own). Measured through the real crash builder +(`instrumentation-tests/test/sourcemaps-runtime.e2e.ts`): a frame at `src/main.js:3:3` was stamped with the bundle's +debug-id, so the backend would remap an already-mapped position, a wrong line. `applyDebugIds` therefore stamps NOTHING +when `process.sourceMapsEnabled === true` (`runtimeMapsStacks`, read through a `globalThis` cast). Already-original +frames need no id. Trade-off: a deployment that sets the flag but ships no map files gets minified frames without an id +(the no-plugin appVersion/appBuild fallback). Bun does not map `Error.stack` and has no `process.sourceMapsEnabled` +(Bun 1.4.4, measured), so it keeps stamping, which is correct. + +--- + ## 8. Deferred - A real-`bugsee-cli` integration e2e (needs the built Rust binary in the harness) — follow-up once CI has it. - Turbopack loader for Next.js (`turbopack.rules`) — Next-adapter follow-up. diff --git a/packages/core/src/debug-id.test.ts b/packages/core/src/debug-id.test.ts index f0d943ad1..923f0050c 100644 --- a/packages/core/src/debug-id.test.ts +++ b/packages/core/src/debug-id.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { applyDebugIds, attachDebugIds, buildDebugIdMap, readDebugIds } from './debug-id'; +import { + applyDebugIds, + attachDebugIds, + buildDebugIdMap, + readDebugIds, + runtimeMapsStacks, +} from './debug-id'; import { parseV8Stack, type StackFrame } from './stack'; // A V8 `Error().stack` whose TOP frame is the bundle's own file (what the injected stub captures). @@ -94,3 +100,84 @@ describe('applyDebugIds', () => { } }); }); + +describe('runtimeMapsStacks', () => { + it('is true only when the runtime reports `process.sourceMapsEnabled === true`', () => { + expect(runtimeMapsStacks({ sourceMapsEnabled: true })).toBe(true); + expect(runtimeMapsStacks({ sourceMapsEnabled: false })).toBe(false); + expect(runtimeMapsStacks({})).toBe(false); // Bun / browser polyfills: property absent + expect(runtimeMapsStacks({ sourceMapsEnabled: 'yes' })).toBe(false); + }); + + it('is false without a process object (browsers, workers, edge)', () => { + expect(runtimeMapsStacks(undefined)).toBe(false); + expect(runtimeMapsStacks(null)).toBe(false); + expect(runtimeMapsStacks(1)).toBe(false); + }); + + it('defaults to the live `globalThis.process`', () => { + const g = globalThis as unknown as { process?: { sourceMapsEnabled?: boolean } }; + const real = g.process; + try { + g.process = { sourceMapsEnabled: true }; + expect(runtimeMapsStacks()).toBe(true); + g.process = {}; + expect(runtimeMapsStacks()).toBe(false); + g.process = undefined; + expect(runtimeMapsStacks()).toBe(false); + } finally { + g.process = real; + } + }); +}); + +describe('applyDebugIds under runtime source-map support (#185)', () => { + // With `node --enable-source-maps` the registration key's top frame is mapped to an ORIGINAL file + // (`src/main.js`), and error frames are original positions too. Stamping the bundle's debug-id onto them + // makes the backend remap an already-mapped position -> a wrong line. + const mappedRegistry = { [bundleStack('/app/src/main.js')]: 'bundle-id' }; + + it('stamps nothing when the runtime already maps stacks', () => { + const frames: StackFrame[] = [{ file: '/app/src/main.js', line: 3, column: 3 }]; + applyDebugIds(frames, { + globalObject: { _bugseeDebugIds: mappedRegistry }, + parseStack: parseV8Stack, + runtimeMapsStacks: true, + }); + expect(frames[0]?.debugId).toBeUndefined(); + }); + + it('still stamps when the runtime does not map stacks', () => { + const frames: StackFrame[] = [{ file: '/app/src/main.js', line: 3, column: 3 }]; + applyDebugIds(frames, { + globalObject: { _bugseeDebugIds: mappedRegistry }, + parseStack: parseV8Stack, + runtimeMapsStacks: false, + }); + expect(frames[0]?.debugId).toBe('bundle-id'); + }); + + it('defaults the probe to the live process: stamping is off while process.sourceMapsEnabled', () => { + const g = globalThis as unknown as { + process?: { sourceMapsEnabled?: boolean }; + _bugseeDebugIds?: Record; + }; + const real = g.process; + const prev = g._bugseeDebugIds; + g._bugseeDebugIds = mappedRegistry; + try { + g.process = { sourceMapsEnabled: true }; + const off: StackFrame[] = [{ file: '/app/src/main.js' }]; + applyDebugIds(off); + expect(off[0]?.debugId).toBeUndefined(); + g.process = { sourceMapsEnabled: false }; + const on: StackFrame[] = [{ file: '/app/src/main.js' }]; + applyDebugIds(on); + expect(on[0]?.debugId).toBe('bundle-id'); + } finally { + g.process = real; + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }); +}); diff --git a/packages/core/src/debug-id.ts b/packages/core/src/debug-id.ts index b51c26879..653448d8b 100644 --- a/packages/core/src/debug-id.ts +++ b/packages/core/src/debug-id.ts @@ -49,15 +49,44 @@ export function attachDebugIds(frames: StackFrame[], debugIdMap: Map debugId` join is meaningless: a frame landing in the file the stub + * happened to map to would be stamped with the bundle's id and the backend would remap an already-mapped + * position (a wrong line). An unstamped, already-original frame is correct; a stamped one is not. (Trade-off: a + * deployment that runs with the flag but ships NO map files gets unmapped frames without an id, i.e. the same + * appVersion/appBuild fallback as having no plugin.) */ export function applyDebugIds( frames: StackFrame[], - options: { globalObject?: unknown; parseStack?: (stack: string) => StackFrame[] } = {}, + options: { + globalObject?: unknown; + parseStack?: (stack: string) => StackFrame[]; + runtimeMapsStacks?: boolean; + } = {}, ): void { + if (options.runtimeMapsStacks ?? runtimeMapsStacks()) { + return; + } const globalObject = options.globalObject ?? (globalThis as unknown); const debugIds = readDebugIds(globalObject); if (Object.keys(debugIds).length === 0) { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4c3735b5f..34ece795f 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -179,6 +179,7 @@ export { attachDebugIds, buildDebugIdMap, readDebugIds, + runtimeMapsStacks, } from './debug-id'; export { checkOrSetAlreadyCaught } from './dedup'; export { diff --git a/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts new file mode 100644 index 000000000..0e371c81a --- /dev/null +++ b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts @@ -0,0 +1,33 @@ +// Child process for sourcemaps-runtime.e2e.ts: loads a bundle stamped like `bugsee-cli sourcemaps inject`, +// throws from it, and prints what the SDK's crash builder produces (frames + debug-ids) plus the registration keys. +import { createRequire } from 'node:module'; +import process from 'node:process'; +import { buildCrashJson } from '@bugsee/core'; + +// tsx turns source maps on for its own TS transform, so the harness pins the mode explicitly. +const mode = process.env.SOURCE_MAPS; +const setter = (process as unknown as { setSourceMapsEnabled?: (on: boolean) => void }) + .setSourceMapsEnabled; +if (mode !== undefined && setter !== undefined) { + setter.call(process, mode === 'on'); +} +const bundlePath = process.env.BUNDLE_PATH as string; +const require = createRequire(import.meta.url); +const app = require(bundlePath) as { fail: () => never }; +let thrown: unknown; +try { + app.fail(); +} catch (error) { + thrown = error; +} +const registry = (globalThis as { _bugseeDebugIds?: Record })._bugseeDebugIds ?? {}; +const crash = buildCrashJson(thrown); +process.stdout.write( + `${JSON.stringify({ + sourceMapsEnabled: (process as unknown as { sourceMapsEnabled?: boolean }).sourceMapsEnabled, + registrationTopFrames: Object.keys(registry).map((k) => (k.split('\n')[1] ?? '').trim()), + frames: crash.exception.frames + .filter((f) => f.user) + .map((f) => ({ at: f.trace, debug_id: f.debug_id })), + })}\n`, +); diff --git a/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts new file mode 100644 index 000000000..8256dfa3c --- /dev/null +++ b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts @@ -0,0 +1,118 @@ +// Issue #185 — `node --enable-source-maps` vs the debug-ID -> file lookup. +// +// Builds a REAL bundle with esbuild (+ external map), stamps it the way `bugsee-cli sourcemaps inject` does +// (runtime stub + `//# debugId=` comment appended AFTER the bundle, so the stub has no source-map mapping), +// then runs it in a real node/bun process through the REAL crash builder (`buildCrashJson`) and reads back +// which frames got a debug-ID. The bundle's debug-ID tells the backend "this position is in the MINIFIED +// bundle, remap it"; stamping a frame that the runtime already mapped to an original `src/*.js` position would +// make the backend remap it AGAIN and show a wrong line. +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { runtimeTargets } from './runtimes'; + +const DEBUG_ID = '11111111-2222-5333-8444-555555555555'; +const pkgRoot = fileURLToPath(new URL('..', import.meta.url)); +const SCENARIO = join(pkgRoot, 'app', 'sourcemaps-runtime-scenario.ts'); + +/** The stub `bugsee-cli sourcemaps inject` appends (same shape: registers `Error().stack` -> debug-id). */ +const STUB = `;!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._bugseeDebugIds=e._bugseeDebugIds||{},e._bugseeDebugIds[n]="${DEBUG_ID}")}catch(e){}}();`; + +interface Result { + sourceMapsEnabled: boolean | undefined; + registrationTopFrames: string[]; + frames: { at: string; debug_id?: string }[]; +} + +describe('debug-ID stamping under runtime source-map support (#185)', () => { + let dir: string; + let bundle: string; + beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), 'bugsee-sm-rt-')); + mkdirSync(join(dir, 'src')); + mkdirSync(join(dir, 'dist')); + writeFileSync( + join(dir, 'src', 'a.js'), + "export function boom() {\n throw new Error('boom from a');\n}\n", + ); + writeFileSync( + join(dir, 'src', 'main.js'), + "import { boom } from './a.js';\nexport function fail() {\n boom();\n}\n", + ); + bundle = join(dir, 'dist', 'app.js'); + execFileSync( + join(pkgRoot, 'node_modules', '.bin', 'esbuild'), + [ + join(dir, 'src', 'main.js'), + '--bundle', + '--platform=node', + '--format=cjs', + '--sourcemap', + `--outfile=${bundle}`, + '--log-level=warning', + ], + { stdio: 'inherit' }, + ); + // inject: stub + id comment go BEFORE the trailing sourceMappingURL comment, as the CLI leaves it. + const lines = readFileSync(bundle, 'utf8').split('\n'); + const at = lines.findIndex((l) => l.startsWith('//# sourceMappingURL=')); + lines.splice(at, 0, STUB, `//# debugId=${DEBUG_ID}`); + writeFileSync(bundle, lines.join('\n')); + }); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + function run(bin: string, args: string[], sourceMaps?: 'on' | 'off'): Result { + const out = execFileSync(bin, [...args, SCENARIO], { + encoding: 'utf8', + env: { + ...process.env, + BUNDLE_PATH: bundle, + ...(sourceMaps ? { SOURCE_MAPS: sourceMaps } : {}), + }, + }); + return JSON.parse(out.trim().split('\n').at(-1) as string) as Result; + } + + for (const target of runtimeTargets()) { + const { bin } = target; + it.skipIf(bin === undefined)( + `${target.name}: default (no source maps) stamps the bundle frames`, + () => { + const r = run(bin as string, [], 'off'); + expect(r.sourceMapsEnabled).not.toBe(true); + expect(r.registrationTopFrames[0]).toContain('dist/app.js'); + const user = r.frames.filter((f) => f.at.includes('dist/app.js')); + expect(user.length).toBeGreaterThan(0); + for (const f of user) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + + it.skipIf(bin === undefined)( + `${target.name}: --enable-source-maps never stamps an already-mapped frame`, + () => { + const r = run(bin as string, ['--enable-source-maps'], 'on'); + const original = r.frames.filter((f) => f.at.includes('/src/')); + if (target.name === 'node') { + // Node maps the stacks BEFORE the SDK sees them: error frames AND the registration key's top frame + // are original `src/*.js` positions, so the bundle's id would be wrong for every one of them. + expect(r.sourceMapsEnabled).toBe(true); + expect(r.registrationTopFrames[0]).toContain('/src/'); + expect(original.length).toBeGreaterThanOrEqual(2); + } + // Whatever the runtime did, a frame that points at an ORIGINAL source must carry no debug-id. + for (const f of original) expect(f.debug_id).toBeUndefined(); + if (target.name === 'bun') { + // Measured (Bun 1.4.4): Bun does NOT apply source maps to Error.stack (no `process.sourceMapsEnabled`), + // so frames stay on the bundle and stamping them is correct. + expect(original).toHaveLength(0); + for (const f of r.frames.filter((x) => x.at.includes('dist/app.js'))) { + expect(f.debug_id).toBe(DEBUG_ID); + } + } + }, + ); + } +}); From 2c36d546884e8738c4b894bbd93abf157204d95d Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 18:38:21 +0500 Subject: [PATCH 2/7] fix(core,node): validate debug-ID registrations per bundle under runtime source maps (#185) A global skip on process.sourceMapsEnabled dropped correct ids when the plugin had deleted the maps (the default) or the flag was enabled after load. Core now keeps a registration only if an injected verifier proves its top-frame file is the stamped bundle; @bugsee/node installs one that checks the file tail for //# debugId=. E2E covers map present, map deleted, late enable and Bun; stub placement matches the CLI. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/PROGRESS.md | 11 ++ docs/design/source-maps.md | 32 ++-- packages/core/src/debug-id.test.ts | 99 ++++++++++--- packages/core/src/debug-id.ts | 38 +++-- packages/core/src/index.ts | 2 + .../app/sourcemaps-runtime-scenario.ts | 34 +++-- .../test/sourcemaps-runtime.e2e.ts | 140 +++++++++++------- packages/node/src/debug-id-verifier.test.ts | 75 ++++++++++ packages/node/src/debug-id-verifier.ts | 62 ++++++++ packages/node/src/launch.test.ts | 32 ++++ packages/node/src/launch.ts | 7 + 11 files changed, 427 insertions(+), 105 deletions(-) create mode 100644 packages/node/src/debug-id-verifier.test.ts create mode 100644 packages/node/src/debug-id-verifier.ts diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 443e7af0f..73166b092 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1310,6 +1310,17 @@ recorded" was false. Still open from #120: WebKit/Firefox projects, the 22-secret smoke, `document.open`. #119 (other masking-option gaps on re-observed observers) is untouched. +### 2026-11-11 — `node --enable-source-maps` vs debug-ID stamping (#185) + +Reproduced through the real crash builder (esbuild bundle + CLI-shaped stub, real node/bun processes, +`instrumentation-tests/test/sourcemaps-runtime.e2e.ts`): with the flag and a map on disk Node maps the registration +key's top frame to `src/main.js`, so a frame at `src/main.js:3:3` was stamped with the bundle's id (wrong line after the +backend remaps). A global skip on the flag was rejected (review): with the plugin-default deleted maps, or the flag +enabled after load, nothing is mapped and the join is correct. Fix: `applyDebugIds` validates each registration while +`process.sourceMapsEnabled` through an injected verifier (`setDebugIdRegistrationVerifier`; `@bugsee/node` installs +`createStampedBundleVerifier`, which requires the top-frame file's tail to carry `//# debugId=`). Bun does not map +`Error.stack` (measured), unaffected. Design: `docs/design/source-maps.md` §7.2. + ### 2026-11-09 — Replay moves onto upstream rrweb 2.2.1 → `krassx/rrweb-2.2.1-a625` Fork `bugsee-port-2.2.1` (merge of rrweb-io/rrweb tag `rrweb@2.2.1` into `bugsee-port-2.2.0-iframe-block`; one diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index ab5e653d3..8cff01e41 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -193,15 +193,29 @@ is a change to the spawn model in §4 and is tracked as OPEN-FINDINGS D3. ## 7.2 Runtime-mapped stacks (`node --enable-source-maps`, #185) -With `node --enable-source-maps` (or `process.setSourceMapsEnabled(true)`) Node rewrites `Error.stack` to ORIGINAL -positions before the SDK sees it, including the stack the injected stub registers (its top frame becomes e.g. -`src/main.js:4:1`, since the appended stub has no mapping of its own). Measured through the real crash builder -(`instrumentation-tests/test/sourcemaps-runtime.e2e.ts`): a frame at `src/main.js:3:3` was stamped with the bundle's -debug-id, so the backend would remap an already-mapped position, a wrong line. `applyDebugIds` therefore stamps NOTHING -when `process.sourceMapsEnabled === true` (`runtimeMapsStacks`, read through a `globalThis` cast). Already-original -frames need no id. Trade-off: a deployment that sets the flag but ships no map files gets minified frames without an id -(the no-plugin appVersion/appBuild fallback). Bun does not map `Error.stack` and has no `process.sourceMapsEnabled` -(Bun 1.4.4, measured), so it keeps stamping, which is correct. +With `node --enable-source-maps` Node rewrites `Error.stack` to ORIGINAL positions before the SDK sees it, but only +when the bundle's `.map` is readable AND source maps were enabled before the bundle loaded +(`process.setSourceMapsEnabled(true)` affects only modules loaded afterwards). Then the stack the injected stub +registers is mapped too: its top frame becomes e.g. `src/main.js:4:1` (the appended stub has no mapping of its own), +so the `file -> debugId` join stamps the bundle's id onto already-mapped frames (measured: `src/main.js:3:3` got the +id; the backend remaps it again, a wrong line). + +Two cases look the same from `process.sourceMapsEnabled` but are different, so a global switch is wrong: +- the plugin DELETES `*.map` after upload by default; with the flag on and no map on disk nothing is mapped, the + registration key and the error frames both stay on `dist/app.js`, and the plain join is correct; +- the flag turned on after the bundle loaded: same, frames are unmapped and the join is correct. + +So the guard is PER REGISTRATION. While `process.sourceMapsEnabled === true` (`runtimeMapsStacks`, read through a +`globalThis` cast), `applyDebugIds` keeps a registration only if the injected verifier proves its top-frame file is the +stamped bundle. `@bugsee/node` installs that verifier at launch (`createStampedBundleVerifier`): the file's tail must +carry `//# debugId=` (the same marker `bundler-plugin-core` reads). A mapped registration points at +`src/main.js`, which has no stamp, so it is dropped and the frames stay unstamped (already original, no id needed). +Core stays runtime-portable: no `node:fs`, the verifier is injected (`setDebugIdRegistrationVerifier` / the +`verifyRegistration` option). With no verifier (browsers, Electron renderers: Chromium does not map `Error.stack` +even where `process.sourceMapsEnabled` reads true) every registration is kept, i.e. the previous behaviour. +Known limit: a registration whose top-frame path was scrubbed to `node_modules/...` (a stamped bundle shipped inside +a dependency) cannot be resolved and is not joined while the flag is on. Bun does not map `Error.stack` and has no +`process.sourceMapsEnabled` (Bun 1.4.4, measured), so it keeps stamping, which is correct. --- diff --git a/packages/core/src/debug-id.test.ts b/packages/core/src/debug-id.test.ts index 923f0050c..f0f794a08 100644 --- a/packages/core/src/debug-id.test.ts +++ b/packages/core/src/debug-id.test.ts @@ -5,6 +5,7 @@ import { buildDebugIdMap, readDebugIds, runtimeMapsStacks, + setDebugIdRegistrationVerifier, } from './debug-id'; import { parseV8Stack, type StackFrame } from './stack'; @@ -131,50 +132,102 @@ describe('runtimeMapsStacks', () => { }); }); -describe('applyDebugIds under runtime source-map support (#185)', () => { - // With `node --enable-source-maps` the registration key's top frame is mapped to an ORIGINAL file - // (`src/main.js`), and error frames are original positions too. Stamping the bundle's debug-id onto them - // makes the backend remap an already-mapped position -> a wrong line. - const mappedRegistry = { [bundleStack('/app/src/main.js')]: 'bundle-id' }; +describe('buildDebugIdMap with an accept predicate', () => { + it('keeps only registrations the predicate accepts, passing (top-frame file, debugId)', () => { + const seen: [string, string][] = []; + const map = buildDebugIdMap( + { + [bundleStack('/app/src/main.js')]: 'mapped-id', + [bundleStack('/app/dist/app.js')]: 'real-id', + }, + parseV8Stack, + (file, id) => { + seen.push([file, id]); + return file.includes('dist'); + }, + ); + expect([...map]).toEqual([['/app/dist/app.js', 'real-id']]); + expect(seen).toEqual([ + ['/app/src/main.js', 'mapped-id'], + ['/app/dist/app.js', 'real-id'], + ]); + }); +}); - it('stamps nothing when the runtime already maps stacks', () => { - const frames: StackFrame[] = [{ file: '/app/src/main.js', line: 3, column: 3 }]; - applyDebugIds(frames, { - globalObject: { _bugseeDebugIds: mappedRegistry }, +describe('applyDebugIds under runtime source-map support (#185)', () => { + // With `node --enable-source-maps` AND a map on disk, the registration key's top frame is mapped to an + // ORIGINAL file (`src/main.js`). Joining on it stamps the bundle's id onto already-mapped frames -> the + // backend remaps them again -> a wrong line. Without the map on disk (the plugin default: maps are deleted + // after upload) nothing is mapped and the plain join is correct. So the guard is PER REGISTRATION. + const registry = { + [bundleStack('/app/src/main.js')]: 'mapped-id', // registered under a mapping runtime + [bundleStack('/app/dist/other.js')]: 'other-id', // a bundle whose map is absent + }; + const verify = (file: string, id: string): boolean => + file === '/app/dist/other.js' && id === 'other-id'; + const frames = (): StackFrame[] => [ + { file: '/app/src/main.js', line: 3, column: 3 }, + { file: '/app/dist/other.js', line: 1, column: 9 }, + ]; + + it('while the runtime maps stacks, drops registrations the verifier rejects and keeps verified ones', () => { + const f = frames(); + applyDebugIds(f, { + globalObject: { _bugseeDebugIds: registry }, parseStack: parseV8Stack, runtimeMapsStacks: true, + verifyRegistration: verify, }); - expect(frames[0]?.debugId).toBeUndefined(); + expect(f[0]?.debugId).toBeUndefined(); + expect(f[1]?.debugId).toBe('other-id'); }); - it('still stamps when the runtime does not map stacks', () => { - const frames: StackFrame[] = [{ file: '/app/src/main.js', line: 3, column: 3 }]; - applyDebugIds(frames, { - globalObject: { _bugseeDebugIds: mappedRegistry }, + it('does not consult the verifier when the runtime does not map stacks', () => { + const f = frames(); + applyDebugIds(f, { + globalObject: { _bugseeDebugIds: registry }, parseStack: parseV8Stack, runtimeMapsStacks: false, + verifyRegistration: () => false, + }); + expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); + }); + + it('keeps every registration when mapping is on but no verifier exists (browser / Electron renderer)', () => { + const f = frames(); + applyDebugIds(f, { + globalObject: { _bugseeDebugIds: registry }, + parseStack: parseV8Stack, + runtimeMapsStacks: true, }); - expect(frames[0]?.debugId).toBe('bundle-id'); + expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); }); - it('defaults the probe to the live process: stamping is off while process.sourceMapsEnabled', () => { + it('uses the installed process-wide verifier by default, and the live process probe', () => { const g = globalThis as unknown as { process?: { sourceMapsEnabled?: boolean }; _bugseeDebugIds?: Record; }; const real = g.process; const prev = g._bugseeDebugIds; - g._bugseeDebugIds = mappedRegistry; + g._bugseeDebugIds = registry; + setDebugIdRegistrationVerifier(verify); try { g.process = { sourceMapsEnabled: true }; - const off: StackFrame[] = [{ file: '/app/src/main.js' }]; - applyDebugIds(off); - expect(off[0]?.debugId).toBeUndefined(); + const mapped = frames(); + applyDebugIds(mapped); + expect(mapped.map((x) => x.debugId)).toEqual([undefined, 'other-id']); g.process = { sourceMapsEnabled: false }; - const on: StackFrame[] = [{ file: '/app/src/main.js' }]; - applyDebugIds(on); - expect(on[0]?.debugId).toBe('bundle-id'); + const plain = frames(); + applyDebugIds(plain); + expect(plain.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); + setDebugIdRegistrationVerifier(undefined); + g.process = { sourceMapsEnabled: true }; + const none = frames(); + applyDebugIds(none); + expect(none.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); } finally { + setDebugIdRegistrationVerifier(undefined); g.process = real; if (prev === undefined) delete g._bugseeDebugIds; else g._bugseeDebugIds = prev; diff --git a/packages/core/src/debug-id.ts b/packages/core/src/debug-id.ts index 653448d8b..17c6fd4de 100644 --- a/packages/core/src/debug-id.ts +++ b/packages/core/src/debug-id.ts @@ -26,11 +26,12 @@ export function readDebugIds(globalObject: unknown): Record { export function buildDebugIdMap( debugIds: Record, parseStack: (stack: string) => StackFrame[], + accept?: (file: string, debugId: string) => boolean, ): Map { const map = new Map(); for (const [stack, debugId] of Object.entries(debugIds)) { const file = parseStack(stack)[0]?.file; - if (file !== undefined) { + if (file !== undefined && (accept === undefined || accept(file, debugId))) { map.set(file, debugId); } } @@ -63,18 +64,31 @@ export function runtimeMapsStacks( return (proc as { sourceMapsEnabled?: unknown }).sourceMapsEnabled === true; } +/** Does this registration (its top-frame file + debug-id) really belong to the stamped bundle? */ +export type RegistrationVerifier = (file: string, debugId: string) => boolean; + +let installedVerifier: RegistrationVerifier | undefined; + +/** + * Install the process-wide registration verifier (a platform with a filesystem: `@bugsee/node`). Module state, + * like `setStackAppRoot`: core is runtime-portable and cannot read files itself. `undefined` removes it. + */ +export function setDebugIdRegistrationVerifier(verifier: RegistrationVerifier | undefined): void { + installedVerifier = verifier; +} + /** * Resolve + stamp debug-IDs onto `frames` in place, reading the registration global (default `globalThis`) * and parsing registered stacks with `parseStack` (default {@link parseV8Stack}). A no-op when no build * injected debug-IDs. * - * Also a no-op when the runtime maps stacks itself ({@link runtimeMapsStacks}; override via - * `options.runtimeMapsStacks`). Then the frames are ALREADY original-source positions and the registration key's - * top frame was mapped too, so the `file -> debugId` join is meaningless: a frame landing in the file the stub - * happened to map to would be stamped with the bundle's id and the backend would remap an already-mapped - * position (a wrong line). An unstamped, already-original frame is correct; a stamped one is not. (Trade-off: a - * deployment that runs with the flag but ships NO map files gets unmapped frames without an id, i.e. the same - * appVersion/appBuild fallback as having no plugin.) + * When the runtime maps stacks itself ({@link runtimeMapsStacks}; override via `options.runtimeMapsStacks`) AND a + * verifier is available (`options.verifyRegistration`, else the installed one), each registration is checked: one + * whose top-frame file is NOT the stamped bundle was source-mapped to an ORIGINAL file, and joining on it would + * stamp the bundle's id onto already-mapped frames (the backend remaps them again: a wrong line, #185). The check is + * per registration, never a global switch: the flag only says the process CAN map, not that this bundle's map is on + * disk (the plugin deletes maps after upload by default) or was enabled before the bundle loaded; in those cases + * the registration is intact and the plain join is correct. Without a verifier every registration is kept. */ export function applyDebugIds( frames: StackFrame[], @@ -82,16 +96,16 @@ export function applyDebugIds( globalObject?: unknown; parseStack?: (stack: string) => StackFrame[]; runtimeMapsStacks?: boolean; + verifyRegistration?: RegistrationVerifier; } = {}, ): void { - if (options.runtimeMapsStacks ?? runtimeMapsStacks()) { - return; - } const globalObject = options.globalObject ?? (globalThis as unknown); const debugIds = readDebugIds(globalObject); if (Object.keys(debugIds).length === 0) { return; } const parseStack = options.parseStack ?? parseV8Stack; - attachDebugIds(frames, buildDebugIdMap(debugIds, parseStack)); + const verifier = options.verifyRegistration ?? installedVerifier; + const verify = (options.runtimeMapsStacks ?? runtimeMapsStacks()) ? verifier : undefined; + attachDebugIds(frames, buildDebugIdMap(debugIds, parseStack, verify)); } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 34ece795f..1d1b1bc6b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -178,8 +178,10 @@ export { applyDebugIds, attachDebugIds, buildDebugIdMap, + type RegistrationVerifier, readDebugIds, runtimeMapsStacks, + setDebugIdRegistrationVerifier, } from './debug-id'; export { checkOrSetAlreadyCaught } from './dedup'; export { diff --git a/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts index 0e371c81a..4cb611eac 100644 --- a/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts +++ b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts @@ -1,19 +1,31 @@ // Child process for sourcemaps-runtime.e2e.ts: loads a bundle stamped like `bugsee-cli sourcemaps inject`, // throws from it, and prints what the SDK's crash builder produces (frames + debug-ids) plus the registration keys. +// SOURCE_MAPS: `on` / `off` pin runtime source-map support BEFORE the bundle loads; `late` enables it AFTER the +// bundle loaded (Node only maps modules loaded afterwards); unset leaves the process flags alone. import { createRequire } from 'node:module'; import process from 'node:process'; -import { buildCrashJson } from '@bugsee/core'; +import { buildCrashJson, setDebugIdRegistrationVerifier, setStackAppRoot } from '@bugsee/core'; +// Internal to @bugsee/node (installed by its launch); imported by path so the public export surface stays unchanged. +import { createStampedBundleVerifier } from '../../node/src/debug-id-verifier'; -// tsx turns source maps on for its own TS transform, so the harness pins the mode explicitly. +const proc = process as unknown as { + setSourceMapsEnabled?: (on: boolean) => void; + sourceMapsEnabled?: boolean; +}; const mode = process.env.SOURCE_MAPS; -const setter = (process as unknown as { setSourceMapsEnabled?: (on: boolean) => void }) - .setSourceMapsEnabled; -if (mode !== undefined && setter !== undefined) { - setter.call(process, mode === 'on'); -} -const bundlePath = process.env.BUNDLE_PATH as string; +const setMaps = (on: boolean): void => proc.setSourceMapsEnabled?.call(process, on); +// tsx turns source maps on for its own TS transform, so the harness pins the mode explicitly. +if (mode === 'on') setMaps(true); +if (mode === 'off' || mode === 'late') setMaps(false); + +// What `launch()` does for the app: scrub frame paths to the app root + install the stamp verifier. +const appRoot = process.env.APP_ROOT as string; +setStackAppRoot(appRoot); +setDebugIdRegistrationVerifier(createStampedBundleVerifier({ appRoot })); + const require = createRequire(import.meta.url); -const app = require(bundlePath) as { fail: () => never }; +const app = require(process.env.BUNDLE_PATH as string) as { fail: () => never }; +if (mode === 'late') setMaps(true); let thrown: unknown; try { app.fail(); @@ -24,10 +36,10 @@ const registry = (globalThis as { _bugseeDebugIds?: Record })._b const crash = buildCrashJson(thrown); process.stdout.write( `${JSON.stringify({ - sourceMapsEnabled: (process as unknown as { sourceMapsEnabled?: boolean }).sourceMapsEnabled, + sourceMapsEnabled: proc.sourceMapsEnabled, registrationTopFrames: Object.keys(registry).map((k) => (k.split('\n')[1] ?? '').trim()), frames: crash.exception.frames - .filter((f) => f.user) + .filter((f) => f.user && !f.trace.includes('sourcemaps-runtime-scenario')) .map((f) => ({ at: f.trace, debug_id: f.debug_id })), })}\n`, ); diff --git a/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts index 8256dfa3c..8393e52cf 100644 --- a/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts +++ b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts @@ -1,11 +1,14 @@ // Issue #185 — `node --enable-source-maps` vs the debug-ID -> file lookup. // -// Builds a REAL bundle with esbuild (+ external map), stamps it the way `bugsee-cli sourcemaps inject` does -// (runtime stub + `//# debugId=` comment appended AFTER the bundle, so the stub has no source-map mapping), -// then runs it in a real node/bun process through the REAL crash builder (`buildCrashJson`) and reads back -// which frames got a debug-ID. The bundle's debug-ID tells the backend "this position is in the MINIFIED -// bundle, remap it"; stamping a frame that the runtime already mapped to an original `src/*.js` position would -// make the backend remap it AGAIN and show a wrong line. +// Builds a REAL minified-position bundle with esbuild (+ external map), stamps it the way +// `bugsee-cli sourcemaps inject` does (the runtime stub and the `//# debugId=` comment APPENDED after the whole bundle, +// so the stub has no source-map mapping of its own), then runs it in a real node/bun process through the REAL crash +// builder (`buildCrashJson`) and reads back which frames got a debug-ID. +// +// A debug-ID tells the backend "this position is in the stamped bundle, remap it". Stamping a frame the runtime already +// mapped to an original `src/*.js` position makes the backend remap it AGAIN -> a wrong line. But the flag alone does +// not mean frames are mapped: the plugin deletes `*.map` after upload by default (then Node cannot map anything), and +// `process.setSourceMapsEnabled(true)` only affects modules loaded afterwards. Those cases must stay stamped. import { execFileSync } from 'node:child_process'; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -29,24 +32,26 @@ interface Result { describe('debug-ID stamping under runtime source-map support (#185)', () => { let dir: string; - let bundle: string; - beforeAll(() => { - dir = mkdtempSync(join(tmpdir(), 'bugsee-sm-rt-')); - mkdirSync(join(dir, 'src')); - mkdirSync(join(dir, 'dist')); + /** Build roots: one keeps `app.js.map` on disk, one has it deleted (the plugin's default after upload). */ + let withMap: string; + let noMap: string; + + function build(root: string, keepMap: boolean): void { + mkdirSync(join(root, 'src'), { recursive: true }); + mkdirSync(join(root, 'dist')); writeFileSync( - join(dir, 'src', 'a.js'), + join(root, 'src', 'a.js'), "export function boom() {\n throw new Error('boom from a');\n}\n", ); writeFileSync( - join(dir, 'src', 'main.js'), + join(root, 'src', 'main.js'), "import { boom } from './a.js';\nexport function fail() {\n boom();\n}\n", ); - bundle = join(dir, 'dist', 'app.js'); + const bundle = join(root, 'dist', 'app.js'); execFileSync( join(pkgRoot, 'node_modules', '.bin', 'esbuild'), [ - join(dir, 'src', 'main.js'), + join(root, 'src', 'main.js'), '--bundle', '--platform=node', '--format=cjs', @@ -56,62 +61,97 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { ], { stdio: 'inherit' }, ); - // inject: stub + id comment go BEFORE the trailing sourceMappingURL comment, as the CLI leaves it. - const lines = readFileSync(bundle, 'utf8').split('\n'); - const at = lines.findIndex((l) => l.startsWith('//# sourceMappingURL=')); - lines.splice(at, 0, STUB, `//# debugId=${DEBUG_ID}`); - writeFileSync(bundle, lines.join('\n')); + // inject: stub, then the id comment LAST, appended after the whole bundle (bugsee-cli inject/mod.rs). + const source = readFileSync(bundle, 'utf8'); + writeFileSync(bundle, `${source.replace(/\n$/, '')}\n${STUB}\n//# debugId=${DEBUG_ID}\n`); + if (!keepMap) rmSync(`${bundle}.map`); + } + + beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), 'bugsee-sm-rt-')); + withMap = join(dir, 'with-map'); + noMap = join(dir, 'no-map'); + mkdirSync(withMap); + mkdirSync(noMap); + build(withMap, true); + build(noMap, false); }); afterAll(() => rmSync(dir, { recursive: true, force: true })); - function run(bin: string, args: string[], sourceMaps?: 'on' | 'off'): Result { + function run( + bin: string, + root: string, + args: string[], + sourceMaps: 'on' | 'off' | 'late', + ): Result { const out = execFileSync(bin, [...args, SCENARIO], { encoding: 'utf8', env: { ...process.env, - BUNDLE_PATH: bundle, - ...(sourceMaps ? { SOURCE_MAPS: sourceMaps } : {}), + BUNDLE_PATH: join(root, 'dist', 'app.js'), + APP_ROOT: root, + SOURCE_MAPS: sourceMaps, }, }); return JSON.parse(out.trim().split('\n').at(-1) as string) as Result; } + const bundleFrames = (r: Result) => r.frames.filter((f) => f.at.includes('dist/app.js')); + const originalFrames = (r: Result) => r.frames.filter((f) => f.at.includes('src/')); + for (const target of runtimeTargets()) { - const { bin } = target; + const { bin, name } = target; + const flag = ['--enable-source-maps']; + + it.skipIf(bin === undefined)(`${name}: source maps off -> bundle frames are stamped`, () => { + const r = run(bin as string, withMap, [], 'off'); + expect(r.sourceMapsEnabled).not.toBe(true); + expect(r.registrationTopFrames[0]).toContain('dist/app.js'); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }); + it.skipIf(bin === undefined)( - `${target.name}: default (no source maps) stamps the bundle frames`, + `${name}: --enable-source-maps never stamps an already-mapped frame`, () => { - const r = run(bin as string, [], 'off'); - expect(r.sourceMapsEnabled).not.toBe(true); + const r = run(bin as string, withMap, flag, 'on'); + if (name === 'node') { + // Node maps the stacks BEFORE the SDK sees them: error frames AND the registration key's top frame are + // original `src/*.js` positions, so the bundle's id would be wrong for every one of them. + expect(r.sourceMapsEnabled).toBe(true); + expect(r.registrationTopFrames[0]).toContain('/src/'); + expect(originalFrames(r).length).toBeGreaterThanOrEqual(2); + expect(r.frames.map((f) => f.debug_id)).not.toContain(DEBUG_ID); + } else { + // Measured (Bun 1.4.4): Bun does NOT apply source maps to Error.stack and has no + // `process.sourceMapsEnabled`, so frames stay on the bundle and stamping them is correct. + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + } + }, + ); + + it.skipIf(bin === undefined)( + `${name}: flag on but the map was deleted (plugin default) -> nothing is mapped, frames stay stamped`, + () => { + const r = run(bin as string, noMap, flag, 'on'); expect(r.registrationTopFrames[0]).toContain('dist/app.js'); - const user = r.frames.filter((f) => f.at.includes('dist/app.js')); - expect(user.length).toBeGreaterThan(0); - for (const f of user) expect(f.debug_id).toBe(DEBUG_ID); + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); }, ); it.skipIf(bin === undefined)( - `${target.name}: --enable-source-maps never stamps an already-mapped frame`, + `${name}: source maps enabled AFTER the bundle loaded -> frames are unmapped and stay stamped`, () => { - const r = run(bin as string, ['--enable-source-maps'], 'on'); - const original = r.frames.filter((f) => f.at.includes('/src/')); - if (target.name === 'node') { - // Node maps the stacks BEFORE the SDK sees them: error frames AND the registration key's top frame - // are original `src/*.js` positions, so the bundle's id would be wrong for every one of them. - expect(r.sourceMapsEnabled).toBe(true); - expect(r.registrationTopFrames[0]).toContain('/src/'); - expect(original.length).toBeGreaterThanOrEqual(2); - } - // Whatever the runtime did, a frame that points at an ORIGINAL source must carry no debug-id. - for (const f of original) expect(f.debug_id).toBeUndefined(); - if (target.name === 'bun') { - // Measured (Bun 1.4.4): Bun does NOT apply source maps to Error.stack (no `process.sourceMapsEnabled`), - // so frames stay on the bundle and stamping them is correct. - expect(original).toHaveLength(0); - for (const f of r.frames.filter((x) => x.at.includes('dist/app.js'))) { - expect(f.debug_id).toBe(DEBUG_ID); - } - } + const r = run(bin as string, withMap, [], 'late'); + if (name === 'node') expect(r.sourceMapsEnabled).toBe(true); + expect(r.registrationTopFrames[0]).toContain('dist/app.js'); + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); }, ); } diff --git a/packages/node/src/debug-id-verifier.test.ts b/packages/node/src/debug-id-verifier.test.ts new file mode 100644 index 000000000..2612db28a --- /dev/null +++ b/packages/node/src/debug-id-verifier.test.ts @@ -0,0 +1,75 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createStampedBundleVerifier, readStampedDebugId } from './debug-id-verifier'; + +const ID = '11111111-2222-5333-8444-555555555555'; + +describe('readStampedDebugId', () => { + it('returns the LAST stamp, lower-cased, only when it is a UUID', () => { + expect( + readStampedDebugId(`x\n//# debugId=${ID.toUpperCase()}\n//# sourceMappingURL=a.map`), + ).toBe(ID); + expect(readStampedDebugId(`//# debugId=${ID}\n//# debugId=${ID.replace('1', '2')}`)).toBe( + ID.replace('1', '2'), + ); + expect(readStampedDebugId('//# debugId=not-a-uuid')).toBeUndefined(); + expect(readStampedDebugId('no stamp')).toBeUndefined(); + }); +}); + +describe('createStampedBundleVerifier', () => { + let dir: string | undefined; + afterEach(() => { + if (dir) rmSync(dir, { recursive: true, force: true }); + dir = undefined; + }); + const fixture = (): string => { + dir = mkdtempSync(join(tmpdir(), 'bugsee-verify-')); + mkdirSync(join(dir, 'dist')); + mkdirSync(join(dir, 'src')); + writeFileSync(join(dir, 'dist', 'app.js'), `console.log(1);\n//# debugId=${ID}\n`); + writeFileSync(join(dir, 'src', 'main.js'), 'export const a = 1;\n'); + return dir; + }; + + it('accepts a file whose tail carries the registered id, rejects an unstamped or differently stamped one', () => { + const root = fixture(); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify(join(root, 'dist', 'app.js'), ID)).toBe(true); + expect(verify(join(root, 'dist', 'app.js'), ID.toUpperCase())).toBe(true); + expect(verify(join(root, 'dist', 'app.js'), 'other')).toBe(false); + expect(verify(join(root, 'src', 'main.js'), ID)).toBe(false); + }); + + it('resolves app-relative (scrubbed) paths and file:// URLs', () => { + const root = fixture(); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify('./dist/app.js', ID)).toBe(true); + expect(verify('./src/main.js', ID)).toBe(false); + expect(verify(pathToFileURL(join(root, 'dist', 'app.js')).href, ID)).toBe(true); + }); + + it('rejects (never throws) for an unreadable file or a malformed URL', () => { + const root = fixture(); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify(join(root, 'missing.js'), ID)).toBe(false); + expect(verify('file://bad host/x', ID)).toBe(false); + }); + + it('reads only the tail of a large file', () => { + const root = fixture(); + writeFileSync(join(root, 'dist', 'big.js'), `${'a'.repeat(100_000)}\n//# debugId=${ID}\n`); + writeFileSync(join(root, 'dist', 'head.js'), `//# debugId=${ID}\n${'a'.repeat(100_000)}`); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify('./dist/big.js', ID)).toBe(true); + expect(verify('./dist/head.js', ID)).toBe(false); + }); + + it('defaults the app root to the working directory', () => { + const verify = createStampedBundleVerifier(); + expect(verify('./definitely/not/here.js', ID)).toBe(false); + }); +}); diff --git a/packages/node/src/debug-id-verifier.ts b/packages/node/src/debug-id-verifier.ts new file mode 100644 index 000000000..7bdb7fe9c --- /dev/null +++ b/packages/node/src/debug-id-verifier.ts @@ -0,0 +1,62 @@ +import { closeSync, fstatSync, openSync, readSync } from 'node:fs'; +import process from 'node:process'; +import { fileURLToPath } from 'node:url'; +import type { RegistrationVerifier } from '@bugsee/core'; +import { resolveFramePath } from './source-context'; + +// #185. Under `--enable-source-maps` a debug-ID registration's top frame may have been mapped to an ORIGINAL file +// (`src/main.js`) instead of the stamped bundle. The bundle a registration belongs to is proven by the file +// itself: `sourcemaps inject` leaves `//# debugId=` in its tail (same marker the bundler plugin reads), so a +// registration is genuine only if its top-frame file still carries that id. Core cannot read files; node supplies this. + +const MARKER = '//# debugId='; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const TAIL_BYTES = 16 * 1024; + +/** The LAST `//# debugId=` stamp in `content` when it is a UUID (the bundler plugin's `readDebugId` rule). */ +export function readStampedDebugId(content: string): string | undefined { + const at = content.lastIndexOf(MARKER); + if (at === -1) { + return undefined; + } + const token = content + .slice(at + MARKER.length) + .trimStart() + .slice(0, 36) + .toLowerCase(); + return UUID_RE.test(token) ? token : undefined; +} + +function readTail(path: string): string { + const fd = openSync(path, 'r'); + try { + const { size } = fstatSync(fd); + const length = Math.min(size, TAIL_BYTES); + const buffer = Buffer.alloc(length); + readSync(fd, buffer, 0, length, size - length); + return buffer.toString('utf8'); + } finally { + closeSync(fd); + } +} + +/** + * A {@link RegistrationVerifier}: true only when `file` (a scrubbed frame path: absolute, app-relative `./x`, or a + * `file://` URL) exists and ends with the registered debug-id stamp. Any failure (missing file, bad URL) is a + * rejection, never a throw: a registration that cannot be proven is not joined on. + */ +export function createStampedBundleVerifier( + options: { appRoot?: string } = {}, +): RegistrationVerifier { + return (file, debugId) => { + try { + const path = file.startsWith('file://') ? fileURLToPath(file) : file; + const stamped = readStampedDebugId( + readTail(resolveFramePath(path, options.appRoot ?? process.cwd())), + ); + return stamped === debugId.toLowerCase(); + } catch { + return false; + } + }; +} diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index d12cb80e5..dbb11740d 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -17,6 +17,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { TraceProducer } from '@bugsee/capture'; import { + applyDebugIds, type BundleStore, BundleStoreToken, CaptureDataEntryBase, @@ -39,9 +40,11 @@ import { type NativeCrashSource, parseLocation, ReportMarkerStoreToken, + type StackFrame, type StoredEntry, serializeBundle, serviceToken, + setDebugIdRegistrationVerifier, setStackAppRoot, TransportToken, } from '@bugsee/core'; @@ -4054,3 +4057,32 @@ describe('launch — environment.app.uptime_s (snapshot at session start)', () = expect(onError).toHaveBeenCalledWith(boom); }); }); + +describe('launch — debug-ID registrations under runtime source-map support (#185)', () => { + afterEach(() => { + setStackAppRoot(undefined); + setDebugIdRegistrationVerifier(undefined); + }); + + it('installs a verifier that accepts the stamped bundle and rejects a mapped original file', () => { + const root = mkdtempSync(join(tmpdir(), 'bugsee-sm-launch-')); + try { + const id = '11111111-2222-5333-8444-555555555555'; + mkdirSync(join(root, 'dist')); + mkdirSync(join(root, 'src')); + writeFileSync(join(root, 'dist', 'app.js'), `x\n//# debugId=${id}\n`); + writeFileSync(join(root, 'src', 'main.js'), 'export {};\n'); + launchTracked('tok', baseOptions({ carrier: {}, appRoot: root })); + const stack = (file: string) => `Error\n at (${file}:1:1)`; + const registry = { [stack(`${root}/dist/app.js`)]: id, [stack(`${root}/src/main.js`)]: id }; + const frames = [{ file: './dist/app.js' }, { file: './src/main.js' }] as StackFrame[]; + applyDebugIds(frames, { + globalObject: { _bugseeDebugIds: registry }, + runtimeMapsStacks: true, + }); + expect(frames.map((f) => f.debugId)).toEqual([id, undefined]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index 56b8ef36d..2fb72b97f 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -66,6 +66,7 @@ import { setCarrierClient, setCarrierLastLaunch, setCarrierStatus, + setDebugIdRegistrationVerifier, setStackAppRoot, TransportToken, withTransportHeaders, @@ -92,6 +93,7 @@ import { createRequestScopedActiveSpanStore } from './active-span-store'; import { createNodeAppIdentitySource } from './app-identity-source'; import { type CpuProfiler, createCpuProfiler } from './cpu-profiler'; import { type CapturedDataStore, ensureSecureDataRoot, resolveDataLocation } from './data-location'; +import { createStampedBundleVerifier } from './debug-id-verifier'; import { createUncaughtExceptionProvider, createUnhandledRejectionProvider, @@ -637,6 +639,11 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc // capture. Dependency frames are already handled without this — they truncate at `node_modules` — // but application frames have no such landmark. setStackAppRoot(options.appRoot ?? safeCwd()); + // #185: under `--enable-source-maps` a debug-ID registration can be mapped to an original file; core only joins + // on registrations whose top-frame file still carries the stamp (the filesystem half core cannot have). + setDebugIdRegistrationVerifier( + createStampedBundleVerifier({ appRoot: options.appRoot ?? safeCwd() }), + ); const sdkVersion = options.sdkVersion ?? SDK_VERSION; const baseUrl = options.endpoint ?? DEFAULT_ENDPOINT; From 3e780d4537419078c94cc61941a7f57af3bb3db4 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 18:48:07 +0500 Subject: [PATCH 3/7] fix(node,core): verify ESM stamps (decoded/query paths), cache verdicts, guard verifier throws (#185) Core's scrubber leaves ESM frames percent-encoded (and Windows as /C:/..), so the verifier now also tries the decoded file-URL reading with query/hash stripped. Verdicts are cached per (file, id) so reports do no repeated file I/O. A throwing verifier is a rejection. E2E gains ESM-under-a-space cases; tests use a hex-letter id. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/design/source-maps.md | 10 +- packages/core/src/debug-id.test.ts | 17 +++ packages/core/src/debug-id.ts | 15 ++- .../app/sourcemaps-runtime-scenario.ts | 6 +- .../test/sourcemaps-runtime.e2e.ts | 44 ++++++- packages/node/src/debug-id-verifier.test.ts | 113 +++++++++++++++++- packages/node/src/debug-id-verifier.ts | 68 +++++++++-- 7 files changed, 247 insertions(+), 26 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 8cff01e41..250a58df4 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -213,8 +213,14 @@ carry `//# debugId=` (the same marker `bundler-plugin-core` r Core stays runtime-portable: no `node:fs`, the verifier is injected (`setDebugIdRegistrationVerifier` / the `verifyRegistration` option). With no verifier (browsers, Electron renderers: Chromium does not map `Error.stack` even where `process.sourceMapsEnabled` reads true) every registration is kept, i.e. the previous behaviour. -Known limit: a registration whose top-frame path was scrubbed to `node_modules/...` (a stamped bundle shipped inside -a dependency) cannot be resolved and is not joined while the flag is on. Bun does not map `Error.stack` and has no +The verifier reads the path the way core scrubs it, which is not always a plain path: ESM frames arrive as `/…/my%20app/dist/app.mjs` +(core strips `file://` without URL-decoding), possibly with an import `?v=1`/`#hash`, and on Windows as `/C:/…`; the +verifier tries the literal path first, then the decoded URL form with the query stripped. Answers are cached per +(file, id) (bounded), so reports cost no file I/O after the first. Known limits: a path scrubbed to +`node_modules/...` has no `./` prefix and is resolved against `process.cwd()`, not the app root, so it verifies when +the first `node_modules` sits in the cwd and is not joined (flag on) in a hoisted monorepo or when `appRoot` differs +from the cwd. Separately (pre-existing): encoded ESM paths never match the app root, so they ship as absolute paths. +Windows hosts were not run. Bun does not map `Error.stack` and has no `process.sourceMapsEnabled` (Bun 1.4.4, measured), so it keeps stamping, which is correct. --- diff --git a/packages/core/src/debug-id.test.ts b/packages/core/src/debug-id.test.ts index f0f794a08..c56d11f33 100644 --- a/packages/core/src/debug-id.test.ts +++ b/packages/core/src/debug-id.test.ts @@ -154,6 +154,23 @@ describe('buildDebugIdMap with an accept predicate', () => { }); }); +describe('buildDebugIdMap with a throwing predicate', () => { + it('treats a throw as a rejection of that registration only', () => { + const map = buildDebugIdMap( + { + [bundleStack('/app/dist/bad.js')]: 'bad-id', + [bundleStack('/app/dist/good.js')]: 'good-id', + }, + parseV8Stack, + (file) => { + if (file.includes('bad')) throw new Error('verifier blew up'); + return true; + }, + ); + expect([...map]).toEqual([['/app/dist/good.js', 'good-id']]); + }); +}); + describe('applyDebugIds under runtime source-map support (#185)', () => { // With `node --enable-source-maps` AND a map on disk, the registration key's top frame is mapped to an // ORIGINAL file (`src/main.js`). Joining on it stamps the bundle's id onto already-mapped frames -> the diff --git a/packages/core/src/debug-id.ts b/packages/core/src/debug-id.ts index 17c6fd4de..11dcb1f60 100644 --- a/packages/core/src/debug-id.ts +++ b/packages/core/src/debug-id.ts @@ -19,6 +19,19 @@ export function readDebugIds(globalObject: unknown): Record { return typeof ids === 'object' && ids !== null ? (ids as Record) : {}; } +/** An injected predicate must never take a report down: a throw is a rejection. */ +function accepts( + accept: (file: string, debugId: string) => boolean, + file: string, + debugId: string, +): boolean { + try { + return accept(file, debugId); + } catch { + return false; + } +} + /** * Build a `file → debugId` map from the registration map: parse each registered stack and key the debug-ID * by its TOP frame's file (the bundle that registered it). @@ -31,7 +44,7 @@ export function buildDebugIdMap( const map = new Map(); for (const [stack, debugId] of Object.entries(debugIds)) { const file = parseStack(stack)[0]?.file; - if (file !== undefined && (accept === undefined || accept(file, debugId))) { + if (file !== undefined && (accept === undefined || accepts(accept, file, debugId))) { map.set(file, debugId); } } diff --git a/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts index 4cb611eac..37b11c456 100644 --- a/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts +++ b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts @@ -4,6 +4,7 @@ // bundle loaded (Node only maps modules loaded afterwards); unset leaves the process flags alone. import { createRequire } from 'node:module'; import process from 'node:process'; +import { pathToFileURL } from 'node:url'; import { buildCrashJson, setDebugIdRegistrationVerifier, setStackAppRoot } from '@bugsee/core'; // Internal to @bugsee/node (installed by its launch); imported by path so the public export surface stays unchanged. import { createStampedBundleVerifier } from '../../node/src/debug-id-verifier'; @@ -24,7 +25,10 @@ setStackAppRoot(appRoot); setDebugIdRegistrationVerifier(createStampedBundleVerifier({ appRoot })); const require = createRequire(import.meta.url); -const app = require(process.env.BUNDLE_PATH as string) as { fail: () => never }; +const bundlePath = process.env.BUNDLE_PATH as string; +const app = ( + bundlePath.endsWith('.mjs') ? await import(pathToFileURL(bundlePath).href) : require(bundlePath) +) as { fail: () => never }; if (mode === 'late') setMaps(true); let thrown: unknown; try { diff --git a/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts index 8393e52cf..007088a94 100644 --- a/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts +++ b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts @@ -35,8 +35,10 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { /** Build roots: one keeps `app.js.map` on disk, one has it deleted (the plugin's default after upload). */ let withMap: string; let noMap: string; + let esmMap: string; + let esmNoMap: string; - function build(root: string, keepMap: boolean): void { + function build(root: string, keepMap: boolean, esm = false): void { mkdirSync(join(root, 'src'), { recursive: true }); mkdirSync(join(root, 'dist')); writeFileSync( @@ -47,14 +49,14 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { join(root, 'src', 'main.js'), "import { boom } from './a.js';\nexport function fail() {\n boom();\n}\n", ); - const bundle = join(root, 'dist', 'app.js'); + const bundle = join(root, 'dist', esm ? 'app.mjs' : 'app.js'); execFileSync( join(pkgRoot, 'node_modules', '.bin', 'esbuild'), [ join(root, 'src', 'main.js'), '--bundle', '--platform=node', - '--format=cjs', + `--format=${esm ? 'esm' : 'cjs'}`, '--sourcemap', `--outfile=${bundle}`, '--log-level=warning', @@ -75,6 +77,13 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { mkdirSync(noMap); build(withMap, true); build(noMap, false); + // ESM bundles under a directory with a SPACE: Node prints the frame as `file:///…/my%20app/dist/app.mjs`. + esmMap = join(dir, 'my app', 'esm-map'); + esmNoMap = join(dir, 'my app', 'esm-no-map'); + mkdirSync(esmMap, { recursive: true }); + mkdirSync(esmNoMap, { recursive: true }); + build(esmMap, true, true); + build(esmNoMap, false, true); }); afterAll(() => rmSync(dir, { recursive: true, force: true })); @@ -88,7 +97,7 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { encoding: 'utf8', env: { ...process.env, - BUNDLE_PATH: join(root, 'dist', 'app.js'), + BUNDLE_PATH: join(root, 'dist', root.includes('esm') ? 'app.mjs' : 'app.js'), APP_ROOT: root, SOURCE_MAPS: sourceMaps, }, @@ -96,11 +105,36 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { return JSON.parse(out.trim().split('\n').at(-1) as string) as Result; } - const bundleFrames = (r: Result) => r.frames.filter((f) => f.at.includes('dist/app.js')); + const bundleFrames = (r: Result) => r.frames.filter((f) => f.at.includes('dist/app.')); const originalFrames = (r: Result) => r.frames.filter((f) => f.at.includes('src/')); for (const target of runtimeTargets()) { const { bin, name } = target; + it.skipIf(bin === undefined)( + `${name}: ESM bundle under a path with a space, flag on, map deleted -> stays stamped`, + () => { + const r = run(bin as string, esmNoMap, ['--enable-source-maps'], 'on'); + // Node prints the ESM frame as a percent-encoded file URL; Bun prints the plain path. + expect(r.registrationTopFrames[0]).toContain(name === 'node' ? 'my%20app' : 'my app'); + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + + it.skipIf(bin === undefined)( + `${name}: ESM bundle under a path with a space, flag on, map present -> mapped frames are not stamped`, + () => { + const r = run(bin as string, esmMap, ['--enable-source-maps'], 'on'); + if (name === 'node') { + expect(originalFrames(r).length).toBeGreaterThanOrEqual(2); + expect(r.frames.map((f) => f.debug_id)).not.toContain(DEBUG_ID); + } else { + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); // Bun does not map + } + }, + ); + const flag = ['--enable-source-maps']; it.skipIf(bin === undefined)(`${name}: source maps off -> bundle frames are stamped`, () => { diff --git a/packages/node/src/debug-id-verifier.test.ts b/packages/node/src/debug-id-verifier.test.ts index 2612db28a..61efd02a3 100644 --- a/packages/node/src/debug-id-verifier.test.ts +++ b/packages/node/src/debug-id-verifier.test.ts @@ -2,18 +2,19 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; +import { parseV8Stack } from '@bugsee/core'; import { afterEach, describe, expect, it } from 'vitest'; import { createStampedBundleVerifier, readStampedDebugId } from './debug-id-verifier'; -const ID = '11111111-2222-5333-8444-555555555555'; +// Hex LETTERS on purpose: an all-digit id cannot tell a case-folding mutation from the original. +const ID = 'abcdef12-2222-5ABC-8444-55555555dEaD'; +const LOWER = ID.toLowerCase(); describe('readStampedDebugId', () => { it('returns the LAST stamp, lower-cased, only when it is a UUID', () => { - expect( - readStampedDebugId(`x\n//# debugId=${ID.toUpperCase()}\n//# sourceMappingURL=a.map`), - ).toBe(ID); - expect(readStampedDebugId(`//# debugId=${ID}\n//# debugId=${ID.replace('1', '2')}`)).toBe( - ID.replace('1', '2'), + expect(readStampedDebugId(`x\n//# debugId=${ID}\n//# sourceMappingURL=a.map`)).toBe(LOWER); + expect(readStampedDebugId(`//# debugId=${ID}\n//# debugId=${LOWER.replace('a', 'b')}`)).toBe( + LOWER.replace('a', 'b'), ); expect(readStampedDebugId('//# debugId=not-a-uuid')).toBeUndefined(); expect(readStampedDebugId('no stamp')).toBeUndefined(); @@ -39,6 +40,7 @@ describe('createStampedBundleVerifier', () => { const root = fixture(); const verify = createStampedBundleVerifier({ appRoot: root }); expect(verify(join(root, 'dist', 'app.js'), ID)).toBe(true); + expect(verify(join(root, 'dist', 'app.js'), LOWER)).toBe(true); expect(verify(join(root, 'dist', 'app.js'), ID.toUpperCase())).toBe(true); expect(verify(join(root, 'dist', 'app.js'), 'other')).toBe(false); expect(verify(join(root, 'src', 'main.js'), ID)).toBe(false); @@ -57,6 +59,7 @@ describe('createStampedBundleVerifier', () => { const verify = createStampedBundleVerifier({ appRoot: root }); expect(verify(join(root, 'missing.js'), ID)).toBe(false); expect(verify('file://bad host/x', ID)).toBe(false); + expect(verify('/%zz/not-decodable.mjs', ID)).toBe(false); }); it('reads only the tail of a large file', () => { @@ -72,4 +75,102 @@ describe('createStampedBundleVerifier', () => { const verify = createStampedBundleVerifier(); expect(verify('./definitely/not/here.js', ID)).toBe(false); }); + + describe('ESM frames as the REAL parse pipeline delivers them (parseV8Stack output)', () => { + // Node prints ESM frames as `file:///…` URLs; core's scrubber strips the scheme WITHOUT decoding, so the + // verifier sees `/…/my%20app/dist/app.mjs`, not a file:// URL. + const topFile = (url: string): string => { + const frame = parseV8Stack(`Error\n at (${url}:1:479)`)[0]; + return frame?.file as string; + }; + + it('opens a path with a space (percent-encoded in the stack)', () => { + const root = fixture(); + const spaced = join(root, 'my app', 'dist'); + mkdirSync(spaced, { recursive: true }); + writeFileSync(join(spaced, 'app.mjs'), `export {};\n//# debugId=${ID}\n`); + const url = pathToFileURL(join(spaced, 'app.mjs')).href; + expect(url).toContain('my%20app'); + const file = topFile(url); + expect(file).toContain('my%20app'); // the scrubber really leaves it encoded + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + }); + + it('strips an import query / hash', () => { + const root = fixture(); + writeFileSync(join(root, 'dist', 'app.mjs'), `export {};\n//# debugId=${ID}\n`); + const url = `${pathToFileURL(join(root, 'dist', 'app.mjs')).href}?v=1#x`; + const file = topFile(url); + expect(file.endsWith('app.mjs?v=1#x')).toBe(true); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + }); + + it('prefers a file literally named with a query/percent over the decoded reading', () => { + const root = fixture(); + writeFileSync(join(root, 'dist', 'a%20b.js'), `//# debugId=${ID}\n`); + expect( + createStampedBundleVerifier({ appRoot: root })(join(root, 'dist', 'a%20b.js'), ID), + ).toBe(true); + }); + + it('Windows drive form: tries the decoded URL reading of `/C:/…` (verified through the read seam)', () => { + const file = topFile('file:///C:/my%20app/dist/app.mjs'); + expect(file).toBe('/C:/my%20app/dist/app.mjs'); + const opened: string[] = []; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: (path) => { + opened.push(path); + if (path.includes('my app')) return `//# debugId=${ID}`; + throw new Error('ENOENT'); + }, + }); + expect(verify(file, ID)).toBe(true); + // literal first (fails), then the decoded form (what a win32 host turns into `C:\my app\dist\app.mjs`) + expect(opened[0]).toBe('/C:/my%20app/dist/app.mjs'); + expect(opened[1]).toContain('C:'); + expect(opened[1]).toContain('my app'); + }); + }); + + describe('cache', () => { + it('answers a repeated (file, id) with no further I/O, and caches rejections too', () => { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: (path) => { + reads++; + if (path.endsWith('good.js')) return `//# debugId=${ID}`; + throw new Error('ENOENT'); + }, + }); + expect(verify('/x/good.js', ID)).toBe(true); + const afterFirst = reads; + expect(verify('/x/good.js', ID)).toBe(true); + expect(reads).toBe(afterFirst); + expect(verify('/x/bad.js', ID)).toBe(false); + const afterBad = reads; + expect(verify('/x/bad.js', ID)).toBe(false); + expect(reads).toBe(afterBad); + // a different id for the same file is a different question + expect(verify('/x/good.js', 'other-id')).toBe(false); + }); + + it('is bounded: after many distinct keys it still answers correctly', () => { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + return `//# debugId=${ID}`; + }, + }); + for (let i = 0; i < 600; i++) expect(verify(`/x/f${i}.js`, ID)).toBe(true); + const before = reads; + expect(verify('/x/f599.js', ID)).toBe(true); // recent: still cached + expect(reads).toBe(before); + expect(verify('/x/f0.js', ID)).toBe(true); // evicted: re-read, same answer + expect(reads).toBe(before + 1); + }); + }); }); diff --git a/packages/node/src/debug-id-verifier.ts b/packages/node/src/debug-id-verifier.ts index 7bdb7fe9c..3e3fd5726 100644 --- a/packages/node/src/debug-id-verifier.ts +++ b/packages/node/src/debug-id-verifier.ts @@ -6,12 +6,15 @@ import { resolveFramePath } from './source-context'; // #185. Under `--enable-source-maps` a debug-ID registration's top frame may have been mapped to an ORIGINAL file // (`src/main.js`) instead of the stamped bundle. The bundle a registration belongs to is proven by the file -// itself: `sourcemaps inject` leaves `//# debugId=` in its tail (same marker the bundler plugin reads), so a +// itself: `sourcemaps inject` leaves `//# debugId=` in its tail (same marker the bundler plugin reads, see +// `bundler-plugin-core/src/debug-ids.ts`; duplicated here because node must not depend on the build tooling), so a // registration is genuine only if its top-frame file still carries that id. Core cannot read files; node supplies this. const MARKER = '//# debugId='; const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const TAIL_BYTES = 16 * 1024; +/** A registration's file does not change during a process, so answers are cached (bounded; emptied when full). */ +const CACHE_MAX = 256; /** The LAST `//# debugId=` stamp in `content` when it is a UUID (the bundler plugin's `readDebugId` rule). */ export function readStampedDebugId(content: string): string | undefined { @@ -41,22 +44,65 @@ function readTail(path: string): string { } /** - * A {@link RegistrationVerifier}: true only when `file` (a scrubbed frame path: absolute, app-relative `./x`, or a - * `file://` URL) exists and ends with the registered debug-id stamp. Any failure (missing file, bad URL) is a - * rejection, never a throw: a registration that cannot be proven is not joined on. + * The filesystem paths a scrubbed frame `file` may denote, most literal first. + * + * Core's scrubber strips `file://` by slicing WITHOUT URL-decoding, so an ESM frame arrives as `/…/my%20app/dist/a.mjs` + * (posix), `/C:/app/dist/a.mjs` (Windows) and may carry the import's `?v=1` / `#hash`. Application frames under the + * app root arrive as `./x`. The literal path is tried first (a file really named `a%20b`), then the decoded URL form. + */ +function candidatePaths(file: string, appRoot: string): string[] { + if (file.startsWith('file://')) { + return [fileURLToPath(file)]; + } + const candidates = [resolveFramePath(file, appRoot)]; + if (file.startsWith('/')) { + const bare = file.replace(/[?#].*$/, ''); + candidates.push(fileURLToPath(`file://${bare}`)); + if (bare !== file) { + candidates.push(bare); + } + } + return candidates; +} + +/** + * A {@link RegistrationVerifier}: true only when `file` (a scrubbed frame path: absolute, app-relative `./x`, a + * URL-encoded ESM path or a `file://` URL) exists and ends with the registered debug-id stamp. Any failure (missing + * file, bad URL) is a rejection, never a throw: a registration that cannot be proven is not joined on. Answers are + * cached per (file, id), so a report costs no file I/O after the first. */ export function createStampedBundleVerifier( - options: { appRoot?: string } = {}, + options: { appRoot?: string; readTail?: (path: string) => string } = {}, ): RegistrationVerifier { + const read = options.readTail ?? readTail; + const cache = new Map(); + const check = (file: string, debugId: string): boolean => { + const wanted = debugId.toLowerCase(); + for (const path of candidatePaths(file, options.appRoot ?? process.cwd())) { + try { + return readStampedDebugId(read(path)) === wanted; + } catch { + // not openable under this reading; try the next + } + } + return false; + }; return (file, debugId) => { + const key = `${file}\0${debugId}`; + const hit = cache.get(key); + if (hit !== undefined) { + return hit; + } + let verdict: boolean; try { - const path = file.startsWith('file://') ? fileURLToPath(file) : file; - const stamped = readStampedDebugId( - readTail(resolveFramePath(path, options.appRoot ?? process.cwd())), - ); - return stamped === debugId.toLowerCase(); + verdict = check(file, debugId); } catch { - return false; + verdict = false; // a malformed URL / cwd failure + } + if (cache.size >= CACHE_MAX) { + cache.clear(); } + cache.set(key, verdict); + return verdict; }; } From fe35c9208073cc56fc3e2d1dc9418a593eac77f7 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 18:55:00 +0500 Subject: [PATCH 4/7] fix(core,node): older-Node probe fallback, literal-path fallback, no caching of transient read errors (#185) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- packages/core/src/debug-id.test.ts | 19 ++++++++ packages/core/src/debug-id.ts | 18 ++++++- packages/node/src/debug-id-verifier.test.ts | 53 ++++++++++++++++++++- packages/node/src/debug-id-verifier.ts | 33 +++++++++---- 4 files changed, 112 insertions(+), 11 deletions(-) diff --git a/packages/core/src/debug-id.test.ts b/packages/core/src/debug-id.test.ts index c56d11f33..ce9ec0726 100644 --- a/packages/core/src/debug-id.test.ts +++ b/packages/core/src/debug-id.test.ts @@ -110,6 +110,25 @@ describe('runtimeMapsStacks', () => { expect(runtimeMapsStacks({ sourceMapsEnabled: 'yes' })).toBe(false); }); + it('falls back to the launch flags where `sourceMapsEnabled` does not exist (Node < 18.19 / 20.7)', () => { + expect(runtimeMapsStacks({ execArgv: ['--no-warnings', '--enable-source-maps'] })).toBe(true); + expect( + runtimeMapsStacks({ env: { NODE_OPTIONS: '--max-old-space-size=4 --enable-source-maps' } }), + ).toBe(true); + expect(runtimeMapsStacks({ execArgv: ['--no-warnings'], env: { NODE_OPTIONS: '--x' } })).toBe( + false, + ); + expect( + runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps-extra --enable' } }), + ).toBe(false); + expect(runtimeMapsStacks({ execArgv: 'nope', env: null })).toBe(false); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: 7 } })).toBe(false); + // an explicit answer always wins over the launch flags (setSourceMapsEnabled(false) after start) + expect( + runtimeMapsStacks({ sourceMapsEnabled: false, execArgv: ['--enable-source-maps'] }), + ).toBe(false); + }); + it('is false without a process object (browsers, workers, edge)', () => { expect(runtimeMapsStacks(undefined)).toBe(false); expect(runtimeMapsStacks(null)).toBe(false); diff --git a/packages/core/src/debug-id.ts b/packages/core/src/debug-id.ts index 11dcb1f60..8dddf2869 100644 --- a/packages/core/src/debug-id.ts +++ b/packages/core/src/debug-id.ts @@ -63,6 +63,8 @@ export function attachDebugIds(frames: StackFrame[], debugIdMap: Map Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); describe('readStampedDebugId', () => { it('returns the LAST stamp, lower-cased, only when it is a UUID', () => { @@ -122,7 +123,7 @@ describe('createStampedBundleVerifier', () => { readTail: (path) => { opened.push(path); if (path.includes('my app')) return `//# debugId=${ID}`; - throw new Error('ENOENT'); + throw enoent(); }, }); expect(verify(file, ID)).toBe(true); @@ -133,6 +134,54 @@ describe('createStampedBundleVerifier', () => { }); }); + it('falls back to the literal path when a real directory name is not a valid file-URL reading', () => { + const root = fixture(); + for (const name of ['100%', 'a%2Fb']) { + mkdirSync(join(root, name, 'dist'), { recursive: true }); + writeFileSync(join(root, name, 'dist', 'app.js'), `//# debugId=${ID}\n`); + expect( + createStampedBundleVerifier({ appRoot: root })(join(root, name, 'dist', 'app.js'), ID), + ).toBe(true); + } + }); + + describe('transient read errors', () => { + it('are rejected but NOT cached: the next call asks again', () => { + let reads = 0; + let failing = true; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + if (failing) throw Object.assign(new Error('too many open files'), { code: 'EMFILE' }); + return `//# debugId=${ID}`; + }, + }); + expect(verify('/x/a.js', ID)).toBe(false); + expect(verify('/x/a.js', ID)).toBe(false); + expect(reads).toBe(4); // two readings per ask (literal + decoded), asked twice + failing = false; + expect(verify('/x/a.js', ID)).toBe(true); + expect(verify('/x/a.js', ID)).toBe(true); + expect(reads).toBe(5); // the success is cached + }); + + it('an error without a code is transient too; a malformed URL is rejected uncached', () => { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + throw new Error('mystery'); + }, + }); + expect(verify('/x/a.js', ID)).toBe(false); + expect(verify('/x/a.js', ID)).toBe(false); + expect(reads).toBe(4); + expect(verify('file://bad host/x', ID)).toBe(false); + }); + }); + describe('cache', () => { it('answers a repeated (file, id) with no further I/O, and caches rejections too', () => { let reads = 0; @@ -141,7 +190,7 @@ describe('createStampedBundleVerifier', () => { readTail: (path) => { reads++; if (path.endsWith('good.js')) return `//# debugId=${ID}`; - throw new Error('ENOENT'); + throw enoent(); }, }); expect(verify('/x/good.js', ID)).toBe(true); diff --git a/packages/node/src/debug-id-verifier.ts b/packages/node/src/debug-id-verifier.ts index 3e3fd5726..4d304d8f0 100644 --- a/packages/node/src/debug-id-verifier.ts +++ b/packages/node/src/debug-id-verifier.ts @@ -57,7 +57,11 @@ function candidatePaths(file: string, appRoot: string): string[] { const candidates = [resolveFramePath(file, appRoot)]; if (file.startsWith('/')) { const bare = file.replace(/[?#].*$/, ''); - candidates.push(fileURLToPath(`file://${bare}`)); + try { + candidates.push(fileURLToPath(`file://${bare}`)); + } catch { + // a literal `%` / `%2F` in a real directory name is not a valid file-URL reading; the literal path stands + } if (bare !== file) { candidates.push(bare); } @@ -65,27 +69,37 @@ function candidatePaths(file: string, appRoot: string): string[] { return candidates; } +/** Errors that mean "there is no such file" (a stable answer), as opposed to a transient EMFILE / EACCES / EIO. */ +const NO_SUCH_FILE = new Set(['ENOENT', 'ENOTDIR', 'ENAMETOOLONG', 'EISDIR', 'EINVAL']); + /** * A {@link RegistrationVerifier}: true only when `file` (a scrubbed frame path: absolute, app-relative `./x`, a * URL-encoded ESM path or a `file://` URL) exists and ends with the registered debug-id stamp. Any failure (missing - * file, bad URL) is a rejection, never a throw: a registration that cannot be proven is not joined on. Answers are - * cached per (file, id), so a report costs no file I/O after the first. + * file, bad URL) is a rejection, never a throw: a registration that cannot be proven is not joined on. Definitive + * answers are cached per (file, id), so a report costs no file I/O after the first; an INCONCLUSIVE one (a transient + * read error such as EMFILE) is not cached and is asked again next time. */ export function createStampedBundleVerifier( options: { appRoot?: string; readTail?: (path: string) => string } = {}, ): RegistrationVerifier { const read = options.readTail ?? readTail; const cache = new Map(); - const check = (file: string, debugId: string): boolean => { + /** true / false when definitive, undefined when a transient error stopped the check. */ + const check = (file: string, debugId: string): boolean | undefined => { const wanted = debugId.toLowerCase(); + let transient = false; for (const path of candidatePaths(file, options.appRoot ?? process.cwd())) { try { return readStampedDebugId(read(path)) === wanted; - } catch { + } catch (error) { // not openable under this reading; try the next + const code = (error as { code?: unknown }).code; + if (typeof code !== 'string' || !NO_SUCH_FILE.has(code)) { + transient = true; + } } } - return false; + return transient ? undefined : false; }; return (file, debugId) => { const key = `${file}\0${debugId}`; @@ -93,11 +107,14 @@ export function createStampedBundleVerifier( if (hit !== undefined) { return hit; } - let verdict: boolean; + let verdict: boolean | undefined; try { verdict = check(file, debugId); } catch { - verdict = false; // a malformed URL / cwd failure + verdict = undefined; // a malformed file URL / cwd failure: reject now, ask again later + } + if (verdict === undefined) { + return false; } if (cache.size >= CACHE_MAX) { cache.clear(); From ad92ce5e5dc6c09b30db1ddf600ed4e08af523bf Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 19:12:06 +0500 Subject: [PATCH 5/7] fix(node,core): verify ESM stamps for files under the app root, larger cache, quoted NODE_OPTIONS (#185) Frames under the app root are scrubbed to ./x without decoding, so ./dist/my%20chunk.mjs and ./dist/a.mjs?v=1 were rejected. The decode and query-strip candidates now apply to relative paths too. Cache bound raised to 4096; no verifier means no runtime probe; the probe is exception-safe and tokenizes quoted NODE_OPTIONS. E2E uses a realpath tmp dir (kills the accept-any-readable-file mutation) and gains under-app-root ESM cases. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/PROGRESS.md | 2 +- docs/design/source-maps.md | 15 ++- packages/core/src/debug-id.test.ts | 51 ++++++++ packages/core/src/debug-id.ts | 24 +++- .../app/sourcemaps-runtime-scenario.ts | 4 +- .../test/sourcemaps-runtime.e2e.ts | 55 ++++++++- packages/node/src/debug-id-verifier.test.ts | 113 +++++++++++++++++- packages/node/src/debug-id-verifier.ts | 35 +++--- 8 files changed, 266 insertions(+), 33 deletions(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 73166b092..f8a632ff7 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1318,7 +1318,7 @@ key's top frame to `src/main.js`, so a frame at `src/main.js:3:3` was stamped wi backend remaps). A global skip on the flag was rejected (review): with the plugin-default deleted maps, or the flag enabled after load, nothing is mapped and the join is correct. Fix: `applyDebugIds` validates each registration while `process.sourceMapsEnabled` through an injected verifier (`setDebugIdRegistrationVerifier`; `@bugsee/node` installs -`createStampedBundleVerifier`, which requires the top-frame file's tail to carry `//# debugId=`). Bun does not map +`createStampedBundleVerifier`, which requires the top-frame file's tail to carry `//# debugId=`). The verifier decodes the percent-encoded ESM frames core leaves (`./dist/my%20chunk.mjs`, `?v=1`), caches verdicts (4096), and old Node (no `process.sourceMapsEnabled`) falls back to `--enable-source-maps` in `execArgv`/`NODE_OPTIONS`. Bun does not map `Error.stack` (measured), unaffected. Design: `docs/design/source-maps.md` §7.2. ### 2026-11-09 — Replay moves onto upstream rrweb 2.2.1 → `krassx/rrweb-2.2.1-a625` diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 250a58df4..de85aba5e 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -213,10 +213,17 @@ carry `//# debugId=` (the same marker `bundler-plugin-core` r Core stays runtime-portable: no `node:fs`, the verifier is injected (`setDebugIdRegistrationVerifier` / the `verifyRegistration` option). With no verifier (browsers, Electron renderers: Chromium does not map `Error.stack` even where `process.sourceMapsEnabled` reads true) every registration is kept, i.e. the previous behaviour. -The verifier reads the path the way core scrubs it, which is not always a plain path: ESM frames arrive as `/…/my%20app/dist/app.mjs` -(core strips `file://` without URL-decoding), possibly with an import `?v=1`/`#hash`, and on Windows as `/C:/…`; the -verifier tries the literal path first, then the decoded URL form with the query stripped. Answers are cached per -(file, id) (bounded), so reports cost no file I/O after the first. Known limits: a path scrubbed to +The verifier reads the path the way core scrubs it, which is not always a plain path: ESM frames arrive +percent-encoded (core strips `file://` without URL-decoding): `/…/my%20app/dist/app.mjs` outside the app root, +`./dist/my%20chunk.mjs` UNDER it (the common case: `launch()` sets the app root to the cwd), possibly with an import +`?v=1`/`#hash`, and on Windows as `/C:/…`. It tries the literal path first, then the decoded form with the query +stripped, then the stripped literal. Answers are cached per (file, id), bounded to 4096 registrations (reports cost no +file I/O after the first for any realistic build; a build with more stamped chunks than that re-reads). Old Node +(18.0-18.18, 20.0-20.6) has no `process.sourceMapsEnabled`, so the probe falls back to `--enable-source-maps` in +`execArgv` / `NODE_OPTIONS` (tokenized on whitespace, quotes stripped); an explicit property always wins. A runtime +`process.setSourceMapsEnabled(true)` on those old versions cannot be observed. With no verifier installed the runtime is +not probed at all. Not handled: a FIFO-backed path (`/dev/fd/N`) would block the synchronous open; a bundle rewritten in +place during a deploy keeps its cached verdict until restart. Known limits: a path scrubbed to `node_modules/...` has no `./` prefix and is resolved against `process.cwd()`, not the app root, so it verifies when the first `node_modules` sits in the cwd and is not joined (flag on) in a hoisted monorepo or when `appRoot` differs from the cwd. Separately (pre-existing): encoded ESM paths never match the app root, so they ship as absolute paths. diff --git a/packages/core/src/debug-id.test.ts b/packages/core/src/debug-id.test.ts index ce9ec0726..359415de4 100644 --- a/packages/core/src/debug-id.test.ts +++ b/packages/core/src/debug-id.test.ts @@ -129,6 +129,30 @@ describe('runtimeMapsStacks', () => { ).toBe(false); }); + it('reads NODE_OPTIONS the way Node tokenizes it: any whitespace, optionally quoted', () => { + const opts = (NODE_OPTIONS: string) => runtimeMapsStacks({ env: { NODE_OPTIONS } }); + expect(opts('--x\t--enable-source-maps')).toBe(true); + expect(opts('--x --enable-source-maps')).toBe(true); + expect(opts('"--enable-source-maps"')).toBe(true); + expect(opts("--x '--enable-source-maps'")).toBe(true); + expect(opts('"--enable-source-maps-extra"')).toBe(false); + }); + + it('never throws: a hostile process object answers false', () => { + const hostile = { + get sourceMapsEnabled(): never { + throw new Error('getter'); + }, + }; + expect(runtimeMapsStacks(hostile)).toBe(false); + const envThrows = { + get env(): never { + throw new Error('env getter'); + }, + }; + expect(runtimeMapsStacks(envThrows)).toBe(false); + }); + it('is false without a process object (browsers, workers, edge)', () => { expect(runtimeMapsStacks(undefined)).toBe(false); expect(runtimeMapsStacks(null)).toBe(false); @@ -239,6 +263,33 @@ describe('applyDebugIds under runtime source-map support (#185)', () => { expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); }); + it('with no verifier at all, never even probes the runtime (identical to the pre-#185 path)', () => { + const g = globalThis as unknown as { + process?: unknown; + _bugseeDebugIds?: Record; + }; + const real = g.process; + const prev = g._bugseeDebugIds; + let probed = 0; + g._bugseeDebugIds = registry; + g.process = { + get sourceMapsEnabled(): boolean { + probed++; + return true; + }, + }; + try { + const f = frames(); + applyDebugIds(f); + expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); + expect(probed).toBe(0); + } finally { + g.process = real; + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }); + it('uses the installed process-wide verifier by default, and the live process probe', () => { const g = globalThis as unknown as { process?: { sourceMapsEnabled?: boolean }; diff --git a/packages/core/src/debug-id.ts b/packages/core/src/debug-id.ts index 8dddf2869..408789b1a 100644 --- a/packages/core/src/debug-id.ts +++ b/packages/core/src/debug-id.ts @@ -73,6 +73,14 @@ const FLAG = '--enable-source-maps'; export function runtimeMapsStacks( proc: unknown = (globalThis as unknown as { process?: unknown }).process, ): boolean { + try { + return probe(proc); + } catch { + return false; // a hostile / exotic `process` shim (a throwing getter) is "not mapping" + } +} + +function probe(proc: unknown): boolean { if (typeof proc !== 'object' || proc === null) { return false; } @@ -86,11 +94,18 @@ export function runtimeMapsStacks( } // Older Node (< 18.19 / 20.7) maps stacks under the flag but has no `process.sourceMapsEnabled`: read the launch flags. // Wrongly true here is harmless (the verifier then checks each registration); wrongly false is the #185 bug. + // A runtime `process.setSourceMapsEnabled(true)` on those versions cannot be observed (documented limit). if (Array.isArray(execArgv) && execArgv.includes(FLAG)) { return true; } const options = env?.NODE_OPTIONS; - return typeof options === 'string' && options.split(/\s+/).includes(FLAG); + return ( + typeof options === 'string' && + options + .split(/\s+/) + .map((token) => token.replace(/^["']|["']$/g, '')) + .includes(FLAG) + ); } /** Does this registration (its top-frame file + debug-id) really belong to the stamped bundle? */ @@ -135,6 +150,11 @@ export function applyDebugIds( } const parseStack = options.parseStack ?? parseV8Stack; const verifier = options.verifyRegistration ?? installedVerifier; - const verify = (options.runtimeMapsStacks ?? runtimeMapsStacks()) ? verifier : undefined; + // No verifier (browsers, Electron renderers, a node process that never launched): exactly the pre-#185 join, and the + // runtime is not even probed. + const verify = + verifier !== undefined && (options.runtimeMapsStacks ?? runtimeMapsStacks()) + ? verifier + : undefined; attachDebugIds(frames, buildDebugIdMap(debugIds, parseStack, verify)); } diff --git a/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts index 37b11c456..4a42ce2fd 100644 --- a/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts +++ b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts @@ -27,7 +27,9 @@ setDebugIdRegistrationVerifier(createStampedBundleVerifier({ appRoot })); const require = createRequire(import.meta.url); const bundlePath = process.env.BUNDLE_PATH as string; const app = ( - bundlePath.endsWith('.mjs') ? await import(pathToFileURL(bundlePath).href) : require(bundlePath) + bundlePath.endsWith('.mjs') + ? await import(pathToFileURL(bundlePath).href + (process.env.IMPORT_QUERY ?? '')) + : require(bundlePath) ) as { fail: () => never }; if (mode === 'late') setMaps(true); let thrown: unknown; diff --git a/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts index 007088a94..d31ea37af 100644 --- a/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts +++ b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts @@ -10,7 +10,7 @@ // not mean frames are mapped: the plugin deletes `*.map` after upload by default (then Node cannot map anything), and // `process.setSourceMapsEnabled(true)` only affects modules loaded afterwards. Those cases must stay stamped. import { execFileSync } from 'node:child_process'; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -37,8 +37,10 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { let noMap: string; let esmMap: string; let esmNoMap: string; + let underSpace: string; + let underQuery: string; - function build(root: string, keepMap: boolean, esm = false): void { + function build(root: string, keepMap: boolean, esm = false, name?: string): void { mkdirSync(join(root, 'src'), { recursive: true }); mkdirSync(join(root, 'dist')); writeFileSync( @@ -49,7 +51,7 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { join(root, 'src', 'main.js'), "import { boom } from './a.js';\nexport function fail() {\n boom();\n}\n", ); - const bundle = join(root, 'dist', esm ? 'app.mjs' : 'app.js'); + const bundle = join(root, 'dist', name ?? (esm ? 'app.mjs' : 'app.js')); execFileSync( join(pkgRoot, 'node_modules', '.bin', 'esbuild'), [ @@ -70,7 +72,9 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { } beforeAll(() => { - dir = mkdtempSync(join(tmpdir(), 'bugsee-sm-rt-')); + // realpath: macOS tmpdir is a symlink; Node would map frames to a nonexistent `/private/private/...` path and the + // verifier would reject for 'file missing' rather than 'no stamp', which makes the map-present cases tautological. + dir = realpathSync(mkdtempSync(join(tmpdir(), 'bugsee-sm-rt-'))); withMap = join(dir, 'with-map'); noMap = join(dir, 'no-map'); mkdirSync(withMap); @@ -84,6 +88,14 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { mkdirSync(esmNoMap, { recursive: true }); build(esmMap, true, true); build(esmNoMap, false, true); + // ESM bundles UNDER the app root (the common case: appRoot = cwd). Core scrubs the frame to `./dist/...` WITHOUT + // decoding it, so a space in the file name stays `%20`, and an import query stays in the path. + underSpace = join(dir, 'under-space'); + underQuery = join(dir, 'under-query'); + mkdirSync(underSpace); + mkdirSync(underQuery); + build(underSpace, false, true, 'my chunk.mjs'); + build(underQuery, false, true); }); afterAll(() => rmSync(dir, { recursive: true, force: true })); @@ -92,12 +104,19 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { root: string, args: string[], sourceMaps: 'on' | 'off' | 'late', + bundleName?: string, + importQuery = '', ): Result { const out = execFileSync(bin, [...args, SCENARIO], { encoding: 'utf8', env: { ...process.env, - BUNDLE_PATH: join(root, 'dist', root.includes('esm') ? 'app.mjs' : 'app.js'), + BUNDLE_PATH: join( + root, + 'dist', + bundleName ?? (root.includes('esm') ? 'app.mjs' : 'app.js'), + ), + IMPORT_QUERY: importQuery, APP_ROOT: root, SOURCE_MAPS: sourceMaps, }, @@ -105,7 +124,7 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { return JSON.parse(out.trim().split('\n').at(-1) as string) as Result; } - const bundleFrames = (r: Result) => r.frames.filter((f) => f.at.includes('dist/app.')); + const bundleFrames = (r: Result) => r.frames.filter((f) => f.at.includes('dist/')); const originalFrames = (r: Result) => r.frames.filter((f) => f.at.includes('src/')); for (const target of runtimeTargets()) { @@ -122,6 +141,30 @@ describe('debug-ID stamping under runtime source-map support (#185)', () => { }, ); + it.skipIf(bin === undefined)( + `${name}: ESM bundle UNDER the app root with a space in its NAME, flag on, map deleted -> stays stamped`, + () => { + const r = run(bin as string, underSpace, ['--enable-source-maps'], 'on', 'my chunk.mjs'); + // Node: the frame is scrubbed to `./dist/my%20chunk.mjs` (relative, still encoded); Bun: the plain relative path. + expect(bundleFrames(r)[0]?.at).toContain( + name === 'node' ? './dist/my%20chunk.mjs' : './dist/my chunk.mjs', + ); + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + + it.skipIf(bin === undefined)( + `${name}: ESM bundle UNDER the app root imported with a ?v=1 query, flag on, map deleted -> stays stamped`, + () => { + const r = run(bin as string, underQuery, ['--enable-source-maps'], 'on', 'app.mjs', '?v=1'); + expect(bundleFrames(r)[0]?.at).toContain('./dist/app.mjs'); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + it.skipIf(bin === undefined)( `${name}: ESM bundle under a path with a space, flag on, map present -> mapped frames are not stamped`, () => { diff --git a/packages/node/src/debug-id-verifier.test.ts b/packages/node/src/debug-id-verifier.test.ts index ea1a665a7..0379ce4a9 100644 --- a/packages/node/src/debug-id-verifier.test.ts +++ b/packages/node/src/debug-id-verifier.test.ts @@ -1,8 +1,8 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; -import { parseV8Stack } from '@bugsee/core'; +import { parseV8Stack, setStackAppRoot } from '@bugsee/core'; import { afterEach, describe, expect, it } from 'vitest'; import { createStampedBundleVerifier, readStampedDebugId } from './debug-id-verifier'; @@ -29,7 +29,7 @@ describe('createStampedBundleVerifier', () => { dir = undefined; }); const fixture = (): string => { - dir = mkdtempSync(join(tmpdir(), 'bugsee-verify-')); + dir = realpathSync(mkdtempSync(join(tmpdir(), 'bugsee-verify-'))); mkdirSync(join(dir, 'dist')); mkdirSync(join(dir, 'src')); writeFileSync(join(dir, 'dist', 'app.js'), `console.log(1);\n//# debugId=${ID}\n`); @@ -182,6 +182,109 @@ describe('createStampedBundleVerifier', () => { }); }); + describe('ESM frames UNDER the app root (scrubbed to `./…`, still percent-encoded)', () => { + afterEach(() => setStackAppRoot(undefined)); + // The common case: launch() sets appRoot = cwd, so core rewrites `file:////dist/x.mjs` to `./dist/x.mjs` + // WITHOUT decoding. Every test here feeds the verifier the real output of parseV8Stack with that root set. + const frameFile = (root: string, rel: string, suffix = ''): string => { + setStackAppRoot(root); + const url = `${pathToFileURL(join(root, rel)).href}${suffix}`; + return parseV8Stack(`Error\n at (${url}:1:479)`)[0]?.file as string; + }; + const stamped = (root: string, rel: string): void => { + mkdirSync(join(root, rel, '..'), { recursive: true }); + writeFileSync(join(root, rel), `export {};\n//# debugId=${ID}\n`); + }; + + it('decodes a space in the file name', () => { + const root = fixture(); + stamped(root, 'dist/my chunk.mjs'); + const file = frameFile(root, 'dist/my chunk.mjs'); + expect(file).toBe('./dist/my%20chunk.mjs'); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + }); + + it('decodes braces / brackets / percent-encoded characters', () => { + const root = fixture(); + stamped(root, 'dist/[id]-{x}.mjs'); + const file = frameFile(root, 'dist/[id]-{x}.mjs'); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + }); + + it('strips an import query and a hash', () => { + const root = fixture(); + stamped(root, 'dist/a.mjs'); + for (const suffix of ['?v=1', '#h', '?v=1#h']) { + const file = frameFile(root, 'dist/a.mjs', suffix); + expect(file).toBe(`./dist/a.mjs${suffix}`); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + } + }); + + it('decodes AND strips together; rejects an unstamped file', () => { + const root = fixture(); + stamped(root, 'dist/my chunk.mjs'); + const file = frameFile(root, 'dist/my chunk.mjs', '?v=2'); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + writeFileSync(join(root, 'dist', 'plain.mjs'), 'export {};\n'); + expect( + createStampedBundleVerifier({ appRoot: root })( + frameFile(root, 'dist/plain.mjs', '?v=1'), + ID, + ), + ).toBe(false); + }); + + it('a relative path that is not a valid percent-encoding stays literal', () => { + const root = fixture(); + stamped(root, 'dist/100%.mjs'); + expect(createStampedBundleVerifier({ appRoot: root })('./dist/100%.mjs', ID)).toBe(true); + }); + }); + + it('after stripping a query, tries the literal stripped path (a file really named with a percent)', () => { + const root = fixture(); + writeFileSync(join(root, 'dist', 'a%20b.mjs'), `//# debugId=${ID}\n`); + const verify = createStampedBundleVerifier({ appRoot: root }); + // literal `…/a%20b.mjs?v=1` and decoded `…/a b.mjs` do not exist; only the stripped literal does + expect(verify(`${join(root, 'dist', 'a%20b.mjs')}?v=1`, ID)).toBe(true); + expect(verify('./dist/a%20b.mjs?v=1', ID)).toBe(true); + }); + + describe('NODE_OPTIONS token handling is delegated to core; verifier cache', () => { + it('caches a definitive miss for every no-such-file code, including EINVAL (the win32 `/C:/` literal)', () => { + for (const code of ['ENOENT', 'ENOTDIR', 'ENAMETOOLONG', 'EISDIR', 'EINVAL']) { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + throw Object.assign(new Error(code), { code }); + }, + }); + expect(verify('/x/a.js', ID)).toBe(false); + const first = reads; + expect(verify('/x/a.js', ID)).toBe(false); + expect(reads).toBe(first); + } + }); + + it('holds a realistic number of registrations without evicting (no re-reads at 1000 chunks)', () => { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + return `//# debugId=${ID}`; + }, + }); + for (let i = 0; i < 1000; i++) verify(`/x/c${i}.js`, ID); + const before = reads; + for (let i = 0; i < 1000; i++) verify(`/x/c${i}.js`, ID); + expect(reads).toBe(before); + }); + }); + describe('cache', () => { it('answers a repeated (file, id) with no further I/O, and caches rejections too', () => { let reads = 0; @@ -214,9 +317,9 @@ describe('createStampedBundleVerifier', () => { return `//# debugId=${ID}`; }, }); - for (let i = 0; i < 600; i++) expect(verify(`/x/f${i}.js`, ID)).toBe(true); + for (let i = 0; i < 5000; i++) expect(verify(`/x/f${i}.js`, ID)).toBe(true); const before = reads; - expect(verify('/x/f599.js', ID)).toBe(true); // recent: still cached + expect(verify('/x/f4999.js', ID)).toBe(true); // recent: still cached expect(reads).toBe(before); expect(verify('/x/f0.js', ID)).toBe(true); // evicted: re-read, same answer expect(reads).toBe(before + 1); diff --git a/packages/node/src/debug-id-verifier.ts b/packages/node/src/debug-id-verifier.ts index 4d304d8f0..962904c1f 100644 --- a/packages/node/src/debug-id-verifier.ts +++ b/packages/node/src/debug-id-verifier.ts @@ -14,7 +14,7 @@ const MARKER = '//# debugId='; const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const TAIL_BYTES = 16 * 1024; /** A registration's file does not change during a process, so answers are cached (bounded; emptied when full). */ -const CACHE_MAX = 256; +const CACHE_MAX = 4096; /** The LAST `//# debugId=` stamp in `content` when it is a UUID (the bundler plugin's `readDebugId` rule). */ export function readStampedDebugId(content: string): string | undefined { @@ -46,25 +46,32 @@ function readTail(path: string): string { /** * The filesystem paths a scrubbed frame `file` may denote, most literal first. * - * Core's scrubber strips `file://` by slicing WITHOUT URL-decoding, so an ESM frame arrives as `/…/my%20app/dist/a.mjs` - * (posix), `/C:/app/dist/a.mjs` (Windows) and may carry the import's `?v=1` / `#hash`. Application frames under the - * app root arrive as `./x`. The literal path is tried first (a file really named `a%20b`), then the decoded URL form. + * Core's scrubber strips `file://` by slicing WITHOUT URL-decoding, so an ESM frame arrives percent-encoded and may + * carry the import's `?v=1` / `#hash`: `/…/my%20app/dist/a.mjs` (posix), `/C:/app/dist/a.mjs` (Windows), and, for the + * common case of a file UNDER the app root, `./dist/my%20chunk.mjs?v=1`. The literal path is tried first (a file + * really named `a%20b`), then the decoded reading with the query/hash stripped, then the stripped literal. */ function candidatePaths(file: string, appRoot: string): string[] { if (file.startsWith('file://')) { return [fileURLToPath(file)]; } const candidates = [resolveFramePath(file, appRoot)]; - if (file.startsWith('/')) { - const bare = file.replace(/[?#].*$/, ''); - try { - candidates.push(fileURLToPath(`file://${bare}`)); - } catch { - // a literal `%` / `%2F` in a real directory name is not a valid file-URL reading; the literal path stands - } - if (bare !== file) { - candidates.push(bare); - } + const bare = file.replace(/[?#].*$/, ''); + let decoded: string | undefined; + try { + // An absolute posix/`/C:/` path goes through the file-URL reading (it also yields `C:\…` on a win32 host); a + // relative one is a plain percent-decode. + decoded = file.startsWith('/') + ? fileURLToPath(`file://${bare}`) + : resolveFramePath(decodeURIComponent(bare), appRoot); + } catch { + // a literal `%` / `%2F` in a real name is not a valid encoding; the literal path stands + } + if (decoded !== undefined) { + candidates.push(decoded); + } + if (bare !== file) { + candidates.push(resolveFramePath(bare, appRoot)); } return candidates; } From 4564eecf5cd8e28c7745b53c881fc9db26b2a0fe Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 19:17:52 +0500 Subject: [PATCH 6/7] fix(node,core): accept any verified candidate, dedupe candidates, =true flag form (#185) The verifier tries every distinct reading and accepts if any carries the stamp (an unrelated file at the literal reading no longer hides the genuine bundle), opens each path once, and treats invalid-argument paths as a definitive miss. The old-Node probe recognizes --enable-source-maps=true and strips double quotes only, like Node. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- packages/core/src/debug-id.test.ts | 13 ++++++- packages/core/src/debug-id.ts | 11 ++++-- packages/node/src/debug-id-verifier.test.ts | 43 +++++++++++++++++++-- packages/node/src/debug-id-verifier.ts | 18 +++++++-- 4 files changed, 74 insertions(+), 11 deletions(-) diff --git a/packages/core/src/debug-id.test.ts b/packages/core/src/debug-id.test.ts index 359415de4..6aaa4d15d 100644 --- a/packages/core/src/debug-id.test.ts +++ b/packages/core/src/debug-id.test.ts @@ -129,15 +129,24 @@ describe('runtimeMapsStacks', () => { ).toBe(false); }); - it('reads NODE_OPTIONS the way Node tokenizes it: any whitespace, optionally quoted', () => { + it('reads NODE_OPTIONS like Node: whitespace-separated tokens, DOUBLE quotes only (single quotes are not stripped)', () => { const opts = (NODE_OPTIONS: string) => runtimeMapsStacks({ env: { NODE_OPTIONS } }); expect(opts('--x\t--enable-source-maps')).toBe(true); expect(opts('--x --enable-source-maps')).toBe(true); expect(opts('"--enable-source-maps"')).toBe(true); - expect(opts("--x '--enable-source-maps'")).toBe(true); + expect(opts("--x '--enable-source-maps'")).toBe(false); expect(opts('"--enable-source-maps-extra"')).toBe(false); }); + it('recognizes the `=true` form of the flag, and not `=false`/`=0`, in execArgv and NODE_OPTIONS', () => { + expect(runtimeMapsStacks({ execArgv: ['--enable-source-maps=true'] })).toBe(true); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=true' } })).toBe(true); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '"--enable-source-maps=1"' } })).toBe(true); + expect(runtimeMapsStacks({ execArgv: ['--enable-source-maps=false'] })).toBe(false); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=0' } })).toBe(false); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=maybe' } })).toBe(false); + }); + it('never throws: a hostile process object answers false', () => { const hostile = { get sourceMapsEnabled(): never { diff --git a/packages/core/src/debug-id.ts b/packages/core/src/debug-id.ts index 408789b1a..ebd096b03 100644 --- a/packages/core/src/debug-id.ts +++ b/packages/core/src/debug-id.ts @@ -80,6 +80,11 @@ export function runtimeMapsStacks( } } +/** `--enable-source-maps`, or its `=true` / `=1` form; `=false` / `=0` / anything else is not on. */ +function isFlagOn(token: unknown): boolean { + return token === FLAG || token === `${FLAG}=true` || token === `${FLAG}=1`; +} + function probe(proc: unknown): boolean { if (typeof proc !== 'object' || proc === null) { return false; @@ -95,7 +100,7 @@ function probe(proc: unknown): boolean { // Older Node (< 18.19 / 20.7) maps stacks under the flag but has no `process.sourceMapsEnabled`: read the launch flags. // Wrongly true here is harmless (the verifier then checks each registration); wrongly false is the #185 bug. // A runtime `process.setSourceMapsEnabled(true)` on those versions cannot be observed (documented limit). - if (Array.isArray(execArgv) && execArgv.includes(FLAG)) { + if (Array.isArray(execArgv) && execArgv.some(isFlagOn)) { return true; } const options = env?.NODE_OPTIONS; @@ -103,8 +108,8 @@ function probe(proc: unknown): boolean { typeof options === 'string' && options .split(/\s+/) - .map((token) => token.replace(/^["']|["']$/g, '')) - .includes(FLAG) + .map((token) => token.replace(/^"|"$/g, '')) // Node strips double quotes only + .some(isFlagOn) ); } diff --git a/packages/node/src/debug-id-verifier.test.ts b/packages/node/src/debug-id-verifier.test.ts index 0379ce4a9..f182dde93 100644 --- a/packages/node/src/debug-id-verifier.test.ts +++ b/packages/node/src/debug-id-verifier.test.ts @@ -159,11 +159,11 @@ describe('createStampedBundleVerifier', () => { }); expect(verify('/x/a.js', ID)).toBe(false); expect(verify('/x/a.js', ID)).toBe(false); - expect(reads).toBe(4); // two readings per ask (literal + decoded), asked twice + expect(reads).toBe(2); // one distinct reading per ask, asked twice failing = false; expect(verify('/x/a.js', ID)).toBe(true); expect(verify('/x/a.js', ID)).toBe(true); - expect(reads).toBe(5); // the success is cached + expect(reads).toBe(3); // the success is cached }); it('an error without a code is transient too; a malformed URL is rejected uncached', () => { @@ -177,7 +177,7 @@ describe('createStampedBundleVerifier', () => { }); expect(verify('/x/a.js', ID)).toBe(false); expect(verify('/x/a.js', ID)).toBe(false); - expect(reads).toBe(4); + expect(reads).toBe(2); expect(verify('file://bad host/x', ID)).toBe(false); }); }); @@ -251,6 +251,43 @@ describe('createStampedBundleVerifier', () => { expect(verify('./dist/a%20b.mjs?v=1', ID)).toBe(true); }); + it('keeps trying later candidates when an UNRELATED file sits at the literal reading', () => { + const root = fixture(); + // the stamped bundle is `a b.mjs`; an unrelated, unstamped file is literally named `a%20b.mjs` + writeFileSync(join(root, 'dist', 'a b.mjs'), `export {};\n//# debugId=${ID}\n`); + writeFileSync(join(root, 'dist', 'a%20b.mjs'), 'export {};\n'); + // likewise an unrelated file literally named `q.mjs?v=1` next to the stamped `q.mjs` + writeFileSync(join(root, 'dist', 'q.mjs'), `export {};\n//# debugId=${ID}\n`); + writeFileSync(join(root, 'dist', 'q.mjs?v=1'), 'export {};\n'); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify('./dist/a%20b.mjs', ID)).toBe(true); + expect(verify('./dist/q.mjs?v=1', ID)).toBe(true); + // ...and a file that is genuinely not stamped under any reading is still rejected + expect(verify('./dist/plain-missing%20x.mjs', ID)).toBe(false); + }); + + it('opens each distinct reading once (deduped), and treats NUL / invalid-arg paths as a definitive miss', () => { + const opened: string[] = []; + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: (path) => { + reads++; + opened.push(path); + throw Object.assign(new Error('bad path'), { code: 'ERR_INVALID_ARG_VALUE' }); + }, + }); + expect(verify('/x/plain.js', ID)).toBe(false); + expect(opened).toEqual(['/x/plain.js']); // literal === decoded: opened once + const after = reads; + expect(verify('/x/plain.js', ID)).toBe(false); + expect(reads).toBe(after); // cached as definitive + expect(verify('./dist/a%00b.mjs', ID)).toBe(false); + const nul = reads; + expect(verify('./dist/a%00b.mjs', ID)).toBe(false); + expect(reads).toBe(nul); + }); + describe('NODE_OPTIONS token handling is delegated to core; verifier cache', () => { it('caches a definitive miss for every no-such-file code, including EINVAL (the win32 `/C:/` literal)', () => { for (const code of ['ENOENT', 'ENOTDIR', 'ENAMETOOLONG', 'EISDIR', 'EINVAL']) { diff --git a/packages/node/src/debug-id-verifier.ts b/packages/node/src/debug-id-verifier.ts index 962904c1f..742c42135 100644 --- a/packages/node/src/debug-id-verifier.ts +++ b/packages/node/src/debug-id-verifier.ts @@ -77,7 +77,14 @@ function candidatePaths(file: string, appRoot: string): string[] { } /** Errors that mean "there is no such file" (a stable answer), as opposed to a transient EMFILE / EACCES / EIO. */ -const NO_SUCH_FILE = new Set(['ENOENT', 'ENOTDIR', 'ENAMETOOLONG', 'EISDIR', 'EINVAL']); +const NO_SUCH_FILE = new Set([ + 'ENOENT', + 'ENOTDIR', + 'ENAMETOOLONG', + 'EISDIR', + 'EINVAL', + 'ERR_INVALID_ARG_VALUE', // a NUL byte (a decoded `%00`) in the path +]); /** * A {@link RegistrationVerifier}: true only when `file` (a scrubbed frame path: absolute, app-relative `./x`, a @@ -95,9 +102,14 @@ export function createStampedBundleVerifier( const check = (file: string, debugId: string): boolean | undefined => { const wanted = debugId.toLowerCase(); let transient = false; - for (const path of candidatePaths(file, options.appRoot ?? process.cwd())) { + // Every distinct reading is tried and ANY carrying the id accepts: a mapped original file never carries the + // stamp, so a wrong accept is impossible, while an unrelated file sitting at the literal reading (`a%20b.mjs` + // next to the stamped `a b.mjs`) must not hide the genuine one. + for (const path of new Set(candidatePaths(file, options.appRoot ?? process.cwd()))) { try { - return readStampedDebugId(read(path)) === wanted; + if (readStampedDebugId(read(path)) === wanted) { + return true; + } } catch (error) { // not openable under this reading; try the next const code = (error as { code?: unknown }).code; From c8c60f72428147da44d52cd802b68642c3f226f8 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 19:18:03 +0500 Subject: [PATCH 7/7] docs: NODE_OPTIONS tokenization note for the #185 probe Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/design/source-maps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index de85aba5e..3af7db687 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -220,7 +220,7 @@ percent-encoded (core strips `file://` without URL-decoding): `/…/my%20app/dis stripped, then the stripped literal. Answers are cached per (file, id), bounded to 4096 registrations (reports cost no file I/O after the first for any realistic build; a build with more stamped chunks than that re-reads). Old Node (18.0-18.18, 20.0-20.6) has no `process.sourceMapsEnabled`, so the probe falls back to `--enable-source-maps` in -`execArgv` / `NODE_OPTIONS` (tokenized on whitespace, quotes stripped); an explicit property always wins. A runtime +`execArgv` / `NODE_OPTIONS` (tokenized on whitespace, double quotes stripped as Node does; `=true`/`=1` forms count, `=false`/`=0` do not); an explicit property always wins. A runtime `process.setSourceMapsEnabled(true)` on those old versions cannot be observed. With no verifier installed the runtime is not probed at all. Not handled: a FIFO-backed path (`/dev/fd/N`) would block the synchronous open; a bundle rewritten in place during a deploy keeps its cached verdict until restart. Known limits: a path scrubbed to