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
13 changes: 13 additions & 0 deletions apps/cli-docs/src/content/docs/migrating-from-v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,19 @@ Two behavioral differences to be aware of:
`--wait-for` (use `--wait=<seconds>`), `--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, 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;
- 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.
- **`--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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ 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 (e.g. 'build/')`
- `--strip-common-prefix - Automatically strip the longest common path prefix from all files`
- `--strip-prefix <value> - 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 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[=<value>] - Wait for the server to fully process the uploaded files, up to the given seconds (default: 300, 0 = no limit; on in CI)`
Expand Down
45 changes: 43 additions & 2 deletions packages/cli/src/commands/sourcemap/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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<void> {
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);
}
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
}
}

export const uploadCommand = buildCommand({
docs: {
brief: "Upload sourcemaps to Sentry",
Expand Down Expand Up @@ -349,13 +377,16 @@ 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 sources directory",
optional: true,
default: false,
},
Expand Down Expand Up @@ -535,6 +566,16 @@ export const uploadCommand = buildCommand({
}),
);

// 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({
org,
project,
Expand Down
187 changes: 187 additions & 0 deletions packages/cli/src/lib/sourcemap/strip-sources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/**
* 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 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";

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;
};

/** 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 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.
*
* 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((source) => source.split("/").slice(0, -1));
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;
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved

/**
* Prepend a `sourceRoot` to a source, unless the source is already absolute
* 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 (
isAbsolutePath(source) ||
source.startsWith("http:") ||
source.startsWith("https:")
) {
return source;
}
return `${root.endsWith("/") ? root.slice(0, -1) : root}/${source}`;
}
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved

/** 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) : [];
});
}

/**
* 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.
*/
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.
*
* 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 }`
* @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 = 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;
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;
}
Loading
Loading