Skip to content

Commit aa80347

Browse files
esetnikclaudesentry-junior[bot]BYK
authored
fix(cli): Recognize debug ID snippets from Oxc and React Native Metro (#2268)
## Summary Fixes #2267. `sentry sourcemap inject` and `sentry sourcemap upload` check whether a file already registers its debug ID by matching the registry write with `DEBUGID_REGISTRATION_RE`. Three forms that Sentry's own tools produce were not matched, so each got a second snippet on a new first line, with `;` prepended to the map's `mappings`: 1. **A template literal ID.** Oxc, the minifier in Vite 8, rewrites a bundler plugin's `e._sentryDebugIds[n]="<id>"` to ``e._sentryDebugIds[t]=`<id>` ``. 2. **A registry initialized with `||=`.** Oxc folds Turbopack's `(e._debugIds||(e._debugIds={}))[n]` into `(e._debugIds||={})[t]`. 3. **A registry that is a bare global.** The React Native Metro plugin emits `_sentryDebugIds[stack]="<id>"`, with no object in front. This one needs no minifier. Through `@sentry/vite-plugin`, the first shifts every uploaded source map one line ahead of the deployed chunk: the plugin uploads prepared copies, so the deployed files never get the extra line. Frames then resolve to the wrong function or fail with `js_invalid_sourcemap_location`. ## Changes One commit per form, all in `DEBUGID_REGISTRATION_RE`: - Accept backticks wherever a quote was accepted: around the ID, and around the registry name in the bracket form (``e[`_sentryDebugIds`]``). - Accept the inline registry initialization written as a logical assignment, `||=` or `??=`. - Accept the registry name as a bare identifier. It must not be the tail of a longer identifier, so `my_sentryDebugIds[t]="<id>"` still gets a snippet. Tests, in the existing tables in `inject.test.ts` (each runs for external and inline maps): - Preserved registrations: `templateLiterals` and `turbopackLogicalAssignment` as Oxc emits them, and `reactNativeMetro` as the Metro plugin emits it. - Near miss that must still be injected: `longerIdentifier`. - 3b36a4a, pushed by sentry-junior, pins `??=` and the backticked bracket form and adds three more near misses. ## Verification Project checks on the branch head (`db3441c`), run locally on macOS: - `pnpm run tsc`: passes. - `pnpm run lint` at the repo root (oxlint, oxfmt, ast-grep, workspace dependency check): passes. - `pnpm run test:e2e` in `packages/cli`: 206 passed, 1 failed, 3 skipped. The failure is `telemetry-exit`, a timing assertion (3.08 s against a 2 s limit) while the suite was running; it passes on its own on this branch and on `main`. - `inject.test.ts`: 72 passed. - Each new case fails when its part of the regex is reverted: `templateLiterals` and `turbopackLogicalAssignment` without the first two commits, `reactNativeMetro` without the third, and `longerIdentifier` if the identifier boundary is dropped. - `pnpm run test` in `packages/cli`: 13,170 passed, 28 failed, 61 skipped. None of the failures is in sourcemap code, and they are not caused by this change: the same 28, in the same six files, fail on unmodified `main` (`f8464f8`) on this machine: `debug-files/upload`, `build/car-extract.integration`, `build/zip-writer`, `delta-upgrade.mocked`, `install-script` and `time-range`. A wider matrix, run locally through `injectDirectory` on the branch head and not committed (150 cases): - **Snippet form x minifier, 120 cases.** Six snippet forms (bundler plugin, this CLI, legacy CLI, formatted bracket form, Turbopack, React Native Metro) through 20 minifier setups: unminified, terser (default, ES2022 with 3 passes and `unsafe`, single quotes, beautify, no mangle), swc (default, ES2022 with 2 passes, no compress), esbuild (default, `esnext`, `es2015`, syntax only) and Oxc via rolldown 1.2.19 (default, no mangle, no compress, `es2015`, `es2020`, `esnext`, whitespace kept). Each file must be left unchanged and register its ID once at runtime. - 114 are left unchanged. - The other 6 are the Metro snippet under Oxc with mangling on. Oxc renames the top-level `var _sentryDebugIds` to `e`, so the file no longer registers under the registry name and injecting a snippet is the correct result. With mangling off the Metro snippet is left unchanged. - On the first commit alone, the five non-Metro forms gave 96 of 100; the 4 failures were Turbopack's snippet under Oxc, fixed by the second commit. - Only Oxc changes the quoting or the initialization. terser, swc and esbuild leave both as written. - **File layout, 30 cases,** all left unchanged: 15 layouts each for the Oxc-minified bundler plugin snippet and the unminified Metro snippet. Debug ID comment before or after `sourceMappingURL`, no trailing newline, CRLF, a hashbang first, a `"use strict"` directive first, the snippet after other code, an uppercase ID, a 32-hex ID, the ID only in the map (`debug_id` or `debugId`), the ID only in the comment, a legacy `//@ sourceMappingURL`, and an inline map with and without the comment. Checked against the regex only, on the branch head: - uglify-js 3.19.3 and Bun 1.4.4 (`--minify`, `--minify-syntax`, `--minify-whitespace`) leave the bundler plugin, CLI, formatted, Turbopack and esbuild-plugin snippets recognisable. - Inputs it must reject: mismatched quotes, a registry read that is not a write, `||={a:1}`, and `&&=`. - Closure Compiler v20240317: `WHITESPACE_ONLY` and `SIMPLE` leave all six snippet forms recognisable. `ADVANCED` renames the `_sentryDebugIds` property (to `g`), so the bundle no longer registers under the registry name and injecting is correct. A real Metro bundle: `metro` 0.88.0 with `createSentryMetroSerializer` from `@sentry/react-native` 8.35.0, built with `--minify true` and `--minify false`. Both bundles carry the bare-global snippet and a `//# debugId=` comment. | CLI | Minified bundle | Unminified bundle | |---|---|---| | `sentry@0.45.0` | unchanged | unchanged | | `sentry@0.49.0` | snippet prepended | snippet prepended | | `main` (`f8464f8`), from source | snippet prepended | snippet prepended | | this branch, from source | unchanged | unchanged | Not tested: a full React Native app build (the bundle above has a plain JS entry file, with no `react-native` runtime). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <126780+BYK@users.noreply.github.com>
1 parent 0fb6f6b commit aa80347

2 files changed

Lines changed: 71 additions & 1 deletion

File tree

‎packages/cli/src/lib/sourcemap/debug-id.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,18 @@ const DEBUGID_REGISTRY = "(?:_sentryDebugIds|_debugIds)";
5959
* Indexed registry writes emitted by Sentry's bundler plugins, the legacy CLI
6060
* (`e._sentryDebugIds[n]="<id>"`), and Turbopack, which initializes the
6161
* registry inline: `(e._debugIds|| (e._debugIds={}))[n]="<id>"`.
62+
*
63+
* The registry may also be a bare global rather than a property: the React
64+
* Native Metro plugin emits `_sentryDebugIds[stack]="<id>"`. A longer
65+
* identifier that merely ends with the registry name does not count.
66+
*
67+
* Minifiers such as Oxc (Vite 8) rewrite these, so two more forms are
68+
* accepted: a string quoted with backticks (`"<id>"` becomes a template
69+
* literal), and the inline initialization written with a logical assignment,
70+
* `(e._debugIds||={})[n]` or `??=`.
6271
*/
6372
const DEBUGID_REGISTRATION_RE = new RegExp(
64-
`(?:\\.\\s*${DEBUGID_REGISTRY}|\\[\\s*["']${DEBUGID_REGISTRY}["']\\s*\\])(?:\\s*=\\s*\\{\\s*\\}\\s*\\)\\s*\\))?\\s*\\[\\s*[$\\w]+\\s*\\]\\s*=\\s*(["'])(${DEBUGID_PATTERN})\\1`,
73+
`(?:(?<![$\\w])${DEBUGID_REGISTRY}|\\[\\s*["'\`]${DEBUGID_REGISTRY}["'\`]\\s*\\])(?:\\s*=\\s*\\{\\s*\\}\\s*\\)\\s*\\)|\\s*(?:\\|\\||\\?\\?)=\\s*\\{\\s*\\}\\s*\\))?\\s*\\[\\s*[$\\w]+\\s*\\]\\s*=\\s*(["'\`])(${DEBUGID_PATTERN})\\1`,
6574
"g",
6675
);
6776

‎packages/cli/test/lib/sourcemap/inject.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,20 @@ describe.each(["external", "inline"] as const)(
638638
})();`,
639639
// Emitted by Next.js 16 with `turbopack.debugIds` (getsentry/toolkit#2189).
640640
turbopack: `;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="${debugId}")}catch(e){}}();`,
641+
// A bundler plugin's snippet after Oxc minification in Vite 8, which
642+
// rewrites its string literals to template literals
643+
// (getsentry/toolkit#2267).
644+
templateLiterals: `(function(){try{var e=typeof globalThis<\`u\`?globalThis:typeof window<\`u\`?window:typeof global<\`u\`?global:typeof self<\`u\`?self:{};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]=\`${debugId}\`,e._sentryDebugIdIdentifier=\`sentry-dbid-${debugId}\`)}catch{}})();`,
645+
// Turbopack's snippet after the same minification, which also folds
646+
// the inline registry initialization into a logical assignment.
647+
turbopackLogicalAssignment: `(function(){try{var e=typeof globalThis<\`u\`?globalThis:typeof global<\`u\`?global:typeof window<\`u\`?window:typeof self<\`u\`?self:{},t=new e.Error().stack;t&&((e._debugIds||={})[t]=\`${debugId}\`)}catch{}})();`,
648+
// Emitted by the React Native Metro plugin, which registers on a bare
649+
// global instead of a property of the global object.
650+
reactNativeMetro: `var _sentryDebugIds,_sentryDebugIdIdentifier;void 0===_sentryDebugIds&&(_sentryDebugIds={});try{var stack=(new Error).stack;stack&&(_sentryDebugIds[stack]="${debugId}",_sentryDebugIdIdentifier="sentry-dbid-${debugId}")}catch(e){}`,
651+
// No minifier tested emits these two, but the registration check
652+
// accepts them, so they pin those branches.
653+
nullishAssignment: `(function(){var e=globalThis,t=new e.Error().stack;t&&((e._debugIds??={})[t]=\`${debugId}\`)})();`,
654+
bracketTemplateRegistry: `(function(){var e=globalThis,t=new e.Error().stack;e[\`_sentryDebugIds\`]=e[\`_sentryDebugIds\`]||{};e[\`_sentryDebugIds\`][t]=\`${debugId}\`})();`,
641655
};
642656

643657
test.each(Object.keys(snippets))(
@@ -761,6 +775,53 @@ describe.each(["external", "inline"] as const)(
761775
);
762776
},
763777
);
778+
779+
// Near misses of the accepted forms that do not register the ID, so
780+
// injection must still happen.
781+
const nearMisses: Record<string, string> = {
782+
interpolatedTemplate: `var e=globalThis,t="s";e._sentryDebugIds=e._sentryDebugIds||{};e._sentryDebugIds[t]=\`\${t}${debugId}\`;`,
783+
andAssignment: `var e=globalThis,t="s";try{(e._debugIds&&={})[t]=\`${debugId}\`}catch{}`,
784+
comparison: `var e=globalThis,t="s";e._sentryDebugIds=e._sentryDebugIds||{};e._sentryDebugIds[t]==\`${debugId}\`;`,
785+
// A different identifier that only ends with the registry name.
786+
longerIdentifier: `var my_sentryDebugIds={},t="s";my_sentryDebugIds[t]="${debugId}";`,
787+
};
788+
789+
test.each(Object.keys(nearMisses))(
790+
"injects despite a %s near miss",
791+
async (format) => {
792+
const jsPath = join(dir, "main.js");
793+
const mapContent = JSON.stringify({
794+
version: 3,
795+
sources: ["main.ts"],
796+
names: [],
797+
mappings: "AAAA",
798+
debugId,
799+
});
800+
const mapUrl =
801+
kind === "inline"
802+
? `data:application/json;base64,${Buffer.from(mapContent).toString("base64")}`
803+
: "main.js.map";
804+
const js = `${nearMisses[format]}\n//# debugId=${debugId}\n//# sourceMappingURL=${mapUrl}\n`;
805+
writeFileSync(jsPath, js);
806+
if (kind === "external") {
807+
writeFileSync(`${jsPath}.map`, mapContent);
808+
}
809+
810+
expect((await injectDirectory(dir))[0]).toMatchObject({
811+
debugId,
812+
injected: true,
813+
});
814+
const sandbox: { _sentryDebugIds?: Record<string, string> } = {};
815+
runInNewContext(readFileSync(jsPath, "utf-8"), sandbox, {
816+
filename: "main.js",
817+
});
818+
expect(
819+
Object.values(sandbox._sentryDebugIds ?? {}).filter(
820+
(id) => id === debugId,
821+
),
822+
).toHaveLength(1);
823+
},
824+
);
764825
},
765826
);
766827

0 commit comments

Comments
 (0)