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
35 changes: 23 additions & 12 deletions packages/cli/src/lib/sourcemap/debug-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,15 +136,19 @@ export function hasDebugIdRegistration(js: string, debugId: string): boolean {
* @internal
*/
export function readRegisteredDebugId(js: string): string | undefined {
const ids = new Set<string>();
let only: string | undefined;
for (const match of js.matchAll(DEBUGID_REGISTRATION_RE)) {
const id = normalizeDebugId(match[2]);
if (id) {
ids.add(id);
if (!id || id === only) {
continue;
}
if (only) {
// A second distinct ID: the file does not identify a single bundle.
return;
}
only = id;
}
const [only] = ids;
return ids.size === 1 ? only : undefined;
return only;
}

/**
Expand Down Expand Up @@ -173,11 +177,18 @@ export function readSourcemapDebugId(map: unknown): string | undefined {
* exactly — position 12 is forced to `4` (version), and position 16 is
* forced to one of `8/9/a/b` (variant, RFC 4122 §4.4).
*
* @param content - File content (string or Buffer) to hash
* Several parts hash the same as their concatenation, without building it:
* for a large bundle and its sourcemap that copy costs hundreds of megabytes.
*
* @param parts - Content (strings or Buffers) to hash, in order
* @returns UUID v4 string, e.g. `"a1b2c3d4-e5f6-4789-abcd-ef0123456789"`
*/
export function contentToDebugId(content: string | Buffer): string {
const hash = createHash("sha256").update(content).digest("hex");
export function contentToDebugId(...parts: (string | Buffer)[]): string {
const hasher = createHash("sha256");
for (const part of parts) {
hasher.update(part);
}
const hash = hasher.digest("hex");
// Position 16 (first char of 5th group in the hash) determines the
// variant nibble. charCodeAt(0) of a hex digit is deterministic.
const v4variant = ["8", "9", "a", "b"][
Expand Down Expand Up @@ -325,7 +336,9 @@ export async function injectDebugId(
);
}
const existingId = jsDebugId ?? readSourcemapDebugId(map);
// An ID from the JS comment was already checked above.
if (
!jsDebugId &&
existingId &&
(skipRuntimeCheck || hasDebugIdRegistration(jsContent, existingId))
) {
Expand All @@ -349,9 +362,7 @@ export async function injectDebugId(
? undefined
: readRegisteredDebugId(jsContent);
const debugId =
existingId ??
registeredId ??
contentToDebugId(`${jsContent}\0${mapContent}`);
existingId ?? registeredId ?? contentToDebugId(jsContent, "\0", mapContent);

// --- Mutate JS file ---
// No IIFE snippet in metadata-only mode (the CLI's own build registers the
Expand Down Expand Up @@ -555,7 +566,7 @@ export async function injectInlineDebugId(
const debugId =
existingId ??
registeredId ??
contentToDebugId(`${jsContent}\0${decoded.json}`);
contentToDebugId(jsContent, "\0", decoded.json);

// Locate the LAST inline directive to rewrite. If it can't be found (the
// discovery parser and this regex disagree on an edge case), abort WITHOUT
Expand Down
43 changes: 40 additions & 3 deletions packages/cli/test/lib/sourcemap/inject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,29 @@ describe("injectDirectory — debug ID uniqueness (regression #3350)", () => {
const ids = debugIdsByName(await injectDirectory(dir));
expect(ids["a.js"]).toBe(ids["b.js"]);
});

test("derives the same debug IDs as earlier releases", async () => {
// Pinned IDs: a change to how the content is hashed must not move the
// debug ID of an unchanged artifact. Non-ASCII text pins the encoding.
const js = 'const greeting = "héllo wörld — 👋";\nconsole.log(greeting);\n';
const map = {
version: 3,
sources: ["greeting.ts"],
names: [],
mappings: "AAAA;AACA",
};
writeFileSync(join(dir, "external.js"), js);
writeFileSync(join(dir, "external.js.map"), JSON.stringify(map));
writeFileSync(
join(dir, "inline.js"),
`${js}//# sourceMappingURL=${toDataUrl(map)}\n`,
);

expect(debugIdsByName(await injectDirectory(dir))).toEqual({
"external.js": "a5990d77-f6cd-4d7f-883b-c5edf83942c8",
"inline.js": "aa29bd7c-8da6-4078-b014-71baf34f6c5f",
});
});
});

/**
Expand Down Expand Up @@ -775,10 +798,24 @@ describe.each(["external", "inline"] as const)(
expect(readFileSync(jsPath, "utf-8")).toBe(after);
});

test("mints an ID when two different IDs are registered at runtime", async () => {
const otherId = "99999999-8888-5777-9666-555555555555";
test("reuses an ID that is registered more than once", async () => {
writeUnstampedBundle(
`${pluginSnippet(debugId)}\n${pluginSnippet(debugId)}`,
);

expect((await injectDirectory(dir))[0]).toMatchObject({
debugId,
injected: true,
});
});

const otherId = "99999999-8888-5777-9666-555555555555";
test.each([
["two different IDs", [debugId, otherId]],
["a repeated ID and then another", [debugId, debugId, otherId]],
])("mints an ID when %s are registered at runtime", async (_, ids) => {
const { jsPath } = writeUnstampedBundle(
`${pluginSnippet(debugId)}\n${pluginSnippet(otherId)}`,
ids.map((id) => pluginSnippet(id)).join("\n"),
);

const [result] = await injectDirectory(dir);
Expand Down
9 changes: 9 additions & 0 deletions packages/cli/test/script/debug-id.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ describe("property: contentToDebugId", () => {
);
});

test("hashes several parts the same as their concatenation", () => {
fcAssert(
property(string(), string(), string(), (a, b, c) => {
expect(contentToDebugId(a, b, c)).toBe(contentToDebugId(a + b + c));
}),
{ numRuns: DEFAULT_NUM_RUNS },
);
});

test("is always lowercase", () => {
fcAssert(
property(string(), (input) => {
Expand Down
Loading