chore: merge main into intrinsic invocation fixes
This commit is contained in:
@@ -0,0 +1,330 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
const createModuleLookupFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-module-lookup-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": JSON.stringify({
|
||||
name: "module-lookup-fixture",
|
||||
type: "commonjs",
|
||||
}),
|
||||
"esm/entry.mjs": [
|
||||
'import "./extensionless";',
|
||||
'import "./directory";',
|
||||
'import "./explicit.js";',
|
||||
'import "./exact.js";',
|
||||
'import "./actual.cjs?cache=1";',
|
||||
'import fallback from "empty-main";',
|
||||
'import "nested-main";',
|
||||
'import "file-only";',
|
||||
'import "ancestor-empty";',
|
||||
'import "ancestor-blocked";',
|
||||
'import "ancestor-sub/parser";',
|
||||
'import "./.hidden.js";',
|
||||
'import "./..pkg.js";',
|
||||
'import "./exact.js/.";',
|
||||
'import "./exact.js/child/..";',
|
||||
'import ".hidden.js";',
|
||||
'import "..pkg.js";',
|
||||
'import ".";',
|
||||
'import "..";',
|
||||
"void fallback;",
|
||||
].join("\n"),
|
||||
"esm/extensionless.js": "module.exports = 1;",
|
||||
"esm/directory/index.js": "module.exports = 2;",
|
||||
"esm/explicit.js.js": "module.exports = 3;",
|
||||
"esm/exact.js": "module.exports = 4;",
|
||||
"esm/actual.cjs": "module.exports = 5;",
|
||||
"esm/.hidden.js": "module.exports = 'local hidden';",
|
||||
"esm/..pkg.js": "module.exports = 'local dot package';",
|
||||
"node_modules/.hidden.js/index.js": "module.exports = 'hidden package';",
|
||||
"node_modules/..pkg.js/index.js": "module.exports = 'dot package';",
|
||||
"esm/typed.mts": 'import value from "./typed-dep.js"; void value;',
|
||||
"esm/typed-dep.ts": "export default 42;",
|
||||
"cjs/entry.cjs": [
|
||||
'require("./extensionless");',
|
||||
'require("./directory");',
|
||||
'require("./feature");',
|
||||
'require("./feature.cjs");',
|
||||
'require("./module-only");',
|
||||
'require("./valid-directory");',
|
||||
'require("./default-js");',
|
||||
'require("./default-json");',
|
||||
'require("./default-node");',
|
||||
'require("empty-main");',
|
||||
'require("nested-main");',
|
||||
'require("file-only");',
|
||||
'require("ancestor-empty");',
|
||||
'require("ancestor-blocked");',
|
||||
'require("ancestor-sub/parser");',
|
||||
'require(".hidden.js");',
|
||||
'require("./.hidden.js");',
|
||||
'require(".");',
|
||||
'require("..");',
|
||||
].join("\n"),
|
||||
"cjs/directory/index.cjs": "module.exports = 6;",
|
||||
"cjs/index.js": "module.exports = 'current directory';",
|
||||
"index.js": "module.exports = 'parent directory';",
|
||||
"cjs/.hidden.js": "module.exports = 'local hidden';",
|
||||
"cjs/extensionless.cjs": "module.exports = 1;",
|
||||
"cjs/feature.cjs": "module.exports = 2;",
|
||||
"cjs/module-only.mjs": "export default 42;",
|
||||
"cjs/valid-directory/index.js": "module.exports = 42;",
|
||||
"cjs/typed.cts":
|
||||
'const value = require("./typed-dep.cjs"); module.exports = value;',
|
||||
"cjs/typed-dep.cts": "module.exports = 42;",
|
||||
"cjs/default-js.js": "module.exports = 3;",
|
||||
"cjs/default-json.json": JSON.stringify({ value: 4 }),
|
||||
// Inventory-only placeholder: never pass this path to Node's runtime.
|
||||
"cjs/default-node.node": "source-owned opaque native-module placeholder",
|
||||
"node_modules/empty-main/package.json": JSON.stringify({ main: "" }),
|
||||
"node_modules/empty-main/index.js": "module.exports = 42;",
|
||||
"node_modules/nested-main/package.json": JSON.stringify({ main: "sub" }),
|
||||
"node_modules/nested-main/sub/package.json": JSON.stringify({
|
||||
main: "other",
|
||||
}),
|
||||
"node_modules/nested-main/sub/other.js": "module.exports = 99;",
|
||||
"node_modules/file-only.js": "module.exports = 7;",
|
||||
"node_modules/ancestor-empty/index.js": "module.exports = 8;",
|
||||
"node_modules/ancestor-blocked/index.js": "module.exports = 9;",
|
||||
"node_modules/ancestor-sub/parser.js": "module.exports = 10;",
|
||||
"esm/runtime-control.mjs": [
|
||||
'const specifiers = ["./extensionless", "./directory", "./explicit.js", "./exact.js", "./actual.cjs?cache=1", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser", "./.hidden.js", "./..pkg.js", "./exact.js/.", "./exact.js/child/..", ".hidden.js", "..pkg.js", ".", ".."];',
|
||||
"const results = [];",
|
||||
"for (const specifier of specifiers) {",
|
||||
" try { const value = (await import(specifier)).default; results.push({ specifier, ok: true, value }); }",
|
||||
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
|
||||
"}",
|
||||
"console.log(JSON.stringify(results));",
|
||||
].join("\n"),
|
||||
"cjs/runtime-control.cjs": [
|
||||
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./module-only", "./valid-directory", "./default-js", "./default-json", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser", ".hidden.js", "./.hidden.js", ".", ".."];',
|
||||
"const results = [];",
|
||||
"for (const specifier of specifiers) {",
|
||||
" try { const value = require(specifier); results.push({ specifier, ok: true, value }); }",
|
||||
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
|
||||
"}",
|
||||
"console.log(JSON.stringify(results));",
|
||||
].join("\n"),
|
||||
});
|
||||
for (const directory of ["esm", "cjs"])
|
||||
await writeFixtureFiles(root, {
|
||||
[`${directory}/node_modules/ancestor-empty/package.json`]: JSON.stringify(
|
||||
{ main: "" },
|
||||
),
|
||||
[`${directory}/node_modules/ancestor-blocked/package.json`]:
|
||||
JSON.stringify({ main: "missing" }),
|
||||
[`${directory}/node_modules/ancestor-sub/package.json`]: "{}",
|
||||
});
|
||||
return root;
|
||||
};
|
||||
|
||||
type RuntimeControlResult = {
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
readonly value?: unknown;
|
||||
};
|
||||
|
||||
const expectNodeRuntimeControls = (
|
||||
esmOutput: string,
|
||||
cjsOutput: string,
|
||||
): void => {
|
||||
const esmResults = JSON.parse(esmOutput) as RuntimeControlResult[];
|
||||
const cjsResults = JSON.parse(cjsOutput) as RuntimeControlResult[];
|
||||
expect(esmResults).toEqual([
|
||||
{
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "./explicit.js",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./exact.js", ok: true, value: 4 },
|
||||
{ specifier: "./actual.cjs?cache=1", ok: true, value: 5 },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-empty", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{
|
||||
specifier: "ancestor-blocked",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "ancestor-sub/parser",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./.hidden.js", ok: true, value: "local hidden" },
|
||||
{ specifier: "./..pkg.js", ok: true, value: "local dot package" },
|
||||
{
|
||||
specifier: "./exact.js/.",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "./exact.js/child/..",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: ".hidden.js",
|
||||
ok: false,
|
||||
code: "ERR_INVALID_MODULE_SPECIFIER",
|
||||
},
|
||||
{
|
||||
specifier: "..pkg.js",
|
||||
ok: false,
|
||||
code: "ERR_INVALID_MODULE_SPECIFIER",
|
||||
},
|
||||
{ specifier: ".", ok: false, code: "ERR_UNSUPPORTED_DIR_IMPORT" },
|
||||
{ specifier: "..", ok: false, code: "ERR_UNSUPPORTED_DIR_IMPORT" },
|
||||
]);
|
||||
expect(cjsResults).toEqual([
|
||||
{
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./feature",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./feature.cjs", ok: true, value: 2 },
|
||||
{ specifier: "./module-only", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "./valid-directory", ok: true, value: 42 },
|
||||
{ specifier: "./default-js", ok: true, value: 3 },
|
||||
{ specifier: "./default-json", ok: true, value: { value: 4 } },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: true, value: 7 },
|
||||
{ specifier: "ancestor-empty", ok: true, value: 8 },
|
||||
{ specifier: "ancestor-blocked", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-sub/parser", ok: true, value: 10 },
|
||||
{ specifier: ".hidden.js", ok: true, value: "hidden package" },
|
||||
{ specifier: "./.hidden.js", ok: true, value: "local hidden" },
|
||||
{ specifier: ".", ok: true, value: "current directory" },
|
||||
{ specifier: "..", ok: true, value: "parent directory" },
|
||||
]);
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"matches Node module lookup for ESM and CommonJS through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createModuleLookupFixture();
|
||||
const [esmControl, cjsControl] = await Promise.all([
|
||||
execute(process.execPath, ["esm/runtime-control.mjs"], {
|
||||
cwd: root,
|
||||
timeout: 5_000,
|
||||
}),
|
||||
execute(process.execPath, ["cjs/runtime-control.cjs"], {
|
||||
cwd: root,
|
||||
timeout: 5_000,
|
||||
}),
|
||||
]);
|
||||
expectNodeRuntimeControls(esmControl.stdout, cjsControl.stdout);
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const expectations = [
|
||||
["import", "./extensionless", null, "not-found"],
|
||||
["import", "./directory", null, "not-found"],
|
||||
["import", "./explicit.js", null, "not-found"],
|
||||
["import", "./exact.js", "esm/exact.js", "resolved"],
|
||||
["import", "./actual.cjs?cache=1", "esm/actual.cjs", "resolved"],
|
||||
["import", "./typed-dep.js", "esm/typed-dep.ts", "resolved"],
|
||||
["import", "empty-main", "node_modules/empty-main/index.js", "resolved"],
|
||||
["import", "nested-main", null, "not-found"],
|
||||
["import", "file-only", null, "external"],
|
||||
["import", "ancestor-empty", null, "not-found"],
|
||||
["import", "ancestor-blocked", null, "not-found"],
|
||||
["import", "ancestor-sub/parser", null, "not-found"],
|
||||
["import", "./.hidden.js", "esm/.hidden.js", "resolved"],
|
||||
["import", "./..pkg.js", "esm/..pkg.js", "resolved"],
|
||||
["import", ".hidden.js", null, "rejected"],
|
||||
["import", "..pkg.js", null, "rejected"],
|
||||
["import", ".", null, "not-found"],
|
||||
["import", "..", null, "not-found"],
|
||||
["import", "./exact.js/.", null, "not-found"],
|
||||
["import", "./exact.js/child/..", null, "not-found"],
|
||||
["require", "./extensionless", null, "not-found"],
|
||||
["require", "./directory", null, "not-found"],
|
||||
["require", "./feature", null, "not-found"],
|
||||
["require", "./feature.cjs", "cjs/feature.cjs", "resolved"],
|
||||
["require", "./module-only", null, "not-found"],
|
||||
[
|
||||
"require",
|
||||
"./valid-directory",
|
||||
"cjs/valid-directory/index.js",
|
||||
"resolved",
|
||||
],
|
||||
["require", "./typed-dep.cjs", "cjs/typed-dep.cts", "resolved"],
|
||||
["require", "./default-js", "cjs/default-js.js", "resolved"],
|
||||
["require", "./default-json", "cjs/default-json.json", "resolved"],
|
||||
["require", "./default-node", "cjs/default-node.node", "resolved"],
|
||||
["require", "empty-main", "node_modules/empty-main/index.js", "resolved"],
|
||||
["require", "nested-main", null, "not-found"],
|
||||
["require", "file-only", "node_modules/file-only.js", "resolved"],
|
||||
[
|
||||
"require",
|
||||
"ancestor-empty",
|
||||
"node_modules/ancestor-empty/index.js",
|
||||
"resolved",
|
||||
],
|
||||
["require", "ancestor-blocked", null, "not-found"],
|
||||
[
|
||||
"require",
|
||||
"ancestor-sub/parser",
|
||||
"node_modules/ancestor-sub/parser.js",
|
||||
"resolved",
|
||||
],
|
||||
["require", ".hidden.js", "node_modules/.hidden.js/index.js", "resolved"],
|
||||
["require", "./.hidden.js", "cjs/.hidden.js", "resolved"],
|
||||
["require", ".", "cjs/index.js", "resolved"],
|
||||
["require", "..", "index.js", "resolved"],
|
||||
] as const;
|
||||
|
||||
for (const [kind, specifier, resolvedPath, status] of expectations) {
|
||||
const matchingProperties = graph.edges
|
||||
.filter((edge) => edge.relation === "imports")
|
||||
.map((edge) => edge.properties)
|
||||
.filter(
|
||||
(properties) =>
|
||||
"module_link_kind" in properties &&
|
||||
properties.module_link_kind === kind &&
|
||||
properties.specifier === specifier,
|
||||
);
|
||||
expect(matchingProperties).toContainEqual(
|
||||
expect.objectContaining({
|
||||
module_link_kind: kind,
|
||||
specifier,
|
||||
resolved_path: resolvedPath,
|
||||
resolution_status: status,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
|
||||
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
type JavaScriptApplicationAnalysisResult,
|
||||
@@ -1530,6 +1531,60 @@ const analyzeComparisonSources = async (
|
||||
);
|
||||
};
|
||||
|
||||
it("retains bundled isolated-world contextBridge APIs through dedicated and generic CLI routes", async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-context-bridge-isolated-cli-",
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "preload.js"),
|
||||
`(() => {
|
||||
const modules = {
|
||||
2(module) { module.exports = require("electron"); },
|
||||
5(module, exports, load) {
|
||||
const electron = load(2);
|
||||
electron.contextBridge.exposeInIsolatedWorld(1001, "isolatedApi", { ping: true });
|
||||
},
|
||||
};
|
||||
function load(id) {
|
||||
const module = { exports: {} };
|
||||
modules[id].call(module.exports, module, module.exports, load);
|
||||
return module.exports;
|
||||
}
|
||||
load(5);
|
||||
})();`,
|
||||
);
|
||||
|
||||
for (const arguments_ of [
|
||||
["analyze-javascript-application", root, "--json"],
|
||||
["analyze", root, "--format", "json"],
|
||||
]) {
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(await runCli(arguments_)).normalized_result,
|
||||
);
|
||||
expect(result.summary.context_bridge_apis).toBe(1);
|
||||
const bridge = result.graph.nodes.find(
|
||||
({ kind }) => kind === "context-bridge-api",
|
||||
);
|
||||
expect(bridge?.observations).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
world: "isolated",
|
||||
world_id: { status: "literal", value: 1001, expression: null },
|
||||
api_key: "isolatedApi",
|
||||
members: ["ping"],
|
||||
resolution_basis: "wrapper-substitution",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
location: expect.objectContaining({
|
||||
available: true,
|
||||
value: expect.objectContaining({ source: "preload.js" }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const runCli = async (
|
||||
arguments_: readonly string[],
|
||||
environment: Readonly<Record<string, string>> = {},
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { buildBinary } from "plist";
|
||||
|
||||
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
|
||||
import { appleAssetCatalogResultSchema } from "../../../src/domain/apple/appleAssetCatalog.js";
|
||||
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
// Exact rooted NIBArchive bytes from #2176; inert parser fixture, not ibtool output.
|
||||
const reportedArchive = Buffer.from(
|
||||
"TklCQXJjaGl2ZQEAAAAKAAAABAAAADIAAAAEAAAAPgAAAAQAAABgAAAABAAAAHwAAACAgIGBgYGCgoGDg4GGTlNSb290hWltYWdli05TSW1hZ2VOYW1liE5TLmJ5dGVzgAoBAAAAgQoCAAAAggoDAAAAgwiHVG9vbGJhco6ATlNJQk9iamVjdERhdGGLgE5TSW1hZ2VWaWV3h4BOU0ltYWdliIBOU1N0cmluZw==",
|
||||
"base64",
|
||||
);
|
||||
const resourceArchive = (field: string) =>
|
||||
encodeNibArchiveFixture({
|
||||
classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
|
||||
objects: [
|
||||
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
|
||||
{ classIndex: 1, values: { image: { ref: 2 } } },
|
||||
{ classIndex: 2, values: { [field]: { ref: 3 } } },
|
||||
{ classIndex: 3, values: { "NS.bytes": "Toolbar" } },
|
||||
],
|
||||
});
|
||||
|
||||
const keyedArchive = (nested: boolean) =>
|
||||
buildBinary({
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$top: { root: { UID: 1 } },
|
||||
$objects: [
|
||||
"$null",
|
||||
{
|
||||
$class: { UID: 2 },
|
||||
...(nested
|
||||
? { nibValues: { NSImageName: "Toolbar" } }
|
||||
: { NSImageName: "Toolbar" }),
|
||||
},
|
||||
{ $classname: "NSImage", $classes: ["NSImage", "NSObject"] },
|
||||
],
|
||||
});
|
||||
|
||||
cliTest.skipIf(process.platform !== "darwin")(
|
||||
"retains recognized NIBArchive resource keys and provenance through CLI and MCP without a catalog",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-asset-resource-keys-");
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [name, field, archive, recognized] of [
|
||||
["reported", "NSImageName", reportedArchive, true],
|
||||
["alias", "imageName", resourceArchive("imageName"), true],
|
||||
["title", "title", resourceArchive("title"), false],
|
||||
["keyed-direct", "NSImageName", keyedArchive(false), true],
|
||||
["keyed-nested", "NSImageName", keyedArchive(true), false],
|
||||
] as const) {
|
||||
const app = join(root, `${name}.app`);
|
||||
const contents = join(app, "Contents");
|
||||
await mkdir(join(contents, "Resources"), { recursive: true });
|
||||
await mkdir(join(contents, "MacOS"));
|
||||
const mach = Buffer.alloc(32);
|
||||
mach.writeUInt32LE(0xfeedfacf, 0);
|
||||
mach.writeUInt32LE(0x0100000c, 4);
|
||||
mach.writeUInt32LE(2, 12);
|
||||
await writeFile(join(contents, "MacOS", "App"), mach);
|
||||
await writeFile(
|
||||
join(contents, "Info.plist"),
|
||||
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
|
||||
);
|
||||
await writeFile(join(contents, "Resources", "Panel.nib"), archive);
|
||||
const decoded = await cli.run({
|
||||
arguments: ["decode-interface-builder", app, "--json"],
|
||||
});
|
||||
expect(decoded.exitCode, decoded.stderr).toBe(0);
|
||||
const graph = interfaceBuilderAnalysisSchema.parse(
|
||||
parseEvidence(decoded.json).normalized_result,
|
||||
).graph;
|
||||
expect(graph.truncated).toBe(false);
|
||||
const resource = graph.nodes.find(
|
||||
(node) =>
|
||||
node.kind === "resource" && node.attributes.class_name === "NSImage",
|
||||
);
|
||||
expect(
|
||||
name === "keyed-direct"
|
||||
? resource?.attributes
|
||||
: resource?.attributes.nibValues,
|
||||
).toMatchObject({
|
||||
[field]: "Toolbar",
|
||||
});
|
||||
const inspected = await cli.run({
|
||||
arguments: ["inspect-asset-catalog", app, "--json"],
|
||||
});
|
||||
expect(inspected.exitCode, inspected.stderr).toBe(0);
|
||||
const result = appleAssetCatalogResultSchema.parse(
|
||||
parseEvidence(inspected.json).normalized_result,
|
||||
);
|
||||
expect(result.catalogs).toEqual([]);
|
||||
expect(result.resource_key_matches).toEqual(
|
||||
!recognized
|
||||
? []
|
||||
: [
|
||||
{
|
||||
source_node_id: resource?.id,
|
||||
source_path: "Contents/Resources/Panel.nib",
|
||||
source_archive_sha256: createHash("sha256")
|
||||
.update(archive)
|
||||
.digest("hex"),
|
||||
field,
|
||||
key: "Toolbar",
|
||||
status: "unmatched",
|
||||
renditions: [],
|
||||
},
|
||||
],
|
||||
);
|
||||
const opened = await call("open_binary", { path: app });
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const mcp = await call("inspect_asset_catalog", {});
|
||||
expect(mcp.isError).not.toBe(true);
|
||||
expect(parseEvidence(mcp.structuredContent).normalized_result).toEqual(
|
||||
result,
|
||||
);
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
@@ -0,0 +1,61 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"retains both repeated chunk callback observations through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-bundler-callbacks-");
|
||||
const source = [
|
||||
'(globalThis.webpackChunkFixture = globalThis.webpackChunkFixture || []).push([[1], {a: function() {}}, function(r) { r(7); r.e("chunk-a"); }]);',
|
||||
'(globalThis.webpackChunkFixture = globalThis.webpackChunkFixture || []).push([[1], {a: function() {}}, function(r) { r(8); r.e("chunk-b"); }]);',
|
||||
].join("\n");
|
||||
await writeFile(join(root, "bundle.js"), source);
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const chunk = graph.nodes.find(({ kind }) => kind === "javascript-chunk");
|
||||
for (const [index, entry, asyncChunk] of [
|
||||
[0, "7", "chunk-a"],
|
||||
[1, "8", "chunk-b"],
|
||||
] as const) {
|
||||
expect(chunk?.observations).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
entry_module_keys: [entry],
|
||||
async_chunk_keys: [asyncChunk],
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({
|
||||
source: "bundle.js",
|
||||
start: { line: index + 1, column: 0 },
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: chunk?.node_id,
|
||||
properties: expect.objectContaining({
|
||||
kind: "bundler-entry-module",
|
||||
module_key: entry,
|
||||
resolution_status: "not-found",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: chunk?.node_id,
|
||||
properties: expect.objectContaining({
|
||||
kind: "bundler-async-chunk",
|
||||
chunk_key: asyncChunk,
|
||||
resolution_status: "not-found",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,69 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"reports every unresolved Electron path through CLI and MCP without launching",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-electron-invalid-paths-");
|
||||
const application = join(root, "main.js");
|
||||
await writeFile(application, "module.exports = {};\n");
|
||||
const missing = {
|
||||
executable_path: join(root, "missing-electron"),
|
||||
application_path: join(root, "missing-application"),
|
||||
application_root: join(root, "missing-root"),
|
||||
};
|
||||
const requestPath = join(root, "input.json");
|
||||
await writeFile(requestPath, JSON.stringify(missing));
|
||||
const response = await cli.run({
|
||||
arguments: ["capture-electron-scenario", requestPath, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode).toBe(1);
|
||||
const expectedIssues = Object.entries(missing).map(([field, path]) => ({
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(path),
|
||||
}));
|
||||
expect(response.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: expectedIssues },
|
||||
});
|
||||
expect(response.stdout).toContain("ENOENT");
|
||||
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [field, path] of Object.entries(missing)) {
|
||||
const result = await call("capture_electron_scenario", {
|
||||
executable_path: process.execPath,
|
||||
application_path: application,
|
||||
application_root: root,
|
||||
[field]: path,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const content = result.content.find((item) => item.type === "text");
|
||||
if (content?.type !== "text") throw new Error("Missing error response");
|
||||
expect(JSON.parse(content.text)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(path),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(content.text).toContain("ENOENT");
|
||||
}
|
||||
const session = await call("binary_session", {});
|
||||
expect(session.isError, JSON.stringify(session)).not.toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,88 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"decodes a rooted UIKit keyed-archive outlet through CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-uikit-outlet-");
|
||||
const app = join(root, "UIKitFixture.app");
|
||||
const contents = join(app, "Contents");
|
||||
const resources = join(contents, "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
await mkdir(join(contents, "MacOS"));
|
||||
await writeFile(
|
||||
join(contents, "MacOS", "Fixture"),
|
||||
thinMach(0xfeedfacf, 0x0100000c),
|
||||
);
|
||||
await writeFile(
|
||||
join(contents, "Info.plist"),
|
||||
"<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
|
||||
);
|
||||
await writeFile(
|
||||
join(resources, "Main.nib"),
|
||||
await readFile(
|
||||
join(process.cwd(), "tests/fixtures/interface-builder/UIKitOutlet.xml"),
|
||||
),
|
||||
);
|
||||
|
||||
const output = await cli.run({
|
||||
arguments: ["decode-interface-builder", app, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
const result = interfaceBuilderAnalysisSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
const owner = result.graph.nodes.find(
|
||||
({ attributes }) => attributes.interface_builder_object_id === "1",
|
||||
);
|
||||
const destination = result.graph.nodes.find(
|
||||
({ attributes }) => attributes.interface_builder_object_id === "2",
|
||||
);
|
||||
const outlet = result.graph.nodes.find(({ kind }) => kind === "outlet");
|
||||
expect(result.documents).toEqual([
|
||||
expect.objectContaining({ connection_count: 1 }),
|
||||
]);
|
||||
expect(outlet).toMatchObject({
|
||||
id: 'ib:"Contents/Resources/Main.nib":outlet:["archive:3"]',
|
||||
name: "view",
|
||||
attributes: {
|
||||
UISource: { archiveUID: 1 },
|
||||
UIDestination: { archiveUID: 2 },
|
||||
UILabel: "view",
|
||||
},
|
||||
});
|
||||
expect(owner).toBeDefined();
|
||||
expect(destination).toBeDefined();
|
||||
expect(
|
||||
result.graph.edges.some(
|
||||
({ from, to, relation }) =>
|
||||
from === owner?.id && to === outlet?.id && relation === "contains",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.graph.edges.some(
|
||||
({ from, to, relation }) =>
|
||||
from === outlet?.id &&
|
||||
to === destination?.id &&
|
||||
relation === "outlet_to",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(result.graph.coverage).toContainEqual(
|
||||
expect.objectContaining({
|
||||
facet: "connections:Contents/Resources/Main.nib",
|
||||
status: "complete",
|
||||
examined: 1,
|
||||
omitted: 0,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -36,11 +36,30 @@ it("returns a nonzero exit for a streamed JSON analysis failure", async () => {
|
||||
|
||||
// `analyze` routes a JavaScript directory to the same workflow and must keep
|
||||
// its typed cancellation contract.
|
||||
it
|
||||
.skipIf(process.platform === "win32")
|
||||
.each(["analyze-javascript-application", "analyze"])(
|
||||
"returns a typed cancelled CLI result and exit 130 after SIGINT through %s",
|
||||
async (command) => {
|
||||
it.skipIf(process.platform === "win32").each([
|
||||
{
|
||||
command: "analyze-javascript-application",
|
||||
phase: "analyze_javascript_application",
|
||||
parsedFiles: null,
|
||||
},
|
||||
{
|
||||
command: "analyze",
|
||||
phase: "analyze_javascript_application",
|
||||
parsedFiles: null,
|
||||
},
|
||||
{
|
||||
command: "analyze-javascript-application",
|
||||
phase: "build_javascript_application_graph",
|
||||
parsedFiles: 1,
|
||||
},
|
||||
{
|
||||
command: "analyze-javascript-application",
|
||||
phase: "hash_javascript_application_evidence",
|
||||
parsedFiles: 1,
|
||||
},
|
||||
])(
|
||||
"returns typed cancellation and exit 130 after SIGINT through $command during $phase",
|
||||
async ({ command, phase, parsedFiles }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-js-cancellation-");
|
||||
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
|
||||
const child = spawn(
|
||||
@@ -70,7 +89,11 @@ it
|
||||
const line = partial.slice(0, newline);
|
||||
partial = partial.slice(newline + 1);
|
||||
const parsed = progressSchema.safeParse(JSON.parse(line));
|
||||
if (parsed.success && !requested) {
|
||||
if (
|
||||
parsed.success &&
|
||||
parsed.data.rea_progress.phase === phase &&
|
||||
!requested
|
||||
) {
|
||||
requested = true;
|
||||
child.kill("SIGINT");
|
||||
}
|
||||
@@ -89,5 +112,18 @@ it
|
||||
code: "cancelled",
|
||||
details: { reason: "cancelled" },
|
||||
});
|
||||
if (parsedFiles !== null)
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
details: {
|
||||
partial_observation: {
|
||||
normalized_result: {
|
||||
statistics: {
|
||||
parsed_javascript_files: parsedFiles,
|
||||
parse_failures: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest.skipIf(process.versions.bun !== undefined).for([
|
||||
{ laterSources: 1, heapMb: 640, methodsCount: 400, retainGraph: true },
|
||||
{ laterSources: 10, heapMb: 640, methodsCount: 400, retainGraph: true },
|
||||
// Even an otherwise empty parent cannot admit this graph after reserving
|
||||
// transient decoding and the next checkpoint, independent of GC timing.
|
||||
{ laterSources: 1, heapMb: 448, methodsCount: 600, retainGraph: false },
|
||||
])(
|
||||
"preserves evidence with $laterSources later checkpoints and a $heapMb MiB parent heap",
|
||||
{ timeout: 90_000 },
|
||||
async ({ laterSources, heapMb, methodsCount, retainGraph }, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-checkpoint-reserve-");
|
||||
const source = Array.from(
|
||||
{ length: methodsCount },
|
||||
(_, index) =>
|
||||
`export function method_${String(index)}(input) { const value = input + ${String(index)}; const pair = { value }; return pair.value; }`,
|
||||
).join("\n");
|
||||
const files: readonly (readonly [string, string])[] = [
|
||||
["a-large.mjs", source],
|
||||
...Array.from(
|
||||
{ length: laterSources },
|
||||
(_, index) =>
|
||||
[
|
||||
`z-tiny-${String(index)}.mjs`,
|
||||
`export const tiny${String(index)} = 1;\n`,
|
||||
] as const,
|
||||
),
|
||||
];
|
||||
for (const [name, text] of files) await writeFile(join(root, name), text);
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze", root, "--format", "json"],
|
||||
environment: {
|
||||
NODE_OPTIONS: `--max-old-space-size=${String(heapMb)} --max-semi-space-size=8`,
|
||||
},
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(response.json).normalized_result,
|
||||
);
|
||||
expect(result.statistics.parsed_javascript_files).toBe(laterSources + 1);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const failures = result.graph.nodes.flatMap(({ observations }) =>
|
||||
observations.flatMap(({ properties }) =>
|
||||
properties.analysis_failure === undefined
|
||||
? []
|
||||
: [properties.analysis_failure],
|
||||
),
|
||||
);
|
||||
const methods = result.semantic_graph.nodes.filter(
|
||||
({ kind, identity }) =>
|
||||
kind === "function" && identity.module_path === "a-large.mjs",
|
||||
);
|
||||
if (retainGraph)
|
||||
expect(methods.map(({ label }) => label).sort()).toEqual(
|
||||
Array.from(
|
||||
{ length: methodsCount },
|
||||
(_, index) => `method_${String(index)}`,
|
||||
).sort(),
|
||||
);
|
||||
else {
|
||||
expect(methods).toHaveLength(0);
|
||||
expect([
|
||||
result.graph.coverage.status,
|
||||
result.semantic_graph.coverage.status,
|
||||
]).toContain("partial");
|
||||
}
|
||||
expect(
|
||||
result.semantic_graph.nodes.some(
|
||||
({ identity, label }) =>
|
||||
identity.module_path === `z-tiny-${String(laterSources - 1)}.mjs` &&
|
||||
label === `tiny${String(laterSources - 1)}`,
|
||||
),
|
||||
).toBe(true);
|
||||
for (const [name, text] of files) {
|
||||
const digest = createHash("sha256").update(text).digest("hex");
|
||||
const node = result.graph.nodes.find(
|
||||
({ kind, identity }) =>
|
||||
kind === "javascript-asset" &&
|
||||
identity.strategy === "content-digest" &&
|
||||
identity.sha256 === digest,
|
||||
);
|
||||
expect(node?.observations).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
path: name,
|
||||
parse_status: "complete",
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
if (retainGraph) expect(failures).toEqual([]);
|
||||
expect(await readFile(join(root, name), "utf8")).toBe(text);
|
||||
if (!retainGraph && name === "a-large.mjs") {
|
||||
const failure = z
|
||||
.object({
|
||||
code: z.literal("resource_constraint"),
|
||||
remediation: z.object({ action: z.string() }),
|
||||
details: z.object({
|
||||
reported_limits: z.object({
|
||||
parent_available_result_budget_bytes: z.number(),
|
||||
module_retention_estimate_bytes: z.number(),
|
||||
graph_retention_estimate_bytes: z.number(),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(failures[0]);
|
||||
const limits = failure.details.reported_limits;
|
||||
expect(
|
||||
limits.module_retention_estimate_bytes +
|
||||
limits.graph_retention_estimate_bytes,
|
||||
).toBeGreaterThan(limits.parent_available_result_budget_bytes);
|
||||
expect(failure.remediation.action).toContain("parent result budget");
|
||||
expect(failure.remediation.action).toContain(
|
||||
"retained static and module facts",
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(response.stderr).not.toMatch(/FATAL ERROR:.*heap/iu);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,147 @@
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { writeJavaScriptSourceSelectionFixture } from "../../fixtures/javascriptSourceSelection.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest.for([
|
||||
{ format: "directory", command: "analyze" },
|
||||
{ format: "asar", command: "analyze-javascript-application" },
|
||||
])(
|
||||
"analyzes selected $format sources through $command with complete artifact identity",
|
||||
{ timeout: 60_000 },
|
||||
async ({ format, command }, { cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-js-source-selection-");
|
||||
const files = await writeJavaScriptSourceSelectionFixture(directory);
|
||||
let input = directory;
|
||||
if (format === "asar") {
|
||||
input = join(
|
||||
await createTestTempDirectory("rea-js-selected-asar-"),
|
||||
"app.asar",
|
||||
);
|
||||
await createPackageWithOptions(directory, input, {});
|
||||
}
|
||||
const requested = ["main.mjs", "package.json", "main.mjs"];
|
||||
const response = await cli.run({
|
||||
arguments: [
|
||||
command,
|
||||
input,
|
||||
...requested.flatMap((path) => ["--source-path", path]),
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
const evidence = parseEvidence(response.json);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(result.source_selection).toEqual({
|
||||
requested_paths: requested,
|
||||
unselected_files: 4,
|
||||
});
|
||||
expect(evidence.parameters.source_paths).toEqual(requested);
|
||||
expect(result.statistics).toMatchObject({
|
||||
relevant_files: 6,
|
||||
parsed_javascript_files: 1,
|
||||
invalid_utf8_files: 0,
|
||||
parse_failures: 0,
|
||||
text_bytes_read:
|
||||
files.get("main.mjs")!.length + files.get("package.json")!.length,
|
||||
});
|
||||
expect(result.graph.coverage.status).toBe("partial");
|
||||
expect(result.semantic_graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
});
|
||||
expect(
|
||||
result.semantic_graph.nodes.some(
|
||||
({ kind, label }) => kind === "function" && label === "selected",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.semantic_graph.unknowns.some(
|
||||
({ reason, detail }) =>
|
||||
reason === "incomplete-module" &&
|
||||
detail.includes("caller-selected source_paths"),
|
||||
),
|
||||
).toBe(true);
|
||||
for (const [path, bytes] of files) {
|
||||
const properties = result.graph.nodes
|
||||
.flatMap(({ observations }) =>
|
||||
observations.map(({ properties }) => properties),
|
||||
)
|
||||
.find(
|
||||
(properties) =>
|
||||
properties.path === path && properties.text_status !== undefined,
|
||||
);
|
||||
expect(properties?.text_status).toBe(
|
||||
requested.includes(path) ? "included" : "outside-analysis-scope",
|
||||
);
|
||||
expect(properties?.parse_status).toBe(
|
||||
path === "main.mjs" ? "complete" : null,
|
||||
);
|
||||
expect(await readFile(join(directory, path))).toEqual(bytes);
|
||||
}
|
||||
const fullResponse = await cli.run({
|
||||
arguments: [command, input, "--format", "json"],
|
||||
});
|
||||
expect(fullResponse.exitCode).toBe(0);
|
||||
const full = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(fullResponse.json).normalized_result,
|
||||
);
|
||||
expect(full.source_selection).toBeUndefined();
|
||||
expect(full.statistics.invalid_utf8_files).toBe(1);
|
||||
expect(full.statistics.parse_failures).toBeGreaterThan(0);
|
||||
expect([
|
||||
result.root_artifact_sha256,
|
||||
result.inventory_manifest_id,
|
||||
result.inventory_graph_sha256,
|
||||
]).toEqual([
|
||||
full.root_artifact_sha256,
|
||||
full.inventory_manifest_id,
|
||||
full.inventory_graph_sha256,
|
||||
]);
|
||||
if (format === "asar")
|
||||
expect(result.root_artifact_sha256).toBe(
|
||||
createHash("sha256")
|
||||
.update(await readFile(input))
|
||||
.digest("hex"),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects source selection when an explicit provider chooses the native lane",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-js-source-native-refusal-",
|
||||
);
|
||||
await writeJavaScriptSourceSelectionFixture(directory);
|
||||
const response = await cli.run({
|
||||
arguments: [
|
||||
"analyze",
|
||||
directory,
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--source-path",
|
||||
"main.mjs",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
});
|
||||
expect(response.exitCode).toBe(1);
|
||||
expect(response.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [{ path: ["source_paths"], reason: "invalid_value" }],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,626 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import type { JavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const workerReferences = (graph: JavaScriptApplicationGraph) =>
|
||||
graph.nodes
|
||||
.filter(({ kind }) => kind === "worker")
|
||||
.flatMap((node) =>
|
||||
node.observations.map(({ properties, evidence }) => ({
|
||||
source:
|
||||
evidence.location.available &&
|
||||
evidence.location.value.kind === "source-range"
|
||||
? evidence.location.value.source
|
||||
: null,
|
||||
declared_specifier: properties.declared_specifier,
|
||||
expression: properties.expression,
|
||||
resolved_path: properties.resolved_path,
|
||||
mapped_paths: graph.edges
|
||||
.filter(
|
||||
({ relation, source_node_id }) =>
|
||||
relation === "maps_to" && source_node_id === node.node_id,
|
||||
)
|
||||
.map(({ properties: edge }) => edge.resolved_path),
|
||||
})),
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"promotes Worker URLs only for known constructor bindings through the CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-identity-");
|
||||
const identityCases = [
|
||||
...["globalThis", "window", "self"].map((namespace) => ({
|
||||
prefix: "",
|
||||
constructor: `new ${namespace}.Worker`,
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
})),
|
||||
...["worker_threads", "node:worker_threads"].flatMap((specifier) => [
|
||||
{
|
||||
prefix: `import { Worker } from "${specifier}";`,
|
||||
constructor: "new Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: `import * as threads from "${specifier}";`,
|
||||
constructor: "new threads.Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
]),
|
||||
{
|
||||
prefix: 'import { Worker as ThreadWorker } from "node:worker_threads";',
|
||||
constructor: "new ThreadWorker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
constructor: "new (Worker as typeof Worker)",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
constructor: "new ((threads as typeof threads).Worker!)",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix:
|
||||
'import { Worker } from "node:worker_threads"; function start(globalThis) { globalThis.URL = Fake;',
|
||||
constructor: "new Worker",
|
||||
suffix: "}",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'globalThis.unrelated = Fake; URL.extra = "metadata";',
|
||||
constructor: "new Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
...[
|
||||
["class Worker {}", "new Worker", ""],
|
||||
["globalThis.Worker = Fake;", "new Worker", ""],
|
||||
["globalThis.Worker = Fake;", "new window.Worker", ""],
|
||||
["globalThis = replacement;", "new globalThis.Worker", ""],
|
||||
["function start(Worker) {", "new Worker", "}"],
|
||||
['import { Worker } from "./custom.js";', "new Worker", ""],
|
||||
["const custom = { Worker: class {} };", "new custom.Worker", ""],
|
||||
["function start(window) {", "new window.Worker", "}"],
|
||||
["function start(globalThis) {", "new globalThis.Worker", "}"],
|
||||
[
|
||||
'import type { Worker } from "node:worker_threads";',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import { type Worker } from "node:worker_threads";',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import type * as threads from "node:worker_threads";',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import threads from "node:worker_threads"; threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'const threads = require("node:worker_threads"); threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import threads = require("node:worker_threads"); threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import { Worker } from "node:worker_threads"; Worker = Fake;',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
["", "Worker", ""],
|
||||
].map(([prefix, constructor, suffix]) => ({
|
||||
prefix,
|
||||
constructor,
|
||||
suffix,
|
||||
resolves: false,
|
||||
})),
|
||||
].map(({ prefix, constructor, suffix, resolves }, index) => ({
|
||||
source: `identity-${index}.ts`,
|
||||
prefix,
|
||||
expression: `${constructor}(new URL("./worker.js", import.meta.url))`,
|
||||
suffix,
|
||||
resolves,
|
||||
}));
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
identityCases.map(({ source, prefix, expression, suffix }) => [
|
||||
source,
|
||||
`${prefix}\n${expression};${suffix}`,
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('existing worker file');",
|
||||
"custom.js": "export class Worker {}",
|
||||
"custom-alias.mjs":
|
||||
'import { Worker as ThreadWorker } from "./custom.js"; new ThreadWorker(new URL("./worker.js", import.meta.url));',
|
||||
});
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(identityCases.length);
|
||||
expect(references.some(({ source }) => source === "custom-alias.mjs")).toBe(
|
||||
false,
|
||||
);
|
||||
for (const { source, expression, resolves } of identityCases)
|
||||
expect(references).toContainEqual({
|
||||
source,
|
||||
declared_specifier: resolves ? "./worker.js" : null,
|
||||
expression: resolves ? null : expression,
|
||||
resolved_path: resolves ? "worker.js" : null,
|
||||
mapped_paths: resolves ? ["worker.js"] : [],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"resolves module-relative Worker URL constructors through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-module-url-");
|
||||
const cases = [
|
||||
{
|
||||
source: "nested/relative.mjs",
|
||||
expression: 'new Worker(new URL("./worker.js", import.meta.url));',
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
},
|
||||
...[
|
||||
'import.meta.unrelated = "metadata";',
|
||||
'globalThis["import.meta"] = { url: "file:///other/entry.mjs" };',
|
||||
'const meta = import.meta; meta.unrelated = "metadata";',
|
||||
'const ambient = globalThis; ambient.unrelated = "metadata";',
|
||||
'const copy = { ...import.meta }; Object.defineProperty(copy, "url", { value: "file:///other/entry.mjs" });',
|
||||
"const copy = { ...globalThis }; copy.URL = replacement;",
|
||||
"function update(globalThis) { const ambient = globalThis; ambient.URL = replacement; } update({});",
|
||||
"const define = Object.defineProperty.bind(Object);",
|
||||
'Object.defineProperty(...[import.meta, "unrelated", { value: "metadata" }]);',
|
||||
'let meta = import.meta; meta = {}; let base = import.meta.url; base = "file:///other/entry.mjs";',
|
||||
].map((mutation, index) => ({
|
||||
source: `nested/unrelated-meta-${index}.mjs`,
|
||||
expression: `import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
})),
|
||||
{
|
||||
source: "nested/parent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("../parent-worker.js", import.meta.url));',
|
||||
specifier: "../parent-worker.js",
|
||||
resolved: "parent-worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/dot-segments.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./child/.././worker.js", import.meta.url));',
|
||||
specifier: "./child/.././worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/template.mjs",
|
||||
expression:
|
||||
"new Worker(new URL(`./template-worker.js`, import.meta.url));",
|
||||
specifier: "./template-worker.js",
|
||||
resolved: "nested/template-worker.js",
|
||||
},
|
||||
...[
|
||||
'new URL("./worker.js", import.meta.url) as URL',
|
||||
'<URL>new URL("./worker.js", import.meta.url)',
|
||||
'new URL("./worker.js", import.meta.url)!',
|
||||
'new URL("./worker.js", import.meta.url) satisfies URL',
|
||||
'((new URL("./worker.js", import.meta.url) as URL)!) satisfies URL',
|
||||
'new (URL as typeof URL)("./worker.js", import.meta.url)',
|
||||
'new URL("./worker.js" as string, import.meta.url as string)',
|
||||
'new URL("./worker.js", (import.meta as ImportMeta).url)',
|
||||
'new globalThis.URL("./worker.js", import.meta.url)',
|
||||
'new window.URL("./worker.js", import.meta.url)',
|
||||
'new self.URL("./worker.js", import.meta.url)',
|
||||
'new global.URL("./worker.js", import.meta.url)',
|
||||
'new ((globalThis as typeof globalThis)["URL"]!)("./worker.js", import.meta.url)',
|
||||
].map((urlExpression, index) => ({
|
||||
source: `nested/typed-${index}.ts`,
|
||||
expression: `new Worker(${urlExpression});`,
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
})),
|
||||
{
|
||||
source: "nested/space.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./space%20worker.js?worker=1#entry", import.meta.url));',
|
||||
specifier: "./space%20worker.js?worker=1#entry",
|
||||
resolved: "nested/space worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/percent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./percent%2520worker.js", import.meta.url));',
|
||||
specifier: "./percent%2520worker.js",
|
||||
resolved: "nested/percent%20worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/literal-percent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./percent%25worker.js", import.meta.url));',
|
||||
specifier: "./percent%25worker.js",
|
||||
resolved: "nested/percent%worker.js",
|
||||
},
|
||||
...["?value=", "#value="].map((suffix, index) => {
|
||||
const specifier = `./worker.js${suffix}%2F%2E%5C%00%FF%GG%2%\\\0`;
|
||||
return {
|
||||
source: `nested/suffix-${index}.mjs`,
|
||||
expression: `new Worker(new URL(${JSON.stringify(specifier)}, import.meta.url));`,
|
||||
specifier,
|
||||
resolved: "nested/worker.js",
|
||||
};
|
||||
}),
|
||||
{
|
||||
source: "bundled/entry.mjs",
|
||||
expression:
|
||||
'self.webpackChunkdemo.push([[1], {1: function(module, exports, require) { new Worker(new URL("./worker.js", import.meta.url)); }, "./worker.js": function(module) { module.exports = 42; }}]);',
|
||||
specifier: "./worker.js",
|
||||
resolved: "bundled/worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/literal.mjs",
|
||||
expression: 'new Worker("./literal-worker.js");',
|
||||
specifier: "./literal-worker.js",
|
||||
resolved: "nested/literal-worker.js",
|
||||
},
|
||||
];
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
cases.flatMap(({ source, expression, resolved }) => [
|
||||
[source, expression],
|
||||
[resolved, `self.postMessage(${JSON.stringify(resolved)});`],
|
||||
]),
|
||||
),
|
||||
"nested/percent worker.js": "self.postMessage('double-decoding decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
expect(workerReferences(result.graph)).toEqual(
|
||||
expect.arrayContaining(
|
||||
cases.map(({ source, specifier, resolved }) => ({
|
||||
source,
|
||||
declared_specifier: specifier,
|
||||
expression: null,
|
||||
resolved_path: resolved,
|
||||
mapped_paths: [resolved],
|
||||
})),
|
||||
),
|
||||
);
|
||||
expect(workerReferences(result.graph)).toHaveLength(cases.length);
|
||||
expect(result.graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "javascript-module",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({ module_key: "./worker.js" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"keeps unsupported Worker URL expressions and missing exact files unresolved through the CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-url-unknown-");
|
||||
const malformedPercentPaths = [
|
||||
["./worker%.js", "worker%.js"],
|
||||
["./worker%2.js", "worker%2.js"],
|
||||
["./worker%GG.js", "worker%GG.js"],
|
||||
["./space%20worker%GG.js", "space worker%GG.js"],
|
||||
];
|
||||
const expressions = {
|
||||
"dynamic-path.mjs": "new Worker(new URL(path, import.meta.url));",
|
||||
"absolute.mjs":
|
||||
'import { Worker } from "node:worker_threads"; new Worker(new URL("/worker.js", import.meta.url));',
|
||||
"typed-apply-meta.ts":
|
||||
'import { Worker } from "node:worker_threads"; Object.defineProperty.apply(Object, ([import.meta, "url", { value: "file:///other.mjs" }] as const)); new Worker(new URL("./worker.js", import.meta.url));',
|
||||
"overwritten-qualified-url.mjs":
|
||||
'globalThis.URL = replacement; new Worker(new globalThis.URL("./worker.js", import.meta.url));',
|
||||
"shadowed-qualified-url.mjs":
|
||||
'function start(window) { new Worker(new window.URL("./worker.js", import.meta.url)); }',
|
||||
...Object.fromEntries(
|
||||
["globalThis.URL", "URL", 'globalThis["URL"]'].map((target, index) => [
|
||||
`overwritten-url-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; const RealURL = URL; ${target} = class { constructor() { return new RealURL("./other.js", import.meta.url); } }; new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
[
|
||||
"delete globalThis.URL;",
|
||||
"({ URL: globalThis.URL } = replacements);",
|
||||
"globalThis[key] = replacement;",
|
||||
'Object.defineProperty(globalThis, "URL", { value: replacement });',
|
||||
'Reflect.set(globalThis, "URL", replacement);',
|
||||
"globalThis.globalThis.URL = replacement;",
|
||||
"globalThis.global.URL = replacement;",
|
||||
"const ambient = globalThis; ambient.URL = replacement;",
|
||||
"const { globalThis: ambient } = globalThis; ambient.URL = replacement;",
|
||||
].map((mutation, index) => [
|
||||
`mutated-url-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
[
|
||||
'import.meta.url = "file:///other/entry.mjs";',
|
||||
"delete import.meta.url;",
|
||||
'Object.defineProperty(import.meta, "url", { value: "file:///other/entry.mjs" });',
|
||||
"import.meta[key] = replacement;",
|
||||
'const meta = import.meta; const alias = meta; alias.url = "file:///other/entry.mjs";',
|
||||
'let meta = import.meta; meta.url = "file:///other/entry.mjs"; meta = {};',
|
||||
'const define = Object.defineProperty; define(import.meta, "url", { value: "file:///other/entry.mjs" });',
|
||||
'const set = Reflect.set.bind(Reflect); set(import.meta, "url", "file:///other/entry.mjs");',
|
||||
'Object.defineProperty.bind(Object, import.meta, "url")({ value: "file:///other/entry.mjs" });',
|
||||
'Object.assign(...[import.meta, { url: "file:///other/entry.mjs" }]);',
|
||||
'Object.defineProperty(...[import.meta, "url", { value: "file:///other/entry.mjs" }]);',
|
||||
].map((mutation, index) => [
|
||||
`mutated-import-meta-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
malformedPercentPaths.map(([specifier], index) => [
|
||||
`malformed-percent-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; new Worker(new URL(${JSON.stringify(specifier)}, import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
"dynamic-base.mjs": 'new Worker(new URL("./worker.js", base));',
|
||||
"shadowed.mjs":
|
||||
'function start(URL) { return new Worker(new URL("./worker.js", import.meta.url)); }',
|
||||
"typed-shadowed.ts":
|
||||
'function start(URL: typeof globalThis.URL) { return new Worker((new (URL as typeof globalThis.URL)("./worker.js", import.meta.url) as URL)!); }',
|
||||
"typed-dynamic-path.ts":
|
||||
"new Worker((new URL(path as string, import.meta.url) as URL)!);",
|
||||
"typed-dynamic-base.ts":
|
||||
'new Worker((new URL("./worker.js", base as string) as URL)!);',
|
||||
"call.mjs": 'new Worker(URL("./worker.js", import.meta.url));',
|
||||
"custom.mjs":
|
||||
'new Worker(new custom.URL("./worker.js", import.meta.url));',
|
||||
"extension.mjs":
|
||||
'new Worker(new URL("./extensionless", import.meta.url));',
|
||||
"directory.mjs": 'new Worker(new URL("./directory", import.meta.url));',
|
||||
"directory-dot.mjs":
|
||||
'new Worker(new URL("./worker.js/.", import.meta.url));',
|
||||
"directory-parent.mjs":
|
||||
'new Worker(new URL("./worker.js/child/..", import.meta.url));',
|
||||
"empty-segment.mjs":
|
||||
'new Worker(new URL("./child//../worker.js", import.meta.url));',
|
||||
"package.mjs":
|
||||
'new Worker(new URL("./package-worker", import.meta.url));',
|
||||
"external.mjs":
|
||||
'new Worker(new URL("https://example.test/worker.js", import.meta.url));',
|
||||
"empty.mjs": 'new Worker(new URL("", import.meta.url));',
|
||||
"query.mjs": 'new Worker(new URL("?worker=1", import.meta.url));',
|
||||
"whitespace.mjs":
|
||||
'new Worker(new URL(" ./worker.js ", import.meta.url));',
|
||||
"control.mjs": 'new Worker(new URL("./worker\\t.js", import.meta.url));',
|
||||
"leading-control.mjs":
|
||||
'new Worker(new URL("\\u0001./worker.js", import.meta.url));',
|
||||
};
|
||||
const knownSpecifiers: Readonly<Record<string, string>> = {
|
||||
"extension.mjs": "./extensionless",
|
||||
"directory.mjs": "./directory",
|
||||
"directory-dot.mjs": "./worker.js/.",
|
||||
"directory-parent.mjs": "./worker.js/child/..",
|
||||
"empty-segment.mjs": "./child//../worker.js",
|
||||
"package.mjs": "./package-worker",
|
||||
"external.mjs": "https://example.test/worker.js",
|
||||
};
|
||||
await writeFixtureFiles(root, {
|
||||
...expressions,
|
||||
...Object.fromEntries(
|
||||
malformedPercentPaths.map(([, decoy]) => [
|
||||
decoy,
|
||||
"self.postMessage('malformed percent pathname decoy');",
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('existing decoy');",
|
||||
"other.js": "self.postMessage('custom URL result decoy');",
|
||||
"extensionless.js": "self.postMessage('extension decoy');",
|
||||
"directory/index.js": "self.postMessage('index decoy');",
|
||||
"package-worker/package.json": JSON.stringify({ main: "selected.js" }),
|
||||
"package-worker/selected.js": "self.postMessage('package main decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(Object.keys(expressions).length);
|
||||
for (const [source, expression] of Object.entries(expressions)) {
|
||||
const specifier = knownSpecifiers[source] ?? null;
|
||||
expect(references).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source,
|
||||
declared_specifier: specifier,
|
||||
expression:
|
||||
specifier === null
|
||||
? expression.slice(
|
||||
expression.indexOf("new Worker("),
|
||||
expression.lastIndexOf(";"),
|
||||
)
|
||||
: null,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"bounds repeated ambient alias branches through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-alias-branches-");
|
||||
const aliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const alias${index + 1} = flag${index} ? alias${index} : alias${index};`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const splitAliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const left${index} = alias${index}; const right${index} = alias${index}; const alias${index + 1} = flag${index} ? left${index} : right${index};`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const memberAliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const alias${index + 1} = flag${index} ? alias${index}.globalThis : alias${index}.window;`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const expression = 'new Worker(new URL("./worker.js", import.meta.url))';
|
||||
await writeFixtureFiles(root, {
|
||||
"entry.mjs": `import { Worker } from "node:worker_threads";\n${aliases}\n${expression};`,
|
||||
"split.mjs": `import { Worker } from "node:worker_threads";\n${splitAliases}\n${expression};`,
|
||||
"member.mjs": `import { Worker } from "node:worker_threads";\n${memberAliases}\n${expression};`,
|
||||
"worker.js": "self.postMessage('existing alias-mutation decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory(
|
||||
"CLI",
|
||||
{ run: (invocation) => cli.run({ ...invocation, timeoutMs: 20_000 }) },
|
||||
root,
|
||||
);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(3);
|
||||
expect(references).toEqual(
|
||||
expect.arrayContaining(
|
||||
["entry.mjs", "split.mjs", "member.mjs"].map((source) => ({
|
||||
source,
|
||||
declared_specifier: null,
|
||||
expression,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
})),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"keeps Node Worker filesystem strings unresolved through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-node-worker-filesystem-");
|
||||
const cases = [
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
expression: 'new Worker("./worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker as ThreadWorker } from "worker_threads";',
|
||||
expression: 'new ThreadWorker("/worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
expression: 'new threads.Worker("./worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
expression: 'new (Worker as typeof Worker)("/worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
expression: 'new ((threads as typeof threads).Worker!)("./worker.js")',
|
||||
},
|
||||
].map((fixture, index) => ({
|
||||
...fixture,
|
||||
source: `nested/node-literal-${index}.ts`,
|
||||
}));
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
cases.map(({ prefix, expression, source }) => [
|
||||
source,
|
||||
`${prefix}\n${expression};`,
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('filesystem-root decoy');",
|
||||
"nested/worker.js": "self.postMessage('source-sibling decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(cases.length);
|
||||
for (const { source, expression } of cases)
|
||||
expect(references).toContainEqual({
|
||||
source,
|
||||
declared_specifier: null,
|
||||
expression,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Windows cannot materialize the pipe-named directory needed for this decoy.
|
||||
cliTest.skipIf(process.platform === "win32")(
|
||||
"keeps file-URL drive letters distinct from encoded POSIX paths through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-url-drive-");
|
||||
await writeFixtureFiles(root, {
|
||||
"dist/drive.mjs": 'new Worker(new URL("c|/worker.js", import.meta.url));',
|
||||
"dist/encoded.mjs":
|
||||
'new Worker(new URL("c%7C/worker.js", import.meta.url));',
|
||||
"dist/c|/worker.js": "self.postMessage('existing relative-path decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(2);
|
||||
expect(references).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
source: "dist/drive.mjs",
|
||||
declared_specifier: "c|/worker.js",
|
||||
expression: null,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
},
|
||||
{
|
||||
source: "dist/encoded.mjs",
|
||||
declared_specifier: "c%7C/worker.js",
|
||||
expression: null,
|
||||
resolved_path: "dist/c|/worker.js",
|
||||
mapped_paths: ["dist/c|/worker.js"],
|
||||
},
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
|
||||
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"preserves literal NIB fields and UTF-8 names through CLI and stdio MCP",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-nib-field-identity-");
|
||||
const app = join(root, "Fixture.app");
|
||||
const contents = join(app, "Contents");
|
||||
await mkdir(join(contents, "Resources"), { recursive: true });
|
||||
await mkdir(join(contents, "MacOS"));
|
||||
await writeFile(
|
||||
join(contents, "MacOS/App"),
|
||||
thinMach(0xfeedfacf, 0x0100000c),
|
||||
);
|
||||
await writeFile(
|
||||
join(contents, "Info.plist"),
|
||||
"<plist><dict><key>CFBundleExecutable</key><string>App</string><key>CFBundleIdentifier</key><string>dev.rea.nib-fields</string></dict></plist>",
|
||||
);
|
||||
const archive = encodeNibArchiveFixture({
|
||||
classes: ["UIView", "\uFEFFCustomView"],
|
||||
objects: [
|
||||
{
|
||||
classIndex: 0,
|
||||
values: {
|
||||
["__proto__"]: { ref: 1 },
|
||||
constructor: 7,
|
||||
enabled: true,
|
||||
"\uFEFFenabled": false,
|
||||
},
|
||||
},
|
||||
{ classIndex: 1, values: { ["__proto__"]: 23 } },
|
||||
],
|
||||
});
|
||||
const path = join(contents, "Resources/Panel.nib");
|
||||
await writeFile(path, archive);
|
||||
const result = await cli.run({
|
||||
arguments: ["decode-interface-builder", app, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
const contract = toolContract("decode_interface_builder");
|
||||
const evidence = contract.outputSchema.parse(result.json);
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
REA_LOG_LEVEL: "silent",
|
||||
REA_ANALYSIS_PROVIDER: "auto",
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
const client = new Client({ name: "nib-field-identity", version: "1" });
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: app },
|
||||
});
|
||||
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
|
||||
const response = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: {},
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const mcp = contract.outputSchema.parse(response.structuredContent);
|
||||
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
} finally {
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
const report = interfaceBuilderAnalysisSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(report.documents[0]?.archive_sha256).toBe(
|
||||
createHash("sha256").update(archive).digest("hex"),
|
||||
);
|
||||
const objects = report.graph.nodes.filter(
|
||||
({ attributes }) => attributes.interface_builder_object_id !== undefined,
|
||||
);
|
||||
expect(objects).toHaveLength(2);
|
||||
expect(objects[0]?.attributes.nibValues).toEqual({
|
||||
["__proto__"]: { objectID: "1" },
|
||||
constructor: 7,
|
||||
enabled: true,
|
||||
"\uFEFFenabled": false,
|
||||
});
|
||||
expect(objects[1]?.attributes).toMatchObject({
|
||||
class_name: "\uFEFFCustomView",
|
||||
nibValues: { ["__proto__"]: 23 },
|
||||
});
|
||||
expect(await readFile(path)).toEqual(archive);
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
@@ -4,15 +4,18 @@ import { createRequire } from "node:module";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
const literalAliases = ["#/x", "#x%2Fy", "#x%2Ey", "#x\\y", "#x\0y"];
|
||||
const fallbackAliases = {
|
||||
"#tab-escape": ["./.\t./outside.cjs", "./config.cjs"],
|
||||
"#newline-escape": ["./.%\n2e/outside.cjs", "./config.cjs"],
|
||||
"#normalized-url": "./con\tfig.cjs",
|
||||
"#trimmed-url": "./config.cjs \t",
|
||||
"#url-suffix": "./config.cjs?selected=one#fragment",
|
||||
"#inactive-array": {
|
||||
node: [{ browser: "./browser.cjs" }],
|
||||
default: "./config.cjs",
|
||||
@@ -30,29 +33,53 @@ const fallbackAliases = {
|
||||
};
|
||||
const resolvedAliases = [...literalAliases, ...Object.keys(fallbackAliases)];
|
||||
const refusedAliases = {
|
||||
"#empty": { target: [], limitation: "an empty imports target array" },
|
||||
"#empty": {
|
||||
target: [],
|
||||
status: "external",
|
||||
limitation: "an empty imports target array",
|
||||
},
|
||||
"#empty-active": {
|
||||
target: { node: [] },
|
||||
status: "external",
|
||||
limitation: "an empty imports target array",
|
||||
},
|
||||
"#null-last": {
|
||||
target: [[], null],
|
||||
status: "external",
|
||||
limitation: "an explicit null imports target",
|
||||
},
|
||||
"#empty-last": {
|
||||
target: [null, []],
|
||||
status: "external",
|
||||
limitation: "an empty imports target array",
|
||||
},
|
||||
"#inactive": {
|
||||
target: [{ browser: "./browser.cjs" }],
|
||||
status: "external",
|
||||
limitation: "it declares browser.",
|
||||
},
|
||||
"#nested-inactive": {
|
||||
status: "external",
|
||||
target: [
|
||||
[{ browser: "./browser.cjs" }, { "rea-inactive": "./inactive.cjs" }],
|
||||
],
|
||||
limitation: "it declares browser, rea-inactive.",
|
||||
},
|
||||
"#escape": {
|
||||
target: "./.\t./outside.cjs",
|
||||
status: "rejected",
|
||||
limitation: "escapes the package root",
|
||||
},
|
||||
"#encoded-separator": {
|
||||
target: ["./con%2ffig.cjs", "./config.cjs"],
|
||||
status: "rejected",
|
||||
limitation: "separator bytes",
|
||||
},
|
||||
"#missing-url": {
|
||||
target: ["./miss\ting.cjs", "./config.cjs"],
|
||||
status: "not-found",
|
||||
limitation: JSON.stringify("./miss\ting.cjs"),
|
||||
},
|
||||
};
|
||||
const allAliases = [...resolvedAliases, ...Object.keys(refusedAliases)];
|
||||
|
||||
@@ -129,26 +156,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
expect.objectContaining({ code: "ERR_PACKAGE_IMPORT_NOT_DEFINED" }),
|
||||
);
|
||||
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode, response.stderr).toBe(0);
|
||||
document = response.json;
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("analyze_javascript_application", {
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
document = response.structuredContent;
|
||||
}
|
||||
const { graph } = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(document).normalized_result;
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
for (const specifier of resolvedAliases)
|
||||
for (const [moduleKind, sourcePath, source] of [
|
||||
["require", "main.cjs", mainSource],
|
||||
@@ -168,7 +176,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
const imports = graph.edges.filter(
|
||||
({ properties }) => properties.module_link_kind === "require",
|
||||
);
|
||||
for (const [specifier, { limitation }] of Object.entries(refusedAliases))
|
||||
for (const [specifier, { status, limitation }] of Object.entries(
|
||||
refusedAliases,
|
||||
))
|
||||
for (const [moduleKind, sourcePath, source] of [
|
||||
["require", "main.cjs", mainSource],
|
||||
["import", "main.mjs", moduleSource],
|
||||
@@ -179,7 +189,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
module_link_kind: moduleKind,
|
||||
specifier,
|
||||
resolved_path: null,
|
||||
resolution_status: "external",
|
||||
resolution_status: status,
|
||||
}),
|
||||
evidence: sourceEvidence(sourcePath, source, limitation),
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
const requests = [
|
||||
{ specifier: "legacy?x", plainName: "legacy", exports: false },
|
||||
{ specifier: "exported#entry", plainName: "exported", exports: true },
|
||||
{ specifier: "@scope/legacy?x", plainName: "@scope/legacy", exports: false },
|
||||
{ specifier: "@scope#entry/pkg", plainName: "@scope/pkg", exports: true },
|
||||
] as const;
|
||||
|
||||
// Windows cannot materialize the question-mark directories in this fixture.
|
||||
cliTest.skipIf(process.platform === "win32").for(["CLI", "stdio MCP"] as const)(
|
||||
"keeps ESM root URL suffixes out of dependency filesystem lookup through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-package-root-suffix-");
|
||||
const sources = {
|
||||
"main.mjs": requests
|
||||
.map(({ specifier }) => `import ${JSON.stringify(specifier)};`)
|
||||
.join("\n"),
|
||||
"main.cjs": requests
|
||||
.map(({ specifier }) => `require(${JSON.stringify(specifier)});`)
|
||||
.join("\n"),
|
||||
};
|
||||
const files: Record<string, string> = { ...sources };
|
||||
for (const item of requests)
|
||||
for (const name of [item.specifier, item.plainName]) {
|
||||
const directory = `node_modules/${name}`;
|
||||
files[`${directory}/package.json`] = JSON.stringify(
|
||||
item.exports ? { exports: "./entry.cjs" } : { main: "./entry.cjs" },
|
||||
);
|
||||
files[`${directory}/entry.cjs`] =
|
||||
`module.exports = ${JSON.stringify(name)};`;
|
||||
}
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([path, text]) => {
|
||||
const absolute = join(root, path);
|
||||
await mkdir(dirname(absolute), { recursive: true });
|
||||
await writeFile(absolute, text);
|
||||
}),
|
||||
);
|
||||
if (surface === "CLI") {
|
||||
const native = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"--eval",
|
||||
`import { createRequire } from "node:module";
|
||||
const require = createRequire(new URL("./main.cjs", import.meta.url));
|
||||
const requests = ${JSON.stringify(requests.map(({ specifier }) => specifier))};
|
||||
const results = await Promise.all(requests.map(async (specifier) => {
|
||||
let esm;
|
||||
try { esm = { value: (await import(specifier)).default, error: null }; }
|
||||
catch (error) { esm = { value: null, error: error.code }; }
|
||||
return { esm, require: require(specifier) };
|
||||
}));
|
||||
console.log(JSON.stringify(results));`,
|
||||
],
|
||||
{ cwd: root, timeout: 5_000 },
|
||||
);
|
||||
expect(JSON.parse(native.stdout)).toEqual(
|
||||
requests.map(({ specifier }) => ({
|
||||
esm: { value: null, error: "ERR_MODULE_NOT_FOUND" },
|
||||
require: specifier,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
for (const { specifier } of requests)
|
||||
for (const [moduleKind, sourcePath] of [
|
||||
["import", "main.mjs"],
|
||||
["require", "main.cjs"],
|
||||
] as const)
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: moduleKind,
|
||||
specifier,
|
||||
resolved_path:
|
||||
moduleKind === "import"
|
||||
? null
|
||||
: `node_modules/${specifier}/entry.cjs`,
|
||||
resolution_status:
|
||||
moduleKind === "import" ? "external" : "resolved",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256")
|
||||
.update(sources[sourcePath])
|
||||
.digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: sourcePath }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,207 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
type SelfNameCase = {
|
||||
readonly directory: string;
|
||||
readonly packageName: string;
|
||||
readonly exportKey: string;
|
||||
readonly specifier: string;
|
||||
readonly selfValue: string;
|
||||
readonly dependency?: {
|
||||
readonly packagePath: string;
|
||||
readonly exportKey: string;
|
||||
readonly value: string;
|
||||
};
|
||||
readonly esmTarget: string;
|
||||
readonly requireTarget: string;
|
||||
readonly esmValue: string;
|
||||
readonly requireValue: string;
|
||||
};
|
||||
|
||||
const cases = [
|
||||
{
|
||||
directory: "scope-prefix",
|
||||
packageName: "@scope",
|
||||
exportKey: "./pkg",
|
||||
specifier: "@scope/pkg",
|
||||
selfValue: "scope self",
|
||||
dependency: {
|
||||
packagePath: "node_modules/@scope/pkg",
|
||||
exportKey: ".",
|
||||
value: "scope dependency",
|
||||
},
|
||||
esmTarget: "scope-prefix/node_modules/@scope/pkg/dependency.cjs",
|
||||
requireTarget: "scope-prefix/self.cjs",
|
||||
esmValue: "scope dependency",
|
||||
requireValue: "scope self",
|
||||
},
|
||||
{
|
||||
directory: "slash-name",
|
||||
packageName: "fixture/sub",
|
||||
exportKey: "./feature",
|
||||
specifier: "fixture/sub/feature",
|
||||
selfValue: "slash self",
|
||||
dependency: {
|
||||
packagePath: "node_modules/fixture",
|
||||
exportKey: "./sub/feature",
|
||||
value: "slash dependency",
|
||||
},
|
||||
esmTarget: "slash-name/node_modules/fixture/dependency.cjs",
|
||||
requireTarget: "slash-name/self.cjs",
|
||||
esmValue: "slash dependency",
|
||||
requireValue: "slash self",
|
||||
},
|
||||
{
|
||||
directory: "slash-exact-name",
|
||||
packageName: "fixture/sub",
|
||||
exportKey: ".",
|
||||
specifier: "fixture/sub",
|
||||
selfValue: "slash exact self",
|
||||
dependency: {
|
||||
packagePath: "node_modules/fixture",
|
||||
exportKey: "./sub",
|
||||
value: "slash exact dependency",
|
||||
},
|
||||
esmTarget: "slash-exact-name/node_modules/fixture/dependency.cjs",
|
||||
requireTarget: "slash-exact-name/self.cjs",
|
||||
esmValue: "slash exact dependency",
|
||||
requireValue: "slash exact self",
|
||||
},
|
||||
{
|
||||
directory: "valid-scoped",
|
||||
packageName: "@scope/pkg",
|
||||
exportKey: "./feature",
|
||||
specifier: "@scope/pkg/feature",
|
||||
selfValue: "valid scoped self",
|
||||
esmTarget: "valid-scoped/self.cjs",
|
||||
requireTarget: "valid-scoped/self.cjs",
|
||||
esmValue: "valid scoped self",
|
||||
requireValue: "valid scoped self",
|
||||
},
|
||||
{
|
||||
directory: "query-self-name",
|
||||
packageName: "self?x",
|
||||
exportKey: ".",
|
||||
specifier: "self?x",
|
||||
selfValue: "query self",
|
||||
esmTarget: "query-self-name/self.cjs",
|
||||
requireTarget: "query-self-name/self.cjs",
|
||||
esmValue: "query self",
|
||||
requireValue: "query self",
|
||||
},
|
||||
{
|
||||
directory: "fragment-self-name",
|
||||
packageName: "@scope/self#entry",
|
||||
exportKey: ".",
|
||||
specifier: "@scope/self#entry",
|
||||
selfValue: "fragment self",
|
||||
esmTarget: "fragment-self-name/self.cjs",
|
||||
requireTarget: "fragment-self-name/self.cjs",
|
||||
esmValue: "fragment self",
|
||||
requireValue: "fragment self",
|
||||
},
|
||||
] satisfies readonly SelfNameCase[];
|
||||
|
||||
const sourceFor = (specifier: string, moduleKind: "import" | "require") =>
|
||||
moduleKind === "import"
|
||||
? `import value from ${JSON.stringify(specifier)};\nexport default value;`
|
||||
: `const value = require(${JSON.stringify(specifier)});\nmodule.exports = value;`;
|
||||
|
||||
const createSelfNameFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-package-self-name-boundary-");
|
||||
const files: Record<string, string> = {};
|
||||
for (const item of cases) {
|
||||
const prefix = item.directory;
|
||||
files[`${prefix}/package.json`] = JSON.stringify({
|
||||
name: item.packageName,
|
||||
exports: { [item.exportKey]: "./self.cjs" },
|
||||
});
|
||||
files[`${prefix}/main.mjs`] = sourceFor(item.specifier, "import");
|
||||
files[`${prefix}/main.cjs`] = sourceFor(item.specifier, "require");
|
||||
files[`${prefix}/self.cjs`] =
|
||||
`module.exports = ${JSON.stringify(item.selfValue)};`;
|
||||
if (item.dependency !== undefined) {
|
||||
const dependencyPrefix = `${prefix}/${item.dependency.packagePath}`;
|
||||
files[`${dependencyPrefix}/package.json`] = JSON.stringify({
|
||||
exports: { [item.dependency.exportKey]: "./dependency.cjs" },
|
||||
});
|
||||
files[`${dependencyPrefix}/dependency.cjs`] =
|
||||
`module.exports = ${JSON.stringify(item.dependency.value)};`;
|
||||
}
|
||||
}
|
||||
files["node-control.mjs"] = `import { createRequire } from "node:module";
|
||||
const cases = ${JSON.stringify(cases.map(({ directory, specifier }) => ({ directory, specifier })))};
|
||||
const esm = await Promise.all(
|
||||
cases.map(async ({ directory }) =>
|
||||
(await import(new URL(directory + "/main.mjs", import.meta.url))).default,
|
||||
),
|
||||
);
|
||||
const require = cases.map(({ directory, specifier }) =>
|
||||
createRequire(new URL(directory + "/main.cjs", import.meta.url))(specifier),
|
||||
);
|
||||
console.log(JSON.stringify({ esm, require }));`;
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([path, content]) => {
|
||||
const absolute = join(root, path);
|
||||
await mkdir(dirname(absolute), { recursive: true });
|
||||
await writeFile(absolute, content);
|
||||
}),
|
||||
);
|
||||
return root;
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"matches self references by parsed ESM name and preserves CommonJS prefix matching through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createSelfNameFixture();
|
||||
if (surface === "CLI") {
|
||||
const native = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[join(root, "node-control.mjs")],
|
||||
{ cwd: root, timeout: 5_000 },
|
||||
);
|
||||
expect(JSON.parse(native.stdout)).toEqual({
|
||||
esm: cases.map(({ esmValue }) => esmValue),
|
||||
require: cases.map(({ requireValue }) => requireValue),
|
||||
});
|
||||
}
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
for (const item of cases)
|
||||
for (const [moduleKind, target] of [
|
||||
["import", item.esmTarget],
|
||||
["require", item.requireTarget],
|
||||
] as const) {
|
||||
const sourcePath = `${item.directory}/main.${moduleKind === "import" ? "mjs" : "cjs"}`;
|
||||
const source = sourceFor(item.specifier, moduleKind);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: moduleKind,
|
||||
specifier: item.specifier,
|
||||
resolved_path: target,
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: sourcePath }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,278 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
type PackageSpecifierCase = {
|
||||
readonly specifier: string;
|
||||
readonly target: string | null;
|
||||
readonly status: "resolved" | "external" | "rejected" | "not-found";
|
||||
readonly value: string | number | null;
|
||||
readonly error: string | null;
|
||||
};
|
||||
|
||||
const requests = [
|
||||
{
|
||||
specifier: "rea-self-fixture",
|
||||
target: "root.cjs",
|
||||
status: "resolved",
|
||||
value: 11,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "rea-self-fixture/feature",
|
||||
target: "feature.cjs",
|
||||
status: "resolved",
|
||||
value: 22,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "rea-self-fixture/feature?cache=1",
|
||||
target: "punctuated.cjs",
|
||||
status: "resolved",
|
||||
value: 33,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "rea-self-fixture/feature?cache=2",
|
||||
target: null,
|
||||
status: "external",
|
||||
value: null,
|
||||
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
specifier: "rea-self-fixture/feature#entry",
|
||||
target: null,
|
||||
status: "external",
|
||||
value: null,
|
||||
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
specifier: "fixture/feature?cache=1",
|
||||
target: null,
|
||||
status: "external",
|
||||
value: null,
|
||||
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
specifier: "fixture/feature#entry",
|
||||
target: null,
|
||||
status: "external",
|
||||
value: null,
|
||||
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
specifier: "fixture/literal?cache=1",
|
||||
target: "node_modules/fixture/literal.cjs",
|
||||
status: "resolved",
|
||||
value: "literal",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/?cache=1",
|
||||
target: null,
|
||||
status: "rejected",
|
||||
value: null,
|
||||
error: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "legacy/#entry",
|
||||
target: null,
|
||||
status: "rejected",
|
||||
value: null,
|
||||
error: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "legacy/nested/?cache=1",
|
||||
target: null,
|
||||
status: "rejected",
|
||||
value: null,
|
||||
error: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "legacy/nested/#entry",
|
||||
target: null,
|
||||
status: "rejected",
|
||||
value: null,
|
||||
error: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "legacy/feature.js",
|
||||
target: "node_modules/legacy/feature.js",
|
||||
status: "resolved",
|
||||
value: "legacy feature",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/feature.js?cache=1",
|
||||
target: "node_modules/legacy/feature.js",
|
||||
status: "resolved",
|
||||
value: "legacy feature",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/feature.js#entry",
|
||||
target: "node_modules/legacy/feature.js",
|
||||
status: "resolved",
|
||||
value: "legacy feature",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/with%20space.js?cache=1",
|
||||
target: "node_modules/legacy/with space.js",
|
||||
status: "resolved",
|
||||
value: "legacy spaced feature",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/feature",
|
||||
target: null,
|
||||
status: "not-found",
|
||||
value: null,
|
||||
error: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
] satisfies readonly PackageSpecifierCase[];
|
||||
|
||||
const createPackageSpecifierFixture = async (): Promise<{
|
||||
readonly root: string;
|
||||
readonly source: string;
|
||||
}> => {
|
||||
const root = await createTestTempDirectory("rea-package-specifier-suffix-");
|
||||
const packagePath = join(root, "node_modules", "fixture");
|
||||
const legacyPackagePath = join(root, "node_modules", "legacy");
|
||||
await Promise.all([
|
||||
mkdir(packagePath, { recursive: true }),
|
||||
mkdir(join(legacyPackagePath, "nested"), { recursive: true }),
|
||||
]);
|
||||
await writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "rea-self-fixture",
|
||||
exports: {
|
||||
".": { import: "./root.cjs", require: "./require.cjs" },
|
||||
"./feature": { import: "./feature.cjs", require: "./require.cjs" },
|
||||
"./feature?cache=1": {
|
||||
import: "./punctuated.cjs",
|
||||
require: "./require.cjs",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const source = requests
|
||||
.map(
|
||||
({ specifier }, index) =>
|
||||
`import value${index} from ${JSON.stringify(specifier)};`,
|
||||
)
|
||||
.join("\n");
|
||||
await Promise.all([
|
||||
writeFile(join(root, "main.mjs"), source),
|
||||
writeFile(join(root, "root.cjs"), "module.exports = 11;"),
|
||||
writeFile(join(root, "feature.cjs"), "module.exports = 22;"),
|
||||
writeFile(join(root, "punctuated.cjs"), "module.exports = 33;"),
|
||||
writeFile(join(root, "require.cjs"), "module.exports = -1;"),
|
||||
]);
|
||||
await writeFile(
|
||||
join(packagePath, "package.json"),
|
||||
JSON.stringify({
|
||||
exports: {
|
||||
"./feature": "./feature.cjs",
|
||||
"./literal?cache=1": "./literal.cjs",
|
||||
},
|
||||
}),
|
||||
);
|
||||
await Promise.all([
|
||||
writeFile(join(packagePath, "feature.cjs"), 'module.exports = "feature";'),
|
||||
writeFile(join(packagePath, "literal.cjs"), 'module.exports = "literal";'),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "package.json"),
|
||||
JSON.stringify({ name: "legacy", main: "./main.cjs" }),
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "main.cjs"),
|
||||
'module.exports = "legacy root";',
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "feature.js"),
|
||||
'module.exports = "legacy feature";',
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "with space.js"),
|
||||
'module.exports = "legacy spaced feature";',
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "nested", "package.json"),
|
||||
JSON.stringify({ main: "./main.cjs" }),
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "nested", "main.cjs"),
|
||||
'module.exports = "legacy nested";',
|
||||
),
|
||||
]);
|
||||
return { root, source };
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"resolves package self references and suffix keys through %s",
|
||||
async (surface, { cli }) => {
|
||||
const { root, source } = await createPackageSpecifierFixture();
|
||||
if (surface === "CLI") {
|
||||
const native = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`const requests = ${JSON.stringify(requests.map(({ specifier }) => specifier))};
|
||||
const results = await Promise.all(requests.map(async (specifier) => {
|
||||
try {
|
||||
const result = await import(specifier);
|
||||
return { value: result.default, error: null };
|
||||
} catch (error) {
|
||||
return { value: null, error: error.code };
|
||||
}
|
||||
}));
|
||||
console.log(JSON.stringify(results));`,
|
||||
],
|
||||
{ cwd: root, timeout: 5_000 },
|
||||
);
|
||||
expect(JSON.parse(native.stdout)).toEqual(
|
||||
requests.map(({ value, error }) => ({ value, error })),
|
||||
);
|
||||
}
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
for (const { specifier, target, status } of requests)
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "import",
|
||||
specifier,
|
||||
resolved_path: target,
|
||||
resolution_status: status,
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
...(specifier === "legacy/feature"
|
||||
? {
|
||||
limitations: expect.arrayContaining([
|
||||
"The selected package ESM subpath target node_modules/legacy/feature does not exist in the inventoried artifact container; ESM subpath targets are exact files, so no extension or directory index was tried.",
|
||||
]),
|
||||
}
|
||||
: {}),
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: "main.mjs" }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -2,14 +2,15 @@ import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
const createPackageSubpathFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-package-subpaths-");
|
||||
@@ -28,12 +29,18 @@ const createPackageSubpathFixture = async () => {
|
||||
'const literal = require("fi%xture");',
|
||||
'const scalar = require("scalar");',
|
||||
'const self = require("../node_modules/fi%xture/run.cjs");',
|
||||
'const uri = require("file:///src/uri-dep.cjs");',
|
||||
'const relativeUri = require("./uri-dep.cjs");',
|
||||
].join("\n");
|
||||
const selfSource = 'const self = require("fi%xture"); module.exports = self;';
|
||||
const importSource = 'import literal from "fi%xture";';
|
||||
const importSource = [
|
||||
'import literal from "fi%xture";',
|
||||
'import uri from "FILE:///src/uri-dep.cjs?token=%2F#entry";',
|
||||
].join("\n");
|
||||
const files = {
|
||||
"src/main.cjs": source,
|
||||
"src/imports.mjs": importSource,
|
||||
"src/uri-dep.cjs": "module.exports = 42;",
|
||||
"src/node_modules/fixture/parser.js": "module.exports = 1;",
|
||||
"src/node_modules/fixture.js": "module.exports = 'file';",
|
||||
"src/node_modules/fixture/index.js": "module.exports = 'directory';",
|
||||
@@ -104,11 +111,20 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"fi%xture": "node_modules/fi%xture.js",
|
||||
scalar: "node_modules/scalar.js",
|
||||
"../node_modules/fi%xture/run.cjs": "node_modules/fi%xture/run.cjs",
|
||||
"./uri-dep.cjs": "src/uri-dep.cjs",
|
||||
};
|
||||
for (const [specifier, target] of Object.entries(expectedTargets))
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(specifier)).replaceAll("\\", "/"),
|
||||
).toBe(target);
|
||||
expect(nativeRequire("./uri-dep.cjs")).toBe(42);
|
||||
for (const specifier of [
|
||||
"file:///src/uri-dep.cjs",
|
||||
pathToFileURL(join(root, "src/uri-dep.cjs")).href,
|
||||
])
|
||||
expect(() => nativeRequire.resolve(specifier)).toThrow(
|
||||
expect.objectContaining({ code: "MODULE_NOT_FOUND" }),
|
||||
);
|
||||
for (const specifier of ["exported/parser/", "exported/hidden", "blocked"])
|
||||
expect(() => nativeRequire.resolve(specifier)).toThrow(
|
||||
expect.objectContaining({ code: "ERR_PACKAGE_PATH_NOT_EXPORTED" }),
|
||||
@@ -124,26 +140,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
).replaceAll("\\", "/"),
|
||||
).toBe("node_modules/fi%xture/actual.cjs");
|
||||
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode, response.stderr).toBe(0);
|
||||
document = response.json;
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("analyze_javascript_application", {
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
document = response.structuredContent;
|
||||
}
|
||||
const { graph } = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(document).normalized_result;
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const imports = graph.edges.filter(
|
||||
({ properties }) => properties.module_link_kind === "require",
|
||||
);
|
||||
@@ -156,6 +153,41 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
},
|
||||
])
|
||||
expectResolvedImports(imports, observation);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "require",
|
||||
specifier: "file:///src/uri-dep.cjs",
|
||||
resolved_path: null,
|
||||
resolution_status: "external",
|
||||
}),
|
||||
evidence: sourceEvidence("src/main.cjs", source),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
kind: "require",
|
||||
specifier: "file:///src/uri-dep.cjs",
|
||||
resolved_path: null,
|
||||
}),
|
||||
evidence: sourceEvidence("src/main.cjs", source),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "import",
|
||||
specifier: "FILE:///src/uri-dep.cjs?token=%2F#entry",
|
||||
resolved_path: "src/uri-dep.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: sourceEvidence("src/imports.mjs", importSource),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
|
||||
@@ -7,7 +7,11 @@ import { z } from "zod";
|
||||
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import {
|
||||
evidenceResultOf,
|
||||
expandToolAvailability,
|
||||
toolAvailabilityInventory,
|
||||
} from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
|
||||
const mainPath = fileURLToPath(
|
||||
@@ -17,22 +21,28 @@ const fixturePath = fileURLToPath(
|
||||
new URL("../../fixtures/fakeLauncher.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
const expectAvailableToolInventory = async (client: Client) => {
|
||||
const listed = await client.listTools();
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
const expectAvailableToolInventory = async (
|
||||
client: Client,
|
||||
listed: Awaited<ReturnType<Client["listTools"]>>,
|
||||
) => {
|
||||
const binarySession = listed.tools.find(
|
||||
({ name }) => name === "binary_session",
|
||||
);
|
||||
if (binarySession === undefined)
|
||||
throw new Error("The compiled catalog omitted binary_session");
|
||||
const status = await client.callTool(
|
||||
{ name: "binary_session", arguments: {} },
|
||||
{ toolDefinition: binarySession },
|
||||
);
|
||||
expect(status.isError).not.toBe(true);
|
||||
const availability = z
|
||||
const inventory = z
|
||||
.object({
|
||||
result: z.object({
|
||||
tool_availability: z.array(
|
||||
z.object({ name: z.string(), available: z.boolean() }),
|
||||
),
|
||||
tool_availability: toolAvailabilityInventory,
|
||||
}),
|
||||
})
|
||||
.parse(status.structuredContent).result.tool_availability;
|
||||
const availability = expandToolAvailability(inventory);
|
||||
// This asserts the compiled entrypoint matches the source catalog. When it
|
||||
// fails, check that `dist/` is current (`npm run build:cached`) before
|
||||
// suspecting a registration bug -- a stale build is by far the likeliest
|
||||
@@ -161,6 +171,9 @@ describe("production stdio runtime", () => {
|
||||
15_000,
|
||||
);
|
||||
|
||||
// Use the suite's bounded acceptance deadline, including its coverage allowance.
|
||||
// This cold-start workflow computes the growing catalog's schema digests; it
|
||||
// verifies catalog and lifecycle behavior, not a 15-second performance target.
|
||||
it("serves the compiled catalog without an initial target or fatal record", async () => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
@@ -180,7 +193,10 @@ describe("production stdio runtime", () => {
|
||||
try {
|
||||
await client.connect(transport);
|
||||
// Keep catalog parity independent of initial target/provider startup.
|
||||
const status = await expectAvailableToolInventory(client);
|
||||
// Validate each called tool against its advertised definition without
|
||||
// asking the SDK to compile every unrelated output schema in the catalog.
|
||||
const listed = await client.listTools();
|
||||
const status = await expectAvailableToolInventory(client, listed);
|
||||
expect(
|
||||
z
|
||||
.object({ result: z.object({ open: z.boolean() }) })
|
||||
@@ -188,10 +204,15 @@ describe("production stdio runtime", () => {
|
||||
).toEqual({ open: false });
|
||||
// Closing the empty session produces a structured lifecycle record,
|
||||
// making the fatal-record check observable without launching a provider.
|
||||
const closed = await client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
const closeBinary = listed.tools.find(
|
||||
({ name }) => name === "close_binary",
|
||||
);
|
||||
if (closeBinary === undefined)
|
||||
throw new Error("The compiled catalog omitted close_binary");
|
||||
const closed = await client.callTool(
|
||||
{ name: "close_binary", arguments: {} },
|
||||
{ toolDefinition: closeBinary },
|
||||
);
|
||||
expect(closed.isError).not.toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
@@ -218,10 +239,7 @@ describe("production stdio runtime", () => {
|
||||
record.level >= 50,
|
||||
);
|
||||
expect(fatal).toEqual([]);
|
||||
// Full catalog discovery and first-call SDK schema compilation take about
|
||||
// 8–9 seconds on one local CPU; the 15-second budget repeatedly expired in
|
||||
// parallel CI shards. Keep a finite budget for the complete workflow.
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
it.runIf(process.platform === "darwin")(
|
||||
"serves a database-kind initial target without a fatal record on macOS",
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
|
||||
import { expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"recovers retained prefixed source-map originals and byte identity through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-retained-map-prefix-");
|
||||
const original = "export const answer: number = 42;";
|
||||
const mapText = `\uFEFF)]}'retained response\r\n${JSON.stringify({
|
||||
version: 3,
|
||||
sources: ["original.ts"],
|
||||
sourcesContent: [original],
|
||||
names: [],
|
||||
mappings: "AAAA",
|
||||
})}`;
|
||||
const mapPath = join(root, "bundle.js.map");
|
||||
await writeFile(
|
||||
join(root, "bundle.js"),
|
||||
"export const answer = 42;\n//# sourceMappingURL=bundle.js.map\n",
|
||||
);
|
||||
await writeFile(mapPath, mapText);
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const mapDigest = createHash("sha256").update(mapText).digest("hex");
|
||||
const originalDigest = createHash("sha256").update(original).digest("hex");
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "source-module",
|
||||
identity: expect.objectContaining({
|
||||
strategy: "source-map-original",
|
||||
source_map_sha256: mapDigest,
|
||||
original_source: "original.ts",
|
||||
source_sha256: originalDigest,
|
||||
}),
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
source_map_reference: expect.objectContaining({
|
||||
source_name: "original.ts",
|
||||
map_path: "bundle.js.map",
|
||||
}),
|
||||
properties: expect.objectContaining({
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
source_name_available: true,
|
||||
content_available: true,
|
||||
content_sha256: originalDigest,
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({ sha256: mapDigest }),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(graph.coverage.status).toBe("complete");
|
||||
expect(await readFile(mapPath, "utf8")).toBe(mapText);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"retains nullable source-map declarations and aligned content through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-nullable-map-");
|
||||
const original = "export const answer: number = 42;";
|
||||
const unnamed = "retained source text without a declared name";
|
||||
const maps = {
|
||||
"absent.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sources: ["unembedded.ts"],
|
||||
sourcesContent: null,
|
||||
names: [],
|
||||
mappings: "AAAA",
|
||||
}),
|
||||
"mixed.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sources: [null, "original.ts"],
|
||||
sourcesContent: [unnamed, original],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
}),
|
||||
"unnamed-empty.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sources: [null, "original.ts"],
|
||||
sourcesContent: [null, original],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
}),
|
||||
};
|
||||
await writeFixtureFiles(root, {
|
||||
...maps,
|
||||
"absent.js":
|
||||
"export const absent = 1;\n//# sourceMappingURL=absent.js.map\n",
|
||||
"mixed.js":
|
||||
"export const answer = 42;\n//# sourceMappingURL=mixed.js.map\n",
|
||||
"unnamed-empty.js":
|
||||
"export const answer = 42;\n//# sourceMappingURL=unnamed-empty.js.map\n",
|
||||
});
|
||||
for (const [mapPath, expectedSource] of [
|
||||
["absent.js.map", "unembedded.ts"],
|
||||
["mixed.js.map", "original.ts"],
|
||||
["unnamed-empty.js.map", "original.ts"],
|
||||
] as const)
|
||||
expect(
|
||||
originalPositionFor(new TraceMap(maps[mapPath], `file:///${mapPath}`), {
|
||||
line: 1,
|
||||
column: 0,
|
||||
}).source,
|
||||
).toBe(`file:///${expectedSource}`);
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const digest = (text: string) =>
|
||||
createHash("sha256").update(text).digest("hex");
|
||||
expect(
|
||||
graph.nodes.filter(
|
||||
(node) => node.identity.strategy === "source-map-original",
|
||||
),
|
||||
).toHaveLength(3);
|
||||
for (const [name, mapPath, content, sourceIndex] of [
|
||||
["unembedded.ts", "absent.js.map", null, 0],
|
||||
["original.ts", "mixed.js.map", original, 1],
|
||||
["original.ts", "unnamed-empty.js.map", original, 1],
|
||||
] as const) {
|
||||
const mapDigest = digest(maps[mapPath]);
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "source-module",
|
||||
identity: expect.objectContaining({
|
||||
strategy: "source-map-original",
|
||||
source_map_sha256: mapDigest,
|
||||
original_source: name,
|
||||
source_sha256: content === null ? null : digest(content),
|
||||
}),
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
source_map_reference: expect.objectContaining({
|
||||
source_name: name,
|
||||
map_path: mapPath,
|
||||
}),
|
||||
properties: expect.objectContaining({
|
||||
source_index: sourceIndex,
|
||||
declaration_index: sourceIndex,
|
||||
source_name_available: true,
|
||||
content_available: content !== null,
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({ sha256: mapDigest }),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const [mapPath, content] of [
|
||||
["mixed.js.map", unnamed],
|
||||
["unnamed-empty.js.map", null],
|
||||
] as const)
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "unknown",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
source_map_reference: null,
|
||||
properties: expect.objectContaining({
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
source_name_available: false,
|
||||
content_available: content !== null,
|
||||
content_sha256: content === null ? null : digest(content),
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: digest(maps[mapPath]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(graph.coverage.status).toBe("complete");
|
||||
for (const [path, text] of Object.entries(maps))
|
||||
expect(await readFile(join(root, path), "utf8")).toBe(text);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"rejects non-string source-map names without inventing originals through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-invalid-map-source-");
|
||||
const mapText = JSON.stringify({
|
||||
version: 3,
|
||||
sources: [42, "discarded.ts"],
|
||||
sourcesContent: [null, "export const answer: number = 42;"],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
});
|
||||
await writeFixtureFiles(root, { "invalid.js.map": mapText });
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
expect(graph.coverage.status).toBe("partial");
|
||||
expect(
|
||||
graph.nodes.some(
|
||||
(node) => node.identity.strategy === "source-map-original",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "unknown",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
operation: "parse-local-source-map",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(mapText).digest("hex"),
|
||||
}),
|
||||
limitations: expect.arrayContaining([
|
||||
"Source map contains a non-string source name.",
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(await readFile(join(root, "invalid.js.map"), "utf8")).toBe(mapText);
|
||||
},
|
||||
);
|
||||
@@ -1,7 +1,9 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { join, relative } from "node:path";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
@@ -10,6 +12,318 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const compiler = join(
|
||||
dirname(createRequire(import.meta.url).resolve("typescript/package.json")),
|
||||
"bin",
|
||||
"tsc",
|
||||
);
|
||||
|
||||
const typedLines = [
|
||||
'export import typed = require("typed-package");',
|
||||
'import type TypeOnly = require("./type-only.cjs");',
|
||||
] as const;
|
||||
const typedSource = typedLines.join("\n");
|
||||
const aliasSource = [
|
||||
'import raw = require("typed-package");',
|
||||
"const alias = raw;",
|
||||
"export { alias };",
|
||||
].join("\n");
|
||||
const mixedSource = [
|
||||
'import { value as imported } from "mixed-package";',
|
||||
'import required = require("mixed-package");',
|
||||
"const mixed = Date.now() > 0 ? imported : required.value;",
|
||||
"export { imported as staticChoice, mixed };",
|
||||
"export const requireChoice = required.value;",
|
||||
].join("\n");
|
||||
const typescriptSourceFiles = {
|
||||
"typed.cts": typedSource,
|
||||
"typed.mts": typedSource,
|
||||
"alias.cts": aliasSource,
|
||||
"alias.mts": aliasSource,
|
||||
"mixed.cts": mixedSource,
|
||||
"mixed.mts": mixedSource,
|
||||
};
|
||||
const typedPackageFiles = {
|
||||
"node_modules/typed-package/package.json": JSON.stringify({
|
||||
exports: { require: "./actual.cjs", import: "./decoy.mjs" },
|
||||
}),
|
||||
"node_modules/typed-package/actual.cjs": "module.exports = 42;",
|
||||
"node_modules/typed-package/actual.d.cts":
|
||||
"declare const value: number; export = value;",
|
||||
"node_modules/typed-package/decoy.mjs": "export default 99;",
|
||||
"node_modules/typed-package/decoy.d.mts":
|
||||
"declare const value: number; export default value;",
|
||||
"node_modules/mixed-package/package.json": JSON.stringify({
|
||||
exports: { require: "./actual.cjs", import: "./decoy.mjs" },
|
||||
}),
|
||||
"node_modules/mixed-package/actual.cjs": "exports.value = 42;",
|
||||
"node_modules/mixed-package/actual.d.cts":
|
||||
"export declare const value: number;",
|
||||
"node_modules/mixed-package/decoy.mjs": "export const value = 99;",
|
||||
"node_modules/mixed-package/decoy.d.mts":
|
||||
"export declare const value: number;",
|
||||
};
|
||||
|
||||
const expectNativeModuleControls = async (root: string): Promise<void> => {
|
||||
const emitted = await createTestTempDirectory("rea-import-equals-output-");
|
||||
await writeFixtureFiles(emitted, typedPackageFiles);
|
||||
await execute(
|
||||
process.execPath,
|
||||
[
|
||||
compiler,
|
||||
"--module",
|
||||
"NodeNext",
|
||||
"--moduleResolution",
|
||||
"NodeNext",
|
||||
"--target",
|
||||
"ES2022",
|
||||
"--skipLibCheck",
|
||||
"--allowJs",
|
||||
"--outDir",
|
||||
emitted,
|
||||
join(root, "typed.cts"),
|
||||
join(root, "typed.mts"),
|
||||
join(root, "alias.cts"),
|
||||
join(root, "alias.mts"),
|
||||
join(root, "mixed.cts"),
|
||||
join(root, "mixed.mts"),
|
||||
],
|
||||
{ cwd: root, timeout: 10_000 },
|
||||
);
|
||||
for (const [filename, script] of [
|
||||
[
|
||||
"typed.cjs",
|
||||
'console.log(require("./typed.cjs").typed, require("./alias.cjs").alias);',
|
||||
],
|
||||
[
|
||||
"typed.mjs",
|
||||
'Promise.all([import("./typed.mjs"), import("./alias.mjs")]).then(([first, second]) => console.log(first.typed, second.alias));',
|
||||
],
|
||||
] as const) {
|
||||
const typedControl = await execute(process.execPath, ["-e", script], {
|
||||
cwd: emitted,
|
||||
timeout: 5_000,
|
||||
});
|
||||
expect(typedControl.stdout.trim()).toBe("42 42");
|
||||
expect(await readFile(join(emitted, filename), "utf8")).not.toContain(
|
||||
"./type-only.cjs",
|
||||
);
|
||||
}
|
||||
for (const [filename, expected] of [
|
||||
["mixed.cjs", "42 42 42"],
|
||||
["mixed.mjs", "99 42 99"],
|
||||
] as const) {
|
||||
const control = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
"-e",
|
||||
`import("./${filename}").then(({staticChoice, requireChoice, mixed}) => console.log(staticChoice, requireChoice, mixed));`,
|
||||
],
|
||||
{ cwd: emitted, timeout: 5_000 },
|
||||
);
|
||||
expect(control.stdout.trim()).toBe(expected);
|
||||
}
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
for (const name of ["dependency", "nested"])
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
|
||||
"\\",
|
||||
"/",
|
||||
),
|
||||
).toBe(`${name}.cjs`);
|
||||
};
|
||||
|
||||
const expectAliasRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
for (const source of ["alias.cts", "alias.mts"]) {
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "export",
|
||||
local_name: "alias",
|
||||
exported_name: "alias",
|
||||
resolution_mode: "require",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(aliasSource).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const expectMixedRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
const exported = (source: string, name: string) =>
|
||||
graph.edges.filter(
|
||||
({ relation, properties, evidence }) =>
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "export" &&
|
||||
properties.exported_name === name &&
|
||||
evidence.location.available &&
|
||||
evidence.location.value.kind === "source-range" &&
|
||||
evidence.location.value.source === source,
|
||||
);
|
||||
for (const source of ["mixed.cts", "mixed.mts"]) {
|
||||
for (const [name, target] of [
|
||||
["staticChoice", source.endsWith(".cts") ? "actual.cjs" : "decoy.mjs"],
|
||||
["requireChoice", "actual.cjs"],
|
||||
] as const)
|
||||
expect(exported(source, name)).toMatchObject([
|
||||
{
|
||||
properties: {
|
||||
resolved_path: `node_modules/mixed-package/${target}`,
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
sha256: createHash("sha256").update(mixedSource).digest("hex"),
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
expect(exported("mixed.cts", "mixed")).toMatchObject([
|
||||
{
|
||||
properties: {
|
||||
resolved_path: "node_modules/mixed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
sha256: createHash("sha256").update(mixedSource).digest("hex"),
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(exported("mixed.mts", "mixed")).toEqual([]);
|
||||
};
|
||||
|
||||
const expectImportEqualsRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
for (const [sourcePath, format] of [
|
||||
["typed.cts", "commonjs"],
|
||||
["typed.mts", "esm"],
|
||||
] as const) {
|
||||
const typedLinks = graph.edges.filter(
|
||||
({ relation, properties, evidence: edgeEvidence }) =>
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "require" &&
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.source === sourcePath,
|
||||
);
|
||||
expect(typedLinks).toHaveLength(1);
|
||||
expect(typedLinks[0]).toMatchObject({
|
||||
properties: {
|
||||
specifier: "typed-package",
|
||||
imported_name: null,
|
||||
local_name: "typed",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
available: true,
|
||||
sha256: createHash("sha256").update(typedSource).digest("hex"),
|
||||
},
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
source: sourcePath,
|
||||
start: { line: 1, column: 7 },
|
||||
end: { line: 1, column: typedLines[0].length },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "export",
|
||||
local_name: "typed",
|
||||
resolution_mode: "require",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: sourcePath }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.nodes.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
semantic_role: "source-module",
|
||||
path: sourcePath,
|
||||
export_names: ["typed"],
|
||||
export_relationships: 1,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, evidence: edgeEvidence }) =>
|
||||
relation === "exposes" &&
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.source === sourcePath,
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
kind: "require",
|
||||
specifier: "typed-package",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.nodes.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
semantic_role: "source-module",
|
||||
path: sourcePath,
|
||||
module_format: format,
|
||||
import_relationships: 1,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" && properties.specifier === "./type-only.cjs",
|
||||
),
|
||||
).toHaveLength(0);
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"retains unbound CommonJS semantic relationships through %s",
|
||||
@@ -34,20 +348,16 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"imports.mjs": 'import "./dependency.cjs";',
|
||||
"dependency.cjs": 'throw new Error("fixture must not execute");',
|
||||
"nested.cjs": 'throw new Error("fixture must not execute");',
|
||||
...typescriptSourceFiles,
|
||||
"type-only.d.cts": "declare const value: unknown; export = value;",
|
||||
};
|
||||
await Promise.all(
|
||||
Object.entries(files).map(([path, text]) =>
|
||||
writeFile(join(root, path), text),
|
||||
),
|
||||
);
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
for (const name of ["dependency", "nested"])
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
|
||||
"\\",
|
||||
"/",
|
||||
),
|
||||
).toBe(`${name}.cjs`);
|
||||
await writeFixtureFiles(root, typedPackageFiles);
|
||||
await expectNativeModuleControls(root);
|
||||
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
@@ -70,6 +380,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expectImportEqualsRelationships(graph);
|
||||
expectAliasRelationships(graph);
|
||||
expectMixedRelationships(graph);
|
||||
const links = graph.edges.filter(
|
||||
({ relation, properties, evidence: edgeEvidence }) =>
|
||||
relation === "imports" &&
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"reports Webpack exports attached to renamed factory parameters",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-webpack-renamed-exports-");
|
||||
await mkdir(join(root, "src"));
|
||||
await writeFile(
|
||||
join(root, "src", "chunk.js"),
|
||||
`globalThis.webpackChunkApp.push([[1], {
|
||||
17(module, __webpack_exports__, __webpack_require__) {
|
||||
__webpack_require__.d(__webpack_exports__, { alpha: () => 1, "beta.gamma": () => 2 });
|
||||
Object.defineProperty(__webpack_exports__, "delta", { enumerable: true, get() { return 3; } });
|
||||
__webpack_require__.d(__webpack_exports__.nested, { nested_target: () => 0 });
|
||||
__webpack_exports__ = { rebound: () => 0 };
|
||||
__webpack_require__.d({}, { unrelated: () => 0 });
|
||||
{ const exports = {}; __webpack_require__.d(exports, { shadowed_exports: () => 5 }); }
|
||||
},
|
||||
23(m, e, r) { r.d(e, { alpha: () => 1 }); }
|
||||
}]);`,
|
||||
);
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(response.json).normalized_result,
|
||||
);
|
||||
const modules = result.graph.nodes
|
||||
.filter(({ kind }) => kind === "javascript-module")
|
||||
.map(({ observations }) => observations[0]?.properties);
|
||||
expect(modules).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
module_key: "17",
|
||||
exports: ["alpha", "beta.gamma", "delta"],
|
||||
}),
|
||||
expect.objectContaining({ module_key: "23", exports: ["alpha"] }),
|
||||
]),
|
||||
);
|
||||
expect(result.graph.coverage.status).toBe("complete");
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user