Merge origin/main into feat/artifact-integrity-policy
Keep both new MCP extraction tests, use main's relocated Apple domain imports, and regenerate the catalog metadata. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -157,13 +157,12 @@ const nativeRequire = (
|
||||
):
|
||||
| { readonly specifier: string; readonly member: string | null }
|
||||
| undefined => {
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const nested = t.isNode(node.object)
|
||||
? nativeRequire(node.object)
|
||||
: undefined;
|
||||
if (nested === undefined) return undefined;
|
||||
const member = semanticStaticPropertyName(node.property, node.computed);
|
||||
return { ...nested, member: member === "" ? nested.member : member };
|
||||
let member: string | null = null;
|
||||
while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
if (!t.isNode(node.object)) return undefined;
|
||||
const property = semanticStaticPropertyName(node.property, node.computed);
|
||||
if (member === null && property !== "") member = property;
|
||||
node = node.object;
|
||||
}
|
||||
if (!t.isCallExpression(node)) return undefined;
|
||||
const name = calleeName(node.callee);
|
||||
@@ -175,7 +174,7 @@ const nativeRequire = (
|
||||
return undefined;
|
||||
const specifier = stringValue(argumentNode(node.arguments[0]));
|
||||
return specifier !== undefined && isNativeSpecifier(specifier, "require")
|
||||
? { specifier, member: null }
|
||||
? { specifier, member }
|
||||
: undefined;
|
||||
};
|
||||
|
||||
|
||||
@@ -119,14 +119,30 @@ const addExport = (output: Set<string>, name: string): void => {
|
||||
};
|
||||
|
||||
const memberPath = (node: t.Node | null | undefined): string => {
|
||||
if (node === undefined || node === null) return "";
|
||||
if (t.isIdentifier(node) || t.isPrivateName(node))
|
||||
return t.isIdentifier(node) ? node.name : "";
|
||||
if (t.isThisExpression(node)) return "this";
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const object = t.isNode(node.object) ? memberPath(node.object) : "";
|
||||
const property = propertyName(node.property);
|
||||
return object === "" ? property : `${object}.${property}`;
|
||||
const properties: string[] = [];
|
||||
let current = node;
|
||||
while (
|
||||
current !== undefined &&
|
||||
current !== null &&
|
||||
(t.isMemberExpression(current) || t.isOptionalMemberExpression(current))
|
||||
) {
|
||||
properties.push(propertyName(current.property));
|
||||
current = t.isNode(current.object) ? current.object : undefined;
|
||||
}
|
||||
return "";
|
||||
|
||||
const root =
|
||||
current !== undefined && t.isIdentifier(current)
|
||||
? current.name
|
||||
: current !== undefined && t.isThisExpression(current)
|
||||
? "this"
|
||||
: "";
|
||||
if (properties.length === 0) return root;
|
||||
|
||||
properties.reverse();
|
||||
const path = root === "" ? [] : [root];
|
||||
for (const property of properties) {
|
||||
if (path.length === 0 && property === "") continue;
|
||||
path.push(property);
|
||||
}
|
||||
return path.join(".");
|
||||
};
|
||||
|
||||
@@ -192,6 +192,51 @@ describe("JavaScript semantic analysis: calls 2", () => {
|
||||
).not.toBe(left.functionFingerprints[0]?.components.literalSetSha256);
|
||||
});
|
||||
|
||||
it("keeps fingerprint relations ordered and effects scoped to their owner", () => {
|
||||
const ordered = analyzeJavaScriptSemantics(`
|
||||
function first() {}
|
||||
function second(one, two) {}
|
||||
function ordered() { first(); second(1, 2); }
|
||||
function timerOwner() { setTimeout(work, 10); }
|
||||
function networkOwner() { fetch('/data'); }
|
||||
function noEffects() { return 1; }
|
||||
`);
|
||||
const reversed = analyzeJavaScriptSemantics(`
|
||||
function first() {}
|
||||
function second(one, two) {}
|
||||
function ordered() { second(1, 2); first(); }
|
||||
function timerOwner() { setTimeout(work, 10); }
|
||||
function networkOwner() { fetch('/data'); }
|
||||
function noEffects() { return 1; }
|
||||
`);
|
||||
const fingerprint = (ir: typeof ordered, name: string) =>
|
||||
ir.functionFingerprints.find((value) =>
|
||||
ir.callables.some(
|
||||
(callable) =>
|
||||
callable.callableId === value.callableId && callable.name === name,
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
fingerprint(ordered, "ordered")?.components.relationShapeSha256,
|
||||
).not.toBe(
|
||||
fingerprint(reversed, "ordered")?.components.relationShapeSha256,
|
||||
);
|
||||
expect(fingerprint(ordered, "timerOwner")?.components.effects).toContain(
|
||||
"timer",
|
||||
);
|
||||
expect(fingerprint(ordered, "networkOwner")?.components.effects).toContain(
|
||||
"network",
|
||||
);
|
||||
expect(fingerprint(ordered, "noEffects")?.components.effects).toEqual([]);
|
||||
expect(
|
||||
fingerprint(ordered, "timerOwner")?.components.effects,
|
||||
).not.toContain("network");
|
||||
expect(
|
||||
fingerprint(ordered, "networkOwner")?.components.effects,
|
||||
).not.toContain("timer");
|
||||
});
|
||||
|
||||
it("retains ambiguous local callees and explicit dynamic frontiers", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function left(value) { return value; }
|
||||
|
||||
@@ -149,6 +149,31 @@ describe("JavaScript semantic analysis: dataflow 1", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript semantic call result flows", () => {
|
||||
it("links only directly assigned scalar call results", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function run() {
|
||||
const direct = produce();
|
||||
const { field } = unpack();
|
||||
const nested = outer(inner());
|
||||
return direct;
|
||||
}
|
||||
`);
|
||||
const bindingNames = new Map(
|
||||
ir.bindings.map(({ bindingId, name }) => [bindingId, name]),
|
||||
);
|
||||
|
||||
expect(
|
||||
ir.callResultFlows.map(({ bindingId }) => bindingNames.get(bindingId)),
|
||||
).toEqual(["direct", "nested"]);
|
||||
expect(ir.callSites).toHaveLength(4);
|
||||
expect(ir.callResultFlows.map(({ callSiteId }) => callSiteId)).toEqual([
|
||||
ir.callSites[0]?.callSiteId,
|
||||
ir.callSites[2]?.callSiteId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript semantic analysis: read-modify-write", () => {
|
||||
it.each(["+= 1", "++", "--", "||= 1", "&&= 1", "??= 1"])(
|
||||
"retains the property read in a read-modify-write operation: %s",
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import * as t from "@babel/types";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
import { onlyBinding, origin } from "./javascriptSemanticAnalysis.fixture.js";
|
||||
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
|
||||
import { calleeName } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
|
||||
|
||||
const memberChain = ".next".repeat(12_000);
|
||||
|
||||
it("retains native addon observations through a deep member initializer", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(
|
||||
`const value = require("./addon.node")${memberChain}.last[""];`,
|
||||
);
|
||||
expect(analysis.electron.native_addon_bindings).toEqual([
|
||||
expect.objectContaining({ specifier: "./addon.node", members: ["last"] }),
|
||||
]);
|
||||
expect(analysis.parse_error_count).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps a deep non-native initializer outside native addon observations", () => {
|
||||
const analysis = analyzeJavaScriptStaticSource(
|
||||
`const value = root${memberChain}.last;`,
|
||||
);
|
||||
expect(analysis.electron.native_addon_bindings).toEqual([]);
|
||||
expect(analysis.parse_status).toBe("complete");
|
||||
});
|
||||
|
||||
it("retains unknown value diagnostics and references after a deep member initializer", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`const value = root${memberChain}.last;`,
|
||||
);
|
||||
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
|
||||
expect(onlyBinding(ir, "value")).toMatchObject({
|
||||
value: { status: "unknown", reason: "Cannot project last from unknown." },
|
||||
provenance: { status: "unknown", reason: "Unbound identifier root." },
|
||||
});
|
||||
expect(ir.references.map(({ name, role }) => ({ name, role }))).toEqual([
|
||||
{ name: "root", role: "read" },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
`const value = require("./dependency.js")${memberChain}[""].last;`,
|
||||
`const dependency = require("./dependency.js"); const value = dependency${memberChain}[""].last;`,
|
||||
`const value = require("./dependency.js")?.next${memberChain}[""].last;`,
|
||||
])("preserves the full literal module path (case %#)", (source) => {
|
||||
const ir = analyzeJavaScriptSemantics(source);
|
||||
const path = origin(onlyBinding(ir, "value"));
|
||||
expect(path.specifier).toBe("./dependency.js");
|
||||
expect(path.importedPath).toEqual([
|
||||
...(source.includes("?.next") ? ["next"] : []),
|
||||
...Array.from({ length: 12_000 }, () => "next"),
|
||||
"",
|
||||
"last",
|
||||
]);
|
||||
expect(ir.coverage.status).toBe("complete");
|
||||
});
|
||||
|
||||
it("retains a deep CommonJS re-export path without inventing dynamic module links", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
module.exports.result = require("./dependency.js")${memberChain}.last;
|
||||
const dynamic = require("./other.js")${memberChain}[key].last;
|
||||
`);
|
||||
expect(ir.moduleLinks).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: "commonjs-export",
|
||||
specifier: "./dependency.js",
|
||||
importedName: "last",
|
||||
exportedName: "result",
|
||||
}),
|
||||
]);
|
||||
expect(onlyBinding(ir, "dynamic").provenance).toMatchObject({
|
||||
status: "unknown",
|
||||
reason: "Dynamic provenance member.",
|
||||
});
|
||||
});
|
||||
|
||||
it("invalidates a deep mutation while retaining unrelated literal properties", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
const root = { untouched: "retained" };
|
||||
root${memberChain}.last = 1;
|
||||
const value = root.untouched;
|
||||
`);
|
||||
expect(onlyBinding(ir, "root").value).toEqual({
|
||||
status: "object",
|
||||
properties: [
|
||||
{ name: "untouched", value: { status: "literal", value: "retained" } },
|
||||
],
|
||||
unknownProperties: true,
|
||||
omittedProperties: null,
|
||||
});
|
||||
expect(onlyBinding(ir, "value").value).toEqual({
|
||||
status: "literal",
|
||||
value: "retained",
|
||||
});
|
||||
});
|
||||
|
||||
it("retains the complete location and unresolved target of a deep call", () => {
|
||||
const callee = `root${memberChain}.last`;
|
||||
const ir = analyzeJavaScriptSemantics(`${callee}();`);
|
||||
expect(ir.callSites).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: "call",
|
||||
resolution: "unresolved",
|
||||
calleeCallableIds: [],
|
||||
calleeLocation: {
|
||||
start: { line: 1, column: 0 },
|
||||
end: { line: 1, column: callee.length },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains deep default values without confusing their reads with parameter bindings", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`export function inspect(value = root${memberChain}.last) { return value; }`,
|
||||
);
|
||||
expect(ir.references.map(({ name, role }) => ({ name, role }))).toEqual([
|
||||
{ name: "root", role: "read" },
|
||||
{ name: "value", role: "read" },
|
||||
]);
|
||||
expect(ir.coverage.status).toBe("complete");
|
||||
});
|
||||
|
||||
it("keeps a shadowed require local through a deep member initializer", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`function inspect(require) { const value = require("./dependency.js")${memberChain}.last; return value; }`,
|
||||
);
|
||||
expect(ir.moduleLinks).toEqual([]);
|
||||
expect(onlyBinding(ir, "value").provenance.origins).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["root.first.last()", "root.first.last"],
|
||||
['root[""].last()', "root..last"],
|
||||
['("")[""].last()', "last"],
|
||||
['("")[""]()', ""],
|
||||
["root[0].last()", "root.0.last"],
|
||||
["root[key].last()", "root.[computed@5].last"],
|
||||
["root?.first.last()", "root.first.last"],
|
||||
[`root${memberChain}.last()`, `root${memberChain}.last`],
|
||||
])("preserves exact callee syntax (case %#)", (source, expected) => {
|
||||
const file = parseJavaScriptSource(source);
|
||||
const statement = file?.program.body[0];
|
||||
if (
|
||||
!t.isExpressionStatement(statement) ||
|
||||
(!t.isCallExpression(statement.expression) &&
|
||||
!t.isOptionalCallExpression(statement.expression))
|
||||
)
|
||||
throw new Error("Expected parsed call expression");
|
||||
expect(calleeName(statement.expression.callee)).toBe(expected);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
|
||||
describe("JavaScript semantic analysis: recovered arguments", () => {
|
||||
it.each([
|
||||
{ source: "0(,)", indexes: [] },
|
||||
{ source: 'call(, "kept", , 42)', indexes: [1, 3] },
|
||||
{ source: 'call?.(, "kept")', indexes: [1] },
|
||||
{ source: 'new Thing(, "kept")', indexes: [1] },
|
||||
])(
|
||||
"retains argument positions in recovered syntax: $source",
|
||||
({ source, indexes }) => {
|
||||
const ir = analyzeJavaScriptSemantics(source);
|
||||
|
||||
expect(ir.coverage.status).toBe("partial");
|
||||
expect(ir.callSites).toHaveLength(1);
|
||||
expect(ir.callSites[0]?.arguments.map(({ index }) => index)).toEqual(
|
||||
indexes,
|
||||
);
|
||||
expect(ir.limitations.join(" ")).toMatch(/parser recovered/iu);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps recovered argument flows bound to their original parameter", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
"function select(first, second) { return second; } const value = 42; select(, value);",
|
||||
);
|
||||
const second = ir.bindings.find(({ name }) => name === "second");
|
||||
|
||||
expect(ir.coverage.status).toBe("partial");
|
||||
expect(second).toBeDefined();
|
||||
expect(ir.argumentFlows).toEqual([
|
||||
expect.objectContaining({
|
||||
argumentIndex: 1,
|
||||
parameterBindingId: second?.bindingId,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -183,9 +183,7 @@ const collectCallResultFlow = (
|
||||
context.ancestors,
|
||||
context.state,
|
||||
).filter(({ projectionPath }) => projectionPath.length === 0)) {
|
||||
const binding = [...context.state.bindingsById.values()].find(
|
||||
({ bindingId }) => bindingId === assigned.bindingId,
|
||||
);
|
||||
const binding = context.state.bindingsById.get(assigned.bindingId);
|
||||
if (binding === undefined) continue;
|
||||
const identifierRange = range(assigned.identifier);
|
||||
const definition = binding.definitions.find(
|
||||
@@ -210,10 +208,13 @@ const retainedArguments = (
|
||||
| t.SpreadElement
|
||||
| t.JSXNamespacedName
|
||||
| t.ArgumentPlaceholder
|
||||
| null
|
||||
)[],
|
||||
): JavaScriptSemanticCallSite["arguments"] => {
|
||||
const retained: JavaScriptSemanticCallSite["arguments"][number][] = [];
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
// Babel recovery can leave null slots; retain the other argument positions.
|
||||
if (node === null) continue;
|
||||
retained.push({
|
||||
index,
|
||||
location: range(node),
|
||||
|
||||
@@ -50,30 +50,36 @@ export const collectJavaScriptSemanticFingerprints = (
|
||||
resourceOperations,
|
||||
parserPartial,
|
||||
} = input;
|
||||
const callSitesByCaller = groupByOwner(
|
||||
calls.callSites,
|
||||
({ callerCallableId }) => callerCallableId,
|
||||
);
|
||||
const captureCountByCallable = countByOwner(
|
||||
calls.closureCaptures,
|
||||
({ callableId }) => callableId,
|
||||
);
|
||||
const promiseEffectsByOwner = groupByOwner(promises, ownerId);
|
||||
const eventEffectsByOwner = groupByOwner(events, ownerId);
|
||||
const timerEffectsByOwner = groupByOwner(timers, ownerId);
|
||||
const childProcessEffectsByOwner = groupByOwner(
|
||||
[...childProcessSpawns, ...childProcessInteractions],
|
||||
ownerId,
|
||||
);
|
||||
const networkEffectsByOwner = groupByOwner(requestOperations, ownerId);
|
||||
const resourceEffectsByOwner = groupByOwner(resourceOperations, ownerId);
|
||||
return callables.flatMap((callable) => {
|
||||
if (callable.kind === "class") return [];
|
||||
const node = state.callableNodesById.get(callable.callableId);
|
||||
if (node === undefined) return [];
|
||||
const syntax = fingerprintSyntax(node, callable.callableId);
|
||||
const promiseEffects = promises.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const eventEffects = events.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const timerEffects = timers.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const childProcessEffects = [
|
||||
...childProcessSpawns,
|
||||
...childProcessInteractions,
|
||||
].filter(({ ownerCallableId }) => ownerCallableId === callable.callableId);
|
||||
const networkEffects = requestOperations.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const resourceEffects = resourceOperations.filter(
|
||||
({ ownerCallableId }) => ownerCallableId === callable.callableId,
|
||||
);
|
||||
const promiseEffects = promiseEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const eventEffects = eventEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const timerEffects = timerEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const childProcessEffects =
|
||||
childProcessEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const networkEffects = networkEffectsByOwner.get(callable.callableId) ?? [];
|
||||
const resourceEffects =
|
||||
resourceEffectsByOwner.get(callable.callableId) ?? [];
|
||||
return [
|
||||
{
|
||||
callableId: callable.callableId,
|
||||
@@ -86,7 +92,12 @@ export const collectJavaScriptSemanticFingerprints = (
|
||||
normalizedAstSha256: digest(syntax.normalizedTokens),
|
||||
controlFlowSha256: digest(syntax.controlFlowTokens),
|
||||
relationShapeSha256: digest(
|
||||
relationShape(callable, calls, promiseEffects),
|
||||
relationShape(
|
||||
callable,
|
||||
callSitesByCaller.get(callable.callableId) ?? [],
|
||||
captureCountByCallable.get(callable.callableId) ?? 0,
|
||||
promiseEffects,
|
||||
),
|
||||
),
|
||||
literalSetSha256: digest(
|
||||
[...new Set(syntax.literals)].sort(compareCodePoints),
|
||||
@@ -114,6 +125,36 @@ export const collectJavaScriptSemanticFingerprints = (
|
||||
});
|
||||
};
|
||||
|
||||
const ownerId = <T extends { readonly ownerCallableId: string | null }>(
|
||||
value: T,
|
||||
): string | null => value.ownerCallableId;
|
||||
|
||||
const groupByOwner = <T, K extends string | null>(
|
||||
values: readonly T[],
|
||||
getOwner: (value: T) => K,
|
||||
): Map<K, T[]> => {
|
||||
const grouped = new Map<K, T[]>();
|
||||
for (const value of values) {
|
||||
const owner = getOwner(value);
|
||||
const ownedValues = grouped.get(owner);
|
||||
if (ownedValues === undefined) grouped.set(owner, [value]);
|
||||
else ownedValues.push(value);
|
||||
}
|
||||
return grouped;
|
||||
};
|
||||
|
||||
const countByOwner = <T, K extends string | null>(
|
||||
values: readonly T[],
|
||||
getOwner: (value: T) => K,
|
||||
): Map<K, number> => {
|
||||
const counts = new Map<K, number>();
|
||||
for (const value of values) {
|
||||
const owner = getOwner(value);
|
||||
counts.set(owner, (counts.get(owner) ?? 0) + 1);
|
||||
}
|
||||
return counts;
|
||||
};
|
||||
|
||||
interface FingerprintSyntax {
|
||||
readonly normalizedTokens: readonly string[];
|
||||
readonly controlFlowTokens: readonly string[];
|
||||
@@ -229,21 +270,16 @@ const semanticLiteral = (node: t.Node): string | null => {
|
||||
|
||||
const relationShape = (
|
||||
callable: JavaScriptSemanticCallable,
|
||||
calls: JavaScriptSemanticCallAnalysis,
|
||||
callSites: JavaScriptSemanticCallAnalysis["callSites"],
|
||||
captureCount: number,
|
||||
promises: readonly JavaScriptSemanticPromiseOperation[],
|
||||
): string[] => [
|
||||
`returns:${String(callable.returnSites.length)}:${callable.returnCoverage.status}`,
|
||||
...calls.callSites
|
||||
.filter(({ callerCallableId }) => callerCallableId === callable.callableId)
|
||||
.map(
|
||||
({ kind, resolution, arguments: args, calleeCallableIds }) =>
|
||||
`call:${kind}:${resolution}:${String(args.length)}:${String(calleeCallableIds.length)}`,
|
||||
),
|
||||
`captures:${String(
|
||||
calls.closureCaptures.filter(
|
||||
({ callableId }) => callableId === callable.callableId,
|
||||
).length,
|
||||
)}`,
|
||||
...callSites.map(
|
||||
({ kind, resolution, arguments: args, calleeCallableIds }) =>
|
||||
`call:${kind}:${resolution}:${String(args.length)}:${String(calleeCallableIds.length)}`,
|
||||
),
|
||||
`captures:${String(captureCount)}`,
|
||||
...promises.map(
|
||||
({ kind, method, ownership, sourceResolution }) =>
|
||||
`promise:${kind}:${method}:${ownership}:${sourceResolution}`,
|
||||
|
||||
@@ -39,11 +39,18 @@ export const collectSemanticMemberMutations = (
|
||||
return;
|
||||
}
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
markValue(
|
||||
node.object,
|
||||
[semanticStaticPropertyKey(node.property, node.computed), ...path],
|
||||
bindings,
|
||||
);
|
||||
const members: (string | null)[] = [];
|
||||
let current: t.Node = node;
|
||||
while (
|
||||
t.isMemberExpression(current) ||
|
||||
t.isOptionalMemberExpression(current)
|
||||
) {
|
||||
members.push(
|
||||
semanticStaticPropertyKey(current.property, current.computed),
|
||||
);
|
||||
current = current.object;
|
||||
}
|
||||
markValue(current, [...members.reverse(), ...path], bindings);
|
||||
return;
|
||||
}
|
||||
for (const value of referencedValues(node, path))
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticBinding,
|
||||
JavaScriptSemanticModuleLink,
|
||||
JavaScriptSemanticReference,
|
||||
@@ -14,6 +13,7 @@ import {
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
type JavaScriptSemanticScopeState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
|
||||
import { compareCodePoints } from "../canonicalOrdering.js";
|
||||
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
|
||||
import {
|
||||
@@ -100,12 +100,16 @@ export const collectSemanticReferences = (
|
||||
): JavaScriptSemanticReference[] => {
|
||||
const output: JavaScriptSemanticReference[] = [];
|
||||
const seen = new Set<string>();
|
||||
const patterns: t.Node[] = [];
|
||||
traverseJavaScriptAst(program, {
|
||||
enter: (node, parent, readAncestors) => {
|
||||
if (isPatternNode(node)) patterns.push(node);
|
||||
if (
|
||||
!t.isIdentifier(node) ||
|
||||
parent === null ||
|
||||
(name !== undefined && node.name !== name)
|
||||
(name !== undefined && node.name !== name) ||
|
||||
(isNonReferenceKey(node, parent) &&
|
||||
!patterns.some((pattern) => bindsIdentifier(pattern, parent, node)))
|
||||
)
|
||||
return;
|
||||
const role = semanticIdentifierRole(node, parent, readAncestors());
|
||||
@@ -138,6 +142,9 @@ export const collectSemanticReferences = (
|
||||
});
|
||||
}
|
||||
},
|
||||
exit: (node) => {
|
||||
if (isPatternNode(node)) patterns.pop();
|
||||
},
|
||||
});
|
||||
return output;
|
||||
};
|
||||
@@ -174,40 +181,6 @@ export const immutableSemanticBindings = (
|
||||
}))
|
||||
.sort((left, right) => compareCodePoints(left.bindingId, right.bindingId));
|
||||
|
||||
/** Recover a literal require origin plus an optional member chain. */
|
||||
const semanticModuleOrigin = (
|
||||
node: t.Node | null | undefined,
|
||||
projection: readonly (string | number | null)[],
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptModuleOrigin | undefined => {
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const nested = t.isNode(node.object)
|
||||
? semanticModuleOrigin(node.object, projection, state)
|
||||
: undefined;
|
||||
const member = semanticStaticPropertyKey(node.property, node.computed);
|
||||
return nested === undefined || member === null
|
||||
? undefined
|
||||
: { ...nested, importedPath: [...nested.importedPath, member] };
|
||||
}
|
||||
if (
|
||||
!t.isCallExpression(node) ||
|
||||
!t.isIdentifier(node.callee, { name: "require" })
|
||||
)
|
||||
return undefined;
|
||||
if (
|
||||
resolveSemanticBindingState(state, node.callee, "require") !== undefined ||
|
||||
semanticResolutionBlocked(state, node.callee, "require")
|
||||
)
|
||||
return undefined;
|
||||
const specifier = stringValue(node.arguments[0]);
|
||||
return specifier === undefined || projection.includes(null)
|
||||
? undefined
|
||||
: {
|
||||
specifier,
|
||||
importedPath: projection.map((segment) => String(segment)),
|
||||
};
|
||||
};
|
||||
|
||||
export {
|
||||
semanticStaticPropertyKey,
|
||||
semanticStaticPropertyName,
|
||||
@@ -318,7 +291,7 @@ const collectRequireLink = (
|
||||
node: t.VariableDeclarator,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
const origin = semanticModuleOrigin(node.init, [], state);
|
||||
const origin = semanticRequireOrigin(node.init, state);
|
||||
if (origin === undefined) return;
|
||||
for (const binding of requirePatternBindings(node.id, origin.importedPath))
|
||||
addModuleLink(state, {
|
||||
@@ -364,7 +337,7 @@ const collectCommonJsExport = (
|
||||
): void => {
|
||||
const exportedName = commonJsExportName(node.left, state);
|
||||
if (exportedName === undefined) return;
|
||||
const origin = semanticModuleOrigin(node.right, [], state);
|
||||
const origin = semanticRequireOrigin(node.right, state);
|
||||
addModuleLink(state, {
|
||||
kind: "commonjs-export",
|
||||
specifier: origin?.specifier ?? null,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type { JavaScriptModuleOrigin } from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
resolveSemanticBindingState,
|
||||
semanticResolutionBlocked,
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
|
||||
import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
/** Recover an unshadowed literal require origin and its exact member path. */
|
||||
export const semanticRequireOrigin = (
|
||||
node: t.Node | null | undefined,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptModuleOrigin | undefined => {
|
||||
const members: string[] = [];
|
||||
while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const member = semanticStaticPropertyKey(node.property, node.computed);
|
||||
if (member === null || !t.isNode(node.object)) return undefined;
|
||||
members.push(member);
|
||||
node = node.object;
|
||||
}
|
||||
if (
|
||||
!t.isCallExpression(node) ||
|
||||
!t.isIdentifier(node.callee, { name: "require" })
|
||||
)
|
||||
return undefined;
|
||||
if (
|
||||
resolveSemanticBindingState(state, node.callee, "require") !== undefined ||
|
||||
semanticResolutionBlocked(state, node.callee, "require")
|
||||
)
|
||||
return undefined;
|
||||
const specifier = stringValue(node.arguments[0]);
|
||||
return specifier === undefined
|
||||
? undefined
|
||||
: { specifier, importedPath: members.reverse() };
|
||||
};
|
||||
@@ -51,3 +51,16 @@ it("preserves source-tree enter/exit order and detached ancestor snapshots", ()
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips sparse child slots without disturbing sibling visit order", () => {
|
||||
const parsed = parseJavaScriptSource("const values = [first, , second];");
|
||||
if (parsed === null)
|
||||
throw new TypeError("Expected a parsed JavaScript fixture");
|
||||
const identifiers: string[] = [];
|
||||
traverseJavaScriptAst(parsed.program, {
|
||||
enter: (node) => {
|
||||
if (t.isIdentifier(node)) identifiers.push(node.name);
|
||||
},
|
||||
});
|
||||
expect(identifiers).toEqual(["values", "first", "second"]);
|
||||
});
|
||||
|
||||
@@ -51,11 +51,19 @@ interface TraversalFrame {
|
||||
}
|
||||
|
||||
const childNodes = (node: t.Node): t.Node[] => {
|
||||
const keys: readonly string[] = t.VISITOR_KEYS[node.type] ?? [];
|
||||
return keys.flatMap((key) => {
|
||||
const keys = t.VISITOR_KEYS[node.type];
|
||||
if (keys === undefined) return [];
|
||||
const children: t.Node[] = [];
|
||||
for (const key of keys) {
|
||||
const value: unknown = Reflect.get(node, key);
|
||||
if (t.isNode(value)) return [value];
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter((item): item is t.Node => t.isNode(item));
|
||||
});
|
||||
if (t.isNode(value)) {
|
||||
children.push(value);
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(value)) continue;
|
||||
for (const item of value) {
|
||||
if (t.isNode(item)) children.push(item);
|
||||
}
|
||||
}
|
||||
return children;
|
||||
};
|
||||
|
||||
@@ -4,17 +4,15 @@ import { invalidateSemanticMutationPath } from "./javascriptSemanticMutationValu
|
||||
|
||||
import type {
|
||||
JavaScriptBindingProvenance,
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticProperty,
|
||||
JavaScriptSemanticValue,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
resolveSemanticBindingState,
|
||||
semanticResolutionBlocked,
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
type JavaScriptSemanticBindingState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
|
||||
import { compareCodePoints } from "../canonicalOrdering.js";
|
||||
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
|
||||
import {
|
||||
@@ -253,15 +251,28 @@ const evaluateMember = (
|
||||
node: t.MemberExpression | t.OptionalMemberExpression,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
if (!t.isNode(node.object))
|
||||
return { status: "unknown", reason: "Unsupported member base." };
|
||||
const key =
|
||||
semanticStaticPropertyKey(node.property, node.computed) ?? undefined;
|
||||
if (key === undefined)
|
||||
return { status: "unknown", reason: "Dynamic member key." };
|
||||
return projectValue(evaluateExpression(node.object, nestedContext(context)), [
|
||||
key,
|
||||
]);
|
||||
const keys: string[] = [];
|
||||
let current: t.Node = node;
|
||||
let value: JavaScriptSemanticValue | undefined;
|
||||
while (
|
||||
t.isMemberExpression(current) ||
|
||||
t.isOptionalMemberExpression(current)
|
||||
) {
|
||||
if (!t.isNode(current.object)) {
|
||||
value = { status: "unknown", reason: "Unsupported member base." };
|
||||
break;
|
||||
}
|
||||
const key = semanticStaticPropertyKey(current.property, current.computed);
|
||||
if (key === null) {
|
||||
value = { status: "unknown", reason: "Dynamic member key." };
|
||||
break;
|
||||
}
|
||||
keys.push(key);
|
||||
current = current.object;
|
||||
}
|
||||
value ??= evaluateExpression(current, nestedContext(context));
|
||||
for (const key of keys.reverse()) value = projectValue(value, [key]);
|
||||
return value;
|
||||
};
|
||||
|
||||
const evaluateAddition = (
|
||||
@@ -425,7 +436,7 @@ const provenanceForExpression = (
|
||||
node: t.Node,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptBindingProvenance => {
|
||||
const required = requireOrigin(node, context.state);
|
||||
const required = semanticRequireOrigin(node, context.state);
|
||||
if (required !== undefined) return semanticOriginsProvenance([required]);
|
||||
if (t.isIdentifier(node)) {
|
||||
const binding = resolveSemanticBindingState(context.state, node, node.name);
|
||||
@@ -437,25 +448,37 @@ const provenanceForExpression = (
|
||||
: provenanceForBinding(binding, nestedContext(context));
|
||||
}
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
if (!t.isNode(node.object))
|
||||
return semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
"Unsupported member base.",
|
||||
const members: string[] = [];
|
||||
let current: t.Node = node;
|
||||
while (
|
||||
t.isMemberExpression(current) ||
|
||||
t.isOptionalMemberExpression(current)
|
||||
) {
|
||||
if (!t.isNode(current.object))
|
||||
return semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
"Unsupported member base.",
|
||||
);
|
||||
const member = semanticStaticPropertyKey(
|
||||
current.property,
|
||||
current.computed,
|
||||
);
|
||||
const member =
|
||||
semanticStaticPropertyKey(node.property, node.computed) ?? undefined;
|
||||
if (typeof member !== "string")
|
||||
return semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
"Dynamic provenance member.",
|
||||
);
|
||||
const base = provenanceForExpression(node.object, nestedContext(context));
|
||||
if (member === null)
|
||||
return semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
"Dynamic provenance member.",
|
||||
);
|
||||
members.push(member);
|
||||
current = current.object;
|
||||
}
|
||||
const base = provenanceForExpression(current, nestedContext(context));
|
||||
const path = members.reverse();
|
||||
return base.status !== "module"
|
||||
? base
|
||||
: semanticOriginsProvenance(
|
||||
base.origins.map((origin) => ({
|
||||
...origin,
|
||||
importedPath: [...origin.importedPath, member],
|
||||
importedPath: [...origin.importedPath, ...path],
|
||||
})),
|
||||
);
|
||||
}
|
||||
@@ -480,33 +503,6 @@ const provenanceForExpression = (
|
||||
return semanticLocalProvenance();
|
||||
};
|
||||
|
||||
const requireOrigin = (
|
||||
node: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptModuleOrigin | undefined => {
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
if (!t.isNode(node.object)) return undefined;
|
||||
const nested = requireOrigin(node.object, state);
|
||||
const member =
|
||||
semanticStaticPropertyKey(node.property, node.computed) ?? undefined;
|
||||
return nested === undefined || typeof member !== "string"
|
||||
? undefined
|
||||
: { ...nested, importedPath: [...nested.importedPath, member] };
|
||||
}
|
||||
if (
|
||||
!t.isCallExpression(node) ||
|
||||
!t.isIdentifier(node.callee, { name: "require" })
|
||||
)
|
||||
return undefined;
|
||||
if (
|
||||
resolveSemanticBindingState(state, node.callee, "require") !== undefined ||
|
||||
semanticResolutionBlocked(state, node.callee, "require")
|
||||
)
|
||||
return undefined;
|
||||
const specifier = stringValue(node.arguments[0]);
|
||||
return specifier === undefined ? undefined : { specifier, importedPath: [] };
|
||||
};
|
||||
|
||||
const mergeValues = (
|
||||
values: readonly JavaScriptSemanticValue[],
|
||||
): JavaScriptSemanticValue => {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { collectJavaScriptExports } from "./javascriptAstFingerprint.js";
|
||||
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
|
||||
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
|
||||
|
||||
const memberChain = ".next".repeat(12_000);
|
||||
|
||||
it("collects a 12,000-member CommonJS export path without recursion", () => {
|
||||
const file = parseJavaScriptSource(`exports${memberChain}.last = 1;`);
|
||||
if (file === null) throw new Error("Expected valid JavaScript");
|
||||
expect(collectJavaScriptExports(file).values).toEqual([
|
||||
`${"next.".repeat(12_000)}last`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves empty, dynamic, this, and private member path behavior", () => {
|
||||
const file = parseJavaScriptSource(`
|
||||
exports[""].value = 1;
|
||||
exports[""] = 0;
|
||||
exports[key].value = 2;
|
||||
this.exports.ignored = 3;
|
||||
class Example { #private = 0; read() { this.#private = 1; } }
|
||||
`);
|
||||
if (file === null) throw new Error("Expected valid JavaScript");
|
||||
expect(collectJavaScriptExports(file).values).toEqual([
|
||||
"",
|
||||
".value",
|
||||
"key.value",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps left-first and outer-member-first bundler runtime matches", () => {
|
||||
const source = `
|
||||
(globalThis.webpackChunkLeft || globalThis.webpackChunkRight).push([[1], { 1: function() {} }]);
|
||||
globalThis.webpackChunkOuter.webpackChunkInner.push([[2], { 2: function() {} }]);
|
||||
`;
|
||||
const analysis = analyzeJavaScriptStaticSource(source);
|
||||
expect(
|
||||
analysis.bundler_registrations.find(({ chunk_keys }) =>
|
||||
chunk_keys.includes("1"),
|
||||
)?.runtime,
|
||||
).toBe("webpackChunkLeft");
|
||||
expect(
|
||||
analysis.bundler_registrations.find(({ chunk_keys }) =>
|
||||
chunk_keys.includes("2"),
|
||||
)?.runtime,
|
||||
).toBe("webpackChunkInner");
|
||||
});
|
||||
|
||||
it("analyzes a 12,000-member bundler runtime chain without recursion", () => {
|
||||
const source = `globalThis.webpackChunkApp${memberChain}.push([[1], { 1: function(module) { module.exports.ok = 42; } }]);`;
|
||||
const analysis = analyzeJavaScriptStaticSource(source);
|
||||
expect(analysis.parse_status).toBe("complete");
|
||||
expect(analysis.parse_error_count).toBe(0);
|
||||
expect(analysis.bundler_registrations).toHaveLength(1);
|
||||
expect(analysis.bundler_registrations[0]).toMatchObject({
|
||||
bundler: "webpack",
|
||||
runtime: "webpackChunkApp",
|
||||
chunk_keys: ["1"],
|
||||
modules: [expect.objectContaining({ exports: ["ok"] })],
|
||||
});
|
||||
});
|
||||
@@ -73,19 +73,38 @@ export const chunkRuntime = (call: t.CallExpression): string | undefined => {
|
||||
};
|
||||
|
||||
const findChunkRuntime = (node: t.Node): string | undefined => {
|
||||
if (t.isIdentifier(node) && /(?:webpack|rspack)Chunk/iu.test(node.name))
|
||||
return node.name;
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const property = semanticStaticPropertyName(node.property, node.computed);
|
||||
if (/(?:webpack|rspack)Chunk/iu.test(property)) return property;
|
||||
return t.isNode(node.object) ? findChunkRuntime(node.object) : undefined;
|
||||
const pending: t.Node[] = [node];
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) continue;
|
||||
if (
|
||||
t.isIdentifier(current) &&
|
||||
/(?:webpack|rspack)Chunk/iu.test(current.name)
|
||||
)
|
||||
return current.name;
|
||||
if (
|
||||
t.isMemberExpression(current) ||
|
||||
t.isOptionalMemberExpression(current)
|
||||
) {
|
||||
const property = semanticStaticPropertyName(
|
||||
current.property,
|
||||
current.computed,
|
||||
);
|
||||
if (/(?:webpack|rspack)Chunk/iu.test(property)) return property;
|
||||
if (t.isNode(current.object)) pending.push(current.object);
|
||||
continue;
|
||||
}
|
||||
if (t.isAssignmentExpression(current)) {
|
||||
pending.push(current.right, current.left);
|
||||
continue;
|
||||
}
|
||||
if (t.isLogicalExpression(current) || t.isBinaryExpression(current)) {
|
||||
pending.push(current.right, current.left);
|
||||
continue;
|
||||
}
|
||||
if (t.isParenthesizedExpression(current) || t.isTSAsExpression(current))
|
||||
pending.push(current.expression);
|
||||
}
|
||||
if (t.isAssignmentExpression(node))
|
||||
return findChunkRuntime(node.left) ?? findChunkRuntime(node.right);
|
||||
if (t.isLogicalExpression(node) || t.isBinaryExpression(node))
|
||||
return findChunkRuntime(node.left) ?? findChunkRuntime(node.right);
|
||||
if (t.isParenthesizedExpression(node) || t.isTSAsExpression(node))
|
||||
return findChunkRuntime(node.expression);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
@@ -520,19 +539,23 @@ export const storageKind = (
|
||||
};
|
||||
|
||||
/** Produce a dotted callee name from member syntax. */
|
||||
export const calleeName = (node: t.Node): string => calleeNameAt(node);
|
||||
|
||||
const calleeNameAt = (node: t.Node): string => {
|
||||
if (t.isIdentifier(node)) return node.name;
|
||||
if (t.isImport(node)) return "import";
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const object = t.isNode(node.object) ? calleeNameAt(node.object) : "";
|
||||
// A dynamic key commits no name: `target[method]()` must not be reported as
|
||||
// `target.method`, which would fabricate a runtime call shape.
|
||||
const property = memberPropertyName(node);
|
||||
return object === "" ? property : `${object}.${property}`;
|
||||
export const calleeName = (node: t.Node): string => {
|
||||
const segments: string[] = [];
|
||||
while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
// Dynamic keys retain their syntax identity instead of inventing a name.
|
||||
segments.push(memberPropertyName(node));
|
||||
if (!t.isNode(node.object)) break;
|
||||
node = node.object;
|
||||
}
|
||||
return "";
|
||||
const base = t.isIdentifier(node)
|
||||
? node.name
|
||||
: t.isImport(node)
|
||||
? "import"
|
||||
: "";
|
||||
segments.push(base);
|
||||
segments.reverse();
|
||||
const first = segments.findIndex((segment) => segment !== "");
|
||||
return first === -1 ? "" : segments.slice(first).join(".");
|
||||
};
|
||||
|
||||
/** Read a member property only when its syntax commits an exact name. */
|
||||
|
||||
Reference in New Issue
Block a user