fix(ci): reconcile Git ownership and preserve portable checks
This commit is contained in:
+451
@@ -0,0 +1,451 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
import { reconstructJavaScriptArtifact } from "../../../support/javascriptApplicationScope.js";
|
||||
import { parseEvidence } from "../../../../src/domain/evidence.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { analyzeJavaScriptApplicationInputSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { writeElectronBoundaryFixture } from "../../../fixtures/electronBoundaryApplication.js";
|
||||
|
||||
describe("static Electron application analysis", () => {
|
||||
it("accepts relative paths and rejects caller-selected analysis bounds", () => {
|
||||
expect(
|
||||
analyzeJavaScriptApplicationInputSchema.safeParse({
|
||||
input_path: "relative/app.asar",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
analyzeJavaScriptApplicationInputSchema.safeParse({
|
||||
input_path: "/tmp/app.asar",
|
||||
limits: { max_findings: 200_000 },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("maps windows, preload, contextBridge, IPC, validations, utility, and native boundaries without execution", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
Reflect.deleteProperty(globalThis, "__rea_electron_fixture_executed");
|
||||
|
||||
const first = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
const second = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
const graph = parseJavaScriptApplicationGraph(first.graph);
|
||||
|
||||
expect(
|
||||
Reflect.get(globalThis, "__rea_electron_fixture_executed"),
|
||||
).toBeUndefined();
|
||||
expect(first.graph).toEqual(second.graph);
|
||||
expectElectronSummary(first);
|
||||
expectElectronRoles(graph);
|
||||
expectElectronBoundaries(graph);
|
||||
});
|
||||
|
||||
it("analyzes the selected local application directory directly", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
});
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
const evidence = parseEvidence(result.value);
|
||||
expect(evidence).toMatchObject({
|
||||
operation: "analyze_javascript_application",
|
||||
predicate_type: "rea.javascript-application-analysis",
|
||||
provider: { id: "rea-javascript-application" },
|
||||
authority: "shipped-artifact",
|
||||
confidence: "derived",
|
||||
subject: { local_path: root, format: "directory" },
|
||||
normalized_result: {
|
||||
input_path: root,
|
||||
summary: { browser_windows: 3 },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps computed identifier member keys unknown", async () => {
|
||||
const root = await computedMemberFixtureDirectory();
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
const nativeBindings = graph.nodes.filter(
|
||||
(node) => node.kind === "native-export",
|
||||
);
|
||||
|
||||
expect(result.electron_summary).toMatchObject({
|
||||
sender_validation_observations: 0,
|
||||
native_addon_bindings: 1,
|
||||
resolved_native_addon_bindings: 1,
|
||||
});
|
||||
expect(nativeBindings).toMatchObject([
|
||||
{
|
||||
observations: [
|
||||
{
|
||||
properties: {
|
||||
requested_members: [],
|
||||
namespace_access: false,
|
||||
dynamic_member_access: true,
|
||||
native_export_verification: "not-performed",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps Electron boundaries through bundler-renamed bindings", async () => {
|
||||
const root = await renamedBindingFixtureDirectory();
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
const handledChannels = graph.nodes.flatMap(({ kind, observations }) =>
|
||||
kind === "ipc-handler"
|
||||
? observations.flatMap(({ properties }) =>
|
||||
properties.side === "main" ? [properties.channel] : [],
|
||||
)
|
||||
: [],
|
||||
);
|
||||
|
||||
expect(result.electron_summary).toMatchObject({
|
||||
browser_windows: 1,
|
||||
context_bridge_apis: 1,
|
||||
exposed_api_members: 2,
|
||||
ipc: {
|
||||
main_handlers: 2,
|
||||
paired_renderer_transmissions: 2,
|
||||
unpaired_literal_renderer_transmissions: 0,
|
||||
},
|
||||
utility_processes: 1,
|
||||
});
|
||||
expect(handledChannels.sort()).toEqual(["rea:read", "rea:write"]);
|
||||
});
|
||||
|
||||
it("maps unchanged var and let require aliases while excluding reassigned bindings", async () => {
|
||||
const root = await requireAliasFixtureDirectory();
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
|
||||
expect(result.electron_summary.ipc).toMatchObject({
|
||||
main_handlers: 2,
|
||||
paired_renderer_transmissions: 2,
|
||||
unpaired_literal_renderer_transmissions: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a tagged cancellation without executing application code", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
Reflect.deleteProperty(globalThis, "__rea_electron_fixture_executed");
|
||||
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: root },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
|
||||
});
|
||||
expect(
|
||||
Reflect.get(globalThis, "__rea_electron_fixture_executed"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
type Reconstruction = Awaited<ReturnType<typeof reconstructJavaScriptArtifact>>;
|
||||
type ApplicationGraph = ReturnType<typeof parseJavaScriptApplicationGraph>;
|
||||
|
||||
const expectElectronSummary = (result: Reconstruction): void => {
|
||||
expect(result.electron_summary).toMatchObject({
|
||||
browser_windows: 3,
|
||||
explicit_web_preferences: 8,
|
||||
preload_entrypoints: 1,
|
||||
context_bridge_apis: 2,
|
||||
exposed_api_members: 5,
|
||||
ipc: {
|
||||
literal_channels: 5,
|
||||
dynamic_channel_operations: 2,
|
||||
paired_renderer_transmissions: 4,
|
||||
ambiguous_renderer_transmissions: 1,
|
||||
unpaired_literal_renderer_transmissions: 1,
|
||||
},
|
||||
sender_validation_observations: 2,
|
||||
utility_processes: 1,
|
||||
resolved_utility_entrypoints: 1,
|
||||
native_addon_bindings: 4,
|
||||
resolved_native_addon_bindings: 4,
|
||||
});
|
||||
};
|
||||
|
||||
const expectElectronRoles = (graph: ApplicationGraph): void => {
|
||||
expect(graph.nodes.map(({ kind }) => kind)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"browser-window",
|
||||
"electron-preload",
|
||||
"context-bridge-api",
|
||||
"ipc-channel",
|
||||
"ipc-handler",
|
||||
"electron-utility",
|
||||
"native-addon",
|
||||
"native-export",
|
||||
]),
|
||||
);
|
||||
const roles = graph.nodes.filter(({ kind }) =>
|
||||
["electron-main", "electron-preload", "electron-renderer"].includes(kind),
|
||||
);
|
||||
expect(roles.length).toBeGreaterThanOrEqual(3);
|
||||
for (const role of roles) {
|
||||
for (const observation of role.observations)
|
||||
expect(observation.properties).toMatchObject({
|
||||
declared_path: expect.any(String),
|
||||
resolution_context: expect.stringMatching(
|
||||
/^(package-entrypoint|filesystem-expression|module-specifier|html-reference)$/u,
|
||||
),
|
||||
resolution_status: expect.stringMatching(
|
||||
/^(resolved|not-found|unavailable|external|rejected)$/u,
|
||||
),
|
||||
limitations: expect.any(Array),
|
||||
});
|
||||
if (
|
||||
role.observations.some(
|
||||
({ properties }) => properties.resolution_status === "resolved",
|
||||
)
|
||||
)
|
||||
expect(
|
||||
graph.edges.some(
|
||||
(edge) =>
|
||||
edge.source_node_id === role.node_id && edge.relation === "maps_to",
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
const dirnamePreload = roles.find(
|
||||
({ kind, observations }) =>
|
||||
kind === "electron-preload" &&
|
||||
observations.some(
|
||||
({ properties }) =>
|
||||
properties.declared_path === "preload.js" &&
|
||||
properties.resolution_context === "filesystem-expression",
|
||||
),
|
||||
);
|
||||
expect(dirnamePreload?.observations[0]?.properties).toMatchObject({
|
||||
declared_path: "preload.js",
|
||||
resolution_context: "filesystem-expression",
|
||||
resolved_path: "preload.js",
|
||||
resolution_status: "resolved",
|
||||
limitations: [],
|
||||
});
|
||||
};
|
||||
|
||||
const expectElectronBoundaries = (graph: ApplicationGraph): void => {
|
||||
expect(graph.nodes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "browser-window",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
preload_path: "preload.js",
|
||||
absence_means_default: false,
|
||||
web_preferences: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "nodeIntegration",
|
||||
value: expect.objectContaining({
|
||||
status: "literal",
|
||||
value: true,
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "browser-window",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
web_preferences: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "nodeIntegration",
|
||||
value: expect.objectContaining({
|
||||
status: "literal",
|
||||
value: false,
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "contextIsolation",
|
||||
value: expect.objectContaining({
|
||||
status: "literal",
|
||||
value: true,
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "context-bridge-api",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
api_key: "reaApi",
|
||||
members: expect.arrayContaining([
|
||||
"nested",
|
||||
"nested.write",
|
||||
"read",
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "ipc-handler",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
fact_kind: "sender-validation-candidate",
|
||||
enforcement: "unknown",
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "native-export",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
native_export_verification: "not-performed",
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const pairingEdges = graph.edges.filter(
|
||||
({ properties }) =>
|
||||
properties.pairing_basis === "unique-exact-literal-channel",
|
||||
);
|
||||
expect(pairingEdges).toHaveLength(4);
|
||||
expect(
|
||||
pairingEdges.some(
|
||||
({ properties }) => properties.channel === "rea:ambiguous",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(graph.limitations.join(" ")).toMatch(/dynamic IPC|ambiguous/iu);
|
||||
};
|
||||
|
||||
const fixtureDirectory = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-electron-boundaries-");
|
||||
await writeElectronBoundaryFixture(root);
|
||||
return root;
|
||||
};
|
||||
|
||||
const requireAliasFixtureDirectory = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-electron-require-aliases-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "rea-electron-require-aliases",
|
||||
main: "main.cjs",
|
||||
}),
|
||||
),
|
||||
writeFile(
|
||||
join(root, "main.cjs"),
|
||||
String.raw`
|
||||
var { ipcMain: main } = require("electron");
|
||||
let listener = require("electron/main").ipcMain;
|
||||
main.handle("rea:read", async () => "value");
|
||||
listener.on("rea:write", () => undefined);
|
||||
|
||||
let replaced = require("electron").ipcMain;
|
||||
replaced = { handle() {} };
|
||||
replaced.handle("rea:reassigned", () => undefined);
|
||||
|
||||
var assignedLater;
|
||||
assignedLater.handle("rea:before-assignment", () => undefined);
|
||||
assignedLater = require("electron").ipcMain;
|
||||
|
||||
if (globalThis.registerIpc) {
|
||||
var conditional = require("electron").ipcMain;
|
||||
}
|
||||
conditional.handle("rea:conditional", () => undefined);
|
||||
`,
|
||||
),
|
||||
writeFile(
|
||||
join(root, "preload.cjs"),
|
||||
String.raw`
|
||||
const { ipcRenderer } = require("electron");
|
||||
ipcRenderer.invoke("rea:read");
|
||||
ipcRenderer.send("rea:write", "value");
|
||||
`,
|
||||
),
|
||||
]);
|
||||
return root;
|
||||
};
|
||||
|
||||
const renamedBindingFixtureDirectory = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-electron-renamed-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({ name: "rea-electron-renamed", main: "main.mjs" }),
|
||||
),
|
||||
// Bundlers rename colliding imports, e.g. esbuild's ipcMain2.
|
||||
writeFile(
|
||||
join(root, "main.mjs"),
|
||||
String.raw`
|
||||
import { BrowserWindow as BrowserWindow2, ipcMain as ipcMain2 } from "electron";
|
||||
import { ipcMain as ipcMain3, utilityProcess as utility } from "electron/main";
|
||||
|
||||
new BrowserWindow2({ webPreferences: { preload: "./preload.cjs" } });
|
||||
ipcMain2.handle("rea:read", async () => "value");
|
||||
ipcMain3.on("rea:write", () => undefined);
|
||||
utility.fork("./worker.js");
|
||||
function register(ipcMain2) {
|
||||
ipcMain2.handle("rea:shadowed", async () => "local");
|
||||
}
|
||||
export { register };
|
||||
`,
|
||||
),
|
||||
writeFile(
|
||||
join(root, "preload.cjs"),
|
||||
String.raw`
|
||||
const { contextBridge: bridge, ipcRenderer: ipc } = require("electron");
|
||||
bridge.exposeInMainWorld("reaApi", {
|
||||
read: () => ipc.invoke("rea:read"),
|
||||
write: (value) => ipc.send("rea:write", value),
|
||||
});
|
||||
`,
|
||||
),
|
||||
writeFile(join(root, "worker.js"), "module.exports = {};"),
|
||||
]);
|
||||
return root;
|
||||
};
|
||||
|
||||
const computedMemberFixtureDirectory = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-electron-computed-members-");
|
||||
await mkdir(join(root, "native"));
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "main.js"),
|
||||
String.raw`
|
||||
const member = "read";
|
||||
const selected = require("./native/addon.node")[member];
|
||||
const startsWith = "includes";
|
||||
function validate(event) {
|
||||
return event.senderFrame.url[startsWith]("file://");
|
||||
}
|
||||
module.exports = { selected, validate };
|
||||
`,
|
||||
),
|
||||
writeFile(join(root, "native", "addon.node"), Buffer.from([0, 1, 2, 3])),
|
||||
]);
|
||||
return root;
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { reconstructJavaScriptArtifact } from "../../../support/javascriptApplicationScope.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
|
||||
const PRELOAD = '{ preload: "./preload.js", sandbox: true }';
|
||||
const EXPLICIT = `webPreferences: ${PRELOAD}`;
|
||||
|
||||
describe("Electron option keys in reconstructed application graphs", () => {
|
||||
it.each([
|
||||
["computed binding", `[webPreferences]: ${PRELOAD}`],
|
||||
["later spread", `${EXPLICIT}, ...options`],
|
||||
["later computed key", `${EXPLICIT}, [getKey()]: null`],
|
||||
["later accessor", `${EXPLICIT}, get webPreferences() { return null; }`],
|
||||
["later duplicate", `${EXPLICIT}, webPreferences: null`],
|
||||
])(
|
||||
"does not associate a BrowserWindow preload from %s",
|
||||
async (_, options) => {
|
||||
const result = await reconstructSource(`
|
||||
const webPreferences = "title";
|
||||
new BrowserWindow({ ${options} });
|
||||
`);
|
||||
const windows = result.graph.nodes.filter(
|
||||
({ kind }) => kind === "browser-window",
|
||||
);
|
||||
expect(windows).toHaveLength(1);
|
||||
const observation = windows[0]?.observations[0];
|
||||
expect(observation).toMatchObject({
|
||||
properties: {
|
||||
options_status: "object-literal",
|
||||
web_preferences_status: "dynamic",
|
||||
web_preferences: [],
|
||||
preload_path: null,
|
||||
preload_resolution_context: null,
|
||||
},
|
||||
evidence: {
|
||||
state: "observed",
|
||||
confidence: "exact",
|
||||
coverage: { status: "partial" },
|
||||
},
|
||||
});
|
||||
expect(result.electron_summary.preload_entrypoints).toBe(0);
|
||||
expect(result.electron_summary.explicit_web_preferences).toBe(0);
|
||||
|
||||
// The independent property:preload heuristic can still discover the nested
|
||||
// literal. It must not carry a BrowserWindow-specific observation or edge.
|
||||
expect(windowPreloadNodes(result)).toEqual([]);
|
||||
expect(
|
||||
result.graph.edges.filter(
|
||||
(edge) =>
|
||||
edge.source_node_id === windows[0]?.node_id &&
|
||||
edge.relation === "loads",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(result.graph.edges).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
relation: "maps_to",
|
||||
evidence: expect.objectContaining({
|
||||
location: observation?.evidence.location,
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["plain key", EXPLICIT],
|
||||
["quoted key", `"webPreferences": ${PRELOAD}`],
|
||||
["computed literal", `["webPreferences"]: ${PRELOAD}`],
|
||||
["later explicit key", `...options, [getKey()]: null, ${EXPLICIT}`],
|
||||
["last duplicate key", `webPreferences: null, ${EXPLICIT}`],
|
||||
])(
|
||||
"retains the BrowserWindow preload association for %s",
|
||||
async (_, options) => {
|
||||
const result = await reconstructSource(
|
||||
`new BrowserWindow({ ${options} });`,
|
||||
);
|
||||
const preloads = windowPreloadNodes(result);
|
||||
expect(preloads).toHaveLength(1);
|
||||
expect(result.electron_summary.preload_entrypoints).toBe(1);
|
||||
expect(result.electron_summary.explicit_web_preferences).toBe(2);
|
||||
expect(result.graph.edges).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
relation: "loads",
|
||||
target_node_id: preloads[0]?.node_id,
|
||||
evidence: expect.objectContaining({
|
||||
state: "inferred",
|
||||
confidence: "high",
|
||||
extractor: expect.objectContaining({
|
||||
operation: "associate-browser-window-preload",
|
||||
}),
|
||||
coverage: expect.objectContaining({ status: "complete" }),
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
relation: "maps_to",
|
||||
source_node_id: preloads[0]?.node_id,
|
||||
properties: expect.objectContaining({
|
||||
resolved_path: "preload.js",
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps a computed serviceName unknown in the utility-process observation", async () => {
|
||||
const result = await reconstructSource(`
|
||||
const serviceName = "env";
|
||||
utilityProcess.fork("./worker.js", [], { [serviceName]: "wrong-name" });
|
||||
`);
|
||||
const utilities = result.graph.nodes.filter(
|
||||
({ kind }) => kind === "electron-utility",
|
||||
);
|
||||
expect(utilities).toHaveLength(1);
|
||||
expect(utilities[0]?.observations[0]).toMatchObject({
|
||||
label: "./worker.js",
|
||||
properties: { service_name: null, module_path: "./worker.js" },
|
||||
evidence: { coverage: { status: "partial" } },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["-0", { status: "dynamic", value: null, expression: "-0" }],
|
||||
["-0.0", { status: "dynamic", value: null, expression: "-0.0" }],
|
||||
["-1e999", { status: "dynamic", value: null, expression: "-1e999" }],
|
||||
["-1", { status: "literal", value: -1, expression: null }],
|
||||
] as const)(
|
||||
"preserves the JSON representation of BrowserWindow preference %s",
|
||||
async (expression, value) => {
|
||||
const result = await reconstructSource(
|
||||
`new BrowserWindow({ webPreferences: { zoomFactor: ${expression} } });`,
|
||||
);
|
||||
const graph: unknown = JSON.parse(JSON.stringify(result.graph));
|
||||
const transported = parseJavaScriptApplicationGraph(graph);
|
||||
const window = transported.nodes.find(
|
||||
({ kind }) => kind === "browser-window",
|
||||
);
|
||||
expect(window?.observations[0]?.properties.web_preferences).toEqual([
|
||||
{ name: "zoomFactor", value },
|
||||
]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
type Reconstruction = Awaited<ReturnType<typeof reconstructJavaScriptArtifact>>;
|
||||
|
||||
const windowPreloadNodes = (result: Reconstruction) =>
|
||||
result.graph.nodes.filter(
|
||||
(node) =>
|
||||
node.kind === "electron-preload" &&
|
||||
node.observations.some(
|
||||
({ properties }) =>
|
||||
properties.mechanism === "BrowserWindow:webPreferences.preload",
|
||||
),
|
||||
);
|
||||
|
||||
const reconstructSource = async (source: string): Promise<Reconstruction> => {
|
||||
const root = await createTestTempDirectory("rea-electron-option-keys-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({ main: "main.js", type: "module" }),
|
||||
),
|
||||
writeFile(
|
||||
join(root, "main.js"),
|
||||
`${source}\nimport { BrowserWindow, utilityProcess } from "electron";\n`,
|
||||
),
|
||||
writeFile(join(root, "preload.js"), "void 0;"),
|
||||
writeFile(join(root, "worker.js"), "void 0;"),
|
||||
]);
|
||||
return reconstructJavaScriptArtifact({ input_path: root });
|
||||
};
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { matchJavaScriptApplicationVersions } from "../../../../src/domain/javascript/javascriptApplicationVersionKeys.js";
|
||||
import { findApplicationFeatureSeeds } from "../../../../src/domain/javascript/javascriptFeatureSeed.js";
|
||||
import { traceApplicationFeatureInputSchema } from "../../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
|
||||
const analyzeSource = async (
|
||||
source: string,
|
||||
extraFiles: Readonly<Record<string, string>> = {},
|
||||
) => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-empty-literal-");
|
||||
await writeFile(join(inputPath, "app.js"), `${source}\n`);
|
||||
for (const [path, text] of Object.entries(extraFiles))
|
||||
await writeFile(join(inputPath, path), text);
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: inputPath,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok)
|
||||
throw new Error(`Expected analysis success: ${result.error.message}`);
|
||||
return javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
};
|
||||
|
||||
it("retains empty literal evidence across the application boundary surfaces", async () => {
|
||||
const sources = [
|
||||
"fetch('');",
|
||||
"new WebSocket('');",
|
||||
"navigator.serviceWorker.register('');",
|
||||
"new Worker('');",
|
||||
"const x = require('');",
|
||||
"import y from ''; y();",
|
||||
"import('');",
|
||||
"localStorage.getItem('');",
|
||||
"localStorage.setItem('', 1);",
|
||||
"indexedDB.open('');",
|
||||
"win.loadFile('');",
|
||||
"win.loadURL('');",
|
||||
"app.get('', handler);",
|
||||
"process.on('', () => 1);",
|
||||
"const { EventEmitter } = require('events'); new EventEmitter().on('', () => 1);",
|
||||
"const { spawn } = require('child_process'); spawn('/bin/x').on('', () => 1);",
|
||||
"const { ipcMain } = require('electron'); ipcMain.handle('', () => 1);",
|
||||
"const { ipcRenderer } = require('electron'); ipcRenderer.invoke('');",
|
||||
"const { contextBridge } = require('electron'); contextBridge.exposeInMainWorld('', {});",
|
||||
];
|
||||
const output = await analyzeSource(sources.join("\n"));
|
||||
expect(output.graph.nodes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: "endpoint" }),
|
||||
expect.objectContaining({ kind: "worker" }),
|
||||
expect.objectContaining({ kind: "ipc-channel" }),
|
||||
expect.objectContaining({ kind: "context-bridge-api" }),
|
||||
]),
|
||||
);
|
||||
expect(output.semantic_graph?.nodes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "request",
|
||||
properties: expect.objectContaining({ endpoint: "" }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "event",
|
||||
properties: expect.objectContaining({ event_name: "" }),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("analyzes a plain long-line loader without package metadata", async () => {
|
||||
const output = await analyzeSource(
|
||||
`var Module = {}; fetch(""); new Worker(""); var payload = "${"x".repeat(65_536)}";`,
|
||||
{ "game-data.js": "Module.data = { ready: true };" },
|
||||
);
|
||||
const nodes = output.graph.nodes.filter(
|
||||
({ kind }) => kind === "endpoint" || kind === "worker",
|
||||
);
|
||||
expect(nodes.map(({ kind }) => kind).sort()).toEqual(["endpoint", "worker"]);
|
||||
for (const node of nodes) {
|
||||
expect(node.identity).toMatchObject({
|
||||
strategy: "artifact-local-key",
|
||||
key: "",
|
||||
});
|
||||
expect(node.observations.map(({ label }) => label)).toEqual([null]);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps exact values for empty literals without synthetic application labels", async () => {
|
||||
const output = await analyzeSource(
|
||||
"fetch(''); fetch('\"\"'); fetch('/api'); process.on('', () => 1);",
|
||||
);
|
||||
const endpoints = output.graph.nodes
|
||||
.filter(({ kind }) => kind === "endpoint")
|
||||
.map(({ identity, observations }) => ({
|
||||
key: identity.strategy === "artifact-local-key" ? identity.key : null,
|
||||
labels: observations.map(({ label }) => label),
|
||||
values: observations.map(({ properties }) => properties.value),
|
||||
}));
|
||||
// The empty endpoint has no display label, so it cannot be confused with
|
||||
// a literal two-quote endpoint; both keep exact identities.
|
||||
expect(endpoints).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ key: "", labels: [null], values: [""] },
|
||||
{ key: '""', labels: ['""'], values: ['""'] },
|
||||
{ key: "/api", labels: ["/api"], values: ["/api"] },
|
||||
]),
|
||||
);
|
||||
expect(endpoints).toHaveLength(3);
|
||||
expect(
|
||||
output.semantic_graph?.nodes
|
||||
.filter(({ kind }) => kind === "event")
|
||||
.map(({ label, properties }) => ({
|
||||
label,
|
||||
eventName: properties.event_name,
|
||||
})),
|
||||
).toEqual([{ label: '""', eventName: "" }]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ version: 3, sources: [""], names: [], mappings: "AAAA" },
|
||||
{ version: 3, sourceRoot: null, sources: [""], names: [], mappings: "AAAA" },
|
||||
{ version: 3, sourceRoot: "", sources: [""], names: [], mappings: "AAAA" },
|
||||
{
|
||||
version: 3,
|
||||
sections: [
|
||||
{
|
||||
offset: { line: 0, column: 0 },
|
||||
map: { version: 3, sources: [""], names: [], mappings: "AAAA" },
|
||||
},
|
||||
],
|
||||
},
|
||||
])("projects an empty source-map source name: %j", async (map) => {
|
||||
const output = await analyzeSource("//# sourceMappingURL=app.js.map", {
|
||||
"app.js.map": JSON.stringify(map),
|
||||
});
|
||||
const originals = output.graph.nodes
|
||||
.filter(({ kind }) => kind === "source-module")
|
||||
.map(({ identity, observations }) => ({
|
||||
originalSource:
|
||||
identity.strategy === "source-map-original"
|
||||
? identity.original_source
|
||||
: null,
|
||||
sources: observations.map(
|
||||
({ source_map_reference }) => source_map_reference?.source_name,
|
||||
),
|
||||
}));
|
||||
expect(originals).toEqual([{ originalSource: "", sources: [""] }]);
|
||||
});
|
||||
|
||||
it("keeps empty and two-quote source-map names distinct", async () => {
|
||||
const output = await analyzeSource("//# sourceMappingURL=app.js.map", {
|
||||
"app.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sources: ["", '""'],
|
||||
names: [],
|
||||
mappings: "AAAA,CCAA",
|
||||
}),
|
||||
});
|
||||
expect(
|
||||
output.graph.nodes
|
||||
.filter(({ kind }) => kind === "source-module")
|
||||
.map(({ identity }) =>
|
||||
identity.strategy === "source-map-original"
|
||||
? identity.original_source
|
||||
: null,
|
||||
)
|
||||
.sort(),
|
||||
).toEqual(["", '""']);
|
||||
});
|
||||
|
||||
it("does not match an empty endpoint with a literal two-quote seed", async () => {
|
||||
const output = await analyzeSource("fetch(''); fetch('\"\"');");
|
||||
const endpoints = new Map(
|
||||
output.graph.nodes
|
||||
.filter(({ kind }) => kind === "endpoint")
|
||||
.map((node) => [
|
||||
node.node_id,
|
||||
node.identity.strategy === "artifact-local-key"
|
||||
? node.identity.key
|
||||
: null,
|
||||
]),
|
||||
);
|
||||
const matches = findApplicationFeatureSeeds(output.graph.nodes, {
|
||||
kind: "string",
|
||||
value: '""',
|
||||
match: "exact",
|
||||
case_sensitive: true,
|
||||
}).filter(({ node_id: nodeId }) => endpoints.has(nodeId));
|
||||
expect(matches.map(({ node_id: nodeId }) => endpoints.get(nodeId))).toEqual([
|
||||
'""',
|
||||
]);
|
||||
});
|
||||
|
||||
const IPC_SOURCE =
|
||||
"const { ipcMain } = require('electron'); ipcMain.handle('', () => 1); ipcMain.handle('\"\"', () => 2);";
|
||||
|
||||
const ipcChannels = (
|
||||
nodes: Awaited<ReturnType<typeof analyzeSource>>["graph"]["nodes"],
|
||||
) =>
|
||||
new Map(
|
||||
nodes
|
||||
.filter(({ kind }) => kind === "ipc-channel")
|
||||
.map((node) => [node.node_id, node.observations[0]?.properties.channel]),
|
||||
);
|
||||
|
||||
it("selects an empty IPC channel with an exact empty seed", async () => {
|
||||
const output = await analyzeSource(IPC_SOURCE);
|
||||
const channels = ipcChannels(output.graph.nodes);
|
||||
const matches = findApplicationFeatureSeeds(output.graph.nodes, {
|
||||
kind: "channel",
|
||||
value: "",
|
||||
match: "exact",
|
||||
case_sensitive: true,
|
||||
});
|
||||
expect(matches.map(({ node_id: nodeId }) => channels.get(nodeId))).toEqual([
|
||||
"",
|
||||
]);
|
||||
});
|
||||
|
||||
const seedSchema = traceApplicationFeatureInputSchema.shape.seed;
|
||||
const validateAdvertisedSeed = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(z.toJSONSchema(seedSchema, { io: "input" }));
|
||||
|
||||
it.each([
|
||||
[{ kind: "channel", value: "", match: "exact" }, true],
|
||||
[{ kind: "string", value: "", match: "exact" }, true],
|
||||
[{ kind: "channel", value: "/x" }, true],
|
||||
[{ kind: "string", value: "" }, false],
|
||||
[{ kind: "channel", value: "" }, false],
|
||||
[{ kind: "channel", value: "", match: "contains" }, false],
|
||||
[{ kind: "node-id", value: "", match: "exact" }, false],
|
||||
] as const)(
|
||||
"validates empty seed %j at runtime and in the advertised schema",
|
||||
(seed, accepted) => {
|
||||
expect(seedSchema.safeParse(seed).success).toBe(accepted);
|
||||
expect(validateAdvertisedSeed(seed)).toBe(accepted);
|
||||
},
|
||||
);
|
||||
|
||||
it("pairs the same empty IPC channel across application versions", async () => {
|
||||
const left = await analyzeSource(IPC_SOURCE);
|
||||
const right = await analyzeSource(`${IPC_SOURCE} // v2`);
|
||||
const leftChannels = ipcChannels(left.graph.nodes);
|
||||
const rightChannels = ipcChannels(right.graph.nodes);
|
||||
const matching = matchJavaScriptApplicationVersions(
|
||||
left.graph.nodes,
|
||||
right.graph.nodes,
|
||||
);
|
||||
expect(
|
||||
matching.pairs
|
||||
.filter(({ left: node }) => node.kind === "ipc-channel")
|
||||
.map(({ left: leftNode, right: rightNode }) => [
|
||||
leftChannels.get(leftNode.node_id),
|
||||
rightChannels.get(rightNode.node_id),
|
||||
]),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
["", ""],
|
||||
['""', '""'],
|
||||
]),
|
||||
);
|
||||
expect(matching.unmatchedLeft.map(({ kind }) => kind)).not.toContain(
|
||||
"ipc-channel",
|
||||
);
|
||||
});
|
||||
|
||||
it("selects an empty context-bridge API with an exact empty seed", async () => {
|
||||
const output = await analyzeSource(
|
||||
"const { contextBridge } = require('electron'); contextBridge.exposeInMainWorld('', {}); contextBridge.exposeInMainWorld('\"\"', {});",
|
||||
);
|
||||
const apis = new Map(
|
||||
output.graph.nodes
|
||||
.filter(({ kind }) => kind === "context-bridge-api")
|
||||
.map((node) => [node.node_id, node.observations[0]?.properties.api_key]),
|
||||
);
|
||||
const matches = findApplicationFeatureSeeds(output.graph.nodes, {
|
||||
kind: "api",
|
||||
value: "",
|
||||
match: "exact",
|
||||
case_sensitive: true,
|
||||
});
|
||||
expect(matches.map(({ node_id: nodeId }) => apis.get(nodeId))).toEqual([""]);
|
||||
});
|
||||
|
||||
it("pairs indexed source-map leaves by raw source name and root", async () => {
|
||||
const map = (value: number) =>
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
sections: ["one", "two"].map((name, line) => ({
|
||||
offset: { line, column: 0 },
|
||||
map: {
|
||||
version: 3,
|
||||
sourceRoot: `../${name}`,
|
||||
sources: ["same.js"],
|
||||
sourcesContent: [`export const value = ${String(value)};`],
|
||||
names: [],
|
||||
mappings: "AAAA",
|
||||
},
|
||||
})),
|
||||
});
|
||||
const left = await analyzeSource("//# sourceMappingURL=app.js.map", {
|
||||
"app.js.map": map(1),
|
||||
});
|
||||
const right = await analyzeSource("//# sourceMappingURL=app.js.map", {
|
||||
"app.js.map": map(2),
|
||||
});
|
||||
const matching = matchJavaScriptApplicationVersions(
|
||||
left.graph.nodes,
|
||||
right.graph.nodes,
|
||||
);
|
||||
const originals = matching.pairs.filter(
|
||||
({ left: node }) => node.kind === "source-module",
|
||||
);
|
||||
expect(originals).toHaveLength(2);
|
||||
for (const pair of originals) {
|
||||
expect(pair).toMatchObject({
|
||||
basis: "source-map-identity",
|
||||
confidence: "high",
|
||||
});
|
||||
expect(pair.left.identity).toMatchObject({
|
||||
original_source: "same.js",
|
||||
source_root: expect.any(String),
|
||||
});
|
||||
if (pair.left.identity.strategy !== "source-map-original")
|
||||
throw new Error("Expected source identity");
|
||||
expect(pair.right.identity).toMatchObject({
|
||||
source_root: pair.left.identity.source_root,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("reports malformed source roots without manufacturing an original path", async () => {
|
||||
const output = await analyzeSource("//# sourceMappingURL=app.js.map", {
|
||||
"app.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sourceRoot: 42,
|
||||
sources: ["a.js"],
|
||||
names: [],
|
||||
mappings: "AAAA",
|
||||
}),
|
||||
});
|
||||
expect(
|
||||
output.graph.nodes.filter(({ kind }) => kind === "source-module"),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
output.graph.nodes.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
limitation: "Source map sourceRoot must be a string or null.",
|
||||
}),
|
||||
evidence: expect.objectContaining({ state: "unavailable" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
|
||||
it.each([
|
||||
{
|
||||
expression:
|
||||
'flag ? require("./dependency.js").value : require("./dependency.js").value',
|
||||
resolved: true,
|
||||
},
|
||||
{
|
||||
expression:
|
||||
'require("./dependency.js").value || require("./dependency.js").value',
|
||||
resolved: true,
|
||||
},
|
||||
{
|
||||
expression: 'flag ? require("./dependency.js").value : localValue',
|
||||
resolved: false,
|
||||
},
|
||||
{
|
||||
expression: 'require("./dependency.js").value ?? localValue',
|
||||
resolved: false,
|
||||
},
|
||||
])(
|
||||
"preserves export provenance for $expression",
|
||||
async ({ expression, resolved }) => {
|
||||
const root = await createTestTempDirectory("rea-js-module-provenance-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "app.js"),
|
||||
`const selected = ${expression};\nexport { selected };\n`,
|
||||
),
|
||||
writeFile(join(root, "dependency.js"), "exports.value = 1;\n"),
|
||||
]);
|
||||
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const analysis = javascriptApplicationAnalysisResultSchema.parse(
|
||||
JSON.parse(JSON.stringify(result.value.normalized_result)),
|
||||
);
|
||||
|
||||
const exportImports = analysis.graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" && properties.exported_name === "selected",
|
||||
);
|
||||
if (!resolved) {
|
||||
expect(exportImports).toEqual([]);
|
||||
return;
|
||||
}
|
||||
expect(exportImports).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
specifier: "./dependency.js",
|
||||
imported_path: ["value"],
|
||||
resolved_path: "dependency.js",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { parseEvidence } from "../../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { writeJavaScriptSourceSelectionFixture } from "../../../fixtures/javascriptSourceSelection.js";
|
||||
|
||||
import { ArtifactReaderFailure } from "../../../../src/artifacts/ArtifactReader.js";
|
||||
import { scanCanonicalArtifactInventory } from "../../../fixtures/artifactInventory.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
|
||||
import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
|
||||
import {
|
||||
analyzeJavaScriptApplication,
|
||||
readJavaScriptArtifactFiles,
|
||||
} from "../../../support/javascriptApplicationScope.js";
|
||||
import { createJavaScriptArtifactReader } from "../../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
|
||||
import { createJavaScriptSourceAnalysis } from "../../../../src/artifacts/javascript/JavaScriptSourceAnalysis.js";
|
||||
import { analyzeAndAdoptJavaScriptArtifactFiles } from "../../../../src/application/javascript/JavaScriptArtifactAnalysis.js";
|
||||
import { createJavaScriptSemanticGraphProjection } from "../../../../src/application/javascript/JavaScriptSemanticGraphBuilder.js";
|
||||
|
||||
describe("JavaScript source selection cancellation boundary", () => {
|
||||
it("keeps unselected files outside scope when the real worker cancels after the last selected file", async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-js-selected-last-cancellation-",
|
||||
);
|
||||
await writeJavaScriptSourceSelectionFixture(root);
|
||||
const snapshot = await scanCanonicalArtifactInventory(root, {});
|
||||
const reader = createJavaScriptArtifactReader(root, "directory");
|
||||
const controller = new AbortController();
|
||||
const sourcePaths = ["main.mjs"];
|
||||
try {
|
||||
const files = await readJavaScriptArtifactFiles(
|
||||
reader,
|
||||
snapshot,
|
||||
controller.signal,
|
||||
sourcePaths,
|
||||
);
|
||||
const worker = createJavaScriptSourceAnalysis(
|
||||
{ heapMb: 512, timeoutMs: 30_000 },
|
||||
1,
|
||||
);
|
||||
let outcome: Awaited<
|
||||
ReturnType<typeof analyzeAndAdoptJavaScriptArtifactFiles>
|
||||
>;
|
||||
try {
|
||||
const realWorker = worker.analyze.bind(worker);
|
||||
outcome = await analyzeAndAdoptJavaScriptArtifactFiles(
|
||||
files,
|
||||
{
|
||||
analyze: async (...args) => {
|
||||
const result = await realWorker(...args);
|
||||
controller.abort();
|
||||
return result;
|
||||
},
|
||||
},
|
||||
createJavaScriptSemanticGraphProjection(),
|
||||
async () => {},
|
||||
controller.signal,
|
||||
);
|
||||
} finally {
|
||||
await worker.close();
|
||||
}
|
||||
expect(outcome.interruption).toBeInstanceOf(AnalysisCancelledError);
|
||||
const unselected = outcome.analysis.files.filter(
|
||||
({ file }) =>
|
||||
!file.text.included && file.text.reason === "outside-analysis-scope",
|
||||
);
|
||||
expect(unselected).toHaveLength(5);
|
||||
expect(
|
||||
unselected.every(
|
||||
({ analysis_failure }) => analysis_failure === undefined,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
outcome.analysis.files.find(({ file }) => file.path === "main.mjs")
|
||||
?.javascript,
|
||||
).toMatchObject({ parse_status: "complete" });
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Selected JavaScript source failure diagnostics", () => {
|
||||
it("analyzes selected files in first-request order and reports only selected progress", async () => {
|
||||
const root = await createTestTempDirectory("rea-js-selected-priority-");
|
||||
await writeJavaScriptSourceSelectionFixture(root);
|
||||
await writeFile(join(root, "z-later.mjs"), "export const later = 1;\n");
|
||||
const progress: string[] = [];
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{
|
||||
input_path: root,
|
||||
source_paths: ["z-later.mjs", "main.mjs", "z-later.mjs"],
|
||||
},
|
||||
{
|
||||
progress: {
|
||||
report: async (event) => {
|
||||
if (event.phase === "parse_javascript_source")
|
||||
progress.push(event.message);
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
const analysis = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
expect(analysis.source_selection).toEqual({
|
||||
requested_paths: ["z-later.mjs", "main.mjs", "z-later.mjs"],
|
||||
unselected_files: 5,
|
||||
});
|
||||
expect(analysis.statistics.parsed_javascript_files).toBe(2);
|
||||
expect(progress).toEqual([
|
||||
expect.stringContaining("z-later.mjs"),
|
||||
expect.stringContaining("main.mjs"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("verifies unselected bytes against the inventoried identity without decoding them", async () => {
|
||||
const root = await createTestTempDirectory("rea-js-unselected-integrity-");
|
||||
await writeJavaScriptSourceSelectionFixture(root);
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: root, source_paths: ["main.mjs"] },
|
||||
{
|
||||
progress: {
|
||||
report: async (event) => {
|
||||
if (event.phase === "read_javascript_artifacts")
|
||||
await writeFile(
|
||||
join(root, "vendor.js"),
|
||||
"changed after inventory\n",
|
||||
);
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
if (result.ok)
|
||||
throw new Error(
|
||||
"Unselected content changes must still fail integrity verification",
|
||||
);
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "artifact_operation_failed",
|
||||
details: { reason: "integrity" },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains selected facts and unselected scope after cancellation between selected sources", async () => {
|
||||
const root = await createTestTempDirectory("rea-js-selected-cancellation-");
|
||||
await writeJavaScriptSourceSelectionFixture(root);
|
||||
await writeFile(join(root, "z-later.mjs"), "export const later = 1;\n");
|
||||
const controller = new AbortController();
|
||||
const source_paths = ["main.mjs", "z-later.mjs"];
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: root, source_paths },
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
report: async (event) => {
|
||||
if (
|
||||
event.phase === "parse_javascript_source" &&
|
||||
event.message.includes("z-later.mjs")
|
||||
)
|
||||
controller.abort();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
if (result.ok) throw new Error("Expected selected-source cancellation");
|
||||
expect(projectAnalysisError(result.error).code).toBe("cancelled");
|
||||
const evidence = parseEvidence(result.error.partialObservation);
|
||||
const partial = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(partial.source_selection).toEqual({
|
||||
requested_paths: source_paths,
|
||||
unselected_files: 5,
|
||||
});
|
||||
expect(
|
||||
partial.semantic_graph.nodes.some(
|
||||
({ kind, label }) => kind === "function" && label === "selected",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(partial.statistics.parsed_javascript_files).toBe(1);
|
||||
expect(partial.graph.coverage.status).toBe("partial");
|
||||
expect(
|
||||
partial.graph.nodes
|
||||
.flatMap(({ observations }) =>
|
||||
observations.map(({ properties }) => properties),
|
||||
)
|
||||
.filter(
|
||||
(properties) => properties.text_status === "outside-analysis-scope",
|
||||
),
|
||||
).toHaveLength(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript application failure diagnostics", () => {
|
||||
it("identifies the rejected result field in caller-visible diagnostics", async () => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-schema-failure-");
|
||||
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
|
||||
const cause = new z.ZodError([
|
||||
{
|
||||
code: "custom",
|
||||
path: ["semantic_graph", "nodes", 42, "application_node_ids", 0],
|
||||
message: "Semantic node references an absent application node",
|
||||
},
|
||||
]);
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: inputPath, format: "directory" },
|
||||
{
|
||||
progress: {
|
||||
report: async (event) => {
|
||||
if (event.terminal) throw cause;
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (result.ok) throw new Error("Expected analysis failure");
|
||||
expect(result.error.cause).toBe(cause);
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "unreadable_output",
|
||||
details: {
|
||||
operation: "analyze_javascript_application",
|
||||
reason:
|
||||
"Result schema rejected 1 issue at /semantic_graph/nodes/42/application_node_ids/0 (custom)",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("retains unexpected failures and their input identity in caller-visible diagnostics", async () => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-failure-");
|
||||
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
|
||||
const cause = new RangeError("Invalid string length");
|
||||
// Retain the original failure locally, but never serialize its object graph.
|
||||
cause.cause = cause;
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: inputPath, format: "directory" },
|
||||
{
|
||||
progress: {
|
||||
report: async (event) => {
|
||||
if (event.terminal) throw cause;
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
if (result.ok) throw new Error("Expected analysis failure");
|
||||
expect(result.error.cause).toBe(cause);
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
provider_id: "rea-javascript-application",
|
||||
operation: "analyze_javascript_application",
|
||||
diagnostics: {
|
||||
input_path: inputPath,
|
||||
error_name: "RangeError",
|
||||
error_message: "Invalid string length",
|
||||
},
|
||||
},
|
||||
});
|
||||
const projection = projectAnalysisError(result.error);
|
||||
expect(JSON.parse(JSON.stringify(projection))).toEqual(projection);
|
||||
});
|
||||
|
||||
it("reports a missing selection as invalid input, not an engine failure", async () => {
|
||||
const root = await createTestTempDirectory("rea-js-missing-");
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: join(root, "missing"),
|
||||
format: "directory",
|
||||
});
|
||||
if (result.ok) throw new Error("Expected missing artifact failure");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "analyze_javascript_application",
|
||||
issues: [{ path: ["input_path"], reason: "invalid_value" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["reported failure", null])(
|
||||
"retains non-Error failures (%s)",
|
||||
async (cause) => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-non-error-");
|
||||
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: inputPath, format: "directory" },
|
||||
{
|
||||
progress: {
|
||||
report: async (event) => {
|
||||
if (event.terminal) throw cause;
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
if (result.ok) throw new Error("Expected analysis failure");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
error_name: "UnknownError",
|
||||
error_message:
|
||||
typeof cause === "string"
|
||||
? cause
|
||||
: "JavaScript analysis failed with a non-Error value",
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([new Error("x".repeat(10_000)), "y".repeat(10_000)])(
|
||||
"preserves long failure messages through JSON projection (%#)",
|
||||
async (cause) => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-oversized-");
|
||||
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
|
||||
const message = cause instanceof Error ? cause.message : cause;
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: inputPath, format: "directory" },
|
||||
{
|
||||
progress: {
|
||||
report: async (event) => {
|
||||
if (event.terminal) throw cause;
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
if (result.ok) throw new Error("Expected analysis failure");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
error_message: message,
|
||||
},
|
||||
},
|
||||
});
|
||||
const projection = projectAnalysisError(result.error);
|
||||
expect(JSON.parse(JSON.stringify(projection))).toEqual(projection);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("JavaScript application cleanup diagnostics", () => {
|
||||
it("preserves cleanup and a complete inventory when translating reader failures", async () => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-cleanup-failure-");
|
||||
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
|
||||
const inventory = await scanCanonicalArtifactInventory(inputPath);
|
||||
const cleanup = {
|
||||
reason: "reader remains open",
|
||||
resources: [`JavaScript artifact reader for ${inputPath}`],
|
||||
};
|
||||
const partialObservation = {
|
||||
kind: "artifact-inventory" as const,
|
||||
inventory,
|
||||
};
|
||||
const failure = new ArtifactReaderFailure("io", "Reader cleanup failed", {
|
||||
cleanup,
|
||||
partialObservation,
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: inputPath, format: "directory" },
|
||||
{
|
||||
progress: {
|
||||
report: async () => {
|
||||
throw failure;
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (result.ok) throw new Error("Expected reader failure");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "ArtifactOperationError",
|
||||
cleanup,
|
||||
partialObservation,
|
||||
});
|
||||
});
|
||||
});
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { javaScriptSemanticQueryResultSchema } from "../../../../src/domain/javascript/javascriptSemanticQuerySchemas.js";
|
||||
import { queryJavaScriptSemanticGraph } from "../../../../src/domain/javascript/javascriptSemanticQuery.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
|
||||
it.each([
|
||||
{
|
||||
source: "export const value = -0;\n",
|
||||
target: { kind: "binding", label: "value" },
|
||||
},
|
||||
{
|
||||
source: "export const root = { value: -0 };\n",
|
||||
target: { kind: "property-slot", propertyPointer: "/value" },
|
||||
},
|
||||
])(
|
||||
"keeps negative-zero value unknown in an exported query (%#)",
|
||||
async ({ source, target }) => {
|
||||
const root = await createTestTempDirectory("rea-signed-zero-");
|
||||
await writeFile(join(root, "app.js"), source);
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const analysis = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
const node =
|
||||
target.kind === "binding"
|
||||
? analysis.semantic_graph.nodes.find(
|
||||
({ kind, label }) => kind === "binding" && label === target.label,
|
||||
)
|
||||
: analysis.semantic_graph.nodes.find(
|
||||
({ kind, properties }) =>
|
||||
kind === "property-slot" &&
|
||||
properties.property_pointer === target.propertyPointer,
|
||||
);
|
||||
if (node === undefined)
|
||||
throw new Error("Expected the selected semantic node");
|
||||
const query = queryJavaScriptSemanticGraph(analysis.semantic_graph, {
|
||||
seed: { kind: "semantic-node", node_id: node.node_id },
|
||||
direction: "backward-provenance",
|
||||
allowed_relations: ["defines"],
|
||||
});
|
||||
const transportedQuery = javaScriptSemanticQueryResultSchema.parse(
|
||||
JSON.parse(JSON.stringify(query)),
|
||||
);
|
||||
expect(transportedQuery.nodes.some(({ kind }) => kind === "literal")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(transportedQuery.coverage.status).toBe("partial");
|
||||
expect(transportedQuery.unknowns).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
reason: "unknown-value",
|
||||
node_id: node.node_id,
|
||||
detail: expect.stringContaining(
|
||||
"Negative zero cannot be preserved by JSON primitive evidence.",
|
||||
),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
|
||||
const graphIdentities = async (source: string) => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-template-literal-");
|
||||
await writeFile(join(inputPath, "app.js"), `${source}\n`);
|
||||
await writeFile(join(inputPath, "dep.js"), "module.exports = 1;\n");
|
||||
await writeFile(join(inputPath, "worker.js"), "self.onmessage = null;\n");
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: inputPath,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok)
|
||||
throw new Error(`Expected analysis success: ${result.error.message}`);
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
return (
|
||||
graph.nodes
|
||||
.filter(({ kind }) => kind !== "javascript-asset" && kind !== "artifact")
|
||||
// Artifact digests differ between spellings; keep the derived keys.
|
||||
.map(({ kind, identity }) => ({
|
||||
kind,
|
||||
strategy: identity.strategy,
|
||||
...(identity.strategy === "artifact-local-key"
|
||||
? {
|
||||
namespace: identity.namespace,
|
||||
// Module-export identity is a JSON tuple whose first entry
|
||||
// binds the whole container; only that digest changes here.
|
||||
key:
|
||||
identity.namespace === "module-export"
|
||||
? JSON.stringify(
|
||||
(JSON.parse(identity.key) as unknown[]).slice(1),
|
||||
)
|
||||
: identity.namespace === "source-module"
|
||||
? identity.key.replace(/^[0-9a-f]{64}:/u, "")
|
||||
: identity.key,
|
||||
}
|
||||
: {}),
|
||||
}))
|
||||
.sort((left, right) =>
|
||||
JSON.stringify(left).localeCompare(JSON.stringify(right)),
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// Each quoted literal has the same length as its template spelling, so
|
||||
// source locations and every derived identity stay comparable.
|
||||
it.each([
|
||||
"fetch('https://api.example.com/v1/users');",
|
||||
"localStorage.setItem('token', 1);",
|
||||
"new Worker('./worker.js');",
|
||||
"const dep = require('./dep.js'); dep();",
|
||||
"import('./dep.js');",
|
||||
])(
|
||||
"reads a template without substitutions as its exact string: %s",
|
||||
async (quoted) => {
|
||||
const template = quoted.replaceAll("'", "`");
|
||||
const expected = await graphIdentities(quoted);
|
||||
expect(
|
||||
expected.some(({ kind }) =>
|
||||
["endpoint", "storage", "worker", "javascript-module"].includes(kind),
|
||||
),
|
||||
).toBe(true);
|
||||
await expect(graphIdentities(template)).resolves.toEqual(expected);
|
||||
},
|
||||
);
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { canonicalJson } from "../../../../src/domain/comparisonSemantics.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { parseJavaScriptSource } from "../../../../src/domain/javascript/javascriptSourceParser.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
|
||||
type ApplicationAnalysis = ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>;
|
||||
|
||||
const analyzeFiles = async (
|
||||
files: ReadonlyMap<string, string>,
|
||||
): Promise<ApplicationAnalysis> => {
|
||||
const root = await createTestTempDirectory("rea-typescript-application-");
|
||||
await Promise.all(
|
||||
[...files].map(([path, source]) => writeFile(join(root, path), source)),
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const analysis = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
return javascriptApplicationAnalysisResultSchema.parse(
|
||||
JSON.parse(canonicalJson(analysis, "TypeScript application analysis")),
|
||||
);
|
||||
};
|
||||
|
||||
it.each(["types.d.ts", "types.d.mts", "types.d.cts"])(
|
||||
"keeps valid ambient declarations complete in %s",
|
||||
async (path) => {
|
||||
const source = "export const value: number;\n";
|
||||
const analysis = await analyzeFiles(new Map([[path, source]]));
|
||||
|
||||
expect(analysis.graph.coverage.status).toBe("complete");
|
||||
expect(parseJavaScriptSource(source, path)?.errors).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains the missing-initializer diagnostic for ordinary TypeScript", () => {
|
||||
const errors = parseJavaScriptSource(
|
||||
"export const value: number;",
|
||||
"types.ts",
|
||||
)?.errors;
|
||||
expect(errors?.map(({ message }) => message)).toContain(
|
||||
"Missing initializer in const declaration. (1:26)",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps CommonJS TypeScript angle-bracket assertions complete", async () => {
|
||||
const source = "export const value = <number>42;\n";
|
||||
const analysis = await analyzeFiles(new Map([["app.cts", source]]));
|
||||
|
||||
expect(analysis.graph.coverage.status).toBe("complete");
|
||||
expect(parseJavaScriptSource(source, "app.cts")?.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("retains exported constant evidence through a type-only satisfies expression", async () => {
|
||||
const analysis = await analyzeFiles(
|
||||
new Map([["app.ts", 'export const value = "ready" satisfies string;\n']]),
|
||||
);
|
||||
|
||||
expect(
|
||||
analysis.semantic_graph.nodes.filter(
|
||||
({ kind, properties }) =>
|
||||
kind === "literal" && properties.value === "ready",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("resolves erased wrappers through the composed application graph", async () => {
|
||||
const source = `
|
||||
const dependency = require("./dependency.ts")["value" as const] satisfies number;
|
||||
export { dependency };
|
||||
function render<T>() { return "ready"; }
|
||||
export const specialized = render<string> satisfies () => string;
|
||||
specialized();
|
||||
`;
|
||||
const analysis = await analyzeFiles(
|
||||
new Map([
|
||||
["app.mts", source],
|
||||
["dependency.ts", "export const value = 1;\n"],
|
||||
]),
|
||||
);
|
||||
|
||||
expect(analysis.graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
specifier: "./dependency.ts",
|
||||
imported_path: ["value"],
|
||||
resolved_path: "dependency.ts",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(analysis.semantic_graph.relations).toContainEqual(
|
||||
expect.objectContaining({ relation: "calls", resolution: "resolved" }),
|
||||
);
|
||||
expect(
|
||||
analysis.graph.nodes.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
semantic_role: "export-return-shapes",
|
||||
exported_name: "specialized",
|
||||
static_return_shapes: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
value_status: "literal",
|
||||
fields: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "", value: "ready" }),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(parseJavaScriptSource(source, "app.mts")?.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("applies TypeScript .mts ambiguity rules while retaining unambiguous generics", () => {
|
||||
expect(
|
||||
parseJavaScriptSource(
|
||||
"export const identity = <T,>(value: T) => value;",
|
||||
"app.mts",
|
||||
)?.errors,
|
||||
).toEqual([]);
|
||||
expect(
|
||||
parseJavaScriptSource(
|
||||
"export const identity = <T>(value: T) => value;",
|
||||
"app.mts",
|
||||
)?.errors.map(({ reasonCode }) => reasonCode),
|
||||
).toContain("ReservedArrowTypeParam");
|
||||
expect(parseJavaScriptSource("const value = <Widget />;", "app.mts")).toBe(
|
||||
null,
|
||||
);
|
||||
});
|
||||
+712
@@ -0,0 +1,712 @@
|
||||
import {
|
||||
primitiveCandidateExpansionSource,
|
||||
primitiveByteExpansionSource,
|
||||
} from "../../../fixtures/javascriptPrimitiveExpansion.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
reconstructJavaScriptArtifact,
|
||||
readJavaScriptArtifactFiles,
|
||||
} from "../../../support/javascriptApplicationScope.js";
|
||||
import {
|
||||
analyzeJavaScriptArtifactFiles,
|
||||
analyzeAndProjectJavaScriptArtifactFiles,
|
||||
} from "../../../../src/application/javascript/JavaScriptArtifactAnalysis.js";
|
||||
import { buildJavaScriptArtifactGraph } from "../../../../src/application/javascript/JavaScriptArtifactGraphBuilder.js";
|
||||
import {
|
||||
buildJavaScriptSemanticGraph,
|
||||
createJavaScriptSemanticGraphProjection,
|
||||
projectJavaScriptSemanticFileSteps,
|
||||
} from "../../../../src/application/javascript/JavaScriptSemanticGraphBuilder.js";
|
||||
import {
|
||||
projectJavaScriptModuleSemantics,
|
||||
type JavaScriptModuleSemanticIr,
|
||||
} from "../../../../src/domain/javascript/javascriptModuleSemanticIr.js";
|
||||
import type { JavaScriptStaticAnalysis } from "../../../../src/domain/javascript/javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "../../../../src/domain/javascript/javascriptArtifactFiles.js";
|
||||
import { completeJavaScriptAnalysisSteps } from "../../../../src/application/javascript/JavaScriptAnalysisControl.js";
|
||||
import {
|
||||
writeJavaScriptAnalysisTransfer,
|
||||
readJavaScriptAnalysisTransfer,
|
||||
} from "../../../../src/javascript/analysis/JavaScriptAnalysisTransfer.js";
|
||||
import { javaScriptWorkerStaticAnalysisSchema } from "../../../../src/javascript/analysis/JavaScriptAnalysisWorkerSchemas.js";
|
||||
import { createJavaScriptArtifactReader } from "../../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
|
||||
import {
|
||||
scanCanonicalArtifactInventory,
|
||||
scanArtifactInventory,
|
||||
} from "../../../fixtures/artifactInventory.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import {
|
||||
createJavaScriptSemanticGraph,
|
||||
isValidatedImmutableJavaScriptSemanticGraph,
|
||||
} from "../../../../src/domain/javascript/javascriptSemanticGraph.js";
|
||||
import { parseJavaScriptSemanticGraph } from "../../../../src/domain/javascript/javascriptSemanticGraphSerialization.js";
|
||||
import { writeJavaScriptArtifactFixture } from "../../../fixtures/javascriptArtifactApplication.js";
|
||||
|
||||
it("reports file progress and honors cancellation before the next source", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
const controller = new AbortController();
|
||||
const progress: string[] = [];
|
||||
await expect(
|
||||
reconstructJavaScriptArtifact({ input_path: root }, controller.signal, {
|
||||
report: async (event) => {
|
||||
if (event.phase === "parse_javascript_source") {
|
||||
progress.push(event.message);
|
||||
if (progress.length === 2) controller.abort();
|
||||
}
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "AnalysisCancelledError",
|
||||
partialObservation: { operation: "analyze_javascript_application" },
|
||||
});
|
||||
expect(progress).toHaveLength(2);
|
||||
expect(progress[0]).not.toBe(progress[1]);
|
||||
});
|
||||
|
||||
it("preserves graph commitments and export shapes when consuming file-local IR", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
await writeFile(
|
||||
join(root, "exports.mjs"),
|
||||
`
|
||||
import { readFile } from "node:fs";
|
||||
export { readFile as read };
|
||||
export function create(value) { return { value, nested: { enabled: true } }; }
|
||||
export function configured(condition) { return { values: [1, null, undefined], choice: condition ? 1 : 2, ...external }; }
|
||||
function unexported() { return "private"; }
|
||||
`,
|
||||
);
|
||||
const snapshot = await scanCanonicalArtifactInventory(root, {});
|
||||
const reader = createJavaScriptArtifactReader(root, "directory");
|
||||
try {
|
||||
const files = await readJavaScriptArtifactFiles(reader, snapshot);
|
||||
const full = analyzeJavaScriptArtifactFiles(files);
|
||||
const projection = createJavaScriptSemanticGraphProjection();
|
||||
const compact = await analyzeAndProjectJavaScriptArtifactFiles(
|
||||
files,
|
||||
projection.projectFile,
|
||||
);
|
||||
const graph = buildJavaScriptArtifactGraph(snapshot, files, full);
|
||||
expect(buildJavaScriptArtifactGraph(snapshot, files, compact)).toEqual(
|
||||
graph,
|
||||
);
|
||||
const semantic = projection.finish(snapshot.manifest.root_sha256, graph);
|
||||
expect(semantic).toEqual(
|
||||
buildJavaScriptSemanticGraph({
|
||||
rootArtifactSha256: snapshot.manifest.root_sha256,
|
||||
applicationGraph: graph,
|
||||
analysis: full,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
semantic.nodes.some(
|
||||
({ application_node_ids }) => application_node_ids.length > 0,
|
||||
),
|
||||
).toBe(true);
|
||||
const exported = compact.files.find(
|
||||
({ file }) => file.path === "exports.mjs",
|
||||
);
|
||||
expect(exported?.semantic?.ir.callables.map(({ name }) => name)).toEqual([
|
||||
"create",
|
||||
"configured",
|
||||
]);
|
||||
expect(
|
||||
full.files
|
||||
.find(({ file }) => file.path === "exports.mjs")
|
||||
?.semantic?.ir.callables.map(({ name }) => name),
|
||||
).toContain("unexported");
|
||||
expect(parseJavaScriptSemanticGraph(semantic)).toEqual(semantic);
|
||||
const transferred = createJavaScriptSemanticGraphProjection();
|
||||
const wireRoot = await createTestTempDirectory("rea-javascript-transfer-");
|
||||
const decodedModules = new Map<string, JavaScriptModuleSemanticIr>();
|
||||
const decodedStatic = new Map<string, JavaScriptStaticAnalysis>();
|
||||
let rejectedInvalidTransfer = false;
|
||||
for (const [index, analyzed] of full.files.entries()) {
|
||||
if (analyzed.javascript !== null) {
|
||||
const raw: unknown = JSON.parse(JSON.stringify(analyzed.javascript));
|
||||
const decodedFacts = javaScriptWorkerStaticAnalysisSchema.parse(raw);
|
||||
expect(decodedFacts).toEqual(analyzed.javascript);
|
||||
decodedStatic.set(analyzed.file.path, decodedFacts);
|
||||
}
|
||||
if (analyzed.semantic === null) continue;
|
||||
const fragment = await completeJavaScriptAnalysisSteps(
|
||||
projectJavaScriptSemanticFileSteps(
|
||||
analyzed.file,
|
||||
analyzed.semantic.ir,
|
||||
transferred.remainingFileNodeBudget(),
|
||||
),
|
||||
);
|
||||
const module = projectJavaScriptModuleSemantics(analyzed.semantic.ir);
|
||||
const wirePath = join(wireRoot, `${String(index)}.jsonl`);
|
||||
const descriptor = await writeJavaScriptAnalysisTransfer(
|
||||
wirePath,
|
||||
module,
|
||||
fragment,
|
||||
);
|
||||
const decoded = await readJavaScriptAnalysisTransfer(
|
||||
wirePath,
|
||||
descriptor,
|
||||
analyzed.file,
|
||||
);
|
||||
expect(decoded.module).toEqual(module);
|
||||
decodedModules.set(analyzed.file.path, decoded.module);
|
||||
transferred.adoptFileProjection(decoded.projection);
|
||||
if (!rejectedInvalidTransfer) {
|
||||
await rejectInvalidTransfer(
|
||||
wirePath,
|
||||
descriptor,
|
||||
analyzed.file,
|
||||
wireRoot,
|
||||
);
|
||||
rejectedInvalidTransfer = true;
|
||||
}
|
||||
}
|
||||
const decodedGraph = buildJavaScriptArtifactGraph(snapshot, files, {
|
||||
...compact,
|
||||
files: compact.files.map((analyzed) => {
|
||||
const module = decodedModules.get(analyzed.file.path);
|
||||
return {
|
||||
...analyzed,
|
||||
javascript:
|
||||
decodedStatic.get(analyzed.file.path) ?? analyzed.javascript,
|
||||
semantic: module === undefined ? analyzed.semantic : { ir: module },
|
||||
};
|
||||
}),
|
||||
});
|
||||
expect(decodedGraph).toEqual(graph);
|
||||
const resealed = await completeJavaScriptAnalysisSteps(
|
||||
transferred.finishImmutableSteps(
|
||||
snapshot.manifest.root_sha256,
|
||||
decodedGraph,
|
||||
),
|
||||
);
|
||||
expect(resealed).toEqual(semantic);
|
||||
expect(isValidatedImmutableJavaScriptSemanticGraph(resealed)).toBe(true);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
const rejectInvalidTransfer = async (
|
||||
wirePath: string,
|
||||
descriptor: Awaited<ReturnType<typeof writeJavaScriptAnalysisTransfer>>,
|
||||
file: JavaScriptArtifactFile,
|
||||
wireRoot: string,
|
||||
): Promise<void> => {
|
||||
await expect(
|
||||
readJavaScriptAnalysisTransfer(wirePath, descriptor, {
|
||||
...file,
|
||||
sha256: "0".repeat(64),
|
||||
}),
|
||||
).rejects.toThrow("different artifact source");
|
||||
await expect(
|
||||
readJavaScriptAnalysisTransfer(
|
||||
wirePath,
|
||||
{ ...descriptor, sha256: "0".repeat(64) },
|
||||
file,
|
||||
),
|
||||
).rejects.toThrow("digest does not match");
|
||||
const wire = await readFile(wirePath, "utf8");
|
||||
const duplicate = wire
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith('{"kind":"node"'));
|
||||
if (duplicate === undefined)
|
||||
throw new Error("Fixture emitted no semantic node record");
|
||||
const invalid = `${wire}${duplicate}\n`;
|
||||
const invalidPath = join(wireRoot, "duplicate.jsonl");
|
||||
await writeFile(invalidPath, invalid);
|
||||
await expect(
|
||||
readJavaScriptAnalysisTransfer(
|
||||
invalidPath,
|
||||
{
|
||||
...descriptor,
|
||||
bytes: Buffer.byteLength(invalid),
|
||||
records: descriptor.records + 1,
|
||||
graph_bytes: descriptor.graph_bytes + Buffer.byteLength(duplicate) + 1,
|
||||
graph_records: descriptor.graph_records + 1,
|
||||
sha256: createHash("sha256").update(invalid).digest("hex"),
|
||||
},
|
||||
file,
|
||||
),
|
||||
).rejects.toThrow("Duplicate JavaScript transfer node identity");
|
||||
};
|
||||
|
||||
it("reports semantic value resource limits in application graph coverage", async () => {
|
||||
const root = await createTestTempDirectory("rea-javascript-semantic-limit-");
|
||||
await writeFile(join(root, "app.js"), primitiveCandidateExpansionSource());
|
||||
await writeFile(join(root, "growth.js"), primitiveByteExpansionSource());
|
||||
const snapshot = await scanCanonicalArtifactInventory(root, {});
|
||||
const reader = createJavaScriptArtifactReader(root, "directory");
|
||||
try {
|
||||
const files = await readJavaScriptArtifactFiles(reader, snapshot);
|
||||
const analysis = analyzeJavaScriptArtifactFiles(files);
|
||||
const graph = buildJavaScriptArtifactGraph(snapshot, files, analysis);
|
||||
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
omitted_count: null,
|
||||
limits: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "javascript_semantic_primitive_candidates",
|
||||
unit: "items",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "javascript_semantic_primitive_bytes",
|
||||
unit: "bytes",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
const sourceModuleLimits = graph.nodes
|
||||
.filter(({ kind }) => kind === "javascript-module")
|
||||
.flatMap(({ observations }) => observations)
|
||||
.filter(
|
||||
({ evidence }) =>
|
||||
evidence.extractor.operation === "recover-source-module",
|
||||
)
|
||||
.flatMap(({ evidence }) => evidence.coverage.limits);
|
||||
expect(sourceModuleLimits).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "javascript_semantic_primitive_candidates",
|
||||
unit: "items",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "javascript_semantic_primitive_bytes",
|
||||
unit: "bytes",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(graph.limitations).toContain(
|
||||
"Primitive candidate budget exceeded (maximum 256 alternatives).",
|
||||
);
|
||||
expect(graph.limitations).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringMatching(/primitive string-byte budget exceeded/i),
|
||||
]),
|
||||
);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reconstructs package, Electron roles, Webpack/Rspack modules, and cross-layer facts without execution", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
Reflect.deleteProperty(globalThis, "__rea_bundle_executed");
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
});
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
const semanticGraph = parseJavaScriptSemanticGraph(result.semantic_graph);
|
||||
|
||||
expect(Reflect.get(globalThis, "__rea_bundle_executed")).toBeUndefined();
|
||||
expect(result.input_path).toBe(root);
|
||||
expect(result.statistics).toMatchObject({
|
||||
modules: 4,
|
||||
parse_failures: 0,
|
||||
relevant_files: expect.any(Number),
|
||||
text_bytes_read: expect.any(Number),
|
||||
});
|
||||
expect(graph.nodes.map(({ kind }) => kind)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"package",
|
||||
"artifact",
|
||||
"electron-main",
|
||||
"electron-preload",
|
||||
"electron-renderer",
|
||||
"javascript-asset",
|
||||
"javascript-chunk",
|
||||
"javascript-module",
|
||||
"worker",
|
||||
"service-worker",
|
||||
"endpoint",
|
||||
"storage",
|
||||
"source-map",
|
||||
"source-module",
|
||||
"native-addon",
|
||||
]),
|
||||
);
|
||||
expect(graph.nodes.filter(({ kind }) => kind === "javascript-chunk")).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({ bundler: "webpack" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({ bundler: "rspack" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
graph.nodes.filter(({ kind }) => kind === "javascript-module"),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
module_key: "1",
|
||||
structural_fingerprint_algorithm: "babel-ast-v1",
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(graph.edges.map(({ relation }) => relation)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"contains",
|
||||
"loads",
|
||||
"imports",
|
||||
"maps_to",
|
||||
"exposes",
|
||||
"calls",
|
||||
"persists_to",
|
||||
]),
|
||||
);
|
||||
assertSemanticLinks(result, graph, semanticGraph);
|
||||
});
|
||||
|
||||
it("produces deterministic ASAR graphs with unpacked native linkage and complete paths/digests", async () => {
|
||||
const root = await createTestTempDirectory("rea-javascript-asar-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
await writeJavaScriptArtifactFixture(source);
|
||||
const archive = join(root, "app.asar");
|
||||
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
|
||||
|
||||
const first = await reconstructJavaScriptArtifact({
|
||||
input_path: archive,
|
||||
format: "asar",
|
||||
});
|
||||
const second = await reconstructJavaScriptArtifact({
|
||||
input_path: archive,
|
||||
format: "asar",
|
||||
});
|
||||
|
||||
expect(first.graph).toEqual(second.graph);
|
||||
expect(first.inventory_graph_sha256).toBe(second.inventory_graph_sha256);
|
||||
expect(first.graph.nodes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "asar-entry",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
entry_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
inventory_artifact_id:
|
||||
expect.stringMatching(/^art_[a-f0-9]{64}$/u),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "native-addon",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
path: "native/addon.node",
|
||||
unpacked: true,
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(first.graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "loads",
|
||||
properties: expect.objectContaining({
|
||||
resolved_path: "native/addon.node",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps suffix-named ASAR directories in the graph and analyzes their files", async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-javascript-asar-suffix-directory-",
|
||||
);
|
||||
const source = join(root, "source");
|
||||
const zipDirectory = join(source, "node_modules", "@zip.js");
|
||||
await mkdir(zipDirectory, { recursive: true });
|
||||
await writeJavaScriptArtifactFixture(source);
|
||||
await writeFile(
|
||||
join(zipDirectory, "entry.js"),
|
||||
"export const packed = true;\n",
|
||||
);
|
||||
const archive = join(root, "app.asar");
|
||||
await createPackageWithOptions(source, archive, {});
|
||||
|
||||
const snapshot = await scanArtifactInventory(archive);
|
||||
const zipDirectoryOccurrence = snapshot.occurrences.find(
|
||||
({ logical_path }) => logical_path === "node_modules/@zip.js",
|
||||
);
|
||||
expect(zipDirectoryOccurrence).toMatchObject({
|
||||
entry_kind: "directory",
|
||||
artifact_id: expect.stringMatching(/^art_[a-f0-9]{64}$/u),
|
||||
});
|
||||
expect(
|
||||
snapshot.nodes.some(
|
||||
({ artifact_id }) => artifact_id === zipDirectoryOccurrence?.artifact_id,
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
await reconstructAsarArchive(archive, [
|
||||
expect.objectContaining({
|
||||
kind: "javascript-asset",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
path: "node_modules/@zip.js/entry.js",
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps ASAR analysis usable when unpacked native companion bytes are absent", async () => {
|
||||
const root = await createTestTempDirectory("rea-javascript-asar-missing-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
await writeJavaScriptArtifactFixture(source);
|
||||
const archive = join(root, "app.asar");
|
||||
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
|
||||
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
|
||||
|
||||
const snapshot = await scanArtifactInventory(archive);
|
||||
const missingNative = snapshot.occurrences.find(
|
||||
({ logical_path }) => logical_path === "native/addon.node",
|
||||
);
|
||||
|
||||
expect(missingNative).toMatchObject({
|
||||
artifact_id: null,
|
||||
hash_status: "unavailable",
|
||||
limitations: expect.arrayContaining([
|
||||
"ASAR unpacked companion bytes were unavailable; no content hash or child artifact was produced.",
|
||||
]),
|
||||
});
|
||||
|
||||
await reconstructAsarArchive(archive, [
|
||||
expect.objectContaining({ kind: "javascript-asset" }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("recurses into filesystem-backed ASAR containers without losing container-relative paths", async () => {
|
||||
const root = await createTestTempDirectory("rea-javascript-nested-asar-");
|
||||
const source = await fixtureDirectory();
|
||||
const outer = join(root, "outer");
|
||||
const resources = join(outer, "resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
await createPackageWithOptions(source, join(resources, "app.asar"), {
|
||||
unpack: "**/*.node",
|
||||
});
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: outer,
|
||||
});
|
||||
|
||||
expect(result.statistics.nested_asar_containers).toBe(1);
|
||||
expect(result.statistics.modules).toBe(4);
|
||||
expect(result.graph.nodes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "artifact",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
label: "resources/app.asar",
|
||||
properties: expect.objectContaining({ format: "asar" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "javascript-asset",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
path: "resources/app.asar/main.js",
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
const assertSemanticLinks = (
|
||||
result: Awaited<ReturnType<typeof reconstructJavaScriptArtifact>>,
|
||||
graph: ReturnType<typeof parseJavaScriptApplicationGraph>,
|
||||
semanticGraph: ReturnType<typeof parseJavaScriptSemanticGraph>,
|
||||
) => {
|
||||
expect(semanticGraph.application_graph_id).toBe(graph.graph_id);
|
||||
const { graph_id: _semanticGraphId, ...semanticGraphInput } = semanticGraph;
|
||||
const mismatchedSemanticGraph = createJavaScriptSemanticGraph({
|
||||
...semanticGraphInput,
|
||||
application_graph_id: `jag_${"f".repeat(64)}`,
|
||||
});
|
||||
const { electron_summary: summary, ...analysisResult } = result;
|
||||
expect(() =>
|
||||
javascriptApplicationAnalysisResultSchema.parse({
|
||||
...analysisResult,
|
||||
summary,
|
||||
semantic_graph: mismatchedSemanticGraph,
|
||||
}),
|
||||
).toThrow(/must commit the containing application graph/u);
|
||||
expect(
|
||||
semanticGraph.nodes.some(
|
||||
({ application_node_ids: identifiers }) => identifiers.length > 0,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(semanticGraph.relations.length).toBeGreaterThan(0);
|
||||
const roles = ["electron-main", "electron-preload"].map((kind) =>
|
||||
graph.nodes.find((node) => node.kind === kind),
|
||||
);
|
||||
expect(roles[0]?.observations[0]?.properties).toMatchObject({
|
||||
declared_path: "main.js",
|
||||
resolution_context: "package-entrypoint",
|
||||
resolved_path: "main.js",
|
||||
resolution_status: "resolved",
|
||||
limitations: [],
|
||||
});
|
||||
expect(roles[1]?.observations[0]?.properties).toMatchObject({
|
||||
declared_path: "preload.js",
|
||||
resolution_context: "filesystem-expression",
|
||||
resolved_path: "preload.js",
|
||||
resolution_status: "resolved",
|
||||
limitations: [],
|
||||
});
|
||||
const mainAsset = graph.nodes.find(
|
||||
(node) =>
|
||||
node.kind === "javascript-asset" &&
|
||||
node.observations.some(
|
||||
({ evidence }) =>
|
||||
evidence.location.available &&
|
||||
evidence.location.value.kind === "artifact-path" &&
|
||||
evidence.location.value.path === "main.js",
|
||||
),
|
||||
);
|
||||
if (mainAsset === undefined)
|
||||
throw new Error("Expected main JavaScript asset");
|
||||
const mainSemanticNodes = semanticGraph.nodes.filter(
|
||||
({ identity }) => identity.module_path === "main.js",
|
||||
);
|
||||
const linkedMainSemanticNodes = mainSemanticNodes.filter(
|
||||
({ application_node_ids: identifiers }) =>
|
||||
identifiers.includes(mainAsset.node_id),
|
||||
);
|
||||
expect(linkedMainSemanticNodes.length).toBeGreaterThan(0);
|
||||
expect(linkedMainSemanticNodes.length).toBeLessThan(mainSemanticNodes.length);
|
||||
for (const role of roles) {
|
||||
expect(role).toBeDefined();
|
||||
expect(
|
||||
graph.edges.some(
|
||||
(edge) =>
|
||||
edge.source_node_id === role?.node_id && edge.relation === "maps_to",
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
const endpointJson = JSON.stringify(
|
||||
graph.nodes.filter(({ kind }) => kind === "endpoint"),
|
||||
);
|
||||
expect(endpointJson).toContain("token=fixture-secret");
|
||||
};
|
||||
|
||||
const reconstructAsarArchive = async (
|
||||
archive: string,
|
||||
expectedNodes: readonly unknown[],
|
||||
): Promise<Awaited<ReturnType<typeof reconstructJavaScriptArtifact>>> => {
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: archive,
|
||||
format: "asar",
|
||||
});
|
||||
expect(result.statistics.parsed_javascript_files).toBeGreaterThan(0);
|
||||
expect(result.graph.nodes).toEqual(
|
||||
expect.arrayContaining([...expectedNodes]),
|
||||
);
|
||||
return result;
|
||||
};
|
||||
|
||||
const fixtureDirectory = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-javascript-artifact-");
|
||||
await writeJavaScriptArtifactFixture(root);
|
||||
return root;
|
||||
};
|
||||
|
||||
for (const extension of ["ts", "tsx", "mts", "cts", "js", "mjs", "cjs"]) {
|
||||
it.each(["directory", "asar"] as const)(
|
||||
`retains ${extension} source facts from a real %s artifact`,
|
||||
async (format) => {
|
||||
const root = await createTestTempDirectory("rea-nodenext-artifacts-");
|
||||
const directory = join(root, "source");
|
||||
await mkdir(directory);
|
||||
const path = `selected.${extension}`;
|
||||
const parameter = ["ts", "tsx", "mts", "cts"].includes(extension)
|
||||
? "value: string"
|
||||
: "value";
|
||||
const source = `
|
||||
globalThis.__rea_nodenext_executed = true;
|
||||
throw new Error("fixture must remain inert");
|
||||
export function selected_feature(${parameter}) { return { value }; }
|
||||
`;
|
||||
await writeFile(join(directory, path), source);
|
||||
let inputPath = directory;
|
||||
if (format === "asar") {
|
||||
inputPath = join(root, "application.asar");
|
||||
await createPackageWithOptions(directory, inputPath, {});
|
||||
}
|
||||
Reflect.deleteProperty(globalThis, "__rea_nodenext_executed");
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: inputPath,
|
||||
format,
|
||||
});
|
||||
expect(
|
||||
Reflect.get(globalThis, "__rea_nodenext_executed"),
|
||||
).toBeUndefined();
|
||||
expect(result.statistics).toMatchObject({
|
||||
relevant_files: 1,
|
||||
parsed_javascript_files: 1,
|
||||
text_bytes_read: Buffer.byteLength(source),
|
||||
parse_failures: 0,
|
||||
});
|
||||
const asset = result.graph.nodes.find(
|
||||
({ kind, observations }) =>
|
||||
kind === "javascript-asset" &&
|
||||
observations.some(({ properties }) => properties.path === path),
|
||||
);
|
||||
expect(asset?.identity).toMatchObject({
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
});
|
||||
expect(asset?.observations[0]?.properties).toMatchObject({
|
||||
path,
|
||||
bytes: Buffer.byteLength(source),
|
||||
file_kind: "javascript",
|
||||
parse_status: "complete",
|
||||
});
|
||||
expect(
|
||||
result.semantic_graph.nodes.some(
|
||||
({ identity }) => identity.module_path === path,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(result.graph.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
findChunkNode,
|
||||
findGraphEdge,
|
||||
findModuleNodeByKey,
|
||||
reconstructJavaScriptFixture,
|
||||
writeFixtureFiles,
|
||||
} from "../../../support/javascriptApplicationFixture.js";
|
||||
|
||||
describe("Webpack and Rspack runtime adapters", () => {
|
||||
it("recovers runtime entry modules, async chunks, and factory require aliases", async () => {
|
||||
const root = await bundlerFixture();
|
||||
const result = await reconstructJavaScriptFixture(root);
|
||||
const graph = result.graph;
|
||||
|
||||
const webpackEntry = findChunkNode(
|
||||
graph,
|
||||
"webpackChunkcustomPortal",
|
||||
"main",
|
||||
);
|
||||
const webpackLazy = findChunkNode(
|
||||
graph,
|
||||
"webpackChunkcustomPortal",
|
||||
"lazy",
|
||||
);
|
||||
const webpackModule = findModuleNodeByKey(graph, "10");
|
||||
const rspackEntry = findChunkNode(
|
||||
graph,
|
||||
"rspackChunkcustomPortal",
|
||||
"editor",
|
||||
);
|
||||
const rspackModel = findChunkNode(
|
||||
graph,
|
||||
"rspackChunkcustomPortal",
|
||||
"model",
|
||||
);
|
||||
const rspackModule = findModuleNodeByKey(graph, "src/entry.ts");
|
||||
|
||||
expect(webpackEntry?.observations[0]?.properties).toMatchObject({
|
||||
bundler: "webpack",
|
||||
runtime_require_name: "__webpack_require__",
|
||||
runtime_module_cache_status: "not-observed",
|
||||
entry_module_keys: ["10"],
|
||||
async_chunk_keys: ["lazy", "missing"],
|
||||
unknown_async_chunk_keys: 1,
|
||||
});
|
||||
expect(webpackModule?.observations[0]?.properties).toMatchObject({
|
||||
factory_require_name: "__webpack_require__",
|
||||
runtime_entry: true,
|
||||
chunk_keys: ["main"],
|
||||
});
|
||||
expect(rspackEntry?.observations[0]?.properties).toMatchObject({
|
||||
bundler: "rspack",
|
||||
runtime_require_name: "r",
|
||||
runtime_module_cache_status: "not-observed",
|
||||
entry_module_keys: ["src/entry.ts"],
|
||||
async_chunk_keys: ["model"],
|
||||
});
|
||||
expect(rspackModule?.observations[0]?.properties).toMatchObject({
|
||||
factory_require_name: "r",
|
||||
runtime_entry: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
findGraphEdge(graph, webpackEntry, webpackModule, "loads"),
|
||||
).toMatchObject({
|
||||
properties: expect.objectContaining({
|
||||
kind: "bundler-entry-module",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
});
|
||||
expect(
|
||||
findGraphEdge(graph, webpackEntry, webpackLazy, "imports"),
|
||||
).toMatchObject({
|
||||
properties: expect.objectContaining({
|
||||
kind: "bundler-async-chunk",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
});
|
||||
expect(
|
||||
findGraphEdge(graph, webpackModule, webpackLazy, "imports"),
|
||||
).toMatchObject({
|
||||
properties: expect.objectContaining({
|
||||
kind: "dynamic-import",
|
||||
specifier: "chunk:lazy",
|
||||
resolved_path: "renderer/chunks/runtime.js#chunk:lazy",
|
||||
}),
|
||||
});
|
||||
expect(
|
||||
findGraphEdge(graph, rspackEntry, rspackModel, "imports"),
|
||||
).toMatchObject({
|
||||
properties: expect.objectContaining({
|
||||
kind: "bundler-async-chunk",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
});
|
||||
expect(
|
||||
findGraphEdge(graph, rspackModule, rspackModel, "imports"),
|
||||
).toMatchObject({
|
||||
properties: expect.objectContaining({
|
||||
kind: "dynamic-import",
|
||||
specifier: "chunk:model",
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
graph.nodes.find((node) =>
|
||||
node.observations.some(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "bundler-chunk-reference" &&
|
||||
properties.chunk_key === "missing" &&
|
||||
properties.resolution_status === "not-found",
|
||||
),
|
||||
),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
graph.edges.some(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "require" &&
|
||||
properties.specifier === "lazy",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("recovers esbuild wrapper modules and Vite preload dependencies", async () => {
|
||||
const root = await esmRuntimeFixture();
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const commonJsModule = findModuleNodeByKey(graph, "src/dep.js");
|
||||
const esmModule = findModuleNodeByKey(graph, "src/core.js");
|
||||
|
||||
expect(commonJsModule?.observations[0]?.properties).toMatchObject({
|
||||
bundler: "esbuild",
|
||||
runtime: "esbuild-commonjs",
|
||||
module_key: "src/dep.js",
|
||||
});
|
||||
expect(esmModule?.observations[0]?.properties).toMatchObject({
|
||||
bundler: "esbuild",
|
||||
runtime: "esbuild-esm",
|
||||
module_key: "src/core.js",
|
||||
});
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "dynamic-import" &&
|
||||
["./feature.js", "./main.css"].includes(String(properties.specifier)),
|
||||
),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
const bundlerFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-bundler-adapters-");
|
||||
await writeFixtureFiles(root, {
|
||||
"renderer/chunks/runtime.js": `
|
||||
// A cache-like name here is not evidence about either registration.
|
||||
const documentation = "__webpack_module_cache__";
|
||||
(globalThis["webpackChunkcustomPortal"] = globalThis["webpackChunkcustomPortal"] || []).push([
|
||||
["main"],
|
||||
{
|
||||
10: (module, exports, __webpack_require__) => {
|
||||
const direct = __webpack_require__(11);
|
||||
const lazy = __webpack_require__.e("lazy").then(
|
||||
__webpack_require__.bind(__webpack_require__, 20)
|
||||
);
|
||||
const missing = __webpack_require__.e("missing");
|
||||
const dynamicChunk = window.name;
|
||||
__webpack_require__.e(dynamicChunk);
|
||||
exports.start = () => [direct, lazy, missing];
|
||||
},
|
||||
11: (module) => { module.exports = "direct"; }
|
||||
},
|
||||
(__webpack_require__) => {
|
||||
__webpack_require__.O(0, ["main"], () => __webpack_require__(10));
|
||||
}
|
||||
]);
|
||||
(globalThis["webpackChunkcustomPortal"] = globalThis["webpackChunkcustomPortal"] || []).push([
|
||||
["lazy"],
|
||||
{
|
||||
20: (module) => {
|
||||
// A marker in a different registration must not be inherited.
|
||||
const documentation = "installedModules";
|
||||
module.exports = "lazy";
|
||||
}
|
||||
}
|
||||
]);
|
||||
(self.rspackChunkcustomPortal = self.rspackChunkcustomPortal || []).push([
|
||||
["editor"],
|
||||
{
|
||||
"src/entry.ts": (module, exports, r) => {
|
||||
r.e("model").then(r.bind(r, "src/model.ts"));
|
||||
exports.render = () => r("src/model.ts");
|
||||
}
|
||||
},
|
||||
(r) => { r("src/entry.ts"); }
|
||||
]);
|
||||
(self.rspackChunkcustomPortal = self.rspackChunkcustomPortal || []).push([
|
||||
["model"],
|
||||
{
|
||||
"src/model.ts": (module) => { module.exports = "model"; }
|
||||
}
|
||||
]);
|
||||
`,
|
||||
});
|
||||
return root;
|
||||
};
|
||||
|
||||
const esmRuntimeFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-esm-runtime-adapters-");
|
||||
await writeFixtureFiles(root, {
|
||||
"main.js": `
|
||||
const __vite__mapDeps = (indexes, map = __vite__mapDeps, dependencies =
|
||||
(map.f || (map.f = ["./feature.js", "./main.css"]))) =>
|
||||
indexes.map((index) => dependencies[index]);
|
||||
const require_dep = __commonJS({
|
||||
"src/dep.js"(exports, module) {
|
||||
module.exports = { value: 1 };
|
||||
}
|
||||
});
|
||||
const init_core = __esm({
|
||||
"src/core.js"() {
|
||||
require_dep();
|
||||
}
|
||||
});
|
||||
__vite__mapDeps([0, 1]);
|
||||
init_core();
|
||||
`,
|
||||
"feature.js": "export const feature = true;",
|
||||
"main.css": ".app { color: green; }",
|
||||
});
|
||||
return root;
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
import { parseExpression } from "@babel/parser";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { staticPath } from "../../../../src/domain/javascript/javascriptStaticAnalysisHelpers.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
|
||||
const urlCases = [
|
||||
["./preload%20name.cjs", "preload name.cjs", "main.mjs"],
|
||||
["./pr%C3%A9load.cjs", "préload.cjs", "main.mjs"],
|
||||
["./preload%3F%23.cjs", "preload?#.cjs", "main.mjs"],
|
||||
["./preload.cjs?cache=1#v2", "preload.cjs", "main.mjs"],
|
||||
["../preload.cjs?cache=1", "preload.cjs", "src/main.mjs"],
|
||||
["./sub/../preload.cjs", "preload.cjs", "main.mjs"],
|
||||
["./preload.cjs", "preload.cjs", "main.mjs"],
|
||||
] as const;
|
||||
|
||||
const unknownExpressions = [
|
||||
'fileURLToPath(new URL("./invalid%.cjs", import.meta.url))',
|
||||
'fileURLToPath(new URL("./preload%2fname.cjs", import.meta.url))',
|
||||
'fileURLToPath(new URL("./preload%5cname.cjs", import.meta.url))',
|
||||
'fileURLToPath(new URL("./%2e/preload.cjs", import.meta.url))',
|
||||
'fileURLToPath(new URL("https://example.test/preload.cjs", import.meta.url))',
|
||||
'fileURLToPath(new URL("//example.test/preload.cjs", import.meta.url))',
|
||||
'fileURLToPath(new URL("#fragment", import.meta.url))',
|
||||
'fileURLToPath(new URL("?cache=1", import.meta.url))',
|
||||
'fileURLToPath(new URL("./preload.cjs", runtimeBase))',
|
||||
"fileURLToPath(new URL(runtimePath, import.meta.url))",
|
||||
'convertFileURLToPath(new URL("./preload.cjs", import.meta.url))',
|
||||
];
|
||||
|
||||
describe("source-relative file URL paths", () => {
|
||||
it.each(urlCases)(
|
||||
"resolves %s to the file read by Node",
|
||||
async (reference, target, sourcePath) => {
|
||||
const root = await createTestTempDirectory("rea-file-url-path-");
|
||||
const sourceFile = join(root, sourcePath);
|
||||
await mkdir(dirname(sourceFile), { recursive: true });
|
||||
await writeFile(join(root, target), 'module.exports = "real preload";\n');
|
||||
if (reference.includes("%") && sourcePath === "main.mjs")
|
||||
await writeFile(
|
||||
join(root, reference),
|
||||
'module.exports = "encoded-name decoy";\n',
|
||||
);
|
||||
const nativePath = fileURLToPath(
|
||||
new URL(reference, pathToFileURL(sourceFile)),
|
||||
);
|
||||
expect(relative(root, nativePath)).toBe(target);
|
||||
expect(await readFile(nativePath, "utf8")).toContain("real preload");
|
||||
await writeFile(
|
||||
sourceFile,
|
||||
`import { fileURLToPath } from "node:url";\nnew BrowserWindow({ webPreferences: { preload: fileURLToPath(new URL(${JSON.stringify(reference)}, import.meta.url)) } });\n`,
|
||||
);
|
||||
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
const preloads = graph.nodes.filter(
|
||||
({ kind }) => kind === "electron-preload",
|
||||
);
|
||||
expect(preloads).toHaveLength(1);
|
||||
expect(preloads[0]?.observations).not.toHaveLength(0);
|
||||
for (const observation of preloads[0]?.observations ?? [])
|
||||
expect(observation.properties).toMatchObject({
|
||||
resolved_path: target,
|
||||
resolution_status: "resolved",
|
||||
resolution_context: "filesystem-expression",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(unknownExpressions)("leaves unsupported %s unknown", (expression) => {
|
||||
expect(
|
||||
staticPath(parseExpression(expression, { sourceType: "module" })),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not URL-decode literal filesystem punctuation", () => {
|
||||
const expression = 'path.join(__dirname, "preload%20?#.cjs")';
|
||||
expect(
|
||||
staticPath(parseExpression(expression, { sourceType: "module" })),
|
||||
).toBe("preload%20?#.cjs");
|
||||
});
|
||||
});
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { reconstructJavaScriptArtifact } from "../../../support/javascriptApplicationScope.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("resolves empty-path HTML script URLs against their canonical base path", async () => {
|
||||
const root = await createTestTempDirectory("rea-html-empty-reference-");
|
||||
await Promise.all([
|
||||
mkdir(join(root, "base-file", "assets"), { recursive: true }),
|
||||
mkdir(join(root, "base-directory", "assets"), { recursive: true }),
|
||||
mkdir(join(root, "escaped"), { recursive: true }),
|
||||
]);
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "document.html"),
|
||||
'<script src="?document=1"></script><script src="#document-fragment"></script>',
|
||||
),
|
||||
writeFile(
|
||||
join(root, "base-file", "index.html"),
|
||||
'<base href="assets/entry.html?base=1#base-fragment"><script src="?base-file=1#script-fragment"></script>',
|
||||
),
|
||||
writeFile(join(root, "base-file", "assets", "entry.html"), "<main></main>"),
|
||||
writeFile(
|
||||
join(root, "base-directory", "index.html"),
|
||||
'<base href="assets/"><script src="?base-directory=1"></script>',
|
||||
),
|
||||
writeFile(
|
||||
join(root, "base-directory", "assets", "index.js"),
|
||||
"export const value = 1;",
|
||||
),
|
||||
writeFile(
|
||||
join(root, "escaped", "index.html"),
|
||||
'<base href="../../outside/"><script src="?escape=1"></script>',
|
||||
),
|
||||
]);
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
const graph = result.graph;
|
||||
const loadFor = (scriptPath: string) =>
|
||||
graph.edges.find(
|
||||
(edge) =>
|
||||
edge.relation === "loads" && edge.properties.script_path === scriptPath,
|
||||
);
|
||||
const targetPath = (edge: NonNullable<ReturnType<typeof loadFor>>) =>
|
||||
graph.nodes
|
||||
.find(({ node_id }) => node_id === edge.target_node_id)
|
||||
?.observations.find(
|
||||
({ properties }) => typeof properties.path === "string",
|
||||
)?.properties.path;
|
||||
const unresolvedReference = (scriptPath: string) =>
|
||||
graph.nodes
|
||||
.flatMap(({ observations }) => observations)
|
||||
.find(
|
||||
({ properties }) =>
|
||||
properties.mechanism === "html-script-reference" &&
|
||||
properties.script_path === scriptPath,
|
||||
)?.properties;
|
||||
|
||||
for (const scriptPath of ["?document=1", "#document-fragment"]) {
|
||||
const edge = loadFor(scriptPath);
|
||||
expect(edge).toMatchObject({
|
||||
properties: {
|
||||
script_path: scriptPath,
|
||||
resolved_path: "document.html",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
});
|
||||
if (edge !== undefined) expect(targetPath(edge)).toBe("document.html");
|
||||
}
|
||||
|
||||
const baseFileEdge = loadFor("?base-file=1#script-fragment");
|
||||
expect(baseFileEdge).toMatchObject({
|
||||
properties: {
|
||||
script_path: "?base-file=1#script-fragment",
|
||||
base_href: "assets/entry.html?base=1#base-fragment",
|
||||
resolved_path: "base-file/assets/entry.html",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
});
|
||||
if (baseFileEdge !== undefined)
|
||||
expect(targetPath(baseFileEdge)).toBe("base-file/assets/entry.html");
|
||||
|
||||
expect(unresolvedReference("?base-directory=1")).toMatchObject({
|
||||
resolution_status: "not-found",
|
||||
limitations: [expect.stringContaining("resolves to directory")],
|
||||
});
|
||||
expect(unresolvedReference("?escape=1")).toMatchObject({
|
||||
resolution_status: "rejected",
|
||||
limitations: [
|
||||
expect.stringContaining("escapes the canonical artifact root"),
|
||||
],
|
||||
});
|
||||
});
|
||||
+521
@@ -0,0 +1,521 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
|
||||
import {
|
||||
findExportNode,
|
||||
findRelationshipEdge,
|
||||
findSourceModule,
|
||||
reconstructJavaScriptFixture,
|
||||
writeFixtureFiles,
|
||||
} from "../../../support/javascriptApplicationFixture.js";
|
||||
|
||||
describe("TypeScript source module loader semantics", () => {
|
||||
it("keeps whole type-only declarations out of runtime module relationships", async () => {
|
||||
const root = await createTestTempDirectory("rea-type-module-links-");
|
||||
await writeFixtureFiles(root, {
|
||||
"main.ts": `
|
||||
import type { Whole } from "./whole";
|
||||
export type { Remote } from "./remote";
|
||||
import { type Inline } from "./inline";
|
||||
export type LocalType = string;
|
||||
export interface LocalInterface { value: string }
|
||||
`,
|
||||
"whole.ts": "export interface Whole { value: string }",
|
||||
"remote.ts": "export interface Remote { value: string }",
|
||||
"inline.ts": "export interface Inline { value: string }",
|
||||
});
|
||||
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const source = findSourceModule(graph, "main.ts");
|
||||
const sourceProperties = source?.observations.find(
|
||||
({ properties }) => properties.semantic_role === "source-module",
|
||||
)?.properties;
|
||||
|
||||
expect(sourceProperties).toMatchObject({
|
||||
import_relationships: 0,
|
||||
type_relationships: 5,
|
||||
export_names: [],
|
||||
type_export_names: ["LocalInterface", "LocalType", "Remote"],
|
||||
});
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
["./whole", "./remote"].includes(String(properties.specifier)),
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ source_node_id, relation, properties }) =>
|
||||
source_node_id === source?.node_id &&
|
||||
relation === "imports" &&
|
||||
properties.kind === "static-import" &&
|
||||
properties.specifier === "./inline",
|
||||
),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
source?.observations
|
||||
.flatMap(({ evidence }) => evidence.limitations)
|
||||
.join(" "),
|
||||
).toContain(
|
||||
"inline type-only imports or re-exports may preserve a module side-effect dependency",
|
||||
);
|
||||
expect(findExportNode(graph, "main.ts", "LocalType")).toBeUndefined();
|
||||
expect(findExportNode(graph, "main.ts", "LocalInterface")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses emitted TypeScript loader semantics without changing dynamic imports", async () => {
|
||||
const root = await createTestTempDirectory("rea-cts-module-loader-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": '{"type":"module"}',
|
||||
"main.cts": `
|
||||
import local = require("./local");
|
||||
import selected from "conditional";
|
||||
export { retained } from "conditional";
|
||||
void import("conditional");
|
||||
void local;
|
||||
void selected;
|
||||
`,
|
||||
"consumer.mts": `
|
||||
import local = require("./local");
|
||||
export { local };
|
||||
`,
|
||||
"local.js": "module.exports = 42;",
|
||||
"node_modules/conditional/package.json": JSON.stringify({
|
||||
exports: {
|
||||
".": {
|
||||
import: "./esm.mjs",
|
||||
require: "./cjs.cjs",
|
||||
},
|
||||
},
|
||||
}),
|
||||
"node_modules/conditional/esm.mjs": "export const retained = 'esm';",
|
||||
"node_modules/conditional/cjs.cjs": "exports.retained = 'cjs';",
|
||||
});
|
||||
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const localRequireEdge = (sourcePath: string) => {
|
||||
const source = findSourceModule(graph, sourcePath);
|
||||
return graph.edges.find(
|
||||
({ source_node_id, relation, properties }) =>
|
||||
source_node_id === source?.node_id &&
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "require" &&
|
||||
properties.specifier === "./local",
|
||||
);
|
||||
};
|
||||
|
||||
expect(
|
||||
findSourceModule(graph, "main.cts")?.observations[0]?.properties,
|
||||
).toMatchObject({ module_format: "commonjs" });
|
||||
expect(localRequireEdge("main.cts")).toMatchObject({
|
||||
properties: { resolved_path: "local.js", local_name: "local" },
|
||||
});
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "import",
|
||||
specifier: "conditional",
|
||||
resolvedPath: "node_modules/conditional/cjs.cjs",
|
||||
localName: "selected",
|
||||
}),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "re-export",
|
||||
specifier: "conditional",
|
||||
resolvedPath: "node_modules/conditional/cjs.cjs",
|
||||
}),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "dynamic-import" &&
|
||||
properties.specifier === "conditional",
|
||||
),
|
||||
).toMatchObject({
|
||||
properties: {
|
||||
resolved_path: "node_modules/conditional/esm.mjs",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
findSourceModule(graph, "consumer.mts")?.observations[0]?.properties,
|
||||
).toMatchObject({ module_format: "esm" });
|
||||
expect(localRequireEdge("consumer.mts")).toMatchObject({
|
||||
properties: { resolved_path: "local.js", local_name: "local" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript module relationships", () => {
|
||||
it("composes bindings, re-exports, dynamic imports, and JSON modules", async () => {
|
||||
const root = await moduleFixture();
|
||||
const first = await reconstructJavaScriptFixture(root);
|
||||
const second = await reconstructJavaScriptFixture(root);
|
||||
const graph = first.graph;
|
||||
|
||||
expect(second.graph).toEqual(graph);
|
||||
expect(findSourceModule(graph, "main.cjs")).toBeDefined();
|
||||
expect(findSourceModule(graph, "consumer.mjs")).toBeDefined();
|
||||
expect(findSourceModule(graph, "dependency.mjs")).toBeDefined();
|
||||
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "require",
|
||||
specifier: "./dependency.mjs",
|
||||
resolvedPath: "dependency.mjs",
|
||||
importedName: "value",
|
||||
localName: "importedValue",
|
||||
}),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" && properties.specifier === "fixture-package",
|
||||
),
|
||||
).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({ resolved_path: null }),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "require",
|
||||
specifier: "fixture-package",
|
||||
resolvedPath: "node_modules/fixture-package/cjs.cjs",
|
||||
localName: "packageValue",
|
||||
}),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "import",
|
||||
specifier: "fixture-package",
|
||||
resolvedPath: "node_modules/fixture-package/esm.mjs",
|
||||
importedName: "default",
|
||||
localName: "packageDefault",
|
||||
}),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "import",
|
||||
specifier: "./values.js",
|
||||
resolvedPath: "values.js",
|
||||
importedName: "value",
|
||||
localName: "alias",
|
||||
}),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "re-export",
|
||||
specifier: "./star.js",
|
||||
resolvedPath: "star.js",
|
||||
importedName: "*",
|
||||
exportedName: "*",
|
||||
}),
|
||||
).toBeDefined();
|
||||
|
||||
const forwarded = findExportNode(graph, "main.cjs", "forwarded");
|
||||
expect(forwarded).toBeDefined();
|
||||
expect(
|
||||
graph.edges.some(
|
||||
({ source_node_id, relation, properties }) =>
|
||||
source_node_id === forwarded?.node_id &&
|
||||
relation === "imports" &&
|
||||
properties.resolved_path === "dependency.mjs" &&
|
||||
properties.imported_name === "value",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "dynamic-import" &&
|
||||
properties.resolved_path === "lazy.js",
|
||||
),
|
||||
).toMatchObject({
|
||||
source_node_id: findSourceModule(graph, "consumer.mjs")?.node_id,
|
||||
});
|
||||
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "require",
|
||||
specifier: "./data.json",
|
||||
resolvedPath: "data.json",
|
||||
})?.properties,
|
||||
).toMatchObject({
|
||||
target_file_kind: "json",
|
||||
target_json_status: "included",
|
||||
});
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "require",
|
||||
specifier: "./broken.json",
|
||||
resolvedPath: "broken.json",
|
||||
})?.properties,
|
||||
).toMatchObject({
|
||||
target_file_kind: "json",
|
||||
target_json_status: "invalid",
|
||||
});
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "require",
|
||||
specifier: "electron",
|
||||
})?.properties,
|
||||
).toMatchObject({ resolution_status: "external", resolved_path: null });
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "require" &&
|
||||
properties.specifier === null,
|
||||
)?.properties,
|
||||
).toMatchObject({ resolved_path: null });
|
||||
|
||||
expect(first.statistics.parse_failures).toBe(1);
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
});
|
||||
expect(graph.limitations.join(" ")).toMatch(/incomplete/iu);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Compiler-dependent TypeScript resolution", () => {
|
||||
it("retains only compiler-independent targets for .ts static imports", async () => {
|
||||
const root = await createTestTempDirectory("rea-ts-conditional-loader-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": '{"type":"commonjs"}',
|
||||
"main.ts": `import { value as different } from "different";
|
||||
import { value as same } from "same";
|
||||
void different; void same;`,
|
||||
"node_modules/different/package.json": JSON.stringify({
|
||||
exports: {
|
||||
".": {
|
||||
import: "./import.mjs",
|
||||
require: "./require.cjs",
|
||||
},
|
||||
},
|
||||
}),
|
||||
"node_modules/different/import.mjs": "export const value = 'import';",
|
||||
"node_modules/different/require.cjs": "exports.value = 'require';",
|
||||
"node_modules/same/package.json": JSON.stringify({
|
||||
exports: { ".": { import: "./shared.js", require: "./shared.js" } },
|
||||
}),
|
||||
"node_modules/same/shared.js": "export const value = 'shared';",
|
||||
});
|
||||
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const different = findRelationshipEdge(graph, {
|
||||
kind: "import",
|
||||
specifier: "different",
|
||||
localName: "different",
|
||||
});
|
||||
const same = findRelationshipEdge(graph, {
|
||||
kind: "import",
|
||||
specifier: "same",
|
||||
localName: "same",
|
||||
resolvedPath: "node_modules/same/shared.js",
|
||||
});
|
||||
const staticFinding = (specifier: string) =>
|
||||
graph.edges.find(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "static-import" &&
|
||||
properties.specifier === specifier,
|
||||
);
|
||||
|
||||
expect(
|
||||
findSourceModule(graph, "main.ts")?.observations[0]?.properties,
|
||||
).toMatchObject({ module_format: "unknown" });
|
||||
expect(different).toMatchObject({
|
||||
properties: {
|
||||
resolution_mode: "compiler-dependent",
|
||||
resolution_status: "unavailable",
|
||||
resolved_path: null,
|
||||
conditional_resolutions: [
|
||||
{
|
||||
mode: "import",
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "node_modules/different/import.mjs",
|
||||
},
|
||||
{
|
||||
mode: "require",
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "node_modules/different/require.cjs",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(same).toMatchObject({
|
||||
properties: {
|
||||
resolution_mode: "compiler-dependent",
|
||||
resolved_path: "node_modules/same/shared.js",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"compiler-dependent without retained compiler options",
|
||||
),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(staticFinding("different")).toMatchObject({
|
||||
properties: {
|
||||
resolution_mode: "compiler-dependent",
|
||||
resolution_status: "unavailable",
|
||||
conditional_resolutions: [
|
||||
{
|
||||
mode: "import",
|
||||
resolved_path: "node_modules/different/import.mjs",
|
||||
},
|
||||
{
|
||||
mode: "require",
|
||||
resolved_path: "node_modules/different/require.cjs",
|
||||
},
|
||||
],
|
||||
},
|
||||
evidence: {
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"compiler-dependent without retained compiler options",
|
||||
),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(staticFinding("same")).toMatchObject({
|
||||
properties: { resolved_path: "node_modules/same/shared.js" },
|
||||
evidence: {
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"compiler-dependent without retained compiler options",
|
||||
),
|
||||
]),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("does not assign one module origin to an export with colliding path encodings", async () => {
|
||||
const root = await createTestTempDirectory("rea-ambiguous-module-origin-");
|
||||
await writeFixtureFiles(root, {
|
||||
"index.js": String.raw`
|
||||
import * as ns from "./fixture.js";
|
||||
const selected = choice ? ns["a\0b"] : ns.a.b;
|
||||
export { selected };
|
||||
`,
|
||||
"fixture.js": "export const fixture = true;\n",
|
||||
});
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const applicationGraph = parseJavaScriptApplicationGraph(
|
||||
JSON.parse(JSON.stringify(graph)),
|
||||
);
|
||||
const selectedExport = findExportNode(
|
||||
applicationGraph,
|
||||
"index.js",
|
||||
"selected",
|
||||
);
|
||||
if (selectedExport === undefined)
|
||||
throw new Error("Expected the selected export node");
|
||||
|
||||
expect(
|
||||
applicationGraph.edges.filter(
|
||||
({ relation, source_node_id, properties }) =>
|
||||
relation === "imports" &&
|
||||
source_node_id === selectedExport.node_id &&
|
||||
properties.local_name === "selected",
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
describe("complete static application projections", () => {
|
||||
it("retains exports and JSON keys beyond the former projection prefix", async () => {
|
||||
const root = await moduleFixture();
|
||||
const exportNames = Array.from(
|
||||
{ length: 140 },
|
||||
(_, index) =>
|
||||
`export const retained_${String(index).padStart(3, "0")} = ${index};`,
|
||||
);
|
||||
const jsonKeys = Object.fromEntries(
|
||||
Array.from({ length: 140 }, (_, index) => [`key_${index}`, index]),
|
||||
);
|
||||
await Promise.all([
|
||||
writeFile(join(root, "many-exports.mjs"), exportNames.join("\n")),
|
||||
writeFile(join(root, "many.json"), JSON.stringify(jsonKeys)),
|
||||
]);
|
||||
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const module = findSourceModule(graph, "many-exports.mjs");
|
||||
const exportObservation = module?.observations.find(
|
||||
({ properties }) => properties.semantic_role === "source-module",
|
||||
);
|
||||
const json = graph.nodes.find((node) =>
|
||||
node.observations.some(
|
||||
({ properties }) => properties.path === "many.json",
|
||||
),
|
||||
);
|
||||
const jsonObservation = json?.observations.find(
|
||||
({ properties }) => properties.path === "many.json",
|
||||
);
|
||||
|
||||
expect(exportObservation?.properties.export_names).toHaveLength(140);
|
||||
expect(exportObservation?.properties.omitted_export_names).toBe(0);
|
||||
expect(jsonObservation?.properties.json_top_level_keys).toHaveLength(140);
|
||||
expect(jsonObservation?.properties.omitted_json_top_level_keys).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
const moduleFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-module-relationships-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": '{"main":"main.cjs"}',
|
||||
"main.cjs": `
|
||||
const { value: importedValue } = require("./dependency.mjs");
|
||||
const data = require("./data.json");
|
||||
const broken = require("./broken.json");
|
||||
const electron = require("electron");
|
||||
const packageValue = require("fixture-package");
|
||||
module.exports.forwarded = importedValue;
|
||||
exports.data = data;
|
||||
exports.broken = broken;
|
||||
exports.electron = electron;
|
||||
exports.packageValue = packageValue;
|
||||
require(dynamicName);
|
||||
`,
|
||||
"dependency.mjs": `
|
||||
export { value } from "./values.js";
|
||||
export * from "./star.js";
|
||||
`,
|
||||
"consumer.mjs": `
|
||||
import { value as alias } from "./values.js";
|
||||
import packageDefault from "fixture-package";
|
||||
export { alias as relayed };
|
||||
void import("./lazy.js");
|
||||
void packageDefault;
|
||||
`,
|
||||
"values.js": "export const value = 42;",
|
||||
"star.js": "export const extra = true;",
|
||||
"lazy.js": "export default 'lazy';",
|
||||
"data.json": '{"name":"fixture","value":42}',
|
||||
"broken.json": '{"name":',
|
||||
"node_modules/fixture-package/package.json": JSON.stringify({
|
||||
exports: {
|
||||
".": {
|
||||
import: "./esm.mjs",
|
||||
require: "./cjs.cjs",
|
||||
},
|
||||
},
|
||||
}),
|
||||
"node_modules/fixture-package/esm.mjs": "export default 'esm';",
|
||||
"node_modules/fixture-package/cjs.cjs": "module.exports = 'cjs';",
|
||||
});
|
||||
return root;
|
||||
};
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import type { JavaScriptArtifactFile } from "../../../../src/domain/javascript/javascriptArtifactFiles.js";
|
||||
import { resolveArtifactPathByContext } from "../../../../src/application/javascript/JavaScriptArtifactPathResolution.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
|
||||
const filesFor = (paths: readonly string[]) =>
|
||||
new Map<string, JavaScriptArtifactFile>(
|
||||
["app/main.js", ...paths].map((path) => [
|
||||
path,
|
||||
{
|
||||
path,
|
||||
container_sha256: "a".repeat(64),
|
||||
sha256: "b".repeat(64),
|
||||
bytes: 0,
|
||||
inventory_artifact_id: `artifact-${path}`,
|
||||
kind: "javascript",
|
||||
unpacked: false,
|
||||
text: { included: true, value: "" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
describe("prefix-only Node builtins", () => {
|
||||
it.each(["import", "require"] as const)(
|
||||
"resolves ordinary packages named test, sqlite and sea for %s",
|
||||
async (moduleKind) => {
|
||||
const root = await createTestTempDirectory("rea-prefix-only-builtins-");
|
||||
const names = ["test", "sqlite", "sea"];
|
||||
for (const name of [...names, "fs"]) {
|
||||
const directory = join(root, "node_modules", name);
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(
|
||||
join(directory, "index.js"),
|
||||
`module.exports = ${JSON.stringify(name)};`,
|
||||
);
|
||||
}
|
||||
const main = join(
|
||||
root,
|
||||
moduleKind === "import" ? "main.mjs" : "main.cjs",
|
||||
);
|
||||
await writeFile(
|
||||
main,
|
||||
names
|
||||
.map((name, index) =>
|
||||
moduleKind === "import"
|
||||
? `import value${index} from ${JSON.stringify(name)}; console.log(value${index});`
|
||||
: `console.log(require(${JSON.stringify(name)}));`,
|
||||
)
|
||||
.join("\n") +
|
||||
(moduleKind === "import"
|
||||
? '\nimport "fs"; import "node:test";'
|
||||
: '\nrequire("fs"); require("node:test");'),
|
||||
);
|
||||
const native = await promisify(execFile)(process.execPath, [main], {
|
||||
timeout: 5_000,
|
||||
});
|
||||
expect(native.stdout.trim().split("\n").slice(0, 3)).toEqual(names);
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
const imports = graph.edges.filter((edge) => edge.relation === "imports");
|
||||
for (const name of names) {
|
||||
const matches = imports.filter(
|
||||
(edge) => edge.properties.specifier === name,
|
||||
);
|
||||
expect(matches.length).toBeGreaterThan(0);
|
||||
for (const edge of matches)
|
||||
expect(edge.properties.resolved_path).toBe(
|
||||
`node_modules/${name}/index.js`,
|
||||
);
|
||||
}
|
||||
for (const name of ["fs", "node:test"]) {
|
||||
const matches = imports.filter(
|
||||
(edge) => edge.properties.specifier === name,
|
||||
);
|
||||
expect(matches.length).toBeGreaterThan(0);
|
||||
for (const edge of matches)
|
||||
expect(edge.properties.resolved_path).toBeNull();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("module specifier punctuation", () => {
|
||||
it.each(["#", "?"])(
|
||||
"keeps CommonJS punctuation and strips URL suffixes for ESM (%s)",
|
||||
(punctuation) => {
|
||||
const literal = `app/dep.cjs${punctuation}literal.cjs`;
|
||||
const stripped = "app/dep.cjs";
|
||||
const commonJs = resolveArtifactPathByContext({
|
||||
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
files: filesFor([literal, stripped]),
|
||||
moduleKind: "require",
|
||||
});
|
||||
expect(commonJs).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: literal,
|
||||
});
|
||||
|
||||
const esm = resolveArtifactPathByContext({
|
||||
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
files: filesFor([literal, stripped]),
|
||||
moduleKind: "import",
|
||||
});
|
||||
expect(esm).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: stripped,
|
||||
});
|
||||
|
||||
const noStrippedTarget = resolveArtifactPathByContext({
|
||||
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
files: filesFor([literal]),
|
||||
moduleKind: "import",
|
||||
});
|
||||
expect(noStrippedTarget).toMatchObject({
|
||||
resolution_status: "not-found",
|
||||
resolved_path: null,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["#", "?"])(
|
||||
"keeps HTML URL suffix handling for %s",
|
||||
(punctuation) => {
|
||||
expect(
|
||||
resolveArtifactPathByContext({
|
||||
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
|
||||
sourcePath: "app/main.js",
|
||||
context: "html-reference",
|
||||
files: filesFor([
|
||||
"app/dep.cjs",
|
||||
`app/dep.cjs${punctuation}literal.cjs`,
|
||||
]),
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "app/dep.cjs",
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("ESM module URL decoding", () => {
|
||||
it("resolves URL-encoded imports to the files loaded by Node", async () => {
|
||||
const cases = [
|
||||
["./plain.mjs", "plain.mjs"],
|
||||
["./space%20name.mjs", "space name.mjs"],
|
||||
["./pr%C3%A9load.mjs", "préload.mjs"],
|
||||
["./name%3F%23.mjs", "name?#.mjs"],
|
||||
["./percent%2520.mjs?cache=1#v2", "percent%20.mjs"],
|
||||
] as const;
|
||||
const root = await createTestTempDirectory("rea-module-url-");
|
||||
const main = join(root, "main.mjs");
|
||||
await writeFile(
|
||||
main,
|
||||
cases
|
||||
.map(
|
||||
([specifier], index) =>
|
||||
`import value${index} from ${JSON.stringify(specifier)}; console.log(value${index});`,
|
||||
)
|
||||
.join("\n"),
|
||||
);
|
||||
for (const [specifier, target] of cases) {
|
||||
await writeFile(
|
||||
join(root, target),
|
||||
`export default ${JSON.stringify(target)};`,
|
||||
);
|
||||
const encoded = specifier.slice(2).split("?", 1)[0]?.split("#", 1)[0];
|
||||
if (encoded !== undefined && encoded !== target)
|
||||
await writeFile(join(root, encoded), 'export default "encoded decoy";');
|
||||
}
|
||||
const native = await promisify(execFile)(process.execPath, [main], {
|
||||
timeout: 5_000,
|
||||
});
|
||||
expect(native.stdout.trim().split("\n")).toEqual(
|
||||
cases.map(([, target]) => target),
|
||||
);
|
||||
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
for (const [specifier, target] of cases) {
|
||||
const imports = graph.edges.filter(
|
||||
(edge) =>
|
||||
edge.relation === "imports" &&
|
||||
edge.properties.specifier === specifier,
|
||||
);
|
||||
expect(imports.length).toBeGreaterThan(0);
|
||||
for (const edge of imports)
|
||||
expect(edge.properties.resolved_path).toBe(target);
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves CommonJS literal percent names", () => {
|
||||
expect(
|
||||
resolveArtifactPathByContext({
|
||||
declaredPath: "./space%20name.cjs",
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "require",
|
||||
files: filesFor(["app/space%20name.cjs", "app/space name.cjs"]),
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolved_path: "app/space%20name.cjs",
|
||||
resolution_status: "resolved",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["./invalid%.mjs", "./invalid%C3.mjs", "./nul%00.mjs"])(
|
||||
"rejects malformed or NUL URL %s",
|
||||
(declaredPath) => {
|
||||
expect(
|
||||
resolveArtifactPathByContext({
|
||||
declaredPath,
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
files: filesFor([`app/${declaredPath.slice(2)}`]),
|
||||
}),
|
||||
).toMatchObject({ resolved_path: null, resolution_status: "rejected" });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const packageEntryUrlCases = [
|
||||
["exports", "./actual%20file.cjs", "actual file.cjs"],
|
||||
["exports", "./actual.cjs?variant", "actual.cjs"],
|
||||
["exports", "./actual.cjs#variant", "actual.cjs"],
|
||||
["exports", "./actual%23file.cjs", "actual#file.cjs"],
|
||||
["exports", "./actual%3Ffile.cjs", "actual?file.cjs"],
|
||||
["exports", "./actual%252Ffile.cjs", "actual%2Ffile.cjs"],
|
||||
["exports", "./actual.cjs", "actual.cjs"],
|
||||
["main", "./actual%20file.cjs", "actual%20file.cjs"],
|
||||
["main", "./actual?file.cjs", "actual?file.cjs"],
|
||||
["main", "./actual#file.cjs", "actual#file.cjs"],
|
||||
] as const;
|
||||
|
||||
it.each(["import", "require"] as const)(
|
||||
"matches Node %s across package exports and main path representations",
|
||||
async (moduleKind) => {
|
||||
const root = await createTestTempDirectory("rea-package-export-url-");
|
||||
for (const [
|
||||
index,
|
||||
[field, declaredPath, target],
|
||||
] of packageEntryUrlCases.entries()) {
|
||||
const name = `fixture-${index}`;
|
||||
const packageRoot = join(root, "node_modules", name);
|
||||
await mkdir(packageRoot, { recursive: true });
|
||||
await writeFile(
|
||||
join(packageRoot, "package.json"),
|
||||
JSON.stringify({
|
||||
name,
|
||||
[field]: declaredPath,
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
join(packageRoot, target),
|
||||
`module.exports=${JSON.stringify(target)};`,
|
||||
);
|
||||
const literal = declaredPath.slice(2).split("?", 1)[0]?.split("#", 1)[0];
|
||||
if (literal !== undefined && literal !== target)
|
||||
await writeFile(
|
||||
join(packageRoot, literal),
|
||||
'module.exports="literal decoy";',
|
||||
);
|
||||
}
|
||||
const main = join(root, moduleKind === "import" ? "main.mjs" : "main.cjs");
|
||||
await writeFile(
|
||||
main,
|
||||
packageEntryUrlCases
|
||||
.map((_, index) =>
|
||||
moduleKind === "import"
|
||||
? `import value${index} from "fixture-${index}"; console.log(value${index});`
|
||||
: `console.log(require("fixture-${index}"));`,
|
||||
)
|
||||
.join("\n"),
|
||||
);
|
||||
const native = await promisify(execFile)(process.execPath, [main], {
|
||||
timeout: 5_000,
|
||||
});
|
||||
expect(native.stdout.trim().split("\n")).toEqual(
|
||||
packageEntryUrlCases.map(([, , target]) => target),
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
for (const [
|
||||
index,
|
||||
[field, declaredPath, target],
|
||||
] of packageEntryUrlCases.entries()) {
|
||||
const imports = graph.edges.filter(
|
||||
(edge) =>
|
||||
edge.relation === "imports" &&
|
||||
edge.properties.specifier === `fixture-${index}`,
|
||||
);
|
||||
expect(
|
||||
imports.length,
|
||||
`${moduleKind}: ${field} ${declaredPath}`,
|
||||
).toBeGreaterThan(0);
|
||||
for (const edge of imports)
|
||||
expect(edge.properties.resolved_path).toBe(
|
||||
`node_modules/fixture-${index}/${target}`,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
describe("package exports URL path rejections", () => {
|
||||
it.each(
|
||||
(["import", "require"] as const).flatMap((moduleKind) =>
|
||||
[
|
||||
"./actual%file.cjs",
|
||||
"./actual%E0%A4file.cjs",
|
||||
"./actual%00file.cjs",
|
||||
"./actual%2Ffile.cjs",
|
||||
"./actual%5Cfile.cjs",
|
||||
"./actual%2Efile.cjs",
|
||||
"./../../../../escape.cjs",
|
||||
].map((declaredPath) => ({ moduleKind, declaredPath })),
|
||||
),
|
||||
)(
|
||||
"rejects $moduleKind URL $declaredPath without borrowing a literal decoy",
|
||||
({ moduleKind, declaredPath }) => {
|
||||
const packagePath = "app/node_modules/fixture/package.json";
|
||||
const files = filesFor([
|
||||
packagePath,
|
||||
`app/node_modules/fixture/${declaredPath.slice(2)}`,
|
||||
]);
|
||||
const metadata = files.get(packagePath);
|
||||
if (metadata === undefined) throw new Error("Missing fixture metadata");
|
||||
files.set(packagePath, {
|
||||
...metadata,
|
||||
kind: "package-json",
|
||||
text: {
|
||||
included: true,
|
||||
value: JSON.stringify({ exports: declaredPath }),
|
||||
},
|
||||
});
|
||||
expect(
|
||||
resolveArtifactPathByContext({
|
||||
declaredPath: "fixture",
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind,
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({ resolved_path: null, resolution_status: "rejected" });
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["import", "require"] as const)(
|
||||
"keeps %s exports inside their inventoried container",
|
||||
(moduleKind) => {
|
||||
const packagePath = "app/node_modules/fixture/package.json";
|
||||
const target = "app/node_modules/fixture/actual file.cjs";
|
||||
const files = filesFor([packagePath, target]);
|
||||
const metadata = files.get(packagePath);
|
||||
const crossContainer = files.get(target);
|
||||
if (metadata === undefined || crossContainer === undefined)
|
||||
throw new Error("Missing fixture files");
|
||||
files.set(packagePath, {
|
||||
...metadata,
|
||||
kind: "package-json",
|
||||
text: {
|
||||
included: true,
|
||||
value: '{"exports":"./actual%20file.cjs"}',
|
||||
},
|
||||
});
|
||||
files.set(target, {
|
||||
...crossContainer,
|
||||
container_sha256: "c".repeat(64),
|
||||
});
|
||||
expect(
|
||||
resolveArtifactPathByContext({
|
||||
declaredPath: "fixture",
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
moduleKind,
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({ resolved_path: null, resolution_status: "not-found" });
|
||||
},
|
||||
);
|
||||
});
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
|
||||
|
||||
it("classifies overloaded open calls from lexical receiver facts", async () => {
|
||||
const inputPath = await createTestTempDirectory(
|
||||
"rea-js-open-classification-",
|
||||
);
|
||||
await writeFile(
|
||||
join(inputPath, "app.js"),
|
||||
`
|
||||
const popup = window;
|
||||
popup.open(url, "/preview");
|
||||
{
|
||||
const indexedDB = { open() {} };
|
||||
indexedDB.open("PROPFIND", "/dav");
|
||||
indexedDB.open(databaseName, "2");
|
||||
}
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open(method, "/api");
|
||||
parent.open("GET", "/parent-target");
|
||||
self.open("POST", "/self-target");
|
||||
document.open("GET", "/document-target");
|
||||
{
|
||||
const parent = new XMLHttpRequest();
|
||||
parent.open(method, "/shadowed-parent");
|
||||
}
|
||||
indexedDB.open("records", "2");
|
||||
`,
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: inputPath,
|
||||
format: "directory",
|
||||
});
|
||||
if (!result.ok)
|
||||
throw new Error(`Expected analysis success: ${result.error.message}`);
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
const endpoints = graph.nodes
|
||||
.filter(({ kind }) => kind === "endpoint")
|
||||
.flatMap(({ observations }) =>
|
||||
observations.map(({ properties }) => properties.value),
|
||||
)
|
||||
.sort();
|
||||
const storage = graph.nodes
|
||||
.filter(({ kind }) => kind === "storage")
|
||||
.flatMap(({ observations }) =>
|
||||
observations.map(({ properties }) => properties.storage_kind),
|
||||
);
|
||||
expect(endpoints).toEqual(["/api", "/dav", "/shadowed-parent"]);
|
||||
expect(storage).toEqual(["indexed-db"]);
|
||||
});
|
||||
+421
@@ -0,0 +1,421 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { createElectronActiveEvidence } from "../../../../src/application/javascript/ElectronActiveEvidence.js";
|
||||
import { reconcileJavaScriptRuntimeEvidence } from "../../../../src/application/javascript/JavaScriptRuntimeReconciliationService.js";
|
||||
import { createEvidence } from "../../../../src/domain/evidence.js";
|
||||
import {
|
||||
parseRuntimeReconciliationInput,
|
||||
reconcileJavaScriptRuntime,
|
||||
} from "../../../../src/domain/javascript/javascriptRuntimeReconciliation.js";
|
||||
import { reconcileJavaScriptRuntimeInputSchema } from "../../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { javascriptRuntimeReconciliationResultSchema } from "../../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { electronActiveObservationInputSchema } from "../../../../src/domain/javascript/electronActiveObservation.js";
|
||||
import { createElectronActiveObservationFixtureResult } from "../../../../src/domain/javascript/electronActiveObservation.fixture.js";
|
||||
|
||||
import {
|
||||
SOURCE,
|
||||
applicationFixture,
|
||||
analyzeFixture,
|
||||
electronRuntimeEvidence,
|
||||
} from "../../../fixtures/javascriptRuntimeReconciliation.js";
|
||||
|
||||
const reconcileInput = (input: unknown) =>
|
||||
reconcileJavaScriptRuntime(
|
||||
parseRuntimeReconciliationInput(
|
||||
reconcileJavaScriptRuntimeInputSchema.parse(input),
|
||||
),
|
||||
);
|
||||
|
||||
it("preserves source-capture input paths for runtime Evidence", async () => {
|
||||
const root = await applicationFixture();
|
||||
const application = await analyzeFixture(root);
|
||||
const runtime = electronRuntimeEvidence(root, SOURCE);
|
||||
const invalidRuntime = createEvidence(undefined, runtime.provider, {
|
||||
predicateType: runtime.predicate_type,
|
||||
operation: runtime.operation,
|
||||
parameters: { ...runtime.parameters, include_script_sources: false },
|
||||
result: runtime.normalized_result,
|
||||
confidence: runtime.confidence,
|
||||
authority: runtime.authority,
|
||||
});
|
||||
|
||||
const result = reconcileJavaScriptRuntimeEvidence({
|
||||
static_layers: [{ role: "application", analysis: application }],
|
||||
runtime_observations: [invalidRuntime],
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [
|
||||
{
|
||||
path: [
|
||||
"runtime_observations",
|
||||
0,
|
||||
"parameters",
|
||||
"include_script_sources",
|
||||
],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Runtime Evidence contains source without source-capture selection",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reconciles runtime scripts inside dot-prefixed child directories", async () => {
|
||||
const root = await applicationFixture();
|
||||
await mkdir(join(root, "..cache"));
|
||||
await writeFile(join(root, "..cache", "app.js"), SOURCE);
|
||||
const result = reconcileInput({
|
||||
static_layers: [
|
||||
{ role: "application", analysis: await analyzeFixture(root) },
|
||||
],
|
||||
runtime_observations: [
|
||||
electronRuntimeEvidence(root, SOURCE, {
|
||||
scriptFile: "..cache/app.js",
|
||||
includeWorker: false,
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(result.reconciliations).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entity_kind: "script",
|
||||
status: "matched",
|
||||
basis: "content-and-location",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches renderer, frame, script bytes, and worker without claiming execution", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const runtimeEvidence = electronRuntimeEvidence(fixture, SOURCE);
|
||||
|
||||
const result = reconcileInput({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
javascriptRuntimeReconciliationResultSchema.parse(result),
|
||||
).not.toThrow();
|
||||
expect(result.source_map_authority).toMatchObject({
|
||||
used_for_primary_matching: false,
|
||||
static_layer_count: 1,
|
||||
runtime_script_declarations: 0,
|
||||
});
|
||||
expect(result.summary).toMatchObject({
|
||||
runtime_targets: 1,
|
||||
runtime_frames: 1,
|
||||
runtime_scripts: 1,
|
||||
runtime_workers: 1,
|
||||
matched: 2,
|
||||
ambiguous: 2,
|
||||
unmatched: 0,
|
||||
});
|
||||
expect(result.reconciliations).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entity_kind: "script",
|
||||
status: "matched",
|
||||
basis: "content-and-location",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
entity_kind: "worker",
|
||||
status: "matched",
|
||||
basis: "artifact-path",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
entity_kind: "target",
|
||||
status: "ambiguous",
|
||||
reason: "ambiguous-static-candidates",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const matched = result.reconciliations.find(
|
||||
({ status }) => status === "matched",
|
||||
);
|
||||
if (matched === undefined)
|
||||
throw new TypeError("Expected one matched runtime reconciliation");
|
||||
expect(
|
||||
javascriptRuntimeReconciliationResultSchema.safeParse({
|
||||
...result,
|
||||
reconciliations: [{ ...matched, static_node_id: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(result.static_load_states).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "javascript-asset",
|
||||
status: "loaded",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(result.limitations.join(" ")).toMatch(
|
||||
/not reported as executed|not code reachability/u,
|
||||
);
|
||||
expect(
|
||||
result.graph.edges
|
||||
.filter(({ relation }) => relation === "observed_as")
|
||||
.every(
|
||||
({ evidence }) =>
|
||||
evidence.authority === "cross-layer-reconciliation" &&
|
||||
evidence.state === "inferred",
|
||||
),
|
||||
).toBe(true);
|
||||
const worker = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "worker",
|
||||
);
|
||||
const frame = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "frame",
|
||||
);
|
||||
expect(result.graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: frame?.runtime_node_id,
|
||||
target_node_id: worker?.runtime_node_id,
|
||||
relation: "contains",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps static load states unknown when one scoped capture omits scripts", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const result = reconcileInput({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [
|
||||
electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
targetId: "target-complete",
|
||||
}),
|
||||
electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
scriptsUnavailable: true,
|
||||
targetId: "target-incomplete",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
result.runtime_captures.map(
|
||||
({ scripts_complete_within_scope }) => scripts_complete_within_scope,
|
||||
),
|
||||
).toEqual(expect.arrayContaining([false, true]));
|
||||
expect(result.summary.static_not_observed).toBe(0);
|
||||
expect(result.static_load_states).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
status: "unknown",
|
||||
reason: "static-or-runtime-coverage-incomplete",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a captured digest disagreement instead of accepting a path match", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const runtimeEvidence = electronRuntimeEvidence(
|
||||
fixture,
|
||||
"export const observed = 'different';\n",
|
||||
);
|
||||
|
||||
const result = reconcileInput({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
const script = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "script",
|
||||
);
|
||||
|
||||
expect(script).toMatchObject({
|
||||
status: "unmatched",
|
||||
reason: "captured-content-disagrees-with-static-location",
|
||||
});
|
||||
expect(script?.candidate_static_nodes).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reconciles active Electron as a partial target-only runtime capture", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const applicationPath = join(fixture, "main.js");
|
||||
const input = {
|
||||
...electronActiveObservationInputSchema.parse({
|
||||
executable_path: process.execPath,
|
||||
application_path: applicationPath,
|
||||
application_root: fixture,
|
||||
actions: [],
|
||||
}),
|
||||
application_root: fixture,
|
||||
};
|
||||
const runtimeEvidence = createElectronActiveEvidence(
|
||||
input,
|
||||
createElectronActiveObservationFixtureResult(applicationPath),
|
||||
{
|
||||
id: "rea-playwright-electron-active",
|
||||
name: "REA Playwright active Electron observation provider",
|
||||
version: "1",
|
||||
},
|
||||
);
|
||||
|
||||
const result = reconcileInput({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
|
||||
expect(result.runtime_captures).toMatchObject([
|
||||
{
|
||||
kind: "electron-active",
|
||||
scripts: 0,
|
||||
frames: 0,
|
||||
workers: 0,
|
||||
scripts_complete_within_scope: false,
|
||||
},
|
||||
]);
|
||||
expect(result.coverage.status).toBe("partial");
|
||||
expect(result.limitations.join(" ")).toMatch(
|
||||
/incomplete|not reported as executed/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("commits complete Electron actions independently from selected arguments", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
const applicationPath = join(fixture, "main.js");
|
||||
const makeInput = (secret: string, selector: string) => ({
|
||||
...electronActiveObservationInputSchema.parse({
|
||||
executable_path: process.execPath,
|
||||
application_path: applicationPath,
|
||||
application_root: fixture,
|
||||
args: ["--token", secret],
|
||||
actions: [
|
||||
{ step_id: "click", kind: "click", selector },
|
||||
{ step_id: "settle", kind: "wait", duration_ms: 37 },
|
||||
{
|
||||
step_id: "open",
|
||||
kind: "deep-link",
|
||||
delivery: "second-instance",
|
||||
url: "rea-fixture://open/item?token=selected",
|
||||
},
|
||||
],
|
||||
}),
|
||||
application_root: fixture,
|
||||
});
|
||||
const provider = {
|
||||
id: "rea-playwright-electron-active",
|
||||
name: "REA Playwright active Electron observation provider",
|
||||
version: "1",
|
||||
};
|
||||
const first = createElectronActiveEvidence(
|
||||
makeInput("first-secret", "#first-secret"),
|
||||
createElectronActiveObservationFixtureResult(applicationPath),
|
||||
provider,
|
||||
);
|
||||
const second = createElectronActiveEvidence(
|
||||
makeInput("first-secret", "#second-secret"),
|
||||
createElectronActiveObservationFixtureResult(applicationPath),
|
||||
provider,
|
||||
);
|
||||
|
||||
expect(first.parameters.scenario_sha256).not.toBe(
|
||||
second.parameters.scenario_sha256,
|
||||
);
|
||||
expect(JSON.stringify(first)).toContain("first-secret");
|
||||
expect(first.parameters.actions).toEqual([
|
||||
{
|
||||
step_id: "click",
|
||||
kind: "click",
|
||||
selector: "#first-secret",
|
||||
window_index: 0,
|
||||
},
|
||||
{ step_id: "settle", kind: "wait", duration_ms: 37 },
|
||||
{
|
||||
step_id: "open",
|
||||
kind: "deep-link",
|
||||
delivery: "second-instance",
|
||||
url: "rea-fixture://open/item?token=selected",
|
||||
},
|
||||
]);
|
||||
expect(first.parameters.args).toEqual(["--token", "first-secret"]);
|
||||
});
|
||||
|
||||
it("imports an operator-provided cache layer through an explicit file mapping", async () => {
|
||||
const application = await applicationFixture();
|
||||
const cache = await createTestTempDirectory("rea-runtime-cache-static-");
|
||||
const runtimeCache = await createTestTempDirectory("rea-runtime-cache-live-");
|
||||
const cacheSource = SOURCE;
|
||||
await mkdir(join(cache, "mapped"));
|
||||
await Promise.all([
|
||||
writeFile(join(cache, "mapped", "chunk.js"), cacheSource),
|
||||
writeFile(join(cache, "outside.js"), "export const outside = true;\n"),
|
||||
writeFile(join(runtimeCache, "chunk.js"), cacheSource),
|
||||
writeFile(join(runtimeCache, "index.html"), "<script></script>"),
|
||||
]);
|
||||
const applicationEvidence = await analyzeFixture(application);
|
||||
const cacheEvidence = await analyzeFixture(cache);
|
||||
const runtimeEvidence = electronRuntimeEvidence(runtimeCache, cacheSource, {
|
||||
scriptFile: "chunk.js",
|
||||
includeWorker: false,
|
||||
});
|
||||
|
||||
const result = reconcileInput({
|
||||
static_layers: [
|
||||
{ role: "application", analysis: applicationEvidence },
|
||||
{
|
||||
role: "cache",
|
||||
analysis: cacheEvidence,
|
||||
runtime_mappings: [
|
||||
{
|
||||
kind: "file-root",
|
||||
root: runtimeCache,
|
||||
artifact_prefix: "mapped",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
const script = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "script",
|
||||
);
|
||||
const cacheLayer = result.static_layers.find(({ role }) => role === "cache");
|
||||
|
||||
expect(script).toMatchObject({
|
||||
status: "matched",
|
||||
basis: "content-and-location",
|
||||
static_layer_id: cacheLayer?.layer_id,
|
||||
});
|
||||
const outside = result.graph.nodes.find(
|
||||
(node) =>
|
||||
node.kind === "javascript-asset" &&
|
||||
node.observations.some(
|
||||
({ properties }) => properties.path === "outside.js",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
result.static_load_states.find(
|
||||
({ static_node_id: nodeId }) => nodeId === outside?.node_id,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
reason: "layer-outside-runtime-scope",
|
||||
});
|
||||
const sharedFile = result.graph.nodes.find(
|
||||
({ observations }) =>
|
||||
observations.some(({ properties }) => properties.path === "app.js") &&
|
||||
observations.some(
|
||||
({ properties }) => properties.path === "mapped/chunk.js",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
sharedFile?.observations.map(({ properties }) => properties.path),
|
||||
).toEqual(expect.arrayContaining(["app.js", "mapped/chunk.js"]));
|
||||
});
|
||||
Reference in New Issue
Block a user