Skip to content
Open
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
53 changes: 49 additions & 4 deletions packages/cli/src/commands/sourcemap/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,27 @@ import {
injectDirectory,
type InjectResult,
} from "../../lib/sourcemap/inject.js";
import {
addWasmDiscoveryCounts,
discoverWasmPairs,
syncWasmPairs,
type WasmSyncResult,
} from "../../lib/sourcemap/wasm.js";

/** Result type for the inject command output. */
type InjectCommandResult = {
modified: number;
skipped: number;
files: InjectResult[];
/** Wasm module + sourcemap pairs reconciled onto the module's build id. */
wasm: WasmSyncResult[];
};

/** Whether a wasm pair was changed on disk. */
function wasmChanged(result: WasmSyncResult): boolean {
return result.mapWritten || result.moduleStamped;
}

/** Format human-readable output for inject results. */
function formatInjectResult(data: InjectCommandResult): string {
const lines: string[] = [];
Expand All @@ -58,6 +71,24 @@ function formatInjectResult(data: InjectCommandResult): string {
}
}

if (data.wasm.length > 0) {
lines.push("");
for (const pair of data.wasm) {
if (pair.skipped) {
lines.push(
`✗ ${pair.wasmPath} → ${colorTag("muted", `skipped: ${pair.skipped}`)}`,
);
continue;
}
const status = wasmChanged(pair) ? "✓" : "–";
// A dry run over an unstamped module cannot know the id it would mint;
// a module whose build_id is too short never gets one.
const debugId =
pair.debugId ?? (pair.moduleStamped ? "(pending)" : "(none)");
lines.push(`${status} ${pair.wasmPath} → ${colorTag("muted", debugId)}`);
}
}

return renderMarkdown(lines.join("\n"));
}

Expand All @@ -69,6 +100,9 @@ export const injectCommand = buildCommand({
"then injects Sentry debug IDs for reliable sourcemap resolution.\n\n" +
"Existing debug IDs are preserved; missing runtime registration snippets are added.\n" +
"Files that already register their debug ID at runtime are left unchanged.\n\n" +
"WebAssembly pairs (app.wasm + app.wasm.map) are handled too: the map " +
"takes the module's build_id as its debug ID, and a module without one " +
"is stamped.\n\n" +
"Exits with an error if zero JS + sourcemap pairs are discovered " +
"(typical cause: bundler not emitting .map files). Pass " +
"--allow-empty to suppress this check for directories that may " +
Expand Down Expand Up @@ -175,8 +209,13 @@ export const injectCommand = buildCommand({
);

const pairs = await discoverFilePairs(dir, extSet, ignoreMatcher);
if (pairs.length === 0 && !flags["allow-empty"]) {
const diag = await diagnoseEmptyDiscovery(dir, { extensions });
const wasmPairs = await discoverWasmPairs(dir, { ignoreMatcher });
if (pairs.length === 0 && wasmPairs.length === 0 && !flags["allow-empty"]) {
const diag = await addWasmDiscoveryCounts(
dir,
await diagnoseEmptyDiscovery(dir, { extensions, ignoreMatcher }),
{ ignoreMatcher },
);
throw buildEmptyDiscoveryError(dir, diag);
}

Expand All @@ -185,14 +224,20 @@ export const injectCommand = buildCommand({
ignoreMatcher,
dryRun: flags["dry-run"],
});
const wasmResults = await syncWasmPairs(wasmPairs, {
dryRun: flags["dry-run"],
});

const modified = results.filter((r) => r.injected).length;
const skipped = results.length - modified;
const modified =
results.filter((r) => r.injected).length +
wasmResults.filter(wasmChanged).length;
const skipped = results.length + wasmResults.length - modified;

yield new CommandOutput({
modified,
skipped,
files: results,
wasm: wasmResults,
});

if (modified > 0) {
Expand Down
136 changes: 110 additions & 26 deletions packages/cli/src/commands/sourcemap/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ import {
type SourcesStrip,
stripSourcemapSources,
} from "../../lib/sourcemap/strip-sources.js";
import {
addWasmDiscoveryCounts,
discoverWasmPairs,
syncWasmPairs,
type WasmPair,
type WasmSyncResult,
} from "../../lib/sourcemap/wasm.js";
import { sentry } from "../../lib/app-identity.js";

/** Result type for the upload command. */
Expand Down Expand Up @@ -174,14 +181,46 @@ type ArtifactContext = {
noRewrite: boolean;
};

/** Compute a JS file's URL-space relative path (post-strip, forward slashes). */
function jsRelativePath(jsPath: string, ctx: ArtifactContext): string {
/** Compute a file's URL-space relative path (post-strip, forward slashes). */
function urlRelativePath(path: string, ctx: ArtifactContext): string {
return stripPath(
relative(ctx.resolvedDir, jsPath).replaceAll("\\", "/"),
relative(ctx.resolvedDir, path).replaceAll("\\", "/"),
ctx.pathStrip,
);
}

/**
* Build the artifact pair for a wasm module and its sourcemap.
*
* Structurally the same as the external-map JS case — the module takes the
* `minified_source` slot — but the debug ID comes off the module's `build_id`
* rather than from hashing content, and the module is uploaded as the bytes on
* disk with no injected snippet.
*/
function buildWasmArtifactPair(
result: WasmSyncResult,
ctx: ArtifactContext,
): ArtifactFile[] {
const wasmRelative = urlRelativePath(result.wasmPath, ctx);
const mapRelative = urlRelativePath(result.mapPath, ctx);
const debugIdField = result.debugId ? { debugId: result.debugId } : {};
return [
{
path: result.wasmPath,
...debugIdField,
type: "minified_source",
url: `${ctx.urlPrefix}${wasmRelative}`,
sourcemapFilename: posixRelative(posixDirname(wasmRelative), mapRelative),
},
{
path: result.mapPath,
...debugIdField,
type: "source_map",
url: `${ctx.urlPrefix}${mapRelative}`,
},
];
}

/**
* Build the `minified_source` + `source_map` artifact pair for a discovered
* file, dispatching on whether the sourcemap is inline or an external file.
Expand All @@ -191,7 +230,7 @@ function buildArtifactPair(
ctx: ArtifactContext,
): ArtifactFile[] {
const { jsPath, map, debugId } = result;
const jsRelative = jsRelativePath(jsPath, ctx);
const jsRelative = urlRelativePath(jsPath, ctx);
const debugIdField = debugId ? { debugId } : {};

if (map.kind === "inline") {
Expand Down Expand Up @@ -285,6 +324,8 @@ export const uploadCommand = buildCommand({
"Upload JavaScript sourcemaps and source files to Sentry using " +
"debug-ID-based matching.\n\n" +
"Automatically injects missing debug IDs and runtime registration snippets, preserving existing IDs.\n" +
"WebAssembly pairs (app.wasm + app.wasm.map) upload alongside, keyed by " +
"the module's build_id.\n" +
"Org/project are auto-detected from DSN, env vars, or config defaults.\n\n" +
"Exits with an error if zero JS + sourcemap pairs are discovered " +
"(typical cause: bundler not emitting .map files). Pass " +
Expand Down Expand Up @@ -514,13 +555,41 @@ export const uploadCommand = buildCommand({
ignoreMatcher,
target.include,
);

if (pairs.length === 0) {
if (!flags["allow-empty"]) {
const diag = await diagnoseEmptyDiscovery(target.dir, {
extensions,
const wasmPairs = missing
? []
: await discoverWasmPairs(target.dir, {
ignoreMatcher,
include: target.include,
});

// Read-only pass, so pairs that can't be used (a `.wasm` that isn't a
// module, a broken map) count as nothing to upload before any credential
// check or write. Each skipped pair is warned about here, once.
const usableWasmPairs: WasmPair[] = (
await syncWasmPairs(wasmPairs, { dryRun: true })
)
.filter((result) => !result.skipped)
.map(({ wasmPath, mapPath }) => ({ wasmPath, mapPath }));

if (pairs.length === 0 && usableWasmPairs.length === 0) {
if (!flags["allow-empty"]) {
if (wasmPairs.length > 0) {
throw new ValidationError(
`Found ${wasmPairs.length} wasm sourcemap pair(s) in '${dir}' ` +
"but none can be uploaded; see the warnings above. Pass " +
"--allow-empty to suppress.",
"directory",
);
}
const diag = await addWasmDiscoveryCounts(
target.dir,
await diagnoseEmptyDiscovery(target.dir, {
extensions,
ignoreMatcher,
include: target.include,
}),
{ ignoreMatcher, include: target.include },
);
throw buildEmptyDiscoveryError(dir, diag);
}
// --allow-empty: nothing to upload, so don't require Sentry
Expand Down Expand Up @@ -556,6 +625,14 @@ export const uploadCommand = buildCommand({
include: target.include,
});

// `--no-rewrite` runs the wasm sync read-only: nothing is stamped and no
// map is rewritten, but a `build_id` already on disk still identifies the
// pair, so it rides along on the manifest entries.
// Skipped pairs were already warned about and are left out of the upload.
const wasmResults = (
await syncWasmPairs(usableWasmPairs, { dryRun: flags["no-rewrite"] })
).filter((result) => !result.skipped);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

const urlPrefix = flags["url-prefix"] ?? "~/";

// Build artifact file list with paths relative to the upload directory
Expand All @@ -569,28 +646,35 @@ export const uploadCommand = buildCommand({
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) =>
[r.jsPath, r.mapPath]
.filter((path): path is string => path !== undefined)
.map((path) =>
stripPath(
relative(resolvedDir, path).replaceAll("\\", "/"),
pathStrip,
),
// Only the JS path participates for inline maps (no standalone .map
// file). Wasm pairs contribute both paths, so a wasm-only upload strips
// its own common directory just as a JS one does.
const allPaths = [
...results.flatMap((r) =>
[r.jsPath, r.mapPath].filter(
(path): path is string => path !== undefined,
),
),
...wasmResults.flatMap((w) => [w.wasmPath, w.mapPath]),
];
const allRelative = allPaths.map((path) =>
stripPath(relative(resolvedDir, path).replaceAll("\\", "/"), pathStrip),
);
pathStrip.common = computeCommonPrefix(allRelative);
}

const artifactFiles: ArtifactFile[] = results.flatMap((result) =>
buildArtifactPair(result, {
resolvedDir,
urlPrefix,
pathStrip,
noRewrite: flags["no-rewrite"] ?? false,
}),
);
const artifactCtx: ArtifactContext = {
resolvedDir,
urlPrefix,
pathStrip,
noRewrite: flags["no-rewrite"] ?? false,
};
const artifactFiles: ArtifactFile[] = [
...results.flatMap((result) => buildArtifactPair(result, artifactCtx)),
...wasmResults.flatMap((result) =>
buildWasmArtifactPair(result, artifactCtx),
),
];

// 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.
Expand Down
32 changes: 32 additions & 0 deletions packages/cli/src/lib/replace-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Replace a file's contents without ever leaving it half-written.
*
* Used where the CLI rewrites a user's build output in place (wasm modules,
* sourcemaps). A plain `writeFile` truncates first, so a full disk or a kill
* mid-write leaves a corrupt artifact; writing a sibling and renaming it over
* the target is atomic on the same filesystem. The original's mode is kept so
* an executable or read-only-for-others file stays that way.
*/

import { randomBytes } from "node:crypto";
import { rename, rm, stat, writeFile } from "node:fs/promises";

/**
* Atomically replace `path` with `data`.
*
* @param path - Existing file to replace
* @param data - New contents
*/
export async function replaceFile(
path: string,
data: string | Uint8Array,
): Promise<void> {
const { mode } = await stat(path);
const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
try {
await writeFile(tmp, data, { mode });
await rename(tmp, path);
} finally {
await rm(tmp, { force: true });
}
}
Loading
Loading