From 3d5c4cb12f1afa237d6d9d0f540a5ee786826abe Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:08:18 +0000 Subject: [PATCH 1/4] fix(cli): Strip sources paths inside maps with --strip-prefix sentry-cli v2 and v3 apply --strip-prefix and --strip-common-prefix to the `sources` paths inside each uploaded source map. v4 only stripped the uploaded file paths, so maps with sources relative to the build output (Wrangler's `../src/index.ts`) kept those paths in stack frames. `sourcemap upload` now strips the uploaded copy of each map the same way, leaving the files on disk unchanged. --no-rewrite uploads sources unchanged. Fixes #2576 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/content/docs/migrating-from-v3.md | 6 + .../skills/sentry-cli/references/sourcemap.md | 6 +- packages/cli/src/commands/sourcemap/upload.ts | 51 ++++- .../cli/src/lib/sourcemap/strip-sources.ts | 176 ++++++++++++++++++ .../test/commands/sourcemap/upload.test.ts | 99 ++++++++++ .../test/lib/sourcemap/strip-sources.test.ts | 148 +++++++++++++++ 6 files changed, 480 insertions(+), 6 deletions(-) create mode 100644 packages/cli/src/lib/sourcemap/strip-sources.ts create mode 100644 packages/cli/test/lib/sourcemap/strip-sources.test.ts diff --git a/apps/cli-docs/src/content/docs/migrating-from-v3.md b/apps/cli-docs/src/content/docs/migrating-from-v3.md index 1e7f8d046..bc383c60b 100644 --- a/apps/cli-docs/src/content/docs/migrating-from-v3.md +++ b/apps/cli-docs/src/content/docs/migrating-from-v3.md @@ -574,6 +574,12 @@ Two behavioral differences to be aware of: `--wait-for` (use `--wait=`), `--no-sourcemap-reference`, `--debug-id-reference`, `--bundle`, `--bundle-sourcemap`, `--strict`. `sourcemap inject` also drops `--release`. Run `sentry sourcemap upload --help` for the current set. +- **Strip flags also rename uploaded files:** as in v3, `--strip-prefix` and + `--strip-common-prefix` strip the `sources` paths inside each uploaded + sourcemap (the files on disk are left as they are), for example + `--strip-prefix ..` turns `../src/index.ts` into `src/index.ts`. In v4 they + also strip the prefix from the uploaded file paths. With `--no-rewrite`, + `sources` are uploaded unchanged. - **`--wait` is on by default in CI:** when a CI environment variable such as `CI` or `GITHUB_ACTIONS` is set, `sourcemap upload` waits up to five minutes for Sentry to process the upload and exits with an error if processing diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/sourcemap.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/sourcemap.md index e37003bff..677b85d39 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/sourcemap.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/sourcemap.md @@ -61,9 +61,9 @@ Upload sourcemaps to Sentry - `--ext - Comma-separated file extensions to process (default: .js,.cjs,.mjs)` - `--ignore - Comma-separated glob patterns to exclude (gitignore-style)` - `--ignore-file - Path to a file with gitignore-style patterns to exclude` -- `--strip-prefix - Strip a prefix from uploaded file paths (e.g. 'build/')` -- `--strip-common-prefix - Automatically strip the longest common path prefix from all files` -- `--no-rewrite - Upload files as-is without injecting debug IDs` +- `--strip-prefix - Strip a prefix from uploaded file paths and from the sources paths inside sourcemaps (e.g. 'build/')` +- `--strip-common-prefix - Automatically strip the longest common path prefix from all files, and each sourcemap's common absolute sources prefix` +- `--no-rewrite - Upload files as-is without injecting debug IDs or stripping sources paths` - `--allow-empty - Exit successfully when no JS + sourcemap pairs are found (default: error out to catch silent build misconfigurations)` - `--wait[=] - Wait for the server to fully process the uploaded files, up to the given seconds (default: 300, 0 = no limit; on in CI)` - `--no-wait - Exit once Sentry accepts the upload, even in CI` diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index 0eca695a9..48d6ade99 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -6,6 +6,7 @@ * env vars, config defaults) — no slash-separated arg parsing needed. */ +import { readFile } from "node:fs/promises"; import { relative, resolve } from "node:path"; import { dirname as posixDirname, @@ -42,6 +43,10 @@ import { readExistingDebugIds, resolveUploadTarget, } from "../../lib/sourcemap/inject.js"; +import { + type SourcesStrip, + stripSourcemapSources, +} from "../../lib/sourcemap/strip-sources.js"; import { sentry } from "../../lib/app-identity.js"; /** Result type for the upload command. */ @@ -232,6 +237,29 @@ function buildArtifactPair( ]; } +/** + * Strip a prefix from the `sources` inside every uploaded sourcemap, in the + * uploaded copy only (the map on disk is left as it is). Sets `content` on + * each `source_map` artifact whose sources changed. + */ +async function stripUploadedSources( + files: ArtifactFile[], + strip: SourcesStrip, +): Promise { + for (const file of files) { + if (file.type !== "source_map") { + continue; + } + const json = file.content + ? file.content.toString("utf-8") + : await readFile(file.path, "utf-8"); + const stripped = stripSourcemapSources(json, strip); + if (stripped !== undefined) { + file.content = Buffer.from(stripped); + } + } +} + export const uploadCommand = buildCommand({ docs: { brief: "Upload sourcemaps to Sentry", @@ -349,19 +377,24 @@ export const uploadCommand = buildCommand({ "strip-prefix": { kind: "parsed", parse: parseText, - brief: "Strip a prefix from uploaded file paths (e.g. 'build/')", + brief: + "Strip a prefix from uploaded file paths and from the sources " + + "paths inside sourcemaps (e.g. 'build/')", optional: true, }, "strip-common-prefix": { kind: "boolean", brief: - "Automatically strip the longest common path prefix from all files", + "Automatically strip the longest common path prefix from all " + + "files, and each sourcemap's common absolute sources prefix", optional: true, default: false, }, "no-rewrite": { kind: "boolean", - brief: "Upload files as-is without injecting debug IDs", + brief: + "Upload files as-is without injecting debug IDs or stripping " + + "sources paths", optional: true, default: false, }, @@ -535,6 +568,18 @@ export const uploadCommand = buildCommand({ }), ); + // As in sentry-cli v2 and v3, the strip flags also rewrite each map's `sources`, + // unless --no-rewrite asks for the files as they are. + if (!flags["no-rewrite"]) { + if (flags["strip-common-prefix"]) { + await stripUploadedSources(artifactFiles, { common: true }); + } else if (pathPrefixToStrip) { + await stripUploadedSources(artifactFiles, { + prefix: pathPrefixToStrip, + }); + } + } + await uploadSourcemaps({ org, project, diff --git a/packages/cli/src/lib/sourcemap/strip-sources.ts b/packages/cli/src/lib/sourcemap/strip-sources.ts new file mode 100644 index 000000000..9fc767cae --- /dev/null +++ b/packages/cli/src/lib/sourcemap/strip-sources.ts @@ -0,0 +1,176 @@ +/** + * Strip path prefixes from the `sources` of a sourcemap, the way sentry-cli + * v2's `sourcemaps upload --strip-prefix` / `--strip-common-prefix` did + * (rust-sourcemap's `RewriteOptions::strip_prefixes`). + */ + +import { logger } from "../logger.js"; + +const log = logger.withTag("sourcemap.strip-sources"); + +/** What to strip: one explicit prefix, or each map's common prefix. */ +export type SourcesStrip = { prefix: string } | { common: true }; + +/** The parts of a regular or index sourcemap that this module reads. */ +type SourcemapJson = { + sources?: unknown; + sourceRoot?: unknown; + sections?: unknown; +}; + +/** Split a path into components that keep their leading separator. */ +function splitPath(path: string): string[] { + const parts: string[] = []; + let last = 0; + for (let i = 0; i < path.length; i += 1) { + if (path[i] === "/" || path[i] === "\\") { + parts.push(path.slice(last, i)); + last = i; + } + } + if (last < path.length) { + parts.push(path.slice(last)); + } + return parts; +} + +/** Whether `path` is a POSIX or Windows drive absolute path. */ +function isAbsolutePath(path: string): boolean { + return path.startsWith("/") || /^[a-zA-Z]:[/\\]./.test(path); +} + +/** + * The longest common directory prefix of the absolute paths in `sources`, or + * `undefined` when there is none (or it is only `/`). Relative sources do not + * take part. + */ +function findCommonSourcesPrefix(sources: string[]): string | undefined { + const split = sources.filter(isAbsolutePath).map(splitPath); + if (split.length === 0) { + return; + } + split.sort((a, b) => a.length - b.length); + const shortest = split[0] ?? []; + let matched = shortest.length; + for (const parts of split) { + let n = 0; + while (n < matched && parts[n] === shortest[n]) { + n += 1; + } + matched = n; + } + const prefix = shortest.slice(0, matched).join(""); + return prefix && prefix !== "/" ? prefix : undefined; +} + +/** Remove `prefix` (with a trailing `/` added if missing) from `source`. */ +function stripPrefix(source: string, prefix: string): string { + const withSlash = prefix.endsWith("/") ? prefix : `${prefix}/`; + return source.startsWith(withSlash) ? source.slice(withSlash.length) : source; +} + +/** + * Prepend a `sourceRoot` to a source, unless the source is already absolute + * (`/…`) or a URL, as v2 did before stripping. + */ +function applySourceRoot(root: string, source: string): string { + if ( + source.startsWith("/") || + source.startsWith("http:") || + source.startsWith("https:") + ) { + return source; + } + return `${root.endsWith("/") ? root.slice(0, -1) : root}/${source}`; +} + +/** String entries of a map's `sources` array. */ +function stringSources(map: SourcemapJson): string[] { + return Array.isArray(map.sources) + ? map.sources.filter((s): s is string => typeof s === "string") + : []; +} + +/** The regular maps inside an index map's `sections`, or the map itself. */ +function regularMaps(map: SourcemapJson): SourcemapJson[] { + if (!Array.isArray(map.sections)) { + return [map]; + } + return map.sections.flatMap((section: unknown) => { + const inner = (section as { map?: unknown } | null)?.map; + return inner && typeof inner === "object" ? regularMaps(inner) : []; + }); +} + +/** + * Fold a map's `sourceRoot` into its `sources` and drop `sourceRoot`, so the + * strip applies to the full source paths. Returns true when the map changed. + */ +function foldSourceRoot(map: SourcemapJson): boolean { + const root = map.sourceRoot; + if (typeof root !== "string" || root === "" || !Array.isArray(map.sources)) { + return false; + } + map.sources = map.sources.map((s: unknown) => + typeof s === "string" ? applySourceRoot(root, s) : s, + ); + delete map.sourceRoot; + return true; +} + +/** + * Strip a prefix from the `sources` paths inside a sourcemap. + * + * Matches sentry-cli v2: a source that starts with the prefix plus `/` loses + * it, others stay as they are. A non-empty `sourceRoot` is folded into + * `sources` first. With `common`, the prefix is the common directory of the + * map's absolute sources; for an index map, of all its sections' sources. + * + * @param json - Sourcemap JSON text + * @param strip - The prefix to strip, or `{ common: true }` + * @returns The rewritten JSON, or `undefined` when nothing changed or the + * text is not a JSON object + */ +export function stripSourcemapSources( + json: string, + strip: SourcesStrip, +): string | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(json); + } catch (error) { + log.debug("Not stripping sources of a sourcemap that is not JSON", error); + return; + } + if (!parsed || typeof parsed !== "object") { + return; + } + const map = parsed as SourcemapJson; + const maps = regularMaps(map); + let prefix: string | undefined; + let changed = false; + if ("prefix" in strip) { + prefix = strip.prefix; + } else if (Array.isArray(map.sections)) { + // v2 flattened index maps first, so the common prefix spans every + // section and is computed after each section's sourceRoot is applied. + changed = maps.map(foldSourceRoot).some(Boolean); + prefix = findCommonSourcesPrefix(maps.flatMap(stringSources)); + } else { + // For a regular map, v2 computed the common prefix before applying + // sourceRoot. + prefix = findCommonSourcesPrefix(stringSources(map)); + } + for (const m of maps) { + changed = foldSourceRoot(m) || changed; + const sources = m.sources; + if (prefix && Array.isArray(sources)) { + const p = prefix; + m.sources = sources.map((s: unknown) => + typeof s === "string" ? stripPrefix(s, p) : s, + ); + changed ||= (m.sources as unknown[]).some((s, i) => s !== sources[i]); + } + } + return changed ? JSON.stringify(map) : undefined; +} diff --git a/packages/cli/test/commands/sourcemap/upload.test.ts b/packages/cli/test/commands/sourcemap/upload.test.ts index 0908bb651..deaae2a02 100644 --- a/packages/cli/test/commands/sourcemap/upload.test.ts +++ b/packages/cli/test/commands/sourcemap/upload.test.ts @@ -945,6 +945,105 @@ describe("sourcemap upload command — --allow-empty behavior", () => { } }); + /** Sources of the uploaded map, read the way the artifact bundle reads it. */ + async function uploadedSources( + files: sourcemapsApi.ArtifactFile[] | undefined, + ): Promise { + const mapFile = files?.find((f) => f.type === "source_map"); + if (!mapFile) { + throw new Error("no source_map artifact uploaded"); + } + const json = mapFile.content ?? (await readFile(mapFile.path)); + return JSON.parse(json.toString("utf-8")).sources; + } + + test("--strip-prefix: strips sources inside the uploaded map (Wrangler ../src)", async () => { + const mapPath = join(dir, "index.js.map"); + await writeFile(join(dir, "index.js"), "console.log(1)\n"); + await writeFile( + mapPath, + JSON.stringify({ + version: 3, + sources: ["../src/index.ts", "../node_modules/hono/dist/index.js"], + names: [], + mappings: "AAAA", + }), + ); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + await func.call(makeContext(), { "strip-prefix": ".." }, dir); + const files = uploadSpy.mock.calls[0]?.[0]?.files; + expect(await uploadedSources(files)).toEqual([ + "src/index.ts", + "node_modules/hono/dist/index.js", + ]); + // Only the uploaded copy changes, as in sentry-cli v2. + const onDisk = JSON.parse(await readFile(mapPath, "utf-8")); + expect(onDisk.sources).toEqual([ + "../src/index.ts", + "../node_modules/hono/dist/index.js", + ]); + } finally { + uploadSpy.mockRestore(); + } + }); + + test("--strip-common-prefix: strips the common absolute sources prefix of an inline map", async () => { + const map = { + version: 3, + sources: ["/home/ci/app/src/a.ts", "/home/ci/app/src/lib/b.ts"], + names: [], + mappings: "AAAA", + }; + const dataUrl = `data:application/json;base64,${Buffer.from(JSON.stringify(map)).toString("base64")}`; + await writeFile( + join(dir, "inline.js"), + `console.log(1)\n//# sourceMappingURL=${dataUrl}\n`, + ); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + await func.call(makeContext(), { "strip-common-prefix": true }, dir); + const files = uploadSpy.mock.calls[0]?.[0]?.files; + expect(await uploadedSources(files)).toEqual(["a.ts", "lib/b.ts"]); + } finally { + uploadSpy.mockRestore(); + } + }); + + test("--strip-prefix + --no-rewrite: uploads sources unchanged", async () => { + await writeFile(join(dir, "index.js"), "console.log(1)\n"); + await writeFile( + join(dir, "index.js.map"), + JSON.stringify({ + version: 3, + sources: ["../src/index.ts"], + names: [], + mappings: "AAAA", + }), + ); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + await func.call( + makeContext(), + { "strip-prefix": "..", "no-rewrite": true }, + dir, + ); + const files = uploadSpy.mock.calls[0]?.[0]?.files; + expect(await uploadedSources(files)).toEqual(["../src/index.ts"]); + } finally { + uploadSpy.mockRestore(); + } + }); + test("--strip-prefix + --strip-common-prefix: mutually exclusive", async () => { await writeFile(join(dir, "app.js"), "console.log(1)\n"); await writeFile( diff --git a/packages/cli/test/lib/sourcemap/strip-sources.test.ts b/packages/cli/test/lib/sourcemap/strip-sources.test.ts new file mode 100644 index 000000000..f1df26f83 --- /dev/null +++ b/packages/cli/test/lib/sourcemap/strip-sources.test.ts @@ -0,0 +1,148 @@ +/** + * Tests for stripping prefixes from sourcemap `sources`, matching sentry-cli + * v2's `--strip-prefix` / `--strip-common-prefix` (rust-sourcemap's + * `strip_prefixes` and `find_common_prefix`). + */ + +import { describe, expect, test } from "vitest"; +import { + type SourcesStrip, + stripSourcemapSources, +} from "../../../src/lib/sourcemap/strip-sources.js"; + +/** Strip `map` and return the parsed result, or `undefined` if unchanged. */ +function strip( + map: object, + how: SourcesStrip, +): { sources?: unknown } | undefined { + const out = stripSourcemapSources(JSON.stringify(map), how); + return out === undefined ? undefined : JSON.parse(out); +} + +describe("stripSourcemapSources with a prefix", () => { + test("strips a Wrangler-style ../ prefix", () => { + const map = { + version: 3, + sources: ["../src/index.ts", "../node_modules/hono/dist/index.js"], + mappings: "AAAA", + }; + expect(strip(map, { prefix: ".." })?.sources).toEqual([ + "src/index.ts", + "node_modules/hono/dist/index.js", + ]); + }); + + test("strips only at a directory boundary", () => { + const map = { version: 3, sources: ["build/a.js", "builder/b.js"] }; + expect(strip(map, { prefix: "build" })?.sources).toEqual([ + "a.js", + "builder/b.js", + ]); + }); + + test("leaves sources that do not start with the prefix", () => { + const map = { version: 3, sources: ["src/a.ts", null] }; + expect(strip(map, { prefix: "dist/../" })).toBeUndefined(); + }); + + test("folds sourceRoot into sources before stripping", () => { + const map = { + version: 3, + sourceRoot: "/app/", + sources: ["src/a.ts", "/abs/b.ts", "https://example.com/c.js"], + }; + const out = strip(map, { prefix: "/app" }); + expect(out?.sources).toEqual([ + "src/a.ts", + "/abs/b.ts", + "https://example.com/c.js", + ]); + expect(out).not.toHaveProperty("sourceRoot"); + }); + + test("strips sources in every index map section", () => { + const map = { + version: 3, + sections: [ + { offset: { line: 0, column: 0 }, map: { sources: ["../src/a.ts"] } }, + { offset: { line: 9, column: 0 }, map: { sources: ["../src/b.ts"] } }, + ], + }; + const out = strip(map, { prefix: "../" }) as { + sections: { map: { sources: string[] } }[]; + }; + expect(out.sections.map((s) => s.map.sources)).toEqual([ + ["src/a.ts"], + ["src/b.ts"], + ]); + }); + + test("returns undefined for text that is not JSON", () => { + expect(stripSourcemapSources("not json", { prefix: "a" })).toBeUndefined(); + }); +}); + +describe("stripSourcemapSources with common: true", () => { + test("strips the common directory of absolute sources", () => { + const map = { + version: 3, + sources: ["/home/ci/app/src/a.ts", "/home/ci/app/src/b/c.ts", "rel.ts"], + }; + expect(strip(map, { common: true })?.sources).toEqual([ + "a.ts", + "b/c.ts", + "rel.ts", + ]); + }); + + test("stops at a directory boundary", () => { + const map = { version: 3, sources: ["/app/bc.ts", "/app/bd.ts"] }; + expect(strip(map, { common: true })?.sources).toEqual(["bc.ts", "bd.ts"]); + }); + + test("handles Windows drive paths", () => { + const map = { version: 3, sources: ["C:/work/app/a.ts", "C:/work/b.ts"] }; + expect(strip(map, { common: true })?.sources).toEqual(["app/a.ts", "b.ts"]); + }); + + test("ignores relative sources and a bare / prefix", () => { + expect( + strip( + { version: 3, sources: ["../src/a.ts", "../src/b.ts"] }, + { + common: true, + }, + ), + ).toBeUndefined(); + expect( + strip({ version: 3, sources: ["/a.ts", "/b.ts"] }, { common: true }), + ).toBeUndefined(); + }); + + test("computes a regular map's prefix before applying sourceRoot", () => { + const map = { version: 3, sourceRoot: "/app", sources: ["a.ts", "b.ts"] }; + const out = strip(map, { common: true }); + expect(out?.sources).toEqual(["/app/a.ts", "/app/b.ts"]); + expect(out).not.toHaveProperty("sourceRoot"); + }); + + test("computes one prefix across all index map sections", () => { + const map = { + version: 3, + sections: [ + { offset: { line: 0, column: 0 }, map: { sources: ["/app/src/a.ts"] } }, + { + offset: { line: 9, column: 0 }, + map: { sourceRoot: "/app/lib", sources: ["b.ts"] }, + }, + ], + }; + const out = strip(map, { common: true }) as { + sections: { map: { sources: string[] } }[]; + }; + expect(out.sections.map((s) => s.map.sources)).toEqual([ + ["src/a.ts"], + ["lib/b.ts"], + ]); + }); +}); From 518525cb0c2b24f10e79196d35a7d1ab99809266 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:18:26 +0000 Subject: [PATCH 2/4] docs(cli): Note sentry-cli's common-prefix rule for one absolute source --- packages/cli/src/lib/sourcemap/strip-sources.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/cli/src/lib/sourcemap/strip-sources.ts b/packages/cli/src/lib/sourcemap/strip-sources.ts index 9fc767cae..69f61249c 100644 --- a/packages/cli/src/lib/sourcemap/strip-sources.ts +++ b/packages/cli/src/lib/sourcemap/strip-sources.ts @@ -40,9 +40,14 @@ function isAbsolutePath(path: string): boolean { } /** - * The longest common directory prefix of the absolute paths in `sources`, or - * `undefined` when there is none (or it is only `/`). Relative sources do not - * take part. + * The longest common prefix of the absolute paths in `sources`, compared by + * path component, as rust-sourcemap's `find_common_prefix` computes it. + * Returns `undefined` when there is none (or it is only `/`). Relative + * sources do not take part. + * + * With only one absolute source the prefix is that whole path, file name + * included, so the strip (which needs the prefix plus `/`) leaves it alone. + * sentry-cli behaves the same way. */ function findCommonSourcesPrefix(sources: string[]): string | undefined { const split = sources.filter(isAbsolutePath).map(splitPath); @@ -123,8 +128,10 @@ function foldSourceRoot(map: SourcemapJson): boolean { * * Matches sentry-cli v2: a source that starts with the prefix plus `/` loses * it, others stay as they are. A non-empty `sourceRoot` is folded into - * `sources` first. With `common`, the prefix is the common directory of the - * map's absolute sources; for an index map, of all its sections' sources. + * `sources` first. With `common`, the prefix is the common prefix of the + * map's absolute sources (see {@link findCommonSourcesPrefix}); for an index + * map, of all its sections' sources. When only one absolute source takes + * part, nothing is stripped. * * @param json - Sourcemap JSON text * @param strip - The prefix to strip, or `{ common: true }` From e810493bf85fc099f36650f8ac8798d6e2cd3000 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:59:06 +0000 Subject: [PATCH 3/4] fix(cli): Strip sources under --no-rewrite, for one source, and with backslashes Three deliberate departures from sentry-cli for the strip flags: - --strip-prefix and --strip-common-prefix also rewrite `sources` with --no-rewrite. Only the uploaded copy changes; sentry-cli rejected the combination. - --strip-common-prefix drops each source's file name before computing the common prefix, so a map with one absolute source gets its directory stripped instead of being left alone. - Backslashes in `sources` become `/` before stripping, as inject already does, so Windows paths like C:\work\app\a.ts can be stripped. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/content/docs/migrating-from-v3.md | 9 ++- .../skills/sentry-cli/references/sourcemap.md | 4 +- packages/cli/src/commands/sourcemap/upload.ts | 24 +++--- .../cli/src/lib/sourcemap/strip-sources.ts | 76 ++++++++++--------- .../test/commands/sourcemap/upload.test.ts | 15 +++- .../test/lib/sourcemap/strip-sources.test.ts | 25 +++++- 6 files changed, 92 insertions(+), 61 deletions(-) diff --git a/apps/cli-docs/src/content/docs/migrating-from-v3.md b/apps/cli-docs/src/content/docs/migrating-from-v3.md index bc383c60b..6c35b7ce2 100644 --- a/apps/cli-docs/src/content/docs/migrating-from-v3.md +++ b/apps/cli-docs/src/content/docs/migrating-from-v3.md @@ -578,8 +578,13 @@ Two behavioral differences to be aware of: `--strip-common-prefix` strip the `sources` paths inside each uploaded sourcemap (the files on disk are left as they are), for example `--strip-prefix ..` turns `../src/index.ts` into `src/index.ts`. In v4 they - also strip the prefix from the uploaded file paths. With `--no-rewrite`, - `sources` are uploaded unchanged. + also strip the prefix from the uploaded file paths, and a few details differ: + - they also work with `--no-rewrite`, which v3 rejected; + - backslashes in `sources` become `/` before stripping, so + `C:\work\app\a.ts` can be stripped; + - `--strip-common-prefix` stops at each source's directory, so a map with a + single absolute source is stripped to its file name, where v3 left it + unchanged. - **`--wait` is on by default in CI:** when a CI environment variable such as `CI` or `GITHUB_ACTIONS` is set, `sourcemap upload` waits up to five minutes for Sentry to process the upload and exits with an error if processing diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/sourcemap.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/sourcemap.md index 677b85d39..2793e83d1 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/sourcemap.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/sourcemap.md @@ -62,8 +62,8 @@ Upload sourcemaps to Sentry - `--ignore - Comma-separated glob patterns to exclude (gitignore-style)` - `--ignore-file - Path to a file with gitignore-style patterns to exclude` - `--strip-prefix - Strip a prefix from uploaded file paths and from the sources paths inside sourcemaps (e.g. 'build/')` -- `--strip-common-prefix - Automatically strip the longest common path prefix from all files, and each sourcemap's common absolute sources prefix` -- `--no-rewrite - Upload files as-is without injecting debug IDs or stripping sources paths` +- `--strip-common-prefix - Automatically strip the longest common path prefix from all files, and each sourcemap's common sources directory` +- `--no-rewrite - Upload files as-is without injecting debug IDs` - `--allow-empty - Exit successfully when no JS + sourcemap pairs are found (default: error out to catch silent build misconfigurations)` - `--wait[=] - Wait for the server to fully process the uploaded files, up to the given seconds (default: 300, 0 = no limit; on in CI)` - `--no-wait - Exit once Sentry accepts the upload, even in CI` diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index 48d6ade99..62094e074 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -386,15 +386,13 @@ export const uploadCommand = buildCommand({ kind: "boolean", brief: "Automatically strip the longest common path prefix from all " + - "files, and each sourcemap's common absolute sources prefix", + "files, and each sourcemap's common sources directory", optional: true, default: false, }, "no-rewrite": { kind: "boolean", - brief: - "Upload files as-is without injecting debug IDs or stripping " + - "sources paths", + brief: "Upload files as-is without injecting debug IDs", optional: true, default: false, }, @@ -568,16 +566,14 @@ export const uploadCommand = buildCommand({ }), ); - // As in sentry-cli v2 and v3, the strip flags also rewrite each map's `sources`, - // unless --no-rewrite asks for the files as they are. - if (!flags["no-rewrite"]) { - if (flags["strip-common-prefix"]) { - await stripUploadedSources(artifactFiles, { common: true }); - } else if (pathPrefixToStrip) { - await stripUploadedSources(artifactFiles, { - prefix: pathPrefixToStrip, - }); - } + // As in sentry-cli, the strip flags also rewrite each map's `sources`. + // Only the uploaded copy changes, so this applies with --no-rewrite too. + if (flags["strip-common-prefix"]) { + await stripUploadedSources(artifactFiles, { common: true }); + } else if (pathPrefixToStrip) { + await stripUploadedSources(artifactFiles, { + prefix: pathPrefixToStrip, + }); } await uploadSourcemaps({ diff --git a/packages/cli/src/lib/sourcemap/strip-sources.ts b/packages/cli/src/lib/sourcemap/strip-sources.ts index 69f61249c..ac743ac1a 100644 --- a/packages/cli/src/lib/sourcemap/strip-sources.ts +++ b/packages/cli/src/lib/sourcemap/strip-sources.ts @@ -1,7 +1,9 @@ /** - * Strip path prefixes from the `sources` of a sourcemap, the way sentry-cli - * v2's `sourcemaps upload --strip-prefix` / `--strip-common-prefix` did - * (rust-sourcemap's `RewriteOptions::strip_prefixes`). + * Strip path prefixes from the `sources` of a sourcemap, the way sentry-cli's + * `sourcemaps upload --strip-prefix` / `--strip-common-prefix` did + * (rust-sourcemap's `RewriteOptions::strip_prefixes`), with two departures: + * backslashes in `sources` become `/` first, and the common prefix stops at + * each source's directory. */ import { logger } from "../logger.js"; @@ -18,39 +20,24 @@ type SourcemapJson = { sections?: unknown; }; -/** Split a path into components that keep their leading separator. */ -function splitPath(path: string): string[] { - const parts: string[] = []; - let last = 0; - for (let i = 0; i < path.length; i += 1) { - if (path[i] === "/" || path[i] === "\\") { - parts.push(path.slice(last, i)); - last = i; - } - } - if (last < path.length) { - parts.push(path.slice(last)); - } - return parts; -} - /** Whether `path` is a POSIX or Windows drive absolute path. */ function isAbsolutePath(path: string): boolean { - return path.startsWith("/") || /^[a-zA-Z]:[/\\]./.test(path); + return path.startsWith("/") || /^[a-zA-Z]:\/./.test(path); } /** - * The longest common prefix of the absolute paths in `sources`, compared by - * path component, as rust-sourcemap's `find_common_prefix` computes it. - * Returns `undefined` when there is none (or it is only `/`). Relative - * sources do not take part. + * The longest common directory of the absolute paths in `sources`, compared + * by path component. Returns `undefined` when there is none (or it is only + * `/`). Relative sources do not take part. * - * With only one absolute source the prefix is that whole path, file name - * included, so the strip (which needs the prefix plus `/`) leaves it alone. - * sentry-cli behaves the same way. + * Unlike rust-sourcemap's `find_common_prefix`, which sentry-cli used, each + * path's file name is dropped first, so a map with one absolute source has + * its directory stripped instead of being left alone. */ function findCommonSourcesPrefix(sources: string[]): string | undefined { - const split = sources.filter(isAbsolutePath).map(splitPath); + const split = sources + .filter(isAbsolutePath) + .map((source) => source.split("/").slice(0, -1)); if (split.length === 0) { return; } @@ -64,7 +51,7 @@ function findCommonSourcesPrefix(sources: string[]): string | undefined { } matched = n; } - const prefix = shortest.slice(0, matched).join(""); + const prefix = shortest.slice(0, matched).join("/"); return prefix && prefix !== "/" ? prefix : undefined; } @@ -107,6 +94,21 @@ function regularMaps(map: SourcemapJson): SourcemapJson[] { }); } +/** + * Turn backslashes in a map's `sources` into `/`, as inject does when it + * rewrites a map. Returns true when the map changed. + */ +function normalizeSeparators(map: SourcemapJson): boolean { + const sources = map.sources; + if (!Array.isArray(sources)) { + return false; + } + map.sources = sources.map((s: unknown) => + typeof s === "string" ? s.replaceAll("\\", "/") : s, + ); + return (map.sources as unknown[]).some((s, i) => s !== sources[i]); +} + /** * Fold a map's `sourceRoot` into its `sources` and drop `sourceRoot`, so the * strip applies to the full source paths. Returns true when the map changed. @@ -126,12 +128,12 @@ function foldSourceRoot(map: SourcemapJson): boolean { /** * Strip a prefix from the `sources` paths inside a sourcemap. * - * Matches sentry-cli v2: a source that starts with the prefix plus `/` loses - * it, others stay as they are. A non-empty `sourceRoot` is folded into - * `sources` first. With `common`, the prefix is the common prefix of the - * map's absolute sources (see {@link findCommonSourcesPrefix}); for an index - * map, of all its sections' sources. When only one absolute source takes - * part, nothing is stripped. + * As in sentry-cli, a source that starts with the prefix plus `/` loses it, + * others stay as they are, and a non-empty `sourceRoot` is folded into + * `sources` first. Backslashes in `sources` become `/` before that. With + * `common`, the prefix is the common directory of the map's absolute sources + * (see {@link findCommonSourcesPrefix}); for an index map, of all its + * sections' sources. * * @param json - Sourcemap JSON text * @param strip - The prefix to strip, or `{ common: true }` @@ -155,13 +157,13 @@ export function stripSourcemapSources( const map = parsed as SourcemapJson; const maps = regularMaps(map); let prefix: string | undefined; - let changed = false; + let changed = maps.map(normalizeSeparators).some(Boolean); if ("prefix" in strip) { prefix = strip.prefix; } else if (Array.isArray(map.sections)) { // v2 flattened index maps first, so the common prefix spans every // section and is computed after each section's sourceRoot is applied. - changed = maps.map(foldSourceRoot).some(Boolean); + changed = maps.map(foldSourceRoot).some(Boolean) || changed; prefix = findCommonSourcesPrefix(maps.flatMap(stringSources)); } else { // For a regular map, v2 computed the common prefix before applying diff --git a/packages/cli/test/commands/sourcemap/upload.test.ts b/packages/cli/test/commands/sourcemap/upload.test.ts index deaae2a02..3be523fb2 100644 --- a/packages/cli/test/commands/sourcemap/upload.test.ts +++ b/packages/cli/test/commands/sourcemap/upload.test.ts @@ -1016,10 +1016,12 @@ describe("sourcemap upload command — --allow-empty behavior", () => { } }); - test("--strip-prefix + --no-rewrite: uploads sources unchanged", async () => { - await writeFile(join(dir, "index.js"), "console.log(1)\n"); + test("--strip-prefix + --no-rewrite: strips sources in the uploaded copy only", async () => { + const jsPath = join(dir, "index.js"); + const mapPath = join(dir, "index.js.map"); + await writeFile(jsPath, "console.log(1)\n"); await writeFile( - join(dir, "index.js.map"), + mapPath, JSON.stringify({ version: 3, sources: ["../src/index.ts"], @@ -1038,7 +1040,12 @@ describe("sourcemap upload command — --allow-empty behavior", () => { dir, ); const files = uploadSpy.mock.calls[0]?.[0]?.files; - expect(await uploadedSources(files)).toEqual(["../src/index.ts"]); + expect(await uploadedSources(files)).toEqual(["src/index.ts"]); + // --no-rewrite still leaves both files on disk untouched. + expect(await readFile(jsPath, "utf-8")).toBe("console.log(1)\n"); + expect(JSON.parse(await readFile(mapPath, "utf-8")).sources).toEqual([ + "../src/index.ts", + ]); } finally { uploadSpy.mockRestore(); } diff --git a/packages/cli/test/lib/sourcemap/strip-sources.test.ts b/packages/cli/test/lib/sourcemap/strip-sources.test.ts index f1df26f83..f00287b87 100644 --- a/packages/cli/test/lib/sourcemap/strip-sources.test.ts +++ b/packages/cli/test/lib/sourcemap/strip-sources.test.ts @@ -1,6 +1,6 @@ /** - * Tests for stripping prefixes from sourcemap `sources`, matching sentry-cli - * v2's `--strip-prefix` / `--strip-common-prefix` (rust-sourcemap's + * Tests for stripping prefixes from sourcemap `sources`, based on sentry-cli's + * `--strip-prefix` / `--strip-common-prefix` (rust-sourcemap's * `strip_prefixes` and `find_common_prefix`). */ @@ -77,6 +77,14 @@ describe("stripSourcemapSources with a prefix", () => { ]); }); + test("turns backslashes into / before stripping", () => { + const map = { version: 3, sources: ["C:\\work\\app\\a.ts", "b\\c.ts"] }; + expect(strip(map, { prefix: "C:/work" })?.sources).toEqual([ + "app/a.ts", + "b/c.ts", + ]); + }); + test("returns undefined for text that is not JSON", () => { expect(stripSourcemapSources("not json", { prefix: "a" })).toBeUndefined(); }); @@ -105,6 +113,19 @@ describe("stripSourcemapSources with common: true", () => { expect(strip(map, { common: true })?.sources).toEqual(["app/a.ts", "b.ts"]); }); + test("strips the directory of a single absolute source", () => { + const map = { version: 3, sources: ["/home/ci/app/src/a.ts", "rel.ts"] }; + expect(strip(map, { common: true })?.sources).toEqual(["a.ts", "rel.ts"]); + }); + + test("handles backslash Windows paths", () => { + const map = { + version: 3, + sources: ["C:\\work\\app\\a.ts", "C:\\work\\app\\lib\\b.ts"], + }; + expect(strip(map, { common: true })?.sources).toEqual(["a.ts", "lib/b.ts"]); + }); + test("ignores relative sources and a bare / prefix", () => { expect( strip( From 1eaabbdd5b1ddc3e5cd8bbc0869aa134d4396a08 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:14:56 +0000 Subject: [PATCH 4/4] fix(cli): Don't prepend sourceRoot to Windows drive sources when stripping sentry-cli prepended `sourceRoot` to any source not starting with `/`, `http:` or `https:`, so `C:/work/a.ts` became `/C:/work/a.ts` and the strip flags no longer matched it. Drive paths, including the ones backslash normalization now produces, count as absolute. --- .../src/content/docs/migrating-from-v3.md | 2 ++ .../cli/src/lib/sourcemap/strip-sources.ts | 12 +++++++----- .../test/lib/sourcemap/strip-sources.test.ts | 18 ++++++++++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/apps/cli-docs/src/content/docs/migrating-from-v3.md b/apps/cli-docs/src/content/docs/migrating-from-v3.md index 6c35b7ce2..4c10540fc 100644 --- a/apps/cli-docs/src/content/docs/migrating-from-v3.md +++ b/apps/cli-docs/src/content/docs/migrating-from-v3.md @@ -582,6 +582,8 @@ Two behavioral differences to be aware of: - they also work with `--no-rewrite`, which v3 rejected; - backslashes in `sources` become `/` before stripping, so `C:\work\app\a.ts` can be stripped; + - a map's `sourceRoot` is not prepended to Windows drive paths such as + `C:/work/a.ts`, which v3 treated as relative; - `--strip-common-prefix` stops at each source's directory, so a map with a single absolute source is stripped to its file name, where v3 left it unchanged. diff --git a/packages/cli/src/lib/sourcemap/strip-sources.ts b/packages/cli/src/lib/sourcemap/strip-sources.ts index ac743ac1a..3993d13e7 100644 --- a/packages/cli/src/lib/sourcemap/strip-sources.ts +++ b/packages/cli/src/lib/sourcemap/strip-sources.ts @@ -1,9 +1,10 @@ /** * Strip path prefixes from the `sources` of a sourcemap, the way sentry-cli's * `sourcemaps upload --strip-prefix` / `--strip-common-prefix` did - * (rust-sourcemap's `RewriteOptions::strip_prefixes`), with two departures: - * backslashes in `sources` become `/` first, and the common prefix stops at - * each source's directory. + * (rust-sourcemap's `RewriteOptions::strip_prefixes`), with three + * departures: backslashes in `sources` become `/` first, `sourceRoot` is not + * prepended to Windows drive paths, and the common prefix stops at each + * source's directory. */ import { logger } from "../logger.js"; @@ -63,11 +64,12 @@ function stripPrefix(source: string, prefix: string): string { /** * Prepend a `sourceRoot` to a source, unless the source is already absolute - * (`/…`) or a URL, as v2 did before stripping. + * or a URL, as sentry-cli did before stripping. Unlike sentry-cli, Windows + * drive paths (`C:/…`) count as absolute too. */ function applySourceRoot(root: string, source: string): string { if ( - source.startsWith("/") || + isAbsolutePath(source) || source.startsWith("http:") || source.startsWith("https:") ) { diff --git a/packages/cli/test/lib/sourcemap/strip-sources.test.ts b/packages/cli/test/lib/sourcemap/strip-sources.test.ts index f00287b87..e0d5fe51e 100644 --- a/packages/cli/test/lib/sourcemap/strip-sources.test.ts +++ b/packages/cli/test/lib/sourcemap/strip-sources.test.ts @@ -60,6 +60,24 @@ describe("stripSourcemapSources with a prefix", () => { expect(out).not.toHaveProperty("sourceRoot"); }); + test("does not prepend sourceRoot to Windows drive paths", () => { + const map = { + version: 3, + sourceRoot: "/root", + sources: ["C:\\work\\a.ts", "C:/work/lib/b.ts", "src/c.ts"], + }; + expect(strip(map, { prefix: "C:/work" })?.sources).toEqual([ + "a.ts", + "lib/b.ts", + "/root/src/c.ts", + ]); + const common = { ...map, sources: ["C:/work/a.ts", "C:/work/lib/b.ts"] }; + expect(strip(common, { common: true })?.sources).toEqual([ + "a.ts", + "lib/b.ts", + ]); + }); + test("strips sources in every index map section", () => { const map = { version: 3,