Skip to content

Commit 88afcc7

Browse files
committed
fix(javascript): retain endpoint candidates through graph projection
1 parent 6e34430 commit 88afcc7

9 files changed

Lines changed: 226 additions & 27 deletions

‎src/application/javascript/JavaScriptArtifactGraphContext.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ export interface AstEdgeInput {
7777
/** Inferred static relationship edge values. */
7878
export interface InferenceEdgeInput extends AstEdgeInput {
7979
readonly limitations?: readonly string[];
80+
readonly confidence?: "high" | "medium" | "low";
8081
readonly relation:
8182
| "imports"
8283
| "loads"
@@ -194,6 +195,9 @@ export const addStaticInferenceEdge = (
194195
range: input.range,
195196
operation: "map-static-relationship",
196197
coverage: input.coverage,
198+
...(input.confidence === undefined
199+
? {}
200+
: { confidence: input.confidence }),
197201
...(input.limitations === undefined
198202
? {}
199203
: { limitations: input.limitations }),

‎src/application/javascript/JavaScriptArtifactGraphFindings.ts‎

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -201,10 +201,17 @@ const addEndpoint = (
201201
input.value.module_runtime,
202202
) ?? input.asset;
203203
const key = compactStringIdentityKey(input.value.value);
204-
const label = `${input.value.kind} endpoint`;
204+
const candidate = input.value.interpretation === "candidate";
205+
const candidateLimitation =
206+
"The unbound method-like argument is only a candidate; its receiver does not establish a network call.";
207+
const label = `${input.value.kind} ${candidate ? "endpoint candidate" : "endpoint"}`;
205208
const node = context.accumulator.addNode({
206209
kind: "endpoint",
207-
identity: artifactLocalIdentity(input.file.sha256, input.value.kind, key),
210+
identity: artifactLocalIdentity(
211+
input.file.sha256,
212+
input.value.kind,
213+
JSON.stringify([input.value.interpretation ?? "literal", key]),
214+
),
208215
observations: [
209216
{
210217
label:
@@ -213,14 +220,25 @@ const addEndpoint = (
213220
endpoint_kind: input.value.kind,
214221
value: input.value.value,
215222
mechanism: input.value.mechanism,
223+
...(candidate ? { interpretation: input.value.interpretation } : {}),
216224
},
217-
evidence: astObservationEvidence({
218-
sha256: input.file.sha256,
219-
path: input.file.path,
220-
range: input.value.location,
221-
operation: "discover-static-endpoint",
222-
coverage: input.coverage,
223-
}),
225+
evidence: candidate
226+
? staticInferenceEvidence({
227+
sha256: input.file.sha256,
228+
path: input.file.path,
229+
range: input.value.location,
230+
operation: "classify-static-endpoint-candidate",
231+
coverage: input.coverage,
232+
confidence: "low",
233+
limitations: [candidateLimitation],
234+
})
235+
: astObservationEvidence({
236+
sha256: input.file.sha256,
237+
path: input.file.path,
238+
range: input.value.location,
239+
operation: "discover-static-endpoint",
240+
coverage: input.coverage,
241+
}),
224242
},
225243
],
226244
});
@@ -231,7 +249,16 @@ const addEndpoint = (
231249
range: input.value.location,
232250
coverage: input.coverage,
233251
relation: input.value.kind === "route" ? "exposes" : "calls",
234-
properties: { mechanism: input.value.mechanism },
252+
properties: {
253+
mechanism: input.value.mechanism,
254+
...(candidate ? { interpretation: input.value.interpretation } : {}),
255+
},
256+
...(candidate
257+
? {
258+
confidence: "low" as const,
259+
limitations: [candidateLimitation],
260+
}
261+
: {}),
235262
});
236263
};
237264

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { expect, it } from "vitest";
2+
3+
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
4+
5+
it("reads exact route-property templates and leaves interpolated values unknown", () => {
6+
const analysis = analyzeJavaScriptStaticSource(`
7+
const routes = [
8+
{ path: \`settings\` },
9+
{ route: \`users/\${userId}\` },
10+
{ path: "/login" },
11+
];
12+
`);
13+
14+
expect(
15+
analysis.endpoints.map(({ value, mechanism, interpretation }) => ({
16+
value,
17+
mechanism,
18+
interpretation,
19+
})),
20+
).toEqual([
21+
{
22+
value: "settings",
23+
mechanism: "property:path",
24+
interpretation: undefined,
25+
},
26+
{
27+
value: "/login",
28+
mechanism: "property:path",
29+
interpretation: undefined,
30+
},
31+
]);
32+
});

‎src/domain/javascript/javascriptStaticAnalysisCalls.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -420,11 +420,12 @@ export const inspectRouteProperty = (
420420
context: FindingContext,
421421
): void => {
422422
const key = semanticStaticPropertyName(node.key, node.computed);
423-
if ((key === "path" || key === "route") && t.isStringLiteral(node.value))
423+
const value = stringValue(node.value);
424+
if ((key === "path" || key === "route") && value !== undefined)
424425
addEndpoint(context, {
425426
node,
426427
kind: "route",
427-
value: node.value.value,
428+
value,
428429
mechanism: `property:${key}`,
429430
});
430431
};

‎src/domain/webBundleAnalyzer.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -902,6 +902,38 @@ const inspection = (source: string) =>
902902
limitations: [],
903903
});
904904

905+
it("recognizes expression-free template literals as route properties", () => {
906+
const result = analyzeCapturedWebBundle(
907+
inspection(`
908+
const routes = [
909+
{ path: \`score-board\`, component: ScoreBoard },
910+
{ route: \`administration\`, component: Admin },
911+
{ path: \`/user/\${name}\`, component: Dynamic },
912+
];
913+
`),
914+
);
915+
916+
expect(result.observations.routes.map(({ value }) => value)).toEqual([
917+
"score-board",
918+
"administration",
919+
]);
920+
});
921+
922+
it("uses the shared parser for decorated captured scripts", () => {
923+
const result = analyzeCapturedWebBundle(
924+
inspection(`@sealed class Widget {} fetch('/decorated');`),
925+
);
926+
927+
expect(result.completeness).toMatchObject({
928+
status: "complete",
929+
parsed_scripts: 1,
930+
parse_failures: 0,
931+
});
932+
expect(result.observations.endpoints).toEqual([
933+
expect.objectContaining({ value: "/decorated" }),
934+
]);
935+
});
936+
905937
it("keeps bare module locations unresolved without inventing URL-relative paths", () => {
906938
const result = analyzeCapturedWebBundle(
907939
inspection(`
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import * as t from "@babel/types";
2+
import { expect, it } from "vitest";
3+
4+
import { parseJavaScriptSource } from "./javascript/javascriptSourceParser.js";
5+
import { objectString } from "./webBundleAnalyzerAst.js";
6+
7+
it("reads WebMCP declaration strings through the exact-literal owner", () => {
8+
const file = parseJavaScriptSource(
9+
"const declaration = { name: `catalog`, description: `Browse catalog` }; const dynamic = { name: `catalog ${scope}` };",
10+
);
11+
const declaration = file?.program.body[0];
12+
if (!t.isVariableDeclaration(declaration))
13+
throw new Error("Expected declaration fixture");
14+
const object = declaration.declarations[0]?.init;
15+
if (!t.isObjectExpression(object))
16+
throw new Error("Expected object expression fixture");
17+
const dynamicDeclaration = file?.program.body[1];
18+
if (!t.isVariableDeclaration(dynamicDeclaration))
19+
throw new Error("Expected dynamic declaration fixture");
20+
const dynamic = dynamicDeclaration.declarations[0]?.init;
21+
if (!t.isObjectExpression(dynamic))
22+
throw new Error("Expected dynamic object expression fixture");
23+
24+
expect(objectString(object, "name")).toBe("catalog");
25+
expect(objectString(object, "description")).toBe("Browse catalog");
26+
expect(objectString(dynamic, "name")).toBeUndefined();
27+
});

‎src/domain/webBundleAnalyzerAst.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import * as t from "@babel/types";
22

33
import { sanitizeBrowserUrl } from "./browserObservation.js";
4-
import { semanticStaticPropertyName } from "./javascript/javascriptAstValues.js";
4+
import {
5+
readExactJavaScriptLiteral,
6+
semanticStaticPropertyName,
7+
} from "./javascript/javascriptAstValues.js";
58

69
/** Pick the endpoint argument for common network-call patterns. */
710

@@ -28,7 +31,11 @@ export const objectString = (
2831
name: string,
2932
): string | undefined => {
3033
const value = objectValue(object, name);
31-
return t.isStringLiteral(value) ? value.value : undefined;
34+
if (value === undefined) return undefined;
35+
const literal = readExactJavaScriptLiteral(value);
36+
return literal.found && typeof literal.value === "string"
37+
? literal.value
38+
: undefined;
3239
};
3340

3441
/** Whether module syntax supplies a URL location without a package/import-map resolver. */

‎src/domain/webBundleAnalyzerInspection.ts‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { parse } from "@babel/parser";
21
import * as t from "@babel/types";
32

43
import { sanitizeEndpointCandidate } from "./browserObservation.js";
@@ -29,6 +28,7 @@ import {
2928
isUrlLikeModuleSpecifier,
3029
} from "./webBundleAnalyzerAst.js";
3130
import { createJavaScriptRpcScan } from "./javascript/javascriptRpcEndpoints.js";
31+
import { parseJavaScriptSource } from "./javascript/javascriptSourceParser.js";
3232

3333
type BundleObservations = WebBundleAnalysis["observations"];
3434
type ChunkEdge = BundleObservations["chunks"]["edges"][number];
@@ -58,16 +58,8 @@ export const analyzeScript = (
5858
script: IncludedScript,
5959
accumulator: AnalysisAccumulator,
6060
): void => {
61-
let file: ReturnType<typeof parse>;
62-
try {
63-
file = parse(script.source.artifact.text, {
64-
sourceType: "unambiguous",
65-
errorRecovery: true,
66-
plugins: ["jsx", "typescript"],
67-
});
68-
} catch (cause: unknown) {
69-
// Unparseable scripts are counted; the failure needs no extra detail.
70-
void cause;
61+
const file = parseJavaScriptSource(script.source.artifact.text);
62+
if (file === null) {
7163
accumulator.failedScripts.push(script.script_key);
7264
return;
7365
}
@@ -216,11 +208,12 @@ const inspectRouteProperty = (
216208
accumulator: AnalysisAccumulator,
217209
): void => {
218210
const key = semanticStaticPropertyName(node.key, node.computed);
219-
if ((key === "path" || key === "route") && t.isStringLiteral(node.value))
211+
const route = stringValue(node.value);
212+
if ((key === "path" || key === "route") && route !== undefined)
220213
addFinding({
221214
collection: accumulator.routes,
222215
script,
223-
rawValue: node.value.value,
216+
rawValue: route,
224217
mechanism: `property:${key}`,
225218
node,
226219
accumulator,
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { rm, writeFile } from "node:fs/promises";
2+
import { join } from "node:path";
3+
4+
import { expect, it } from "vitest";
5+
6+
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
7+
import { scanCanonicalArtifactInventory } from "../../../fixtures/artifactInventory.js";
8+
import { readJavaScriptArtifactFiles } from "../../../support/javascriptApplicationScope.js";
9+
import { createJavaScriptArtifactReader } from "../../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
10+
import { analyzeJavaScriptArtifactFiles } from "../../../../src/application/javascript/JavaScriptArtifactAnalysis.js";
11+
import { buildJavaScriptArtifactGraph } from "../../../../src/application/javascript/JavaScriptArtifactGraphBuilder.js";
12+
13+
it("keeps ambiguous endpoint candidates inferred through artifact graph projection", async () => {
14+
const root = await createTestTempDirectory("rea-js-endpoint-certainty-");
15+
await writeFile(join(root, "app.js"), 'form.get("shared"); fetch("shared");');
16+
const snapshot = await scanCanonicalArtifactInventory(root, {});
17+
const reader = createJavaScriptArtifactReader(root, "directory");
18+
try {
19+
const files = await readJavaScriptArtifactFiles(reader, snapshot);
20+
const analysis = analyzeJavaScriptArtifactFiles(files);
21+
const graph = buildJavaScriptArtifactGraph(snapshot, files, analysis);
22+
const endpoints = graph.nodes.filter(({ kind }) => kind === "endpoint");
23+
const candidate = endpoints.find(({ observations }) =>
24+
observations.some(
25+
({ properties }) => properties.interpretation === "candidate",
26+
),
27+
);
28+
const observed = endpoints.find(({ observations }) =>
29+
observations.some(
30+
({ properties }) =>
31+
properties.value === "shared" &&
32+
properties.interpretation === undefined,
33+
),
34+
);
35+
36+
expect(candidate).toBeDefined();
37+
expect(observed).toBeDefined();
38+
expect(candidate?.node_id).not.toBe(observed?.node_id);
39+
const candidateObservation = candidate?.observations[0];
40+
expect(candidateObservation?.properties).toMatchObject({
41+
value: "shared",
42+
interpretation: "candidate",
43+
});
44+
expect(candidateObservation?.evidence).toMatchObject({
45+
authority: "static-relationship-inference",
46+
state: "inferred",
47+
confidence: "low",
48+
location: {
49+
available: true,
50+
value: { kind: "source-range", source: "app.js" },
51+
},
52+
});
53+
expect(candidateObservation?.evidence.limitations).toEqual(
54+
expect.arrayContaining([expect.stringContaining("only a candidate")]),
55+
);
56+
expect(observed?.observations[0]?.evidence).toMatchObject({
57+
authority: "ast-static-analysis",
58+
state: "observed",
59+
confidence: "exact",
60+
});
61+
const candidateEdge = graph.edges.find(
62+
({ target_node_id }) => target_node_id === candidate?.node_id,
63+
);
64+
expect(candidateEdge?.properties.interpretation).toBe("candidate");
65+
expect(candidateEdge?.evidence).toMatchObject({
66+
state: "inferred",
67+
confidence: "low",
68+
});
69+
expect(candidateEdge?.evidence.limitations).toEqual(
70+
expect.arrayContaining([expect.stringContaining("only a candidate")]),
71+
);
72+
} finally {
73+
await reader.close();
74+
await rm(root, { recursive: true, force: true });
75+
}
76+
});

0 commit comments

Comments
 (0)