From da29585212ae29e6292d88ef319eebe12d34b9a8 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:39:06 +0000 Subject: [PATCH] feat(cli): Allow repeated and combined strip flags in sourcemap upload As in sentry-cli, `--strip-prefix` can be repeated (each path loses the first prefix it starts with) and combined with `--strip-common-prefix`. In `sources`, the common prefix is tried after the explicit prefixes, as rust-sourcemap's `strip_prefixes` did. Uploaded file paths lose the explicit prefix first, then the common prefix of what's left. Fixes #2596 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/content/docs/migrating-from-v3.md | 5 +- .../skills/sentry-cli/references/sourcemap.md | 2 +- packages/cli/src/commands/sourcemap/upload.ts | 97 ++++++++------- .../cli/src/lib/sourcemap/strip-sources.ts | 58 +++++---- .../test/commands/sourcemap/upload.test.ts | 117 +++++++++++++++--- .../test/lib/sourcemap/strip-sources.test.ts | 40 ++++-- 6 files changed, 225 insertions(+), 94 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 4c10540fc..626354670 100644 --- a/apps/cli-docs/src/content/docs/migrating-from-v3.md +++ b/apps/cli-docs/src/content/docs/migrating-from-v3.md @@ -578,7 +578,10 @@ 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, and a few details differ: + also strip the prefix from the uploaded file paths. As in v3, `--strip-prefix` + can be repeated (each path loses the first prefix it starts with) and + combined with `--strip-common-prefix`; uploaded file paths lose the explicit + prefix first and then the common prefix of what's left. 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; 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 2793e83d1..84d55950f 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,7 +61,7 @@ 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 and from the sources paths inside sourcemaps (e.g. 'build/')` +- `--strip-prefix ... - Strip a prefix from uploaded file paths and from the sources paths inside sourcemaps (e.g. 'build/'; repeatable, first match wins)` - `--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)` diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index 62094e074..ca471900b 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -132,15 +132,24 @@ function computeCommonPrefix(paths: string[]): string { return first.slice(0, common); } +/** The file-path strips for one upload, each prefix ending in `/`. */ +type PathStrip = { + /** `--strip-prefix` values; the first one a path starts with is removed. */ + prefixes: string[]; + /** Common prefix (`--strip-common-prefix`) removed after them, or `""`. */ + common: string; +}; + /** - * Strip a prefix from a file path. If the path doesn't start with - * the prefix, returns it unchanged. + * Strip a file path: the first matching explicit prefix, then the common + * prefix. A prefix the path doesn't start with leaves it unchanged. */ -function stripPrefix(path: string, prefix: string): string { - if (prefix && path.startsWith(prefix)) { - return path.slice(prefix.length); - } - return path; +function stripPath(path: string, strip: PathStrip): string { + const prefix = strip.prefixes.find((p) => path.startsWith(p)); + const rest = prefix ? path.slice(prefix.length) : path; + return strip.common && rest.startsWith(strip.common) + ? rest.slice(strip.common.length) + : rest; } /** Context shared across artifact-file construction for one upload. */ @@ -149,16 +158,18 @@ type ArtifactContext = { resolvedDir: string; /** URL prefix applied to every artifact URL (e.g. `"~/"`). */ urlPrefix: string; - /** Directory prefix to strip from relative paths (may be empty). */ - pathPrefixToStrip: string; + /** Directory prefixes to strip from relative paths. */ + pathStrip: PathStrip; /** True when `--no-rewrite` is set (upload as-is, keeping existing debug IDs). */ noRewrite: boolean; }; /** Compute a JS file's URL-space relative path (post-strip, forward slashes). */ function jsRelativePath(jsPath: string, ctx: ArtifactContext): string { - const rel = relative(ctx.resolvedDir, jsPath).replaceAll("\\", "/"); - return ctx.pathPrefixToStrip ? stripPrefix(rel, ctx.pathPrefixToStrip) : rel; + return stripPath( + relative(ctx.resolvedDir, jsPath).replaceAll("\\", "/"), + ctx.pathStrip, + ); } /** @@ -211,13 +222,10 @@ function buildArtifactPair( } // External map on disk. - let mapRelative = relative(ctx.resolvedDir, map.mapPath).replaceAll( - "\\", - "/", + const mapRelative = stripPath( + relative(ctx.resolvedDir, map.mapPath).replaceAll("\\", "/"), + ctx.pathStrip, ); - if (ctx.pathPrefixToStrip) { - mapRelative = stripPrefix(mapRelative, ctx.pathPrefixToStrip); - } return [ { path: jsPath, @@ -377,9 +385,10 @@ export const uploadCommand = buildCommand({ "strip-prefix": { kind: "parsed", parse: parseText, + variadic: true, brief: "Strip a prefix from uploaded file paths and from the sources " + - "paths inside sourcemaps (e.g. 'build/')", + "paths inside sourcemaps (e.g. 'build/'; repeatable, first match wins)", optional: true, }, "strip-common-prefix": { @@ -431,7 +440,7 @@ export const uploadCommand = buildCommand({ ext?: string; ignore?: string; "ignore-file"?: string; - "strip-prefix"?: string; + "strip-prefix"?: string[]; "strip-common-prefix"?: boolean; "no-rewrite"?: boolean; "allow-empty"?: boolean; @@ -510,13 +519,6 @@ export const uploadCommand = buildCommand({ }; } - // Validate mutually exclusive flags before any file mutation - if (flags["strip-prefix"] && flags["strip-common-prefix"]) { - throw new ValidationError( - "--strip-prefix and --strip-common-prefix are mutually exclusive", - ); - } - const resolved = await resolveOrgAndProject({ cwd: this.cwd, usageHint: usageHint(), @@ -538,41 +540,44 @@ export const uploadCommand = buildCommand({ // Build artifact file list with paths relative to the upload directory const resolvedDir = resolve(target.dir); - // Normalize --strip-prefix to end with "/" so it strips at directory - // boundaries. Without this, "build" would strip from "build/app.js" - // leaving "/app.js" instead of "app.js". - let pathPrefixToStrip = flags["strip-prefix"] ?? ""; - if (pathPrefixToStrip && !pathPrefixToStrip.endsWith("/")) { - pathPrefixToStrip = `${pathPrefixToStrip}/`; - } + // Normalize each --strip-prefix to end with "/" so it strips at + // directory boundaries. Without this, "build" would strip from + // "build/app.js" leaving "/app.js" instead of "app.js". + const prefixes = (flags["strip-prefix"] ?? []) + .filter(Boolean) + .map((p) => (p.endsWith("/") ? p : `${p}/`)); + const pathStrip: PathStrip = { prefixes, common: "" }; if (flags["strip-common-prefix"]) { + // The common prefix of the paths left after the explicit prefixes. // Only the JS path participates for inline maps (no standalone .map file). - const allRelative = results.flatMap((r) => { - const rels = [relative(resolvedDir, r.jsPath).replaceAll("\\", "/")]; - if (r.mapPath) { - rels.push(relative(resolvedDir, r.mapPath).replaceAll("\\", "/")); - } - return rels; - }); - pathPrefixToStrip = computeCommonPrefix(allRelative); + const allRelative = results.flatMap((r) => + [r.jsPath, r.mapPath] + .filter((path): path is string => path !== undefined) + .map((path) => + stripPath( + relative(resolvedDir, path).replaceAll("\\", "/"), + pathStrip, + ), + ), + ); + pathStrip.common = computeCommonPrefix(allRelative); } const artifactFiles: ArtifactFile[] = results.flatMap((result) => buildArtifactPair(result, { resolvedDir, urlPrefix, - pathPrefixToStrip, + pathStrip, noRewrite: flags["no-rewrite"] ?? false, }), ); // 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) { + if (prefixes.length > 0 || flags["strip-common-prefix"]) { await stripUploadedSources(artifactFiles, { - prefix: pathPrefixToStrip, + prefixes, + common: flags["strip-common-prefix"] ?? false, }); } diff --git a/packages/cli/src/lib/sourcemap/strip-sources.ts b/packages/cli/src/lib/sourcemap/strip-sources.ts index 3993d13e7..4a5f64fc8 100644 --- a/packages/cli/src/lib/sourcemap/strip-sources.ts +++ b/packages/cli/src/lib/sourcemap/strip-sources.ts @@ -11,8 +11,14 @@ 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 }; +/** + * What to strip: explicit prefixes, and with `common`, each map's common + * prefix after them. Each source loses the first one it starts with. + */ +export type SourcesStrip = { + prefixes?: readonly string[]; + common?: boolean; +}; /** The parts of a regular or index sourcemap that this module reads. */ type SourcemapJson = { @@ -56,10 +62,18 @@ function findCommonSourcesPrefix(sources: string[]): string | undefined { 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; +/** + * Remove the first of `prefixes` (each with a trailing `/` added if missing) + * that `source` starts with. + */ +function stripFirstPrefix(source: string, prefixes: readonly string[]): string { + for (const prefix of prefixes) { + const withSlash = prefix.endsWith("/") ? prefix : `${prefix}/`; + if (source.startsWith(withSlash)) { + return source.slice(withSlash.length); + } + } + return source; } /** @@ -128,17 +142,17 @@ function foldSourceRoot(map: SourcemapJson): boolean { } /** - * Strip a prefix from the `sources` paths inside a sourcemap. + * Strip prefixes from the `sources` paths inside a sourcemap. * - * 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 + * As in sentry-cli, each source loses the first prefix (plus `/`) it starts + * with, 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. + * `common`, the common directory of the map's absolute sources (see + * {@link findCommonSourcesPrefix}; for an index map, of all its sections' + * sources) is tried after the explicit prefixes. * * @param json - Sourcemap JSON text - * @param strip - The prefix to strip, or `{ common: true }` + * @param strip - The prefixes to strip, and whether to strip the common one * @returns The rewritten JSON, or `undefined` when nothing changed or the * text is not a JSON object */ @@ -158,27 +172,25 @@ export function stripSourcemapSources( } const map = parsed as SourcemapJson; const maps = regularMaps(map); - let prefix: string | undefined; + let common: string | undefined; let changed = maps.map(normalizeSeparators).some(Boolean); - if ("prefix" in strip) { - prefix = strip.prefix; - } else if (Array.isArray(map.sections)) { + if (strip.common && 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; - prefix = findCommonSourcesPrefix(maps.flatMap(stringSources)); - } else { + common = findCommonSourcesPrefix(maps.flatMap(stringSources)); + } else if (strip.common) { // For a regular map, v2 computed the common prefix before applying // sourceRoot. - prefix = findCommonSourcesPrefix(stringSources(map)); + common = findCommonSourcesPrefix(stringSources(map)); } + const prefixes = [...(strip.prefixes ?? []), ...(common ? [common] : [])]; for (const m of maps) { changed = foldSourceRoot(m) || changed; const sources = m.sources; - if (prefix && Array.isArray(sources)) { - const p = prefix; + if (prefixes.length > 0 && Array.isArray(sources)) { m.sources = sources.map((s: unknown) => - typeof s === "string" ? stripPrefix(s, p) : s, + typeof s === "string" ? stripFirstPrefix(s, prefixes) : s, ); changed ||= (m.sources as unknown[]).some((s, i) => s !== sources[i]); } diff --git a/packages/cli/test/commands/sourcemap/upload.test.ts b/packages/cli/test/commands/sourcemap/upload.test.ts index 3be523fb2..068df2729 100644 --- a/packages/cli/test/commands/sourcemap/upload.test.ts +++ b/packages/cli/test/commands/sourcemap/upload.test.ts @@ -38,7 +38,7 @@ type UploadFuncArgs = { ext?: string; ignore?: string; "ignore-file"?: string; - "strip-prefix"?: string; + "strip-prefix"?: string[]; "strip-common-prefix"?: boolean; "no-rewrite"?: boolean; "allow-empty"?: boolean; @@ -896,7 +896,7 @@ describe("sourcemap upload command — --allow-empty behavior", () => { .mockResolvedValue(undefined); try { const ctx = makeContext(); - await func.call(ctx, { "strip-prefix": "static/js/" }, dir); + await func.call(ctx, { "strip-prefix": ["static/js/"] }, dir); expect(uploadSpy).toHaveBeenCalledTimes(1); const callArgs = uploadSpy.mock.calls[0]?.[0]; const urls = callArgs?.files.map((f) => f.url); @@ -948,8 +948,11 @@ 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, + url?: string, ): Promise { - const mapFile = files?.find((f) => f.type === "source_map"); + const mapFile = files?.find( + (f) => f.type === "source_map" && (url === undefined || f.url === url), + ); if (!mapFile) { throw new Error("no source_map artifact uploaded"); } @@ -974,7 +977,7 @@ describe("sourcemap upload command — --allow-empty behavior", () => { .spyOn(sourcemapsApi, "uploadSourcemaps") .mockResolvedValue(undefined); try { - await func.call(makeContext(), { "strip-prefix": ".." }, dir); + await func.call(makeContext(), { "strip-prefix": [".."] }, dir); const files = uploadSpy.mock.calls[0]?.[0]?.files; expect(await uploadedSources(files)).toEqual([ "src/index.ts", @@ -1036,7 +1039,7 @@ describe("sourcemap upload command — --allow-empty behavior", () => { try { await func.call( makeContext(), - { "strip-prefix": "..", "no-rewrite": true }, + { "strip-prefix": [".."], "no-rewrite": true }, dir, ); const files = uploadSpy.mock.calls[0]?.[0]?.files; @@ -1051,20 +1054,104 @@ describe("sourcemap upload command — --allow-empty behavior", () => { } }); - test("--strip-prefix + --strip-common-prefix: mutually exclusive", async () => { - await writeFile(join(dir, "app.js"), "console.log(1)\n"); + test("--strip-prefix: repeatable, the first matching prefix wins", async () => { + await mkdir(join(dir, "static", "js"), { recursive: true }); + await mkdir(join(dir, "workers"), { recursive: true }); + await writeFile(join(dir, "static", "js", "app.js"), "console.log(1)\n"); await writeFile( - join(dir, "app.js.map"), + join(dir, "static", "js", "app.js.map"), + JSON.stringify({ + version: 3, + sources: ["../src/app.ts", "webpack://app/src/util.ts"], + names: [], + mappings: "AAAA", + }), + ); + await writeFile(join(dir, "workers", "index.js"), "console.log(2)\n"); + await writeFile( + join(dir, "workers", "index.js.map"), JSON.stringify({ version: 3, sources: [], names: [], mappings: "" }), ); - const ctx = makeContext(); - await expect( - func.call( - ctx, - { "strip-prefix": "foo/", "strip-common-prefix": true }, + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + await func.call( + makeContext(), + { + "strip-prefix": [ + "static/js", + "static", + "workers", + "..", + "webpack://app", + ], + }, dir, - ), - ).rejects.toBeInstanceOf(ValidationError); + ); + const files = uploadSpy.mock.calls[0]?.[0]?.files; + const urls = files?.map((f) => f.url); + expect(urls).toEqual( + expect.arrayContaining(["~/app.js", "~/app.js.map", "~/index.js"]), + ); + expect(await uploadedSources(files, "~/app.js.map")).toEqual([ + "src/app.ts", + "src/util.ts", + ]); + } finally { + uploadSpy.mockRestore(); + } + }); + + test("--strip-prefix + --strip-common-prefix: explicit prefixes first, then the common prefix", async () => { + await mkdir(join(dir, "build", "assets", "js"), { recursive: true }); + for (const name of ["main", "vendor"]) { + await writeFile( + join(dir, "build", "assets", "js", `${name}.js`), + "console.log(1)\n", + ); + await writeFile( + join(dir, "build", "assets", "js", `${name}.js.map`), + JSON.stringify({ + version: 3, + sources: [ + "../src/a.ts", + "/home/ci/app/src/b.ts", + "/home/ci/app/c.ts", + ], + names: [], + mappings: "AAAA", + }), + ); + } + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + await func.call( + makeContext(), + { "strip-prefix": ["build", ".."], "strip-common-prefix": true }, + dir, + ); + const files = uploadSpy.mock.calls[0]?.[0]?.files; + // "build/" first, then the common "assets/js/" of what's left. + expect(files?.map((f) => f.url).sort()).toEqual([ + "~/main.js", + "~/main.js.map", + "~/vendor.js", + "~/vendor.js.map", + ]); + // ".." first, then the common "/home/ci/app" of the absolute sources. + expect(await uploadedSources(files)).toEqual([ + "src/a.ts", + "src/b.ts", + "c.ts", + ]); + } finally { + uploadSpy.mockRestore(); + } }); test("sourceMappingURL: last directive wins over earlier ones", async () => { diff --git a/packages/cli/test/lib/sourcemap/strip-sources.test.ts b/packages/cli/test/lib/sourcemap/strip-sources.test.ts index e0d5fe51e..a3cb24c3f 100644 --- a/packages/cli/test/lib/sourcemap/strip-sources.test.ts +++ b/packages/cli/test/lib/sourcemap/strip-sources.test.ts @@ -26,7 +26,7 @@ describe("stripSourcemapSources with a prefix", () => { sources: ["../src/index.ts", "../node_modules/hono/dist/index.js"], mappings: "AAAA", }; - expect(strip(map, { prefix: ".." })?.sources).toEqual([ + expect(strip(map, { prefixes: [".."] })?.sources).toEqual([ "src/index.ts", "node_modules/hono/dist/index.js", ]); @@ -34,15 +34,37 @@ describe("stripSourcemapSources with a prefix", () => { 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([ + expect(strip(map, { prefixes: ["build"] })?.sources).toEqual([ "a.js", "builder/b.js", ]); }); + test("strips the first matching prefix only", () => { + const map = { + version: 3, + sources: ["../src/a.ts", "webpack://app/src/b.ts", "../../c.ts", "d.ts"], + }; + expect( + strip(map, { prefixes: ["webpack://app", "..", "../.."] })?.sources, + ).toEqual(["src/a.ts", "src/b.ts", "../c.ts", "d.ts"]); + }); + + test("tries the common prefix after the explicit prefixes", () => { + const map = { + version: 3, + sources: ["../src/a.ts", "/home/ci/app/a.ts", "/home/ci/app/lib/b.ts"], + }; + expect(strip(map, { prefixes: [".."], common: true })?.sources).toEqual([ + "src/a.ts", + "a.ts", + "lib/b.ts", + ]); + }); + 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(); + expect(strip(map, { prefixes: ["dist/../"] })).toBeUndefined(); }); test("folds sourceRoot into sources before stripping", () => { @@ -51,7 +73,7 @@ describe("stripSourcemapSources with a prefix", () => { sourceRoot: "/app/", sources: ["src/a.ts", "/abs/b.ts", "https://example.com/c.js"], }; - const out = strip(map, { prefix: "/app" }); + const out = strip(map, { prefixes: ["/app"] }); expect(out?.sources).toEqual([ "src/a.ts", "/abs/b.ts", @@ -66,7 +88,7 @@ describe("stripSourcemapSources with a prefix", () => { sourceRoot: "/root", sources: ["C:\\work\\a.ts", "C:/work/lib/b.ts", "src/c.ts"], }; - expect(strip(map, { prefix: "C:/work" })?.sources).toEqual([ + expect(strip(map, { prefixes: ["C:/work"] })?.sources).toEqual([ "a.ts", "lib/b.ts", "/root/src/c.ts", @@ -86,7 +108,7 @@ describe("stripSourcemapSources with a prefix", () => { { offset: { line: 9, column: 0 }, map: { sources: ["../src/b.ts"] } }, ], }; - const out = strip(map, { prefix: "../" }) as { + const out = strip(map, { prefixes: ["../"] }) as { sections: { map: { sources: string[] } }[]; }; expect(out.sections.map((s) => s.map.sources)).toEqual([ @@ -97,14 +119,16 @@ 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([ + expect(strip(map, { prefixes: ["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(); + expect( + stripSourcemapSources("not json", { prefixes: ["a"] }), + ).toBeUndefined(); }); });