fix(browser): retain effective source-map response urls

Preserve source-map response identity and legacy omission, admit identities before body reading, and retain completed results and cleanup causes within the existing output budget. Price fixed envelopes once.

Closes #1729.
Closes #1738.

Co-authored-by: allisaid <curruptdwastaken@gmail.com>
This commit is contained in:
clyde
2026-10-11 15:35:43 +08:00
committed by GitHub
parent 81dc64e3cd
commit 062723e44e
9 changed files with 636 additions and 100 deletions
+136 -46
View File
@@ -6,6 +6,8 @@ import {
} from "../javascript/sourceMaps/DecodedSourceMap.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import type { AnalysisErrorOptions } from "../domain/analysisErrorBase.js";
import { isUrlLikeModuleSpecifier } from "../domain/webBundleAnalyzerAst.js";
import { analyzeParsedJavaScriptReferences } from "../domain/javascript/javascriptSemanticAnalysis.js";
import { traverseJavaScriptAst } from "../domain/javascript/javascriptSemanticTraversal.js";
@@ -103,8 +105,7 @@ export const fetchWebSourceMaps = async (
reservation >
SOURCE_MAP_OUTPUT_BYTES - budget.decodedRecords.expandedBytes
) {
const unprocessed = requests.length - items.length;
limitation = `Source-map output budget was exhausted before processing ${String(unprocessed)} requested map${unprocessed === 1 ? "" : "s"}. Their results are unknown.`;
limitation = sourceMapOutputLimitation(requests.length - items.length);
break;
}
const expandedBytesBeforeItem = budget.decodedRecords.expandedBytes;
@@ -126,11 +127,30 @@ export const fetchWebSourceMaps = async (
host,
budget,
);
if (item.artifact === null)
if (item.artifact === null) {
const failureBytes =
sourceMapFailureReservation(
request,
item.effective_url ?? null,
item.limitation,
item.status,
) + 1;
if (failureBytes > SOURCE_MAP_OUTPUT_BYTES - expandedBytesBeforeItem) {
limitation = sourceMapOutputLimitation(
requests.length - items.length,
);
break;
}
budget.decodedRecords.expandedBytes =
expandedBytesBeforeItem + reservation;
expandedBytesBeforeItem + failureBytes;
}
items.push(item);
}
} catch (cause: unknown) {
if (signal?.aborted === true) throw cause;
if (cause instanceof SourceMapFormatFailure && cause.reason === "limit")
limitation = sourceMapOutputLimitation(requests.length - items.length);
else throw cause;
} finally {
clearTimeout(timeout);
signal?.removeEventListener("abort", abortFromCaller);
@@ -145,6 +165,9 @@ export const fetchWebSourceMaps = async (
});
};
const sourceMapOutputLimitation = (unprocessed: number): string =>
`source-map output budget could not retain results for ${String(unprocessed)} requested map${unprocessed === 1 ? "" : "s"}. their results are unknown.`;
const sourceMapsStatus = (
items: readonly SourceMapItem[],
omitted: boolean,
@@ -211,26 +234,55 @@ const fetchOne = async (
"policy_filtered",
"Declared source-map URL is outside the approved exact origins.",
);
let effectiveUrl: string | null = null;
try {
const fetched = await fetchFollowingApprovedRedirects(
request.fetchUrl,
input.allowed_origins,
signal,
host,
(url) => {
effectiveUrl = url;
},
);
if (fetched === undefined)
return emptySourceMapItem(
request,
"policy_filtered",
"A source-map redirect left the approved exact origins.",
effectiveUrl,
);
const { response, fetchedUrl } = fetched;
try {
// Admit the resolution identity before reading or retaining its body.
consumeExpandedBytes(budget.decodedRecords, jsonBytes(fetchedUrl) - 4);
} catch (cause: unknown) {
try {
await response.body?.cancel();
} catch (cleanupCause: unknown) {
if (cause instanceof SourceMapFormatFailure && cause.reason === "limit")
throw sourceMapOutputError(cause, {
cause: new AggregateError(
[cause, cleanupCause],
"Source-map response cleanup failed after its output exceeded capacity.",
),
cleanup: {
reason:
"Source-map response cancellation failed after its output exceeded capacity.",
resources: ["source-map-response"],
},
});
throw cause;
}
throw cause;
}
if (!response.ok) {
await response.body?.cancel();
return emptySourceMapItem(
request,
"fetch_failed",
`Source-map server returned HTTP ${String(response.status)}.`,
fetchedUrl,
);
}
checkOperation(undefined, signal, budget.deadlineAt);
@@ -250,13 +302,21 @@ const fetchOne = async (
},
);
} catch (cause: unknown) {
if (cause instanceof AnalysisResourceConstraintError) throw cause;
if (cause instanceof SourceMapFormatFailure && cause.reason === "limit")
throw cause;
if (
signal?.aborted === true &&
!(signal.reason instanceof SourceMapDeadlineError)
)
throw cause;
if (cause instanceof SourceMapEncodingError)
return emptySourceMapItem(request, "invalid", cause.message);
return emptySourceMapItem(
request,
"invalid",
cause.message,
effectiveUrl,
);
return emptySourceMapItem(
request,
"fetch_failed",
@@ -265,6 +325,7 @@ const fetchOne = async (
cause instanceof SourceMapDeadlineError
? cause.message
: "Source-map fetch or validation failed.",
effectiveUrl,
);
}
};
@@ -288,6 +349,7 @@ const fetchFollowingApprovedRedirects = async (
allowedOrigins: readonly string[],
signal: AbortSignal | undefined,
host: SourceMapFetchHost,
observeResponse: (url: string) => void,
): Promise<{ response: Response; fetchedUrl: string } | undefined> => {
let current = initialUrl;
const visited = new Set<string>();
@@ -309,6 +371,7 @@ const fetchFollowingApprovedRedirects = async (
}),
signal,
);
observeResponse(current);
if (signal !== undefined && signalIsAborted(signal)) {
await response.body?.cancel(signal.reason).catch(() => undefined);
throw signal.reason;
@@ -464,6 +527,7 @@ const normalizeSourceMap = (
request,
"invalid",
"Source-map JSON is not a version 3 map.",
fetchedUrl,
);
const retainedBytesBeforeMap = context.budget.expandedBytes;
try {
@@ -476,8 +540,8 @@ const normalizeSourceMap = (
});
context.budget.expandedBytes =
retainedBytesBeforeMap -
sourceMapFailureReservation(request) +
sourceMapSuccessReservation(request);
SOURCE_MAP_FAILURE_ENVELOPE_BYTES +
SOURCE_MAP_SUCCESS_ENVELOPE_BYTES;
consumeExpandedBytes(
context.budget,
jsonBytes(text) +
@@ -583,7 +647,7 @@ const normalizeSourceMap = (
) - 4,
);
const parsed = {
...sourceMapContext(request),
...sourceMapContext(request, fetchedUrl),
artifact: createWebTextArtifact(text, "application/source-map+json"),
original_sources: originalSources,
original_module_edges: modules.edges,
@@ -602,7 +666,12 @@ const normalizeSourceMap = (
// reservation while keeping cumulative fetch and decoder-work accounting.
context.budget.expandedBytes = retainedBytesBeforeMap;
if (cause instanceof SourceMapFormatFailure && cause.reason === "limit")
return emptySourceMapItem(request, "fetch_failed", cause.message);
return emptySourceMapItem(
request,
"fetch_failed",
cause.message,
fetchedUrl,
);
if (
context.signal?.aborted === true ||
cause instanceof SourceMapDeadlineError
@@ -612,6 +681,7 @@ const normalizeSourceMap = (
request,
"invalid",
"Source-map JSON mappings could not be decoded safely.",
fetchedUrl,
);
}
};
@@ -718,17 +788,22 @@ const approvedUrl = (
}
};
const sourceMapContext = (request: WebSourceMapRequest) => ({
const sourceMapContext = (
request: WebSourceMapRequest,
effectiveUrl: string | null = null,
) => ({
script_key: request.scriptKey,
declared_url: request.declaredUrl,
effective_url: effectiveUrl,
});
const emptySourceMapItem = (
request: WebSourceMapRequest,
status: Extract<SourceMapItem, { readonly artifact: null }>["status"],
limitation: string,
effectiveUrl: string | null = null,
): Extract<SourceMapItem, { readonly artifact: null }> => ({
...sourceMapContext(request),
...sourceMapContext(request, effectiveUrl),
status,
artifact: null,
original_sources: [],
@@ -798,6 +873,18 @@ const expandedOutputFailure = (): SourceMapFormatFailure =>
`Expanded source-map evidence exceeds the ${WEB_SOURCE_MAP_LIMITS.outputBytes / (1024 * 1024)} MiB public representation budget.`,
);
const sourceMapOutputError = (
cause: SourceMapFormatFailure,
options?: AnalysisErrorOptions,
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(
"analyze_web_bundle",
"transport",
cause.message,
{ maximum_source_map_output_bytes: SOURCE_MAP_OUTPUT_BYTES },
{ cause, ...options },
);
const resolvedSourceLimitFailure = (): SourceMapFormatFailure =>
new SourceMapFormatFailure(
"limit",
@@ -821,42 +908,45 @@ const artifactMetadataBytes = (mediaType: string, text: string): number =>
}),
) - 2;
const sourceMapFailureReservation = (request: WebSourceMapRequest): number => {
const envelope = emptySourceMapItem(
{ ...request, declaredUrl: "", scriptKey: "" },
"fetch_failed",
"x".repeat(SOURCE_MAP_FAILURE_LIMITATION_RESERVE),
);
return (
Buffer.byteLength(JSON.stringify(envelope)) -
4 +
jsonBytes(request.declaredUrl) +
jsonBytes(request.scriptKey)
);
};
// Price invariant envelopes once using the producer's representation. Dynamic
// identities keep their own charges when the map's envelope changes.
const EMPTY_SOURCE_MAP_FAILURE = emptySourceMapItem(
{ scriptKey: "", declaredUrl: "", fetchUrl: "" },
"fetch_failed",
"x".repeat(SOURCE_MAP_FAILURE_LIMITATION_RESERVE),
);
const SOURCE_MAP_FAILURE_ENVELOPE_BYTES =
Buffer.byteLength(JSON.stringify(EMPTY_SOURCE_MAP_FAILURE)) - 4;
const SOURCE_MAP_SUCCESS_ENVELOPE_BYTES =
Buffer.byteLength(
JSON.stringify({
...EMPTY_SOURCE_MAP_FAILURE,
status: "included",
limitation: null,
}),
) - 4;
const sourceMapSuccessReservation = (request: WebSourceMapRequest): number => {
const context = sourceMapContext({
...request,
declaredUrl: "",
scriptKey: "",
});
const envelope = {
...context,
status: "included",
artifact: null,
original_sources: [],
original_module_edges: [],
mappings: [],
limitation: null,
};
return (
Buffer.byteLength(JSON.stringify(envelope)) -
4 +
jsonBytes(request.declaredUrl) +
jsonBytes(request.scriptKey)
);
};
const sourceMapFailureReservation = (
request: WebSourceMapRequest,
effectiveUrl: string | null = null,
limitation?: string,
status: Extract<
SourceMapItem,
{ readonly artifact: null }
>["status"] = "fetch_failed",
): number =>
SOURCE_MAP_FAILURE_ENVELOPE_BYTES +
jsonBytes(request.declaredUrl) +
jsonBytes(request.scriptKey) +
(effectiveUrl === null ? 0 : jsonBytes(effectiveUrl) - 4) +
Math.max(
0,
(limitation === undefined ? 0 : jsonBytes(limitation)) -
SOURCE_MAP_FAILURE_LIMITATION_RESERVE -
2,
) +
jsonBytes(status) -
jsonBytes("fetch_failed");
const sourceEntryOverheadBytes = (): number =>
Buffer.byteLength('{"source":,"artifact":null}');