feat(browser): trace captured website module imports (#879)
* feat(browser): trace captured website module imports Compose verified exported scripts, inert native import syntax and a narrow Chromium resolution port. Preserve query/fragment identity, import-map context, all reported capture candidates and explicit unknown execution. Share named CLI/MCP contracts and retain native reports, diagnostics and cleanup failures. Add focused boundary regressions and a real module-loading oracle to the existing conditional Chrome lane. No captured application code is executed by module tracing, and no selected website asset is refetched. Refs #851, #774 Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis) Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) * fix(browser): preserve module contexts and source bindings Keep capture completeness inline, validate actual source text against its digest, and separate unsupported URL contexts from malformed input. Use the importer origin for native module resolution and the selected map base independently, including mixed HTTP/HTTPS and escaped HTML attributes. Refs #851, #774 Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis) Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
@@ -2,6 +2,35 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildCapabilityInventory } from "./CapabilityInventory.js";
|
||||
|
||||
it("reports module syntax and native resolution availability separately", () => {
|
||||
const input = { open: false, capabilities: [] };
|
||||
const unavailable = buildCapabilityInventory(input, {
|
||||
processCaptureEnabled: false,
|
||||
}).find((tool) => tool.name === "trace_web_module_imports");
|
||||
expect(unavailable).toMatchObject({
|
||||
available: true,
|
||||
default_mode_available: false,
|
||||
modes: [
|
||||
expect.objectContaining({
|
||||
name: "sources-without-literal-imports",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "native-literal-resolution",
|
||||
available: false,
|
||||
}),
|
||||
],
|
||||
});
|
||||
const enabled = buildCapabilityInventory(input, {
|
||||
processCaptureEnabled: false,
|
||||
webModuleResolutionEnabled: true,
|
||||
}).find((tool) => tool.name === "trace_web_module_imports");
|
||||
expect(enabled).toMatchObject({
|
||||
available: true,
|
||||
default_mode_available: true,
|
||||
});
|
||||
});
|
||||
|
||||
const enabledPolicy: Parameters<typeof buildCapabilityInventory>[1] = {
|
||||
processCaptureEnabled: true,
|
||||
browserObservationEnabled: true,
|
||||
|
||||
@@ -37,6 +37,7 @@ export type AvailabilityPolicy = {
|
||||
readonly firmwareExtractionEnabled?: boolean;
|
||||
readonly androidAnalysisEnabled?: boolean;
|
||||
readonly javascriptRecoveryEnabled?: boolean;
|
||||
readonly webModuleResolutionEnabled?: boolean;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
readonly browserScenarioEnabled?: boolean;
|
||||
readonly electronObservationEnabled?: boolean;
|
||||
@@ -237,6 +238,34 @@ const workflowAvailabilityFor = ({
|
||||
kind,
|
||||
policy,
|
||||
}: AvailabilityContext): Availability | null => {
|
||||
if (name === "trace_web_module_imports")
|
||||
return {
|
||||
reason: "available",
|
||||
remediation: null,
|
||||
defaultModeAvailable: policy.webModuleResolutionEnabled === true,
|
||||
modes: [
|
||||
{
|
||||
name: "sources-without-literal-imports",
|
||||
available: true,
|
||||
missing_operations: [],
|
||||
remediation: null,
|
||||
},
|
||||
policy.webModuleResolutionEnabled === true
|
||||
? {
|
||||
name: "native-literal-resolution",
|
||||
available: true,
|
||||
missing_operations: [],
|
||||
remediation: null,
|
||||
}
|
||||
: {
|
||||
name: "native-literal-resolution",
|
||||
available: false,
|
||||
missing_operations: ["native-module-resolver"],
|
||||
remediation:
|
||||
"Provide an absolute REA_BROWSER_EXECUTABLE supporting import.meta.resolve; no binary target is required.",
|
||||
},
|
||||
],
|
||||
};
|
||||
if (name === "recover_javascript_sources")
|
||||
return policy.javascriptRecoveryEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type {
|
||||
WebModuleFile,
|
||||
WebModuleResolution,
|
||||
WebModuleTraceInput,
|
||||
} from "../domain/webModuleTrace.js";
|
||||
import type { webScriptExportManifestSchema } from "../domain/webScriptExport.js";
|
||||
import type { z } from "zod";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
|
||||
type JsonObject = Record<string, JsonValue>;
|
||||
|
||||
/** Verified selected source and capture metadata; provider protocols stay outside. */
|
||||
export interface WebModuleArtifacts {
|
||||
readonly manifest: z.output<typeof webScriptExportManifestSchema>;
|
||||
readonly manifestFile: WebModuleFile;
|
||||
readonly sourceFile: WebModuleFile;
|
||||
readonly source: string;
|
||||
readonly importMap: {
|
||||
readonly file: WebModuleFile;
|
||||
readonly baseUrl: string;
|
||||
readonly value: JsonObject;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** Read selected local artifacts without refetching website assets. */
|
||||
export interface WebModuleArtifactPort {
|
||||
load(
|
||||
input: WebModuleTraceInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebModuleArtifacts, AnalysisError>>;
|
||||
}
|
||||
|
||||
/** Resolve literal specifiers in a selected URL/map context without executing the selected application. */
|
||||
export interface WebModuleResolutionBatch {
|
||||
readonly engine: { readonly id: string; readonly version: string };
|
||||
readonly resolutions: readonly WebModuleResolution[];
|
||||
readonly diagnostics: readonly string[];
|
||||
readonly rawResult: JsonObject;
|
||||
}
|
||||
|
||||
/** Replaceable native resolution engine, with no provider protocol in callers. */
|
||||
export interface WebModuleResolutionPort {
|
||||
resolve(
|
||||
input: {
|
||||
readonly importerUrl: string;
|
||||
readonly importMap: {
|
||||
readonly baseUrl: string;
|
||||
readonly value: JsonObject;
|
||||
} | null;
|
||||
readonly specifiers: readonly string[];
|
||||
},
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebModuleResolutionBatch, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { WebModuleTraceService } from "./WebModuleTraceService.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import {
|
||||
webModuleTraceResultSchema,
|
||||
type WebModuleResolution,
|
||||
} from "../domain/webModuleTrace.js";
|
||||
import {
|
||||
webModuleArtifactsFixture,
|
||||
webModuleResolverFixture,
|
||||
} from "../../tests/fixtures/webModuleTrace.js";
|
||||
|
||||
const args = { manifest_path: "/analysis/manifest.json", script_index: 0 };
|
||||
it.each([
|
||||
{ ...args, importer_url: "file:///tmp/main.js" },
|
||||
{ ...args, import_map: { path: "/map.json", base_url: "file:///tmp/maps/" } },
|
||||
])(
|
||||
"distinguishes valid unsupported URL contexts from malformed input: %j",
|
||||
async (input) => {
|
||||
const result = await new WebModuleTraceService(
|
||||
{
|
||||
load: () => {
|
||||
throw new Error("must not acquire artifacts");
|
||||
},
|
||||
},
|
||||
webModuleResolverFixture,
|
||||
).trace(input);
|
||||
if (result.ok) throw new Error("expected unsupported context");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("file:"),
|
||||
});
|
||||
},
|
||||
);
|
||||
it("rejects source text changed across the artifact port while retaining the original digest", async () => {
|
||||
const artifacts = {
|
||||
...webModuleArtifactsFixture("import(name)"),
|
||||
source: "import(other)",
|
||||
};
|
||||
const result = await new WebModuleTraceService(
|
||||
{ load: () => Promise.resolve(ok(artifacts)) },
|
||||
{
|
||||
resolve: () => {
|
||||
throw new Error("must not acquire engine");
|
||||
},
|
||||
},
|
||||
).trace(args);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
});
|
||||
it("rejects sparse resolver arrays rather than relabeling literal imports as computed unknowns", async () => {
|
||||
const artifacts = webModuleArtifactsFixture('import "./dep.js";');
|
||||
const service = new WebModuleTraceService(
|
||||
{ load: () => Promise.resolve(ok(artifacts)) },
|
||||
{
|
||||
resolve: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
engine: { id: "fixture", version: "1" },
|
||||
resolutions: new Array<WebModuleResolution>(1),
|
||||
diagnostics: [],
|
||||
rawResult: {},
|
||||
}),
|
||||
),
|
||||
},
|
||||
);
|
||||
const result = await service.trace(args);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
});
|
||||
describe("selected module trace workflow", () => {
|
||||
it("composes selected source, derived resolution and explicit computed/execution unknowns", async () => {
|
||||
const artifacts = webModuleArtifactsFixture();
|
||||
const service = new WebModuleTraceService(
|
||||
{ load: () => Promise.resolve(ok(artifacts)) },
|
||||
webModuleResolverFixture,
|
||||
);
|
||||
const response = await service.trace(args);
|
||||
if (!response.ok) throw response.error;
|
||||
const result = webModuleTraceResultSchema.parse(
|
||||
response.value.normalized_result,
|
||||
);
|
||||
expect(result.importer).toEqual({
|
||||
url: artifacts.manifest.scripts[0]?.url,
|
||||
basis: "reported-source-url",
|
||||
});
|
||||
expect(result.manifest.capture_completeness).toEqual(
|
||||
artifacts.manifest.capture_completeness,
|
||||
);
|
||||
expect(result.imports[0]?.resolution).toEqual({
|
||||
state: "resolved",
|
||||
url: "https://app.test/dep.js",
|
||||
});
|
||||
expect(result.imports[1]?.resolution).toEqual({
|
||||
state: "unknown",
|
||||
reason: "computed-specifier",
|
||||
});
|
||||
expect(result.imports.every((item) => item.execution === "unknown")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(response.value.subject).toMatchObject({
|
||||
local_path: artifacts.sourceFile.path,
|
||||
digest: { sha256: artifacts.sourceFile.sha256 },
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
{ ...args, manifest_path: "relative.json" },
|
||||
{
|
||||
...args,
|
||||
import_map: { path: "relative.json", base_url: "https://app.test/" },
|
||||
},
|
||||
{ ...args, importer_url: "not a URL" },
|
||||
{ ...args, import_map: { path: "/map.json", base_url: "relative" } },
|
||||
])(
|
||||
"rejects malformed context before acquiring artifacts: %j",
|
||||
async (input) => {
|
||||
const service = new WebModuleTraceService(
|
||||
{
|
||||
load: () => {
|
||||
throw new Error("must not acquire");
|
||||
},
|
||||
},
|
||||
webModuleResolverFixture,
|
||||
);
|
||||
const response = await service.trace(input);
|
||||
if (response.ok) throw new Error("expected invalid input");
|
||||
expect(projectAnalysisError(response.error)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [expect.objectContaining({ reason: "invalid_format" })],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
it("handles computed-only sources without acquiring the optional engine", async () => {
|
||||
const artifacts = webModuleArtifactsFixture("import(name)");
|
||||
const service = new WebModuleTraceService(
|
||||
{ load: () => Promise.resolve(ok(artifacts)) },
|
||||
{
|
||||
resolve: () => {
|
||||
throw new Error("engine must not start");
|
||||
},
|
||||
},
|
||||
);
|
||||
const result = await service.trace(args);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(
|
||||
webModuleTraceResultSchema.parse(result.value.normalized_result).engine,
|
||||
).toBeNull();
|
||||
});
|
||||
it("rejects incomplete resolution rather than fabricating unknown values", async () => {
|
||||
const artifacts = webModuleArtifactsFixture();
|
||||
const service = new WebModuleTraceService(
|
||||
{ load: () => Promise.resolve(ok(artifacts)) },
|
||||
{
|
||||
resolve: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
engine: { id: "fixture", version: "1" },
|
||||
resolutions: [],
|
||||
diagnostics: [],
|
||||
rawResult: {},
|
||||
}),
|
||||
),
|
||||
},
|
||||
);
|
||||
const response = await service.trace(args);
|
||||
expect(response.ok).toBe(false);
|
||||
if (!response.ok) expect(response.error._tag).toBe("AnalysisOutputError");
|
||||
});
|
||||
it("preserves an explicit selected importer context", async () => {
|
||||
const artifacts = webModuleArtifactsFixture();
|
||||
const result = await new WebModuleTraceService(
|
||||
{ load: () => Promise.resolve(ok(artifacts)) },
|
||||
webModuleResolverFixture,
|
||||
).trace({ ...args, importer_url: "https://selected.test/base/main.js" });
|
||||
if (!result.ok) throw result.error;
|
||||
expect(
|
||||
webModuleTraceResultSchema.parse(result.value.normalized_result)
|
||||
.imports[0]?.resolution,
|
||||
).toEqual({ state: "resolved", url: "https://selected.test/base/dep.js" });
|
||||
});
|
||||
it("honors cancellation before any artifacts are acquired", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const service = new WebModuleTraceService(
|
||||
{
|
||||
load: () => {
|
||||
throw new Error("must not acquire");
|
||||
},
|
||||
},
|
||||
webModuleResolverFixture,
|
||||
);
|
||||
const result = await service.trace(args, { signal: controller.signal });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
collectWebModuleImports,
|
||||
matchCapturedModules,
|
||||
} from "../domain/webModuleImports.js";
|
||||
import {
|
||||
webModuleTraceInputSchema,
|
||||
webModuleFileSchema,
|
||||
webModuleResolutionSchema,
|
||||
webModuleTraceResultSchema,
|
||||
type WebModuleResolution,
|
||||
type WebModuleTraceResult,
|
||||
} from "../domain/webModuleTrace.js";
|
||||
import { webScriptExportManifestSchema } from "../domain/webScriptExport.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type {
|
||||
WebModuleArtifactPort,
|
||||
WebModuleResolutionPort,
|
||||
WebModuleResolutionBatch,
|
||||
} from "./WebModulePorts.js";
|
||||
|
||||
const OPERATION = "trace_web_module_imports";
|
||||
const artifactsSchema = z.strictObject({
|
||||
manifest: webScriptExportManifestSchema,
|
||||
manifestFile: webModuleFileSchema,
|
||||
sourceFile: webModuleFileSchema,
|
||||
source: z.string(),
|
||||
importMap: z
|
||||
.strictObject({
|
||||
file: webModuleFileSchema,
|
||||
baseUrl: z.string().min(1),
|
||||
value: jsonObjectSchema,
|
||||
})
|
||||
.nullable(),
|
||||
});
|
||||
const resolutionBatchSchema = z.strictObject({
|
||||
engine: z.strictObject({ id: z.string().min(1), version: z.string().min(1) }),
|
||||
resolutions: z.array(webModuleResolutionSchema),
|
||||
diagnostics: z.array(z.string()),
|
||||
rawResult: jsonObjectSchema,
|
||||
});
|
||||
const LIMITATIONS = [
|
||||
"Resolution is derived under the selected importer URL and optional import map; it does not establish that the map was installed in the captured page.",
|
||||
"Reported source URLs do not establish an inline script's document base. Select importer_url explicitly when that context differs or is unknown.",
|
||||
"Captured candidates retain reported capture metadata; their bytes are not reverified by this trace unless selected as the source.",
|
||||
"A resolved URL or captured source does not prove loading, execution, UI causality, or module namespace identity. Execution remains unknown.",
|
||||
"Only native ES module syntax is resolved. Bundler module IDs, computed imports, workers and non-HTTP(S) importer contexts are outside this trace.",
|
||||
"Source-map declarations do not establish retained map bytes or executed original-source coverage.",
|
||||
"Selected application code is parsed as data and never executed. The owned resolver executes only REA's trusted stub; its page requests are locally fulfilled or blocked.",
|
||||
"Manifest, source and import-map limits are 32 MiB, 16 MiB and 4 MiB. Native resolution has a 20-second deadline; cleanup may extend it. One renderer is requested; no aggregate host memory limit is claimed.",
|
||||
];
|
||||
|
||||
/** Compose verified captures, inert syntax and a replaceable URL resolution engine. */
|
||||
export class WebModuleTraceService {
|
||||
constructor(
|
||||
readonly artifacts: WebModuleArtifactPort,
|
||||
readonly resolver: WebModuleResolutionPort,
|
||||
) {}
|
||||
|
||||
async trace(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (isAborted(options?.signal))
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const parsed = webModuleTraceInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError(
|
||||
OPERATION,
|
||||
{ cause: parsed.error },
|
||||
projectInputIssues(parsed.error.issues, rawInput),
|
||||
),
|
||||
);
|
||||
const input = parsed.data;
|
||||
for (const [path, value] of [
|
||||
["manifest_path", input.manifest_path],
|
||||
["import_map.path", input.import_map?.path],
|
||||
] as const)
|
||||
if (value !== undefined && !isAbsolute(value))
|
||||
return invalid(
|
||||
path.split("."),
|
||||
"Expected an absolute filesystem path on this host.",
|
||||
);
|
||||
for (const [path, value] of [
|
||||
["importer_url", input.importer_url],
|
||||
["import_map.base_url", input.import_map?.base_url],
|
||||
] as const)
|
||||
if (value !== undefined) {
|
||||
const admission = admitContext(value, path.split("."));
|
||||
if (!admission.ok) return admission;
|
||||
}
|
||||
const loaded = await this.artifacts.load(input, options);
|
||||
if (!loaded.ok) return loaded;
|
||||
const verified = artifactsSchema.safeParse(loaded.value);
|
||||
if (!verified.success)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Artifact port returned a malformed source/manifest report.",
|
||||
),
|
||||
);
|
||||
const data = verified.data;
|
||||
if (
|
||||
(input.import_map?.path ?? null) !==
|
||||
(data.importMap?.file.path ?? null) ||
|
||||
(input.import_map?.base_url ?? null) !== (data.importMap?.baseUrl ?? null)
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Artifact port changed the selected import-map identity/context.",
|
||||
),
|
||||
);
|
||||
const selected = data.manifest.scripts[input.script_index];
|
||||
if (
|
||||
selected === undefined ||
|
||||
selected.content.state !== "exported" ||
|
||||
selected.content.sha256 !== data.sourceFile.sha256 ||
|
||||
selected.content.bytes !== data.sourceFile.bytes ||
|
||||
Buffer.byteLength(data.source) !== data.sourceFile.bytes ||
|
||||
createHash("sha256").update(data.source, "utf8").digest("hex") !==
|
||||
data.sourceFile.sha256 ||
|
||||
data.manifestFile.path !== input.manifest_path
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Artifact port did not bind the selected source and manifest identities.",
|
||||
),
|
||||
);
|
||||
const importerUrl = input.importer_url ?? selected.url;
|
||||
const importerAdmission = admitContext(importerUrl, ["importer_url"]);
|
||||
if (!importerAdmission.ok) return importerAdmission;
|
||||
const syntax = collectWebModuleImports(data.source);
|
||||
const literals = syntax.imports
|
||||
.filter((reference) => reference.specifier !== null)
|
||||
.map((reference) => reference.specifier ?? "");
|
||||
let resolution: WebModuleResolutionBatch | null = null;
|
||||
if (literals.length > 0) {
|
||||
const execution = await this.resolver.resolve(
|
||||
{
|
||||
importerUrl,
|
||||
importMap:
|
||||
data.importMap === null
|
||||
? null
|
||||
: {
|
||||
baseUrl: data.importMap.baseUrl,
|
||||
value: data.importMap.value,
|
||||
},
|
||||
specifiers: literals,
|
||||
},
|
||||
options,
|
||||
);
|
||||
if (!execution.ok) return execution;
|
||||
const report = resolutionBatchSchema.safeParse(execution.value);
|
||||
if (!report.success)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Resolver returned malformed or incomplete native evidence.",
|
||||
),
|
||||
);
|
||||
resolution = report.data;
|
||||
if (resolution.resolutions.length !== literals.length)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Resolver did not return every selected literal specifier.",
|
||||
),
|
||||
);
|
||||
}
|
||||
if (isAborted(options?.signal))
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
let literalIndex = 0;
|
||||
const imports: WebModuleTraceResult["imports"] = [];
|
||||
for (const reference of syntax.imports) {
|
||||
let resolved:
|
||||
| WebModuleResolution
|
||||
| { state: "unknown"; reason: "computed-specifier" };
|
||||
if (reference.specifier === null)
|
||||
resolved = { state: "unknown", reason: "computed-specifier" };
|
||||
else {
|
||||
const reported = resolution?.resolutions[literalIndex++];
|
||||
if (reported === undefined)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Resolver omitted a selected literal specifier.",
|
||||
),
|
||||
);
|
||||
resolved = reported;
|
||||
}
|
||||
imports.push({
|
||||
...reference,
|
||||
resolution: resolved,
|
||||
captured_candidates:
|
||||
resolved.state === "resolved"
|
||||
? matchCapturedModules(resolved.url, data.manifest.scripts)
|
||||
: [],
|
||||
execution: "unknown",
|
||||
});
|
||||
}
|
||||
const normalized = webModuleTraceResultSchema.safeParse({
|
||||
manifest: {
|
||||
...data.manifestFile,
|
||||
reported_output_directory: data.manifest.output_directory,
|
||||
capture_sha256: data.manifest.capture_sha256,
|
||||
capture_path: data.manifest.capture_path,
|
||||
capture_kind: data.manifest.capture_kind,
|
||||
capture_completeness: data.manifest.capture_completeness,
|
||||
source_evidence_id: data.manifest.source_evidence_id,
|
||||
},
|
||||
source: {
|
||||
...data.sourceFile,
|
||||
script_index: input.script_index,
|
||||
script: selected,
|
||||
},
|
||||
importer: {
|
||||
url: importerUrl,
|
||||
basis:
|
||||
input.importer_url === undefined
|
||||
? "reported-source-url"
|
||||
: "caller-selected",
|
||||
},
|
||||
import_map:
|
||||
data.importMap === null
|
||||
? null
|
||||
: { ...data.importMap.file, base_url: data.importMap.baseUrl },
|
||||
parser: {
|
||||
state: syntax.state,
|
||||
diagnostics: syntax.diagnostics,
|
||||
location_units: "UTF-16 offsets and columns; one-based lines",
|
||||
},
|
||||
engine: resolution?.engine ?? null,
|
||||
imports,
|
||||
diagnostics: resolution?.diagnostics ?? [],
|
||||
limitations: LIMITATIONS,
|
||||
});
|
||||
if (!normalized.success)
|
||||
return err(new AnalysisOutputError(OPERATION, normalized.error.message));
|
||||
return ok(
|
||||
createEvidence(
|
||||
{
|
||||
path: data.sourceFile.path,
|
||||
sha256: data.sourceFile.sha256,
|
||||
format: "file",
|
||||
},
|
||||
{
|
||||
id: "rea-web-module-trace",
|
||||
name: "REA captured module relationship trace",
|
||||
version: "1",
|
||||
},
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters: jsonObjectSchema.parse(input),
|
||||
result: normalized.data,
|
||||
rawResult: resolution?.rawResult ?? null,
|
||||
confidence: "derived",
|
||||
authority: "historical-reference",
|
||||
limitations: LIMITATIONS,
|
||||
locations: [
|
||||
{ kind: "artifact-path", path: data.sourceFile.path },
|
||||
{ kind: "artifact-path", path: input.manifest_path },
|
||||
],
|
||||
evidenceLinks:
|
||||
data.manifest.source_evidence_id === null
|
||||
? []
|
||||
: [data.manifest.source_evidence_id],
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const admitContext = (
|
||||
value: string,
|
||||
path: readonly string[],
|
||||
): Result<null, AnalysisError> => {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
return invalid(
|
||||
path,
|
||||
"Expected an absolute context URL. Select importer_url explicitly when the reported source URL is unknown.",
|
||||
);
|
||||
}
|
||||
if (url.username !== "" || url.password !== "")
|
||||
return invalid(
|
||||
path,
|
||||
"Module context URLs must not contain username/password userinfo.",
|
||||
);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:")
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"web-module-resolution",
|
||||
OPERATION,
|
||||
"unsupported_context_scheme",
|
||||
{
|
||||
userMessage: `${path.join(".")} ${value} uses unsupported ${url.protocol} context. This trace currently supports HTTP(S) importer/map contexts; select a supported context explicitly when appropriate.`,
|
||||
},
|
||||
),
|
||||
);
|
||||
return ok(null);
|
||||
};
|
||||
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
|
||||
const invalid = (path: readonly string[], message: string) =>
|
||||
err(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{ path, reason: "invalid_format", message },
|
||||
]),
|
||||
);
|
||||
Reference in New Issue
Block a user