Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion apps/cli-docs/src/content/docs/migrating-from-v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Upload sourcemaps to Sentry
- `--ext <value> - Comma-separated file extensions to process (default: .js,.cjs,.mjs)`
- `--ignore <value> - Comma-separated glob patterns to exclude (gitignore-style)`
- `--ignore-file <value> - Path to a file with gitignore-style patterns to exclude`
- `--strip-prefix <value> - Strip a prefix from uploaded file paths and from the sources paths inside sourcemaps (e.g. 'build/')`
- `--strip-prefix <value>... - 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)`
Expand Down
97 changes: 51 additions & 46 deletions packages/cli/src/commands/sourcemap/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -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,
);
}

/**
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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(),
Expand All @@ -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,
});
}

Expand Down
58 changes: 35 additions & 23 deletions packages/cli/src/lib/sourcemap/strip-sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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
*/
Expand All @@ -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]);
}
Expand Down
Loading
Loading