From 39cc4d4c3a6f528abd9f70b01b22df908506b20f Mon Sep 17 00:00:00 2001 From: Ethan Setnik Date: Sat, 14 Nov 2026 11:16:43 -0500 Subject: [PATCH] fix(cli): Reuse a debug ID that a bundle only registers at runtime A bundler plugin leaves its snippet in each output file, but adds the `//# debugId=` comment and the map's ID only to the copies it uploads. Given that output, `sourcemap inject` and `sourcemap upload` found no ID, minted one and prepended a second snippet. The bundle then registered two IDs, and the SDK reports the one registered last, which is the original and not the one the sourcemap was uploaded under. When a file has no comment and no map ID but registers exactly one ID at runtime, reuse it: write the comment and the map ID, and add no snippet. A file that registers several different IDs still gets its own, as before. Fixes #2269 Co-Authored-By: Claude Fable 5.2 --- packages/cli/src/lib/sourcemap/debug-id.ts | 73 ++++++++++++--- packages/cli/src/lib/sourcemap/inject.ts | 10 +- .../cli/test/lib/sourcemap/inject.test.ts | 92 +++++++++++++++++++ 3 files changed, 159 insertions(+), 16 deletions(-) diff --git a/packages/cli/src/lib/sourcemap/debug-id.ts b/packages/cli/src/lib/sourcemap/debug-id.ts index c2ec98824..2c19a7ae4 100644 --- a/packages/cli/src/lib/sourcemap/debug-id.ts +++ b/packages/cli/src/lib/sourcemap/debug-id.ts @@ -111,6 +111,33 @@ export function hasDebugIdRegistration(js: string, debugId: string): boolean { return false; } +/** + * Read the debug ID a runtime snippet already registers, for a file that + * carries it nowhere else. A bundler plugin's output is in that state: the + * snippet is in the bundle, while the `//# debugId=` comment and the map's ID + * are only added to the copies the plugin uploads. + * + * Reusing it keeps the bundle on one ID. Minting another would add a second + * snippet, and the SDK reports the ID registered last, which is the original + * one and not the one the sourcemap was uploaded under. + * + * @param js - JavaScript file content + * @returns The canonical ID, or `undefined` when the file registers none, or + * registers more than one and so does not identify a single bundle + * @internal + */ +export function readRegisteredDebugId(js: string): string | undefined { + const ids = new Set(); + for (const match of js.matchAll(DEBUGID_REGISTRATION_RE)) { + const id = normalizeDebugId(match[2]); + if (id) { + ids.add(id); + } + } + const [only] = ids; + return ids.size === 1 ? only : undefined; +} + /** * Read a pre-existing debug ID off a parsed sourcemap. * @@ -305,25 +332,32 @@ export async function injectDebugId( // separator can't occur in JS/JSON text, so the two inputs can't bleed // across the boundary. Collisions now require both files to be // byte-identical, in which case sharing an ID is correct. - const debugId = existingId ?? contentToDebugId(`${jsContent}\0${mapContent}`); + // + // A file with no ID of its own may still register one at runtime; that ID + // is reused, see {@link readRegisteredDebugId}. + const registeredId = + existingId || skipRuntimeCheck + ? undefined + : readRegisteredDebugId(jsContent); + const debugId = + existingId ?? + registeredId ?? + contentToDebugId(`${jsContent}\0${mapContent}`); // --- Mutate JS file --- - let newJs: string; - if (skipSnippet) { - // Metadata-only mode: just append the debugId comment, no IIFE snippet. - // Used by the CLI's own build where the debug ID is registered in source. - newJs = jsContent; - } else { - // Full mode: prepend the runtime IIFE snippet (for user-facing injection). - newJs = prependDebugIdSnippet(jsContent, getDebugIdSnippet(debugId)); - } + // No IIFE snippet in metadata-only mode (the CLI's own build registers the + // ID in source), nor when the bundle already registers this ID. + const addSnippet = !skipSnippet && !registeredId; + let newJs = addSnippet + ? prependDebugIdSnippet(jsContent, getDebugIdSnippet(debugId)) + : jsContent; if (!jsDebugId) { newJs += `\n${DEBUGID_COMMENT_PREFIX}${debugId}\n`; } // --- Mutate sourcemap --- mutateSourcemap(map, debugId, { - snippetLine: skipSnippet ? undefined : countHeaderLines(jsContent), + snippetLine: addSnippet ? countHeaderLines(jsContent) : undefined, }); // Write both files concurrently @@ -503,8 +537,16 @@ export async function injectInlineDebugId( // byte-identical inline map still get distinct debug IDs // (getsentry/sentry-cli#3350). `jsContent` already embeds the inline map, // so this is belt-and-suspenders, but keeps the two paths symmetric. + // + // As on the external path, an ID the bundle already registers is reused. + const registeredId = + existingId || isLikelyBinary(jsBytes) + ? undefined + : readRegisteredDebugId(jsContent); const debugId = - existingId ?? contentToDebugId(`${jsContent}\0${decoded.json}`); + existingId ?? + registeredId ?? + contentToDebugId(`${jsContent}\0${decoded.json}`); // Locate the LAST inline directive to rewrite. If it can't be found (the // discovery parser and this regex disagree on an edge case), abort WITHOUT @@ -521,9 +563,10 @@ export async function injectInlineDebugId( } // Mutate the decoded map (IIFE adds one top line — same offset as external). + // A reused registration adds no snippet, so no line either. const map = decoded.map as SourcemapJson; mutateSourcemap(map, debugId, { - snippetLine: countHeaderLines(jsContent), + snippetLine: registeredId ? undefined : countHeaderLines(jsContent), }); const newDataUrl = encodeInlineSourcemap(map, decoded.dataUrlPrefix); @@ -540,7 +583,9 @@ export async function injectInlineDebugId( newDataUrl + jsContent.slice(end); - let newJs = prependDebugIdSnippet(rewritten, getDebugIdSnippet(debugId)); + let newJs = registeredId + ? rewritten + : prependDebugIdSnippet(rewritten, getDebugIdSnippet(debugId)); if (!jsDebugId) { newJs += `\n${DEBUGID_COMMENT_PREFIX}${debugId}\n`; } diff --git a/packages/cli/src/lib/sourcemap/inject.ts b/packages/cli/src/lib/sourcemap/inject.ts index d513c4f98..99b204b8d 100644 --- a/packages/cli/src/lib/sourcemap/inject.ts +++ b/packages/cli/src/lib/sourcemap/inject.ts @@ -19,6 +19,7 @@ import { injectDebugId, injectInlineDebugId, readJsDebugId, + readRegisteredDebugId, readSourcemapDebugId, } from "./debug-id.js"; import { @@ -179,16 +180,21 @@ export async function injectDirectory( // Match the real run's ID precedence and runtime registration check. const jsBytes = await readFile(jsPath); const js = jsBytes.toString("utf-8"); + const binary = isLikelyBinary(jsBytes); const existing = readJsDebugId(js) ?? (await readMapDebugId(map)); + // An ID the bundle only registers at runtime is reused; the file still + // changes, since the comment and the map ID are written. + const registered = + existing || binary ? undefined : readRegisteredDebugId(js); results.push({ jsPath, map, mapPath, injected: !( existing && - (isLikelyBinary(jsBytes) || hasDebugIdRegistration(js, existing)) + (binary || hasDebugIdRegistration(js, existing)) ), - debugId: existing ?? "(pending)", + debugId: existing ?? registered ?? "(pending)", }); continue; } diff --git a/packages/cli/test/lib/sourcemap/inject.test.ts b/packages/cli/test/lib/sourcemap/inject.test.ts index 0d42a88a2..1e6429c43 100644 --- a/packages/cli/test/lib/sourcemap/inject.test.ts +++ b/packages/cli/test/lib/sourcemap/inject.test.ts @@ -683,6 +683,98 @@ describe.each(["external", "inline"] as const)( }, ); + // What a bundler plugin leaves in its output directory: the snippet, but + // neither the comment nor a map ID (getsentry/toolkit#2269). + const pluginSnippet = (id: string): string => + `!function(){try{var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="${id}",e._sentryDebugIdIdentifier="sentry-dbid-${id}");}catch(e){}}();`; + + /** Write `main.js` with no debug ID comment and a map with no ID. */ + function writeUnstampedBundle(body: string): { + jsPath: string; + js: string; + } { + const jsPath = join(dir, "main.js"); + const mapContent = JSON.stringify({ + version: 3, + sources: ["main.ts"], + names: [], + mappings: ";AAAA", + }); + const mapUrl = + kind === "inline" + ? `data:application/json;base64,${Buffer.from(mapContent).toString("base64")}` + : "main.js.map"; + const js = `${body}\n//# sourceMappingURL=${mapUrl}\n`; + writeFileSync(jsPath, js); + if (kind === "external") { + writeFileSync(`${jsPath}.map`, mapContent); + } + return { jsPath, js }; + } + + /** Read back the map that injection wrote, external or inline. */ + function readInjectedMap(jsPath: string): Record { + if (kind === "external") { + return JSON.parse(readFileSync(`${jsPath}.map`, "utf-8")); + } + const url = readFileSync(jsPath, "utf-8").match( + /\/\/# sourceMappingURL=(\S+)/, + )?.[1]; + return tryDecodeInlineSourcemap(url ?? "")?.map as Record< + string, + unknown + >; + } + + test("reuses an ID that is only registered at runtime", async () => { + const snippet = pluginSnippet(debugId); + const { jsPath, js } = writeUnstampedBundle(snippet); + + expect((await injectDirectory(dir, { dryRun: true }))[0]).toMatchObject({ + debugId, + injected: true, + }); + expect(readFileSync(jsPath, "utf-8")).toBe(js); + + expect((await injectDirectory(dir))[0]).toMatchObject({ + debugId, + injected: true, + }); + const after = readFileSync(jsPath, "utf-8"); + // No second snippet: the bundle still starts with its own. + expect(after.startsWith(snippet)).toBe(true); + expect(after).toContain(`//# debugId=${debugId}`); + expect(readInjectedMap(jsPath)).toMatchObject({ + debug_id: debugId, + debugId, + mappings: ";AAAA", + }); + const sandbox: { _sentryDebugIds?: Record } = {}; + runInNewContext(after, sandbox, { filename: "main.js" }); + expect(Object.values(sandbox._sentryDebugIds ?? {})).toEqual([debugId]); + + // A second run finds the comment and the registration, and does nothing. + expect((await injectDirectory(dir))[0]).toMatchObject({ + debugId, + injected: false, + }); + expect(readFileSync(jsPath, "utf-8")).toBe(after); + }); + + test("mints an ID when two different IDs are registered at runtime", async () => { + const otherId = "99999999-8888-5777-9666-555555555555"; + const { jsPath } = writeUnstampedBundle( + `${pluginSnippet(debugId)}\n${pluginSnippet(otherId)}`, + ); + + const [result] = await injectDirectory(dir); + expect(result?.injected).toBe(true); + expect([debugId, otherId]).not.toContain(result?.debugId); + // Two chunks concatenated into one file do not identify one bundle, so + // the file gets its own ID and snippet as before. + expect(readFileSync(jsPath, "utf-8").startsWith(";!function")).toBe(true); + }); + test.each(["comment", "debugId", "debug_id", "comment and map"])( "registers an ID from %s exactly once", async (source) => {