test(javascript): consolidate artifact graph and resolution coverage

This commit is contained in:
morluto committed 2026-11-17 21:54:42 -05:00
1 parent b2af0d77e0
commit 1ff7be8c70
22 files changed
+595 -1590

No files matched your search

@@ -51,7 +51,7 @@ it("updates held nodes and deduplicates observations across finalization", () =>
expect(identifiers).toEqual(identifiers.toSorted());
accumulator.addNode(nodeInput("later"));
accumulator.addNode(first);
accumulator.addNode(alpha);
expect(labels()).toEqual(["alpha", "beta", "later", "雪😀"]);
const published = accumulator.nodes();
expect(
@@ -266,30 +266,19 @@ it("does not count a whole type-only import when semantics are skipped", async (
expect(electronSemantics).toBeUndefined();
});
it("does not treat a worker URL path as an Electron module", async () => {
// `new Worker(new URL("electron", import.meta.url))` records a `worker`
// reference whose specifier is a path relative to the importing source.
const { electronSemantics } = await graphFor(
`const worker = new Worker(new URL("electron", import.meta.url));\n`,
(entry) => ({ ...entry, semantic: null }),
);
expect(electronSemantics).toBeUndefined();
});
it("reports the same Electron applicability as the retained static fact", async () => {
// `analysis_coverage.applicability.electron` is the domain owner of the same
// question, so a worker URL path must be unknown for both outputs.
it("retains an electron-named worker URL without claiming Electron coverage", async () => {
const entry = await analyzedEntry(
`const worker = new Worker(new URL("electron", import.meta.url));\n`,
);
expect(entry.javascript?.references).toContainEqual(
expect.objectContaining({ kind: "worker", specifier: "electron" }),
);
expect(entry.javascript?.analysis_coverage.applicability.electron).toBe(
"unknown",
);
const graph = await graphFor(
`const worker = new Worker(new URL("electron", import.meta.url));\n`,
);
const graph = graphForEntries([{ ...entry, semantic: null }]);
expect(graph.electronSemantics).toBeUndefined();
expect(graph.limitations).not.toContain(EMPTY_COVERAGE);
});
it("does not count a resolve-only Electron reference as coverage", async () => {
@@ -1,6 +1,6 @@
import { addElectronIpcBoundaries } from "./ElectronBoundaryGraphIpc.js";
import { createElectronIpcContext } from "./ElectronBoundaryAnalysis.js";
import { describe, expect, it } from "vitest";
import { expect, it } from "vitest";
import { createHash } from "node:crypto";
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
@@ -80,7 +80,6 @@ const analysisFor = (
});
const contextFor = (
file: JavaScriptArtifactFile,
analysis: JavaScriptArtifactAnalysis,
): JavaScriptArtifactGraphContext => {
const accumulator = new JavaScriptArtifactGraphAccumulator();
@@ -97,11 +96,12 @@ const contextFor = (
// remain on the individual files and do not imply missing inventory paths.
coverage: { scope: "root", status: "complete" },
} as unknown as ArtifactInventorySnapshot;
const files = analysis.files.map(({ file }) => file);
const fileSet = {
files: [file],
files,
unavailable_relevant_files: [],
containers: [],
text_bytes_read: file.bytes,
text_bytes_read: files.reduce((total, { bytes }) => total + bytes, 0),
invalid_utf8_files: 0,
};
return {
@@ -111,7 +111,7 @@ const contextFor = (
analysis,
directoryPaths: new Set<string>(),
root: createJavaScriptArtifactRootNode(accumulator, snapshot),
filesByPath: new Map([[file.path, file]]),
filesByPath: new Map(files.map((entry) => [entry.path, entry])),
unanalyzedFiles: undefined,
fileNodes: new Map(),
assetNodes: new Map(),
@@ -127,68 +127,54 @@ const contextFor = (
};
};
const fileObservation = (context: JavaScriptArtifactGraphContext) => {
const node = context.accumulator
it("distinguishes interrupted JavaScript analysis from unattempted analysis", () => {
const interrupted = skippedFile();
const text = "export const ignored = true;";
const unattempted: JavaScriptArtifactFile = {
...interrupted,
path: "unattempted.js",
sha256: createHash("sha256").update(text).digest("hex"),
bytes: Buffer.byteLength(text),
text: { included: true, value: text },
};
const analysis = analysisFor([
skippedEntry(interrupted),
{ file: unattempted, javascript: null, semantic: null },
]);
const context = contextFor(analysis);
addJavaScriptArtifactFiles(context);
const observations = context.accumulator
.nodes()
.find(({ kind }) => kind === "javascript-asset");
if (node === undefined) throw new Error("Expected a javascript-asset node");
const observation = node.observations[0];
if (observation === undefined) throw new Error("Expected a file observation");
return observation.properties;
};
describe("skipped JavaScript parse reporting", () => {
it("marks parse_status skipped for a JavaScript file whose worker analysis failed", () => {
const file = skippedFile();
const context = contextFor(file, analysisFor([skippedEntry(file)]));
addJavaScriptArtifactFiles(context);
expect(fileObservation(context).parse_status).toBe("skipped");
expect(fileObservation(context).analysis_coverage).toMatchObject({
syntax: { status: "not-examined", error_count: null },
semantics: { unknown_findings: null },
examination: { status: "not-examined" },
.filter(({ kind }) => kind === "javascript-asset")
.flatMap(({ observations }) => observations);
expect(observations).toHaveLength(2);
for (const [path, status, reason] of [
["main.js", "skipped", "JavaScript analysis did not complete."],
["unattempted.js", null, "JavaScript source analysis was not performed."],
] as const) {
const observation = observations.find(
({ properties }) => properties.path === path,
);
expect(observation?.properties).toMatchObject({
parse_status: status,
analysis_coverage: {
syntax: { status: "not-examined", error_count: null },
semantics: { unknown_findings: null },
examination: { status: "not-examined" },
unexamined_reason: reason,
},
});
});
it("keeps parse_status null for a JavaScript file never attempted", () => {
const file = skippedFile();
const entry: AnalyzedJavaScriptArtifactFile = {
file,
javascript: null,
semantic: null,
};
const context = contextFor(file, analysisFor([entry]));
addJavaScriptArtifactFiles(context);
expect(fileObservation(context).parse_status).toBeNull();
});
it("keeps the parsed status for an analyzed JavaScript file", () => {
const file = skippedFile();
const javascript = analyzeJavaScriptStaticSource(
"const {ipcMain}=require('electron');\n",
);
const entry: AnalyzedJavaScriptArtifactFile = {
file,
javascript,
semantic: null,
};
const context = contextFor(file, analysisFor([entry]));
addJavaScriptArtifactFiles(context);
expect(fileObservation(context).parse_status).toBe(javascript.parse_status);
expect(fileObservation(context).analysis_coverage).toEqual(
javascript.analysis_coverage,
);
});
}
});
it("preserves omitted inventory facts on an unavailable artifact", () => {
const file = skippedFile();
const base = contextFor(file, analysisFor([]));
const base = contextFor(analysisFor([]));
const context: JavaScriptArtifactGraphContext = {
...base,
fileSet: {
...base.fileSet,
files: [],
unavailable_relevant_files: [
{
path: file.path,
@@ -260,13 +246,7 @@ it.each([false, true])(
},
{ file: page, javascript: null, semantic: null },
]);
const base = contextFor(window, analysis);
const files = [setter, window, page];
const context: JavaScriptArtifactGraphContext = {
...base,
fileSet: { ...base.fileSet, files },
filesByPath: new Map(files.map((file) => [file.path, file])),
};
const context = contextFor(analysis);
context.applicationRootsBySource.set(setter.path, new Set(["a"]));
context.applicationRootsBySource.set(window.path, new Set(["b"]));
if (possibleOwner)
@@ -387,12 +367,9 @@ it.each([
{ file: otherPage, javascript: null, semantic: null },
];
const analysis = analysisFor(entries);
const base = contextFor(main, analysis);
const files = entries.map(({ file }) => file);
const base = contextFor(analysis);
const context: JavaScriptArtifactGraphContext = {
...base,
fileSet: { ...base.fileSet, files },
filesByPath: new Map(files.map((file) => [file.path, file])),
unanalyzedFiles:
gap === "opaque"
? {
@@ -460,7 +437,7 @@ it("attaches sender validation to the innermost handler after a long minified li
const javascript = analyzeJavaScriptStaticSource(source);
expect(javascript.electron.sender_validations).toHaveLength(1);
const analysis = analysisFor([{ file, javascript, semantic: null }]);
const context = contextFor(file, analysis);
const context = contextFor(analysis);
addJavaScriptArtifactFiles(context);
addElectronIpcBoundaries(
context,
@@ -512,7 +489,7 @@ it("projects package parse status from the package observation", () => {
},
],
};
const context = contextFor(file, analysis);
const context = contextFor(analysis);
addJavaScriptArtifactFiles(context);
const observation = context.accumulator
.nodes()
@@ -31,8 +31,6 @@ it.each([
])(
"retains above-root traversal before synthetic URL normalization: %s",
(declaredPath) => {
const actual = new URL(declaredPath, "file:///selected-root/app/main.mjs");
expect(actual.pathname.startsWith("/selected-root/")).toBe(false);
expect(
resolveArtifactPathByContext({
declaredPath,
@@ -55,8 +53,6 @@ it.each([
])(
"retains an inside-root URL without banning synthetic-looking names: %s",
(declaredPath, target) => {
const actual = new URL(declaredPath, "file:///selected-root/app/main.mjs");
expect(actual.pathname).toBe(`/selected-root/${target}`);
expect(
resolveArtifactPathByContext({
declaredPath,
@@ -348,20 +348,6 @@ describe("runtime host path classification", () => {
});
},
);
it("normalizes discarded relative URL segments before pathname validation", () => {
expect(
resolve({
declaredPath: "./discard%2F/../window.cjs",
sourcePath: "app/main.mjs",
context: "module-specifier",
moduleKind: "import",
files: fileMap([file("app/window.cjs", "root")]),
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/window.cjs",
});
});
it("retains unknown URL identity for an unpaired source directory segment", () => {
expect(
resolve({
@@ -942,33 +928,7 @@ describe("unavailable package metadata", () => {
});
describe("bare package root file lookup", () => {
it("uses loader-specific bare package roots when only a sibling .js file exists", () => {
const absentDirectory = fileMap([
file("app/entry.mjs", "root"),
file("app/node_modules/fixture.js", "root"),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/entry.mjs",
context: "module-specifier",
moduleKind: "import",
files: absentDirectory,
}),
).toMatchObject({ resolution_status: "external", resolved_path: null });
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/entry.mjs",
context: "module-specifier",
moduleKind: "require",
files: absentDirectory,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture.js",
});
it("uses the sibling file only for CommonJS when a package directory also exists", () => {
const packageDirectory = fileMap([
file("app/entry.mjs", "root"),
file("app/node_modules/fixture.js", "root"),
@@ -999,26 +959,6 @@ describe("bare package root file lookup", () => {
});
describe("legacy package main lookup", () => {
it("treats an empty package main as absent and resolves the root index", () => {
const files = fileMap([
file("app/src/entry.cjs", "root"),
file("app/node_modules/fixture/package.json", "root", '{"main":""}'),
file("app/node_modules/fixture/index.js", "root"),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/src/entry.cjs",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/index.js",
});
});
it.each(["import", "require"] as const)(
"limits %s package-main probes to Node's file extensions",
(moduleKind) => {
@@ -1043,57 +983,6 @@ describe("legacy package main lookup", () => {
).toMatchObject({ resolution_status: "not-found", resolved_path: null });
},
);
it("retains inventoried directories during legacy ESM main finalization", () => {
const files = fileMap([
file("app/src/entry.mjs", "root"),
file(
"app/node_modules/fixture/package.json",
"root",
'{"main":"./lib/"}',
),
file("app/node_modules/fixture/lib.js", "root"),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/src/entry.mjs",
context: "module-specifier",
moduleKind: "import",
files,
directoryPaths: new Set(["app/node_modules/fixture/lib/.js"]),
}),
).toMatchObject({
resolution_status: "rejected",
resolved_path: null,
candidate_path: "app/node_modules/fixture/lib/.js",
});
});
it.each(["import", "require"] as const)(
"does not recursively resolve a nested package from a %s package main",
(moduleKind) => {
const files = fileMap([
file("app/src/entry.js", "root"),
file("app/node_modules/fixture/package.json", "root", '{"main":"sub"}'),
file(
"app/node_modules/fixture/sub/package.json",
"root",
'{"main":"other"}',
),
file("app/node_modules/fixture/sub/other.js", "root"),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/src/entry.js",
context: "module-specifier",
moduleKind,
files,
}),
).toMatchObject({ resolution_status: "not-found", resolved_path: null });
},
);
});
describe("legacy package main metadata validation and fallback", () => {
@@ -1142,65 +1031,15 @@ describe("legacy package main metadata validation and fallback", () => {
}),
).toMatchObject({ resolution_status: "unavailable", resolved_path: null });
});
it.each(["import", "require"] as const)(
"uses Node's index fallback for a non-string %s package main",
(moduleKind) => {
const files = fileMap([
file("app/src/entry.js", "root"),
file("app/node_modules/fixture/package.json", "root", '{"main":42}'),
file("app/node_modules/fixture/index.js", "root"),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/src/entry.js",
context: "module-specifier",
moduleKind,
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/index.js",
});
},
);
it.each(["import", "require"] as const)(
"does not treat a root-pointing %s package main as a dotfile module",
(moduleKind) => {
const files = fileMap([
file("src/entry.js", "root"),
file("node_modules/fixture/package.json", "root", '{"main":"../.."}'),
file("index.js", "root"),
file(".js", "root"),
file(".json", "root"),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "src/entry.js",
context: "module-specifier",
moduleKind,
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "index.js",
});
},
);
});
describe("CommonJS bare package ancestor lookup", () => {
it.each([
["absent metadata", undefined, true],
["empty metadata", "{}", true],
["empty main", '{"main":""}', true],
["truthy missing main", '{"main":"missing"}', false],
["absent metadata", undefined],
["empty metadata", "{}"],
] as const)(
"handles %s before an ancestor package for both loaders",
(_name, packageJson, commonJsUsesAncestor) => {
(_name, packageJson) => {
const files = fileMap([
file("app/src/entry.js", "root"),
file("app/src/node_modules/fixture/placeholder.js", "root"),
@@ -1215,26 +1054,20 @@ describe("CommonJS bare package ancestor lookup", () => {
]),
file("app/node_modules/fixture/index.js", "root"),
]);
for (const moduleKind of ["import", "require"] as const) {
const resolution = resolve({
declaredPath: "fixture",
sourcePath: "app/src/entry.js",
context: "module-specifier",
moduleKind,
files,
});
if (moduleKind === "require" && commonJsUsesAncestor) {
expect(resolution).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/index.js",
});
} else {
expect(resolution).toMatchObject({
resolution_status: "not-found",
resolved_path: null,
});
}
}
const input = {
declaredPath: "fixture",
sourcePath: "app/src/entry.js",
context: "module-specifier",
files,
} as const;
expect(resolve({ ...input, moduleKind: "require" })).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/index.js",
});
expect(resolve({ ...input, moduleKind: "import" })).toMatchObject({
resolution_status: "not-found",
resolved_path: null,
});
},
);
});
@@ -1404,38 +1237,6 @@ describe("contextual JavaScript artifact path resolution", () => {
});
});
it("applies document and base-href semantics to HTML references", () => {
const files = fileMap([
file("renderer/index.html", "root"),
file("assets/app.js", "root"),
file("renderer/local.js", "root"),
]);
expect(
resolve({
declaredPath: "app.js?v=1",
sourcePath: "renderer/index.html",
context: "html-reference",
htmlBaseHref: "/assets/",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "assets/app.js",
});
expect(
resolve({
declaredPath: "./local.js",
sourcePath: "renderer/index.html",
context: "html-reference",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "renderer/local.js",
});
});
it.each(["node:fs", "electron", "../../escape.js", "%2e%2e/escape.js"])(
"fails closed for unsafe or external module declaration %s",
(declaredPath) => {
@@ -1732,113 +1533,6 @@ describe("contextual JavaScript package path resolution", () => {
});
});
describe("package exports subpath resolution", () => {
it("resolves exact subpath keys through import and require conditions", () => {
const files = fileMap([
file("app/src/consumer.js", "root"),
file(
"app/node_modules/fixture/package.json",
"root",
JSON.stringify({
exports: {
".": "./index.cjs",
"./parser": {
import: "./parser.mjs",
require: "./parser.cjs",
default: "./fallback.js",
},
},
}),
),
file("app/node_modules/fixture/index.cjs", "root"),
file("app/node_modules/fixture/parser.mjs", "root"),
file("app/node_modules/fixture/parser.cjs", "root"),
file("app/node_modules/fixture/fallback.js", "root"),
]);
expect(
resolve({
declaredPath: "fixture/parser",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/parser.mjs",
});
expect(
resolve({
declaredPath: "fixture/parser",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/parser.cjs",
});
});
it("resolves array subpath targets at their first string entry", () => {
const files = fileMap([
file("app/src/consumer.js", "root"),
file(
"app/node_modules/fixture/package.json",
"root",
JSON.stringify({
exports: {
"./parser": [{ import: "./parser.mjs" }, "./parser.cjs"],
},
}),
),
file("app/node_modules/fixture/parser.cjs", "root"),
]);
expect(
resolve({
declaredPath: "fixture/parser",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/parser.cjs",
});
});
it("resolves subpaths of scoped packages", () => {
const files = fileMap([
file("app/src/consumer.js", "root"),
file(
"app/node_modules/@scope/fixture/package.json",
"root",
JSON.stringify({
exports: { "./parser": "./parser.cjs" },
}),
),
file("app/node_modules/@scope/fixture/parser.cjs", "root"),
]);
expect(
resolve({
declaredPath: "@scope/fixture/parser",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/@scope/fixture/parser.cjs",
});
});
});
describe("scoped package directory and specifier resolution", () => {
it("resolves CommonJS bare scoped package directory to index or package main", () => {
const files = fileMap([
@@ -2196,34 +1890,6 @@ describe("package exports subpath encapsulation", () => {
limitations: [expect.stringContaining("explicit null exports target")],
});
});
it("reports a missing selected subpath target without index fallback", () => {
const files = fileMap([
file("app/src/consumer.js", "root"),
file(
"app/node_modules/fixture/package.json",
"root",
JSON.stringify({
exports: { "./parser": "./parser.cjs" },
}),
),
file("app/node_modules/fixture/parser/index.js", "root"),
]);
expect(
resolve({
declaredPath: "fixture/parser",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "not-found",
resolved_path: null,
limitations: [expect.stringContaining("exports targets are exact files")],
});
});
});
describe("package subpath directory ownership", () => {
@@ -2516,61 +2182,9 @@ describe("package exports exact targets", () => {
}
},
);
it("keeps extension and index fallbacks for a legacy main entry", () => {
for (const [main, target] of [
["./file", "app/node_modules/fixture/file.js"],
["./folder", "app/node_modules/fixture/folder/index.js"],
] as const) {
const files = fileMap([
file("app/consumer.js", "root"),
file(
"app/node_modules/fixture/package.json",
"root",
JSON.stringify({ main }),
),
file(target, "root"),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/consumer.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({ resolution_status: "resolved", resolved_path: target });
}
});
});
describe("package import alias resolution", () => {
it.each(["import", "require"] as const)(
"resolves an exact #%s alias from the enclosing package imports map",
(moduleKind) => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./config.cjs" },
}),
"main.js": "",
"config.cjs": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind,
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
declared_path: "#config",
});
},
);
it("resolves an alias from a nested file through the enclosing package root", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
@@ -2616,32 +2230,6 @@ describe("package import alias resolution", () => {
});
});
it("uses a nested package imports map rather than the application root", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./root.cjs" },
}),
"root.cjs": "",
"node_modules/fixture/package.json": JSON.stringify({
imports: { "#config": "./local.cjs" },
}),
"node_modules/fixture/index.js": "",
"node_modules/fixture/local.cjs": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "node_modules/fixture/index.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "node_modules/fixture/local.cjs",
});
});
it("does not inherit an ancestor imports map across a nested package.json", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
@@ -2667,32 +2255,6 @@ describe("package import alias resolution", () => {
);
expect(outcome.limitations.join(" ")).not.toContain("root.cjs");
});
it("does not apply a nested package map to the application root importer", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./root.cjs" },
}),
"main.js": "",
"root.cjs": "",
"node_modules/fixture/package.json": JSON.stringify({
imports: { "#config": "./local.cjs" },
}),
"node_modules/fixture/local.cjs": "",
});
expect(
resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "root.cjs",
});
});
});
describe("package import alias target selection", () => {
@@ -2753,79 +2315,9 @@ describe("package import alias target selection", () => {
resolved_path: "config.cjs",
});
});
it("does not add an extension or index to a selected import target", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./config" },
}),
"main.js": "",
"config.cjs": "",
"config/index.js": "",
});
const outcome = resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(outcome).toMatchObject({
resolution_status: "not-found",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain(
"import targets are exact files",
);
});
});
describe("package import alias refusals", () => {
it("reports a missing exact alias without looking in another package", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": "./config.cjs" },
}),
"main.js": "",
"config.cjs": "",
});
const outcome = resolve({
declaredPath: "#other",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain("#other");
expect(outcome.limitations.join(" ")).toContain("#config");
});
it("reports an explicit null import target as blocked", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
imports: { "#config": null },
}),
"main.js": "",
"config.cjs": "",
});
const outcome = resolve({
declaredPath: "#config",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "require",
files,
});
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain("explicit null");
});
it("leaves wildcard import aliases unresolved", () => {
const files = aliasFiles({
"package.json": JSON.stringify({
@@ -3068,107 +2560,10 @@ describe("directory package entrypoint precedence", () => {
});
});
describe("contextual JavaScript module identity", () => {
it("retains CommonJS and ESM file-base identity during inert extraction", () => {
const analysis = analyzeJavaScriptStaticSource(
`
import { BrowserWindow } from "electron";
import path, { dirname } from "node:path";
import { fileURLToPath } from "node:url";
new BrowserWindow({ webPreferences: {
preload: path.resolve("ignored", __dirname, "preload.cjs")
}});
new BrowserWindow({ webPreferences: {
preload: fileURLToPath(new URL("./preload.mjs", import.meta.url))
}});
new BrowserWindow({ webPreferences: {
preload: path.join(path.dirname(__filename), "legacy-preload.js")
}});
new BrowserWindow({ webPreferences: {
preload: path.posix.resolve("/ignored", dirname(fileURLToPath(import.meta.url)), "esm-preload.js")
}});
new BrowserWindow({ webPreferences: {
preload: path.posix.resolve(__dirname, "/shared", "absolute-preload.js/")
}});
new BrowserWindow({ webPreferences: {
preload: path.posix.resolve(\`/templates\`, "template-preload.js")
}});
new BrowserWindow({ webPreferences: {
preload: new URL("./remote-base.js", location.href)
}});
new BrowserWindow().loadURL("file:///renderer/index.html");
`,
);
expect(analysis.role_paths).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: "preload.cjs",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "./preload.mjs",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "legacy-preload.js",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "esm-preload.js",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "/shared/absolute-preload.js",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "/templates/template-preload.js",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "file:///renderer/index.html",
resolution_context: "module-specifier",
}),
]),
);
expect(analysis.electron.browser_windows).toEqual(
expect.arrayContaining([
expect.objectContaining({
preload_path: "preload.cjs",
preload_resolution_context: "filesystem-expression",
}),
expect.objectContaining({
preload_path: "./preload.mjs",
preload_resolution_context: "filesystem-expression",
}),
expect.objectContaining({
preload_path: "esm-preload.js",
preload_resolution_context: "filesystem-expression",
}),
expect.objectContaining({
preload_path: "/shared/absolute-preload.js",
preload_resolution_context: "filesystem-expression",
}),
expect.objectContaining({
preload_path: "/templates/template-preload.js",
preload_resolution_context: "filesystem-expression",
}),
]),
);
expect(analysis.role_paths).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ path: "./remote-base.js" }),
]),
);
});
});
describe("TypeScript NodeNext emitted-extension resolution", () => {
const container = "container";
it.each([
["./dep.js", "src/dep.ts"],
["./ui/Button.js", "src/ui/Button.tsx"],
["./cfg.mjs", "src/cfg.mts"],
["./legacy.cjs", "src/legacy.cts"],
@@ -3195,44 +2590,6 @@ describe("TypeScript NodeNext emitted-extension resolution", () => {
describe("TypeScript declaration fallback ownership", () => {
const container = "container";
it.each([
["./dep.js", "src/dep.d.ts"],
["./cfg.mjs", "src/cfg.d.mts"],
["./legacy.cjs", "src/legacy.d.cts"],
] as const)(
"retains %s as compile-time evidence without inventing a runtime target",
(specifier, target) => {
const files = fileMap([
file("src/main.ts", container),
file(target, container, "export const value = 1;"),
]);
for (const moduleKind of ["import", "require"] as const) {
expect(
resolve({
declaredPath: specifier,
sourcePath: "src/main.ts",
context: "module-specifier",
moduleKind,
files,
}),
).toMatchObject({
resolution_status: "unavailable",
resolved_path: null,
candidate_path: target,
});
}
expect(
resolve({
declaredPath: "./" + target.slice(4),
sourcePath: "src/main.ts",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "resolved", resolved_path: target });
},
);
it("prefers a present runtime file and keeps the fallback off for JS callers", () => {
const files = fileMap([
file("src/main.ts", container),
@@ -3361,59 +2718,45 @@ describe("url-reference directory and empty-segment semantics", () => {
});
it.each([
["./nested//worker.js", null],
["./nested//../worker.js", "dist/nested/worker.js"],
["./nested//worker.js", null, "dist/nested/worker.js"],
["./nested//../worker.js", "dist/nested/worker.js", "dist/worker.js"],
])(
"keeps empty URL path segments significant: %s",
(declaredPath, resolvedPath) => {
(declaredPath, urlPath, commonJsPath) => {
// A dot segment removes the preceding empty segment, never `nested`.
expect(new URL(declaredPath, "file:///root/dist/app.mjs").pathname).toBe(
resolvedPath === null
? "/root/dist/nested//worker.js"
: `/root/${resolvedPath}`,
);
const input = {
declaredPath,
sourcePath: "dist/app.mjs",
files: fileMap([
file("dist/worker.js", "root"),
file("dist/nested/worker.js", "root"),
]),
};
const urlResolution = {
resolution_status: urlPath === null ? "unavailable" : "resolved",
resolved_path: urlPath,
};
for (const context of ["url-reference", "html-reference"] as const)
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context,
files: fileMap([
file("dist/worker.js", "root"),
file("dist/nested/worker.js", "root"),
]),
}),
context,
).toMatchObject({ resolved_path: resolvedPath });
expect(resolve({ ...input, context }), context).toMatchObject(
urlResolution,
);
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
...input,
context: "module-specifier",
moduleKind: "import",
files: fileMap([
file("dist/worker.js", "root"),
file("dist/nested/worker.js", "root"),
]),
}),
).toMatchObject({ resolved_path: resolvedPath });
).toMatchObject(urlResolution);
// CommonJS keeps filesystem path semantics.
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
...input,
context: "module-specifier",
moduleKind: "require",
files: fileMap([
file("dist/worker.js", "root"),
file("dist/nested/worker.js", "root"),
]),
}),
).toMatchObject({
resolved_path:
declaredPath === "./nested//worker.js"
? "dist/nested/worker.js"
: "dist/worker.js",
resolution_status: "resolved",
resolved_path: commonJsPath,
});
},
);
@@ -3760,31 +3103,6 @@ const aliasFiles = (
);
describe("exact HTML resource resolution", () => {
it.each([
["extension", ["app.js"]],
["directory index", ["app/index.js"]],
["directory package", ["app/package.json", "app/entry.js"]],
] as const)("does not infer a file from %s fallback", (_name, paths) => {
const files = fileMap([
file("index.html", "root"),
...paths.map((path) =>
file(
path,
"root",
path.endsWith("package.json") ? '{"main":"entry.js"}' : "",
),
),
]);
expect(
resolve({
declaredPath: "./app",
sourcePath: "index.html",
context: "html-reference",
files,
}),
).toMatchObject({ resolution_status: "not-found", resolved_path: null });
});
it("prefers an exact extensionless resource and retains URL suffix handling", () => {
const files = fileMap([
file("renderer/index.html", "root"),
@@ -35,22 +35,16 @@ const resolve = (declaredPath: string, htmlBaseHref: string) =>
files,
jsonDocuments,
});
const documentUrl = "https://artifact.test/renderer/index.html";
describe("HTML base href URL components", () => {
it.each(["?base=1", "#base-fragment"])(
"keeps the document pathname for suffix-only base href %s",
(base) => {
const resolvedBase = new URL(base, documentUrl);
expect(new URL("app.js", resolvedBase).pathname).toBe("/renderer/app.js");
expect(resolve("app.js", base)).toMatchObject({
resolved_path: "renderer/app.js",
resolution_status: "resolved",
});
const emptyPathReference = "?script=1#fragment";
expect(new URL(emptyPathReference, resolvedBase).pathname).toBe(
"/renderer/index.html",
);
expect(resolve(emptyPathReference, base)).toMatchObject({
declared_path: emptyPathReference,
resolved_path: "renderer/index.html",
@@ -64,12 +58,6 @@ describe("HTML base href URL components", () => {
"/assets/#/wrong/",
"/assets/index.html?cache=/wrong/",
])("ignores query and fragment path-looking characters in %s", (base) => {
expect(
new URL(
"app.js",
new URL(base, "https://artifact.test/renderer/index.html"),
).pathname,
).toBe("/assets/app.js");
expect(resolve("app.js", base)).toMatchObject({
resolution_status: "resolved",
resolved_path: "assets/app.js",
@@ -93,15 +81,8 @@ describe("HTML base href dot segments", () => {
["a/..", "renderer/app.js"],
["..", "app.js"],
])(
"resolves %s against the document directory like the URL parser",
"resolves %s against the document directory",
(base, expected) => {
// A relative reference resolves against the base URL's directory, which
// drops a trailing "." or ".." segment instead of stepping through it.
expect(
decodeURIComponent(
new URL("app.js", new URL(base, documentUrl)).pathname,
).replace(/^\/+/, ""),
).toBe(expected);
expect(resolve("app.js", base)).toMatchObject({
resolution_status: "resolved",
resolved_path: expected,
@@ -128,10 +109,6 @@ describe("HTML base href dot segments", () => {
});
describe("HTML base href empty segments", () => {
it("lets the script reference remove an empty segment from the base", () => {
// URL resolution keeps the base's empty segment until `..` removes it.
expect(
new URL("../app.js", new URL("./assets//", documentUrl)).pathname,
).toBe("/renderer/assets/app.js");
expect(resolve("../app.js", "./assets//")).toMatchObject({
resolution_status: "resolved",
resolved_path: "renderer/assets/app.js",
@@ -169,10 +146,6 @@ describe("HTML base href path syntax", () => {
});
});
describe("HTML reference URL text", () => {
const urlPath = (declared: string, base: string) =>
decodeURIComponent(
new URL(declared.trim(), new URL(base.trim(), documentUrl)).pathname,
).replace(/^\/+/, "");
it.each([
["%61pp.js", "/assets/", "assets/app.js"],
[" app.js ", "/assets/", "assets/app.js"],
@@ -182,9 +155,8 @@ describe("HTML reference URL text", () => {
["app.js", " /%61ssets/ ", "assets/app.js"],
["/%61ssets/app.js", "", "assets/app.js"],
])(
"resolves %j against base %j like the URL parser",
"resolves %j against base %j",
(declared, base, expected) => {
if (base !== "") expect(urlPath(declared, base)).toBe(expected);
expect(resolve(declared, base)).toMatchObject({
declared_path: declared,
resolution_status: "resolved",
@@ -229,7 +201,7 @@ describe("HTML reference URL text", () => {
});
},
);
it.each(["%2e%2e/app.js", "a%2fapp.js", "%2\nfapp.js", "%2\ne%2\te/app.js"])(
it.each(["%2e%2e/app.js", "a%2fapp.js", "%2\ne%2\te/app.js"])(
"still rejects encoded dot and separator bytes in %j",
(declared) => {
expect(resolve(declared, "")).toMatchObject({
@@ -47,6 +47,8 @@ it("retains only declared package metadata despite inherited host fields", () =>
);
let absent: ReturnType<JavaScriptJsonDocuments["read"]>;
let declared: ReturnType<JavaScriptJsonDocuments["read"]>;
let absentMain: unknown;
let undeclaredModule: unknown;
try {
for (const [key, value] of Object.entries(inherited))
Object.defineProperty(Object.prototype, key, {
@@ -56,6 +58,8 @@ it("retains only declared package metadata despite inherited host fields", () =>
});
absent = documents.read(absentFile);
declared = documents.read(declaredFile);
absentMain = absent.packageFields?.main;
undeclaredModule = declared.packageFields?.module;
} finally {
for (const key of Object.keys(inherited)) {
const descriptor = previous[key];
@@ -64,16 +68,16 @@ it("retains only declared package metadata despite inherited host fields", () =>
else Object.defineProperty(Object.prototype, key, descriptor);
}
}
expect(absent.status).toBe("included");
expect(declared.status).toBe("included");
expect(absent).toMatchObject({ nextDependency: "unproven" });
expect(declared).toMatchObject({ nextDependency: "declared" });
expect(absentMain).toBeUndefined();
expect(undeclaredModule).toBeUndefined();
expect(absent).toMatchObject({ status: "included", nextDependency: "unproven" });
expect(declared).toMatchObject({
status: "included",
nextDependency: "declared",
});
if (absent.packageFields === null || declared.packageFields === null)
throw new Error("Expected package metadata fields");
expect(Object.getPrototypeOf(absent.packageFields)).toBeNull();
expect(Object.getPrototypeOf(declared.packageFields)).toBeNull();
for (const key of Object.keys(inherited))
expect(Object.hasOwn(absent.packageFields, key)).toBe(false);
expect(Object.keys(absent.packageFields)).toEqual([]);
expect(declared.packageFields).toEqual({
name: "source-name",
version: "1.0.0",
@@ -84,13 +88,19 @@ it("retains only declared package metadata despite inherited host fields", () =>
expect(Object.hasOwn(declared.packageFields, "module")).toBe(false);
});
it("reparses changed text and availability on a reused file object", () => {
it("refreshes JSON facts when a reused file changes without rewriting prior evidence", () => {
const documents = new JavaScriptJsonDocuments();
const file = mutableFile();
const original = documents.read(file);
expect(original).toMatchObject({
status: "included",
packageFields: { main: "a.cjs" },
file.path = "nested/package.json";
expect(documents.read(file).source.path).toBe("nested/package.json");
file.container_sha256 = "container-b";
expect(documents.read(file).source.container_sha256).toBe("container-b");
file.sha256 = "file-b";
expect(documents.read(file).source).toEqual({
path: "nested/package.json",
container_sha256: "container-b",
sha256: "file-b",
});
file.text = { included: true, value: "{" };
@@ -109,51 +119,25 @@ it("reparses changed text and availability on a reused file object", () => {
expect(updated).toMatchObject({
status: "included",
packageFields: { main: "b.cjs" },
source: {
path: "nested/package.json",
container_sha256: "container-b",
sha256: "file-b",
},
});
expect(original).toMatchObject({
status: "included",
source: { path: "package.json" },
source: {
path: "package.json",
container_sha256: "container-a",
sha256: "file-a",
},
packageFields: { main: "a.cjs" },
});
expect(invalid.status).toBe("invalid");
expect(unavailable.status).toBe("unavailable");
});
it("rebuilds source provenance when path and content digests change", () => {
const documents = new JavaScriptJsonDocuments();
const file = mutableFile();
const original = documents.read(file);
file.path = "nested/package.json";
const moved = documents.read(file);
expect(moved.source.path).toBe("nested/package.json");
file.container_sha256 = "container-b";
const recontained = documents.read(file);
expect(recontained.source).toMatchObject({
path: "nested/package.json",
container_sha256: "container-b",
sha256: "file-a",
});
file.sha256 = "file-b";
const rehashed = documents.read(file);
expect(rehashed.source).toMatchObject({
path: "nested/package.json",
container_sha256: "container-b",
sha256: "file-b",
});
expect(original.source).toEqual({
path: "package.json",
container_sha256: "container-a",
sha256: "file-a",
});
expect(original).toMatchObject({
status: "included",
packageFields: { main: "a.cjs" },
});
});
it("retains only syntax and keys for ordinary JSON, with package fields scoped to its format", () => {
const documents = new JavaScriptJsonDocuments();
const file = mutableFile();
@@ -1,9 +1,6 @@
import { expect, it } from "vitest";
import {
HTML_INLINE_SCRIPT_LOCATION_LIMIT,
htmlArtifactReferences,
} from "./htmlArtifactReferences.js";
import { htmlArtifactReferences } from "./htmlArtifactReferences.js";
it.each([
['<script data-src="decoy.js"></script>', []],
@@ -30,13 +27,6 @@ it.each([
'<svg><foreignObject><script src="actual.js"></script></foreignObject></svg>',
["actual.js"],
],
['<script type="application/json" src="actual.js"></script>', ["actual.js"]],
['<script type="importmap" src="actual.js"></script>', ["actual.js"]],
['<script type="speculationrules" src="actual.js"></script>', ["actual.js"]],
['<script language="vbscript" src="actual.js"></script>', ["actual.js"]],
['<script type=" Text/JavaScript " src="actual.js"></script>', ["actual.js"]],
['<script type="MODULE" src="actual.js"></script>', ["actual.js"]],
['<script type=" module " src="actual.js"></script>', ["actual.js"]],
])("extracts document references from %s", (text, expected) => {
expect(
htmlArtifactReferences(text).scripts.map(({ scriptPath }) => scriptPath),
@@ -153,26 +143,20 @@ it.each([
expect(result.inlineScriptCount).toBe(0);
});
it("shares precise body coordinates and location limits across HTML and SVG", () => {
it("retains exact SVG body coordinates and skips SVG inside templates", () => {
const prefix = '<!doctype html>\n<svg><script src="ignored.js">';
const body = "\nrun();\n";
expect(
htmlArtifactReferences(`${prefix}${body}</script></svg>`).inlineScripts,
).toEqual([
const result = htmlArtifactReferences(
`${prefix}${body}</script></svg><template><svg><script>x</script></svg></template>`,
);
expect(result.inlineScriptCount).toBe(1);
expect(result.inlineScripts).toEqual([
{
scriptType: "classic",
text: body,
location: { start: { line: 2, column: 30 }, end: { line: 4, column: 0 } },
},
]);
const repeated = "<script>x</script><svg><script>y</script></svg>".repeat(60);
const result = htmlArtifactReferences(repeated);
expect(result.inlineScriptCount).toBe(120);
expect(result.inlineScripts).toHaveLength(HTML_INLINE_SCRIPT_LOCATION_LIMIT);
expect(
htmlArtifactReferences("<template><svg><script>x</script></svg></template>")
.inlineScriptCount,
).toBe(0);
});
it("retains exact inline script body coordinates, including unclosed scripts", () => {
@@ -196,23 +180,6 @@ it("retains exact inline script body coordinates, including unclosed scripts", (
]);
});
it("counts every inline body but retains bounded locations", () => {
const count = 150_000;
const text = "<script>x</script>".repeat(count);
const { inlineScripts, inlineScriptCount } = htmlArtifactReferences(text);
expect(inlineScriptCount).toBe(count);
expect(inlineScripts).toHaveLength(HTML_INLINE_SCRIPT_LOCATION_LIMIT);
const column = 18 * (HTML_INLINE_SCRIPT_LOCATION_LIMIT - 1) + 8;
expect(inlineScripts.at(-1)).toEqual({
scriptType: "classic",
location: {
start: { line: 1, column },
end: { line: 1, column: column + 1 },
},
text: "x",
});
});
it.each([
['type=" Text/JavaScript "', "classic"],
['type="MODULE"', "module"],
@@ -1,10 +1,10 @@
import { posix } from "node:path";
import { fileURLToPath } from "node:url";
import { parseExpression } from "@babel/parser";
import { describe, expect, it } from "vitest";
import { analyzeCommonJsStaticFixture } from "../../../tests/fixtures/javascriptCommonJsAnalysis.js";
import type { JavaScriptStaticPathContext } from "./javascriptStaticAnalysisTypes.js";
it.each([
['path.join(__dirname, "page.html")', "page.html", "source-directory"],
@@ -49,13 +49,6 @@ it.each(["loadFile", "loadURL"])(
);
},
);
import { parserPluginsForPath } from "./javascriptSourceParser.js";
import {
calleeName,
staticPath,
staticPathResolutionContext,
} from "./javascriptStaticAnalysisHelpers.js";
import type { JavaScriptStaticPathContext } from "./javascriptStaticAnalysisTypes.js";
const absoluteParts = [
["/app", "/shared/preload.js"],
@@ -136,6 +129,17 @@ const unknownExpressions = [
'path.join(__dirname, new URL("./pre%2Fload.js", import.meta.url))',
'path.resolve(__dirname, new URL("./", import.meta.url), "preload.js")',
'path.resolve("/app", new URL("./", import.meta.url), "preload.js")',
'new URL("./remote-base.js", location.href)',
"path.join()",
'path.join("/app", runtimeFile)',
"path.join(...parts)",
'fileURLToPath("file:///app/%2Fpreload.js")',
'fileURLToPath("file:///app/%5Cpreload.js")',
'fileURLToPath("file:///app/%")',
'fileURLToPath("file:///C:/app/preload.js")',
'fileURLToPath("file://remote/share/preload.js")',
'fileURLToPath("file:///app/preload.js", options)',
"fileURLToPath(selectedUrl)",
];
const pathValueExpressions = [
@@ -304,7 +308,6 @@ describe("inert JavaScript path resolution", () => {
});
it.each(unknownExpressions)("keeps unsupported %s unknown", (expression) => {
expect(staticPath(parsePathExpression(expression))).toBeUndefined();
const { analysis, windowExpression, utilityExpression } =
analyzePathConsumers(expression);
expect(analysis.parse_status).toBe("partial");
@@ -365,14 +368,6 @@ describe("inert JavaScript path resolution", () => {
}),
]);
});
it.each([
"path.join()",
'path.join("/app", runtimeFile)',
"path.join(...parts)",
])("preserves unresolved join syntax in %s", (expression) =>
expect(staticPath(parsePathExpression(expression))).toBeUndefined(),
);
});
it.each([
@@ -417,24 +412,6 @@ it("retains Worker URL references through their separate URL-aware producer", ()
expect(analysis.role_paths).toEqual([]);
});
it.each([
'fileURLToPath("file:///app/%2Fpreload.js")',
'fileURLToPath("file:///app/%5Cpreload.js")',
'fileURLToPath("file:///app/%")',
'fileURLToPath("file:///C:/app/preload.js")',
'fileURLToPath("file://remote/share/preload.js")',
'fileURLToPath("file:///app/preload.js", options)',
"fileURLToPath(selectedUrl)",
])("leaves platform-dependent or invalid %s unknown", (expression) =>
expect(staticPath(parsePathExpression(expression))).toBeUndefined(),
);
const parsePathExpression = (expression: string) =>
parseExpression(expression, {
sourceType: "module",
plugins: parserPluginsForPath("preload.ts"),
});
const analyzePathConsumers = (expression: string) => {
const property = `preload: ${expression}`;
const genericPrefix =
@@ -443,9 +420,6 @@ const analyzePathConsumers = (expression: string) => {
const windowExpression = `${windowPrefix}${property} } })`;
const utilityExpression = `utilityProcess.fork(${expression})`;
return {
property,
genericPrefix,
windowPrefix,
windowExpression,
utilityExpression,
analysis: analyzeCommonJsStaticFixture(
@@ -459,36 +433,6 @@ const assertPathProjection = (
path: string,
context: JavaScriptStaticPathContext,
) => {
const node = parsePathExpression(expression);
// This syntax matrix supplies identity explicitly; full-source cases prove it.
const pathIntrinsics = (
callee: import("@babel/types").Node,
fact?:
| "resolve"
| "join"
| "file-url-to-path"
| "source-url"
| "source-directory",
) => {
if (fact === "source-directory") {
const name = calleeName(
callee.type === "CallExpression" ? callee.callee : callee,
);
return (
name === "__dirname" || name === "dirname" || name.endsWith(".dirname")
);
}
if (fact === "source-url") return true;
const name = calleeName(callee);
if (fact === "file-url-to-path") return name.endsWith("fileURLToPath");
return (
(name === (fact ?? "resolve") ||
name.endsWith(`.${fact ?? "resolve"}`)) &&
!name.includes("win32")
);
};
expect(staticPath(node, pathIntrinsics)).toBe(path);
expect(staticPathResolutionContext(node, pathIntrinsics)).toBe(context);
const { analysis, windowExpression, utilityExpression } =
analyzePathConsumers(expression);
expect(analysis.parse_status).toBe("complete");
@@ -4,29 +4,24 @@ import { expect, it } from "vitest";
import { analyzeCommonJsStaticFixture } from "../../../tests/fixtures/javascriptCommonJsAnalysis.js";
it.each(["/other", "relative"])(
"keeps a shadowed source-directory parameter dynamic: %s",
(directory) => {
const actual = posix.resolve("/runtime/base", directory, "decoy.cjs");
expect(actual).not.toBe("/source/app/decoy.cjs");
const analysis = analyzeCommonJsStaticFixture(`
const path = require('node:path');
const {BrowserWindow, utilityProcess} = require('electron');
function build(__dirname) {
new BrowserWindow({webPreferences:{preload:path.resolve(runtimeBase,__dirname,'decoy.cjs')}});
utilityProcess.fork(path.resolve(runtimeBase,__dirname,'decoy.cjs'));
}
build(${JSON.stringify(directory)});
`);
expect(analysis.role_paths).toEqual([]);
expect(analysis.electron.browser_windows).toMatchObject([
{ preload_path: null, preload_resolution_context: null },
]);
expect(analysis.electron.utility_processes).toMatchObject([
{ module_path: null, module_resolution_context: null },
]);
},
);
it("keeps a shadowed source-directory parameter dynamic", () => {
const analysis = analyzeCommonJsStaticFixture(`
const path = require('node:path');
const {BrowserWindow, utilityProcess} = require('electron');
function build(__dirname) {
new BrowserWindow({webPreferences:{preload:path.resolve(runtimeBase,__dirname,'decoy.cjs')}});
utilityProcess.fork(path.resolve(runtimeBase,__dirname,'decoy.cjs'));
}
build("/other");
`);
expect(analysis.role_paths).toEqual([]);
expect(analysis.electron.browser_windows).toMatchObject([
{ preload_path: null, preload_resolution_context: null },
]);
expect(analysis.electron.utility_processes).toMatchObject([
{ module_path: null, module_resolution_context: null },
]);
});
const localResolvers = [
[
@@ -123,9 +118,6 @@ const nodeResolvers = [
] as const;
it("does not treat a constructed Node resolver as a path call", () => {
expect(() => Reflect.construct(posix.resolve, ["/app", "decoy.cjs"])).toThrow(
TypeError,
);
const analysis = analyzeCommonJsStaticFixture(`
const helper = require('node:path');
const {BrowserWindow} = require('electron');
@@ -140,9 +132,6 @@ it("does not treat a constructed Node resolver as a path call", () => {
it.each(nodeResolvers)(
"retains proven Node %s right-to-left anchoring",
(_name, setup, callee) => {
expect(
posix.resolve("/actual/runtime.cjs", "/fixture/app", "decoy.cjs"),
).toBe("/fixture/app/decoy.cjs");
const expression = `${callee}(runtimePath, __dirname, "decoy.cjs")`;
const analysis = analyzeCommonJsStaticFixture(`
const {BrowserWindow, utilityProcess} = require('electron');
@@ -1,6 +1,4 @@
import { createRequire, wrap } from "node:module";
import { posix } from "node:path";
import { fileURLToPath } from "node:url";
import { runInThisContext } from "node:vm";
import { expect, it } from "vitest";
@@ -26,68 +24,38 @@ it.each([false, true])(
assigned ? "relative/preload.cjs" : "/source/app/preload.cjs",
);
const analysis = analyzeCommonJsStaticFixture(
`${setup}const{BrowserWindow}=require('electron');new BrowserWindow({webPreferences:{preload:path.join(__dirname,'preload.cjs')}});`,
`${setup}
const {BrowserWindow, utilityProcess} = require('electron');
new BrowserWindow({webPreferences:{preload:path.join(__dirname,'preload.cjs')}});
utilityProcess.fork(path.join(__dirname,'worker.cjs'));`,
);
expect(analysis.electron.browser_windows).toMatchObject([
{ preload_path: assigned ? null : "preload.cjs" },
]);
expect(analysis.electron.utility_processes).toMatchObject([
{ module_path: assigned ? null : "worker.cjs" },
]);
},
);
it("keeps local dirname methods from proving a source anchor", () => {
const helper = { dirname: (_url: string) => "/other" };
expect(
posix.resolve(
"/runtime/base",
helper.dirname("file:///source/app/main.mjs"),
"decoy.cjs",
),
).toBe("/other/decoy.cjs");
const analysis = analyzeCommonJsStaticFixture(
`import path from 'node:path';const helper={dirname:()=>'/other'};const{BrowserWindow}=require('electron');new BrowserWindow({webPreferences:{preload:path.resolve(runtimeBase,helper.dirname(import.meta.url),'decoy.cjs')}});`,
);
expect(analysis.electron.browser_windows).toMatchObject([
{ preload_path: null },
]);
});
it("retains a proven Node dirname of the decoded module URL", () => {
expect(
posix.dirname(
fileURLToPath("file:///source/app/main.mjs", { windows: false }),
),
).toBe("/source/app");
const analysis = analyzeCommonJsStaticFixture(
`import path from 'node:path';import{fileURLToPath}from'node:url';const{BrowserWindow}=require('electron');new BrowserWindow({webPreferences:{preload:path.resolve(runtimeBase,path.dirname(fileURLToPath(import.meta.url)),'preload.cjs')}});`,
);
expect(analysis.electron.browser_windows).toMatchObject([
{ preload_path: "preload.cjs" },
]);
});
it.each([false, true])(
"preserves a decoded module URL through its real dirname owner: local=%s",
(local) => {
const decoded = fileURLToPath("file:///source/app/main.mjs", {
windows: false,
});
const helper = { dirname: (_file: string) => "/other" };
expect(local ? helper.dirname(decoded) : posix.dirname(decoded)).toBe(
local ? "/other" : "/source/app",
);
const analysis = analyzeCommonJsStaticFixture(`
import path from 'node:path';import*as url from 'node:url';
const helper={dirname:()=>'/other'};const{BrowserWindow}=require('electron');
new BrowserWindow({webPreferences:{preload:path.resolve(runtimeBase,${local ? "helper" : "path"}.dirname(url.fileURLToPath(import.meta.url)),'preload.cjs')}});
`);
expect(analysis.electron.browser_windows).toMatchObject([
{ preload_path: local ? null : "preload.cjs" },
{
preload_path: local ? null : "preload.cjs",
preload_resolution_context: local ? null : "filesystem-expression",
},
]);
},
);
it("does not use a URL string as a filesystem source-file anchor", () => {
expect(posix.dirname("file:///source/app/main.mjs")).not.toBe("/source/app");
const analysis = analyzeCommonJsStaticFixture(
`import path from 'node:path';const{BrowserWindow}=require('electron');new BrowserWindow({webPreferences:{preload:path.resolve(runtimeBase,path.dirname(import.meta.url),'decoy.cjs')}});`,
);
@@ -107,15 +75,3 @@ it.each([false, true])(
]);
},
);
it.each([false, true])(
"preserves the utility-process dirname parameter until assigned: assigned=%s",
(assigned) => {
const analysis = analyzeCommonJsStaticFixture(
`var __dirname;${assigned ? "__dirname='relative';" : ""}const path=require('node:path');const{utilityProcess}=require('electron');utilityProcess.fork(path.join(__dirname,'worker.cjs'));`,
);
expect(analysis.electron.utility_processes).toMatchObject([
{ module_path: assigned ? null : "worker.cjs" },
]);
},
);
@@ -46,6 +46,17 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
script: "app.js#route=%2Ffoo",
resolved: "assets/app.js",
},
{
source: "views/root-base.html",
base: "/assets/",
script: "app.js?v=1",
resolved: "assets/app.js",
},
{
source: "views/document-relative.html",
script: "./app.js?v=1",
resolved: "views/app.js",
},
{
source: "base-self.html",
base: "assets/app.js?redirect=%5Croot",
@@ -89,6 +100,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
),
"app.js": "globalThis.rootApp = true;",
"assets/app.js": "globalThis.nestedApp = true;",
"views/app.js": "globalThis.viewApp = true;",
});
const result = await analyzeJavaScriptDirectory(surface, cli, root);
@@ -10,6 +10,12 @@ import {
} from "../../support/cli/javascriptApplication.js";
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
const declarationFallbacks = [
["./dep.js", "dep.d.ts"],
["./cfg.mjs", "cfg.d.mts"],
["./legacy.cjs", "legacy.d.cts"],
] as const;
cliTest.for(["CLI", "stdio MCP"] as const)(
"preserves module classification and explicit source identities through %s",
async (surface, { cli }) => {
@@ -55,11 +61,15 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
]
.map((specifier) => `require(${JSON.stringify(specifier)});`)
.join("\n"),
"fallback.cts": 'require("./only.js");',
"fallback.cts": declarationFallbacks
.map(([specifier]) => `require(${JSON.stringify(specifier)});`)
.join("\n"),
"fallback.mts": declarationFallbacks
.map(([specifier]) => `import ${JSON.stringify(specifier)};`)
.join("\n"),
"dep.d.ts": "export declare const value: number;",
"cfg.d.mts": "export declare const value: number;",
"legacy.d.cts": "export declare const value: number;",
"only.d.ts": "export declare const value: number;",
"dep.mjs": 'throw new Error("must never load");',
"local.file.mjs": 'throw new Error("must never load");',
"node_modules/dep.mjs": 'throw new Error("must never load");',
@@ -125,17 +135,26 @@ console.log(JSON.stringify({
for (const edge of matches)
expect(edge.properties.resolved_path).toBeNull();
}
for (const suffix of ["dep.d.ts", "cfg.d.mts", "legacy.d.cts"]) {
const matches = edges(`./${suffix}`);
expect(matches.length, suffix).toBeGreaterThan(0);
for (const [specifier, declaration] of declarationFallbacks) {
const matches = edges(`./${declaration}`);
expect(matches.length, declaration).toBeGreaterThan(0);
for (const edge of matches)
expect(edge.properties).toMatchObject({
resolution_status: "resolved",
resolved_path: suffix,
resolved_path: declaration,
});
const fallbacks = edges(specifier).map(({ properties }) => properties);
for (const moduleKind of ["import", "require"])
expect(fallbacks, specifier).toContainEqual(
expect.objectContaining({
module_link_kind: moduleKind,
resolution_status: "unavailable",
resolved_path: null,
candidate_path: declaration,
}),
);
}
for (const [specifier, status] of [
["./only.js", "unavailable"],
["./absent.mjs", "not-found"],
["mapped/missing", "not-found"],
["mapped/invalid", "rejected"],
@@ -84,39 +84,31 @@ cliTest(
},
);
cliTest.for([
"invalid-html",
"empty-html",
"reference-html",
"invalid-json",
] as const)(
"retains applicable unavailable HTML reference scope through CLI for %s",
async (testCase, { cli }) => {
cliTest(
"reports unavailable HTML without inventing script loads",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-unavailable-html-");
const reference = '<script src="main.js"></script>';
const html =
testCase === "invalid-html"
? Buffer.concat([Buffer.from(reference), Buffer.from([0xff])])
: testCase === "reference-html"
? reference
: "<html></html>";
await writeFile(
join(root, "package.json"),
'{"name":"html-scope","main":"main.js"}',
);
await writeFile(join(root, "main.js"), "module.exports = 42;");
await writeFile(join(root, "index.html"), html);
await writeFile(
join(root, "data.json"),
testCase === "invalid-json" ? Buffer.from([0xff]) : "{}",
const files = {
"package.json": '{"name":"html-scope","main":"main.js"}',
"main.js": "module.exports = 42;",
"invalid.html": Buffer.concat([
Buffer.from(reference),
Buffer.from([0xff]),
]),
"empty.html": "<html></html>",
"reference.html": reference,
};
await Promise.all(
Object.entries(files).map(([path, content]) =>
writeFile(join(root, path), content),
),
);
const response = await cli.run({
arguments: [
"analyze-javascript-application",
root,
...["package.json", "main.js", "index.html", "data.json"].flatMap(
(path) => ["--source-path", path],
),
...Object.keys(files).flatMap((path) => ["--source-path", path]),
"--format",
"json",
],
@@ -127,36 +119,43 @@ cliTest.for([
);
const scopes = result.graph.nodes
.filter(({ kind }) => kind === "unknown")
.flatMap(({ observations }) => observations);
const htmlScopes = scopes.filter(
({ properties }) =>
properties.path === "index.html" &&
properties.operation === "parse-html-script-references",
);
expect(htmlScopes).toHaveLength(testCase === "invalid-html" ? 1 : 0);
if (testCase === "invalid-html") {
expect(htmlScopes[0]?.evidence).toMatchObject({
authority: "artifact-bytes",
state: "unavailable",
});
expect(htmlScopes[0]?.properties.limitation).toContain("invalid-utf8");
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: false,
});
}
expect(
scopes.filter(
.flatMap(({ observations }) => observations)
.filter(
({ properties }) =>
properties.path === "data.json" &&
properties.operation === "parse-json-module",
),
).toHaveLength(testCase === "invalid-json" ? 1 : 0);
expect(
result.graph.edges.filter(
({ relation, properties }) =>
relation === "loads" && properties.script_path !== undefined,
),
).toHaveLength(testCase === "reference-html" ? 1 : 0);
properties.operation === "parse-html-script-references",
);
expect(scopes).toMatchObject([
{
properties: {
path: "invalid.html",
limitation: expect.stringContaining("invalid-utf8"),
},
evidence: { authority: "artifact-bytes", state: "unavailable" },
},
]);
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: false,
});
const loads = result.graph.edges.filter(
({ relation, properties }) =>
relation === "loads" && properties.script_path !== undefined,
);
expect(loads).toMatchObject([
{
properties: {
script_path: "main.js",
resolved_path: "main.js",
resolution_status: "resolved",
},
evidence: {
location: {
available: true,
value: { kind: "source-range", source: "reference.html" },
},
},
},
]);
},
);
@@ -31,8 +31,22 @@ const fallbackAliases = {
require: ["file:///outside.cjs", "./config.cjs"],
},
};
const resolvedAliases = [...literalAliases, ...Object.keys(fallbackAliases)];
const resolvedAliases = [
"#config",
...literalAliases,
...Object.keys(fallbackAliases),
];
const refusedAliases = {
"#blocked": {
target: null,
status: "external",
limitation: "an explicit null imports target",
},
"#exact-file": {
target: "./extensionless",
status: "not-found",
limitation: "import targets are exact files",
},
"#empty": {
target: [],
status: "external",
@@ -86,7 +100,6 @@ const allAliases = [...resolvedAliases, ...Object.keys(refusedAliases)];
const createPackageImportAliasFixture = async () => {
const root = await createTestTempDirectory("rea-package-import-aliases-");
const mainSource = [
'const config = require("#config");',
'const nested = require("./node_modules/fixture/index.cjs");',
'const missing = require("#missing");',
...allAliases.map((specifier) => `require(${JSON.stringify(specifier)});`),
@@ -118,6 +131,8 @@ const createPackageImportAliasFixture = async () => {
"main.cjs": mainSource,
"main.mjs": moduleSource,
"config.cjs": "module.exports = 'app-config';",
"extensionless.js": "module.exports = 'extension decoy';",
"extensionless/index.js": "module.exports = 'index decoy';",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
imports: { "#config": "./local.cjs" },
@@ -200,16 +215,6 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
),
}),
);
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
specifier: "#config",
resolved_path: "config.cjs",
resolution_status: "resolved",
}),
evidence: sourceEvidence("main.cjs", mainSource),
}),
);
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
@@ -232,7 +237,8 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
}),
evidence: expect.objectContaining({
limitations: expect.arrayContaining([
expect.stringContaining("does not define package import alias"),
expect.stringContaining("does not define package import alias #missing"),
expect.stringContaining("#config"),
]),
}),
}),
@@ -12,11 +12,11 @@ const cases = [
{ name: "null-main", metadata: { main: null } },
{ name: "false-main", metadata: { main: false } },
{ name: "zero-main", metadata: { main: 0 } },
{ name: "numeric-main", metadata: { main: 42 } },
{ name: "true-main", metadata: { main: true } },
{ name: "object-main", metadata: { main: {} } },
{ name: "empty-main", metadata: { main: "" } },
{ name: "missing-main", metadata: {} },
{ name: "string-main", metadata: { main: "./index.js" } },
] as const;
cliTest.for(["CLI", "stdio MCP"] as const)(
@@ -145,6 +145,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
.join("\n"),
"local.js": 'module.exports = "local.js";',
"local/index.js": 'module.exports = "local/index.js";',
"local-control.cjs": 'console.log(JSON.stringify(require("./local/")));',
};
for (const item of packages) {
files[`node_modules/${item.name}/package.json`] = JSON.stringify({
@@ -167,8 +168,6 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
"console.log(JSON.stringify(results));",
].join("\n");
}
files["local-control.cjs"] =
'console.log(JSON.stringify(require("./local/")));';
await writeFixtureFiles(root, files);
for (const kind of ["require", "import"] as const) {
const control = await runNodeJsonControl(
@@ -188,31 +187,33 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
),
);
}
expect(await runNodeJsonControl(root, "local-control.cjs")).toBe(
"local/index.js",
);
const local = await runNodeJsonControl(root, "local-control.cjs");
expect(local).toBe("local/index.js");
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
const relationships = graph.edges
.filter(({ relation }) => relation === "imports")
.map(({ properties }) => properties);
for (const kind of ["require", "import"] as const)
for (const item of packages)
for (const item of packages) {
const path = item[kind];
const rejectedDirectory = kind === "import" && "importError" in item;
expect(relationships).toContainEqual(
expect.objectContaining({
module_link_kind: kind,
specifier: item.name,
resolved_path:
item[kind] === null
? null
: `node_modules/${item.name}/${item[kind]}`,
resolution_status:
item[kind] === null
? "importError" in item
? "rejected"
: "not-found"
path === null ? null : `node_modules/${item.name}/${path}`,
resolution_status: rejectedDirectory
? "rejected"
: path === null
? "not-found"
: "resolved",
...(rejectedDirectory && {
candidate_path: `node_modules/${item.name}/lib/.js`,
}),
}),
);
}
expect(relationships).toContainEqual(
expect.objectContaining({
module_link_kind: "require",
@@ -25,6 +25,7 @@ const createPackageSubpathFixture = async () => {
'const file = require("fixture");',
'const packageDirectory = require("fixture/");',
'const selected = require("@scope/selected");',
'const scopedParser = require("@scope/selected/parser");',
'const blocked = require("blocked");',
'const literal = require("fi%xture");',
'const scalar = require("scalar");',
@@ -36,6 +37,7 @@ const createPackageSubpathFixture = async () => {
const importSource = [
'import literal from "fi%xture";',
'import uri from "FILE:///src/uri-dep.cjs?token=%2F#entry";',
'import parser from "@scope/selected/parser";',
].join("\n");
const files = {
"src/main.cjs": source,
@@ -58,7 +60,7 @@ const createPackageSubpathFixture = async () => {
exports: {
"./parser": "./parser.cjs",
"./parser/": "./parser.cjs",
"./missing": "./missing.cjs",
"./missing": "./missing",
},
}),
"node_modules/exported/parser.cjs": "module.exports = 6;",
@@ -66,9 +68,14 @@ const createPackageSubpathFixture = async () => {
"node_modules/exported/missing/index.js": "module.exports = 8;",
"node_modules/@scope/selected.js": "module.exports = 'sibling';",
"node_modules/@scope/selected/package.json": JSON.stringify({
exports: { require: "./actual.cjs" },
exports: {
".": { require: "./actual.cjs" },
"./parser": [{ import: "./parser.mjs" }, "./parser.cjs"],
},
}),
"node_modules/@scope/selected/actual.cjs": "module.exports = 'export';",
"node_modules/@scope/selected/parser.cjs": "module.exports = 'cjs parser';",
"node_modules/@scope/selected/parser.mjs": "export default 'esm parser';",
"node_modules/blocked.js": "module.exports = 'sibling';",
"node_modules/blocked/package.json": JSON.stringify({
exports: { ".": null },
@@ -102,6 +109,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
"nested/parser": "node_modules/nested/parser/entry.js",
"exported/parser": "node_modules/exported/parser.cjs",
"@scope/selected": "node_modules/@scope/selected/actual.cjs",
"@scope/selected/parser": "node_modules/@scope/selected/parser.cjs",
"fi%xture": "node_modules/fi%xture.js",
scalar: "node_modules/scalar.js",
"../node_modules/fi%xture/run.cjs": "node_modules/fi%xture/run.cjs",
@@ -111,7 +119,6 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
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,
@@ -136,12 +143,6 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
expect(graph.coverage.status).toBe("complete");
const requireFileUrl = graph.edges.find(
({ properties }) =>
properties.module_link_kind === "require" &&
properties.specifier === "file:///src/uri-dep.cjs",
);
expect(requireFileUrl?.evidence.limitations.length).toBeGreaterThan(0);
const imports = graph.edges.filter(
({ properties }) => properties.module_link_kind === "require",
);
@@ -154,41 +155,19 @@ 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: null,
resolution_status: "unavailable",
}),
evidence: sourceEvidence("src/imports.mjs", importSource),
}),
expectResolvedImports(
graph.edges.filter(
({ properties }) => properties.module_link_kind === "import",
),
{
sourcePath: "src/imports.mjs",
source: importSource,
targets: {
"@scope/selected/parser": "node_modules/@scope/selected/parser.mjs",
},
},
);
expectFileUrlImports(graph.edges, source, importSource);
expect(graph.edges).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
@@ -200,10 +179,10 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
evidence: sourceEvidence("src/imports.mjs", importSource),
}),
);
for (const [specifier, status] of [
for (const [specifier, status, limitation] of [
["exported/parser/", "external"],
["exported/hidden", "external"],
["exported/missing", "not-found"],
["exported/missing", "not-found", "exports targets are exact files"],
["blocked", "external"],
])
expect(imports).toContainEqual(
@@ -213,6 +192,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
resolved_path: null,
resolution_status: status,
}),
evidence: sourceEvidence("src/main.cjs", source, limitation),
}),
);
const preloads = graph.nodes.filter(
@@ -240,6 +220,54 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
},
);
const expectFileUrlImports = (
edges: z.infer<
typeof javascriptApplicationAnalysisResultSchema
>["graph"]["edges"],
source: string,
importSource: string,
): void => {
expect(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,
"CommonJS require specifiers do not resolve file URLs",
),
}),
);
expect(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(edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: "import",
specifier: "FILE:///src/uri-dep.cjs?token=%2F#entry",
resolved_path: null,
resolution_status: "unavailable",
}),
evidence: sourceEvidence("src/imports.mjs", importSource),
}),
);
};
const expectResolvedImports = (
imports: z.infer<
typeof javascriptApplicationAnalysisResultSchema
@@ -263,7 +291,11 @@ const expectResolvedImports = (
);
};
const sourceEvidence = (sourcePath: string, source: string): unknown =>
const sourceEvidence = (
sourcePath: string,
source: string,
limitation?: string,
): unknown =>
expect.objectContaining({
artifact: expect.objectContaining({
available: true,
@@ -276,4 +308,11 @@ const sourceEvidence = (sourcePath: string, source: string): unknown =>
source: sourcePath,
}),
}),
...(limitation === undefined
? {}
: {
limitations: expect.arrayContaining([
expect.stringContaining(limitation),
]),
}),
});
@@ -433,6 +433,7 @@ const expectSuffixOnlyRenderersUnresolved = (graph: ApplicationGraph): void => {
expect(
renderers.get("file:///renderer/index.html")?.observations[0]?.properties,
).toMatchObject({
resolution_context: "module-specifier",
resolved_path: "renderer/index.html",
resolution_status: "resolved",
});
@@ -5,7 +5,6 @@ import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
import { analyzeArtifactFiles } from "../../../fixtures/javascriptArtifactAnalysis.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
it("does not infer renderer loads from external data blocks or import maps", async () => {
@@ -44,35 +43,4 @@ it("does not infer renderer loads from external data blocks or import maps", asy
.map(({ properties }) => properties.script_path)
.sort(),
).toEqual(["classic.js", "module.js"]);
const sources = await analyzeArtifactFiles({
files: [
{
path: "index.html",
container_sha256: "a".repeat(64),
sha256: "b".repeat(64),
bytes: Buffer.byteLength(html),
inventory_artifact_id: "html_fixture",
kind: "html",
unpacked: false,
text: { included: true, value: html },
},
],
unavailable_relevant_files: [],
containers: [],
text_bytes_read: Buffer.byteLength(html),
invalid_utf8_files: 0,
});
expect(
sources.analysis.html_scripts.map(({ script_path, script_type }) => [
script_path,
script_type,
]),
).toEqual([
["classic.js", "classic"],
["module.js", "module"],
["data.js", null],
["imports.js", null],
["rules.js", null],
["unsupported.js", null],
]);
});
@@ -159,6 +159,19 @@ it("distinguishes unavailable and unselected JSON while preserving unknown key c
json_parse_status: "unavailable",
omitted_json_top_level_keys: null,
});
const scopes = graph.nodes
.filter(({ kind }) => kind === "unknown")
.flatMap(({ observations }) => observations)
.filter(({ properties }) => properties.path === unavailable);
expect(scopes).toMatchObject([
{
properties: {
operation: "parse-json-module",
limitation: expect.stringContaining("invalid-utf8"),
},
evidence: { authority: "artifact-bytes", state: "unavailable" },
},
]);
for (const path of unselected)
expect(
observations.find(
@@ -2,55 +2,16 @@ import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
defaultTreeAdapter,
parse,
type DefaultTreeAdapterTypes,
} from "parse5";
import { expect, it } from "vitest";
import { reconstructJavaScriptArtifact } from "../../support/javascriptApplicationScope.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const cases = [
['<script data-src="decoy.js"></script>', []],
['<script x:src="decoy.js"></script>', []],
[`<script title='src="decoy.js"'></script>`, []],
["<script src=actual.js></script>", ["actual.js"]],
['<script title=">" src="actual.js"></script>', ["actual.js"]],
['<script src="actual.js"></script>', ["actual.js"]],
["<script src='actual.js'></script>", ["actual.js"]],
['<script data-src="decoy.js" src="actual.js"></script>', ["actual.js"]],
['<!-- <script src="decoy.js"></script> -->', []],
['<textarea><script src="decoy.js"></script></textarea>', []],
['<template><script src="decoy.js"></script></template>', []],
['<script src="actual&#46;js" src="decoy.js"></script>', ["actual.js"]],
] as const;
it.each(cases)(
"projects local loads from actual HTML attributes in %s",
async (html, expected) => {
const root = await createTestTempDirectory("rea-html-entrypoints-");
await Promise.all([
writeFile(join(root, "index.html"), html),
writeFile(join(root, "actual.js"), "globalThis.ownedActual = true;"),
writeFile(join(root, "decoy.js"), "globalThis.ownedDecoy = true;"),
]);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const loads = result.graph.edges.filter(
({ relation, properties }) =>
relation === "loads" && properties.script_path !== undefined,
);
expect(loads.map(({ properties }) => properties.resolved_path)).toEqual(
expected,
);
},
);
it("preserves source digest, opening-tag range and decoded local base resolution", async () => {
const root = await createTestTempDirectory("rea-html-entrypoint-evidence-");
const opening = '<script title=">" src="actual&#46;js">';
const prefix = '<base data-href="decoy/"><base href=assets/>\n';
const opening = '<script title=">" src="actual&#46;js" src="decoy.js">';
const prefix =
'<base data-href="decoy/"><base href=assets/><template><script src="decoy.js"></script></template>\n';
const html = `${prefix}${opening}</script>`;
await mkdir(join(root, "assets"));
await Promise.all([
@@ -59,6 +20,7 @@ it("preserves source digest, opening-tag range and decoded local base resolution
join(root, "assets", "actual.js"),
"globalThis.ownedActual = true;",
),
writeFile(join(root, "assets", "decoy.js"), "globalThis.decoy = true;"),
]);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const loads = result.graph.edges.filter(
@@ -91,106 +53,101 @@ it("preserves source digest, opening-tag range and decoded local base resolution
});
});
const coordinateCases = [
{ name: "LF", prefix: "before\n", opening: '<script src="actual.js">' },
{ name: "CRLF", prefix: "before\r\n", opening: '<script src="actual.js">' },
{ name: "bare CR", prefix: "before\r", opening: '<script src="actual.js">' },
{
name: "mixed CRLF and CR",
prefix: "before\r\nafter\r",
opening: '<script src="actual.js">',
},
{
name: "CR inside opening tag",
prefix: "before\n",
opening: '<script\r src="actual.js">',
},
{
name: "CRLF inside opening tag",
prefix: "before\n",
opening: '<script\r\n src="actual.js">',
},
{
name: "astral UTF-16 columns",
prefix: "😀",
opening: '<script src="actual.js">',
},
{
name: "U+2028 literal text",
prefix: "before\u2028",
opening: '<script src="actual.js">',
},
] as const;
it("preserves external and inline HTML script ranges across line endings", async () => {
const root = await createTestTempDirectory("rea-html-coordinate-evidence-");
const opening = '<script src="actual.js">';
const missingOpening = '<script src="missing.js">';
const closing = "</script>";
const inlineOpening = "<script>";
const cases = [
["lf", "before\n", opening, 2, 0, 2, 24],
["crlf", "before\r\n", opening, 2, 0, 2, 24],
["cr", "before\r", opening, 2, 0, 2, 24],
["mixed", "before\r\nafter\r", opening, 3, 0, 3, 24],
["tag-cr", "before\n", '<script\r src="actual.js">', 2, 0, 3, 17],
["tag-crlf", "before\n", '<script\r\n src="actual.js">', 2, 0, 3, 17],
["astral", "😀", opening, 1, 2, 1, 26],
["literal-separator", "before\u2028", opening, 1, 7, 1, 31],
] as const;
const documents = cases.map(
([name, prefix, tag, startLine, startColumn, endLine, endColumn]) => ({
source: `${name}.html`,
html: `${prefix}${tag}${closing}${missingOpening}${closing}${inlineOpening}\r\nrun();\rnext();\n${closing}`,
start: { line: startLine, column: startColumn },
end: { line: endLine, column: endColumn },
}),
);
await Promise.all([
writeFile(join(root, "actual.js"), "export const actual = true;"),
...documents.map(({ source, html }) => writeFile(join(root, source), html)),
]);
it.each(coordinateCases)(
"retains parse5 source coordinates for resolved and unresolved scripts with $name",
async ({ prefix, opening }) => {
const root = await createTestTempDirectory("rea-html-coordinate-evidence-");
const html = `${prefix}${opening}</script><script src="missing.js"></script>`;
const expected = htmlScriptRanges(html);
expect(expected).toHaveLength(2);
await Promise.all([
writeFile(join(root, "index.html"), html),
writeFile(join(root, "actual.js"), "export const actual = true;"),
]);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const resolved = result.graph.edges.filter(
({ relation, properties }) =>
relation === "loads" && properties.script_path === "actual.js",
);
const unresolved = result.graph.nodes
.flatMap(({ observations }) => observations)
.filter(
({ properties }) =>
properties.mechanism === "html-script-reference" &&
properties.script_path === "missing.js",
const { graph } = await reconstructJavaScriptArtifact({ input_path: root });
const loads = graph.edges.filter(
({ relation, properties }) =>
relation === "loads" && properties.script_path === "actual.js",
);
const observations = graph.nodes.flatMap(({ observations }) => observations);
const unresolved = observations.filter(
({ properties }) =>
properties.mechanism === "html-script-reference" &&
properties.script_path === "missing.js",
);
const inlineGaps = observations.filter(
({ properties }) => properties.operation === "parse-html-inline-scripts",
);
for (const records of [loads, unresolved, inlineGaps])
expect(records).toHaveLength(documents.length);
for (const { source, html, start, end } of documents) {
const missingStart = { line: end.line, column: end.column + closing.length };
const missingEnd = {
line: end.line,
column: missingStart.column + missingOpening.length,
};
const artifact = {
available: true,
sha256: createHash("sha256").update(html).digest("hex"),
};
for (const [records, range] of [
[loads, { start, end }],
[unresolved, { start: missingStart, end: missingEnd }],
] as const) {
const record = records.find(
({ evidence }) =>
evidence.location.available &&
evidence.location.value.kind === "source-range" &&
evidence.location.value.source === source,
);
expect(resolved).toHaveLength(1);
expect(unresolved).toHaveLength(1);
for (const [index, observation] of [resolved[0], unresolved[0]].entries()) {
expect(observation).toMatchObject({
evidence: {
artifact: {
available: true,
sha256: createHash("sha256").update(html).digest("hex"),
},
location: {
available: true,
value: {
kind: "source-range",
source: "index.html",
...expected[index],
},
},
expect(record?.evidence, source).toMatchObject({
artifact,
location: {
available: true,
value: { kind: "source-range", source, ...range },
},
});
}
},
);
const htmlScriptRanges = (html: string) => {
const pending: DefaultTreeAdapterTypes.Node[] = [
parse(html, { sourceCodeLocationInfo: true }),
];
const ranges = [];
while (pending.length > 0) {
const node = pending.pop();
if (node === undefined) continue;
if (defaultTreeAdapter.isElementNode(node) && node.tagName === "script") {
const location = node.sourceCodeLocation?.startTag;
if (location === undefined)
throw new Error("Missing parse5 script range");
ranges.push({
start: { line: location.startLine, column: location.startCol - 1 },
end: { line: location.endLine, column: location.endCol - 1 },
});
}
if ("childNodes" in node) {
for (const child of node.childNodes.toReversed()) pending.push(child);
}
const gap = inlineGaps.find(({ properties }) => properties.path === source);
expect(gap, source).toMatchObject({
evidence: { artifact },
properties: {
inline_scripts: [
{
script_type: "classic",
location: {
start: {
line: end.line,
column:
missingEnd.column + closing.length + inlineOpening.length,
},
end: { line: end.line + 3, column: 0 },
},
},
],
},
});
}
return ranges;
};
});
it("reports unanalyzed inline HTML scripts instead of claiming complete coverage", async () => {
const root = await createTestTempDirectory("rea-html-inline-scripts-");
@@ -288,58 +245,14 @@ it("keeps complete coverage when HTML has only external scripts and data blocks"
).toBe(false);
});
it.each(coordinateCases)(
"retains parse5 source coordinates for inline script bodies with $name",
async ({ prefix }) => {
const root = await createTestTempDirectory("rea-html-inline-coordinates-");
const html = `${prefix}<script>\r\nrun();\rnext();\n</script>`;
await writeFile(join(root, "index.html"), html);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const gap = result.graph.nodes
.flatMap(({ observations }) => observations)
.find(
({ properties }) =>
properties.operation === "parse-html-inline-scripts",
);
expect(gap?.properties.inline_scripts).toEqual([
{ script_type: "classic", location: inlineBodyRange(html) },
]);
},
);
const inlineBodyRange = (html: string) => {
const pending: DefaultTreeAdapterTypes.Node[] = [
parse(html, { sourceCodeLocationInfo: true }),
];
while (pending.length > 0) {
const node = pending.pop();
if (node === undefined) continue;
if (defaultTreeAdapter.isElementNode(node) && node.tagName === "script") {
const opening = node.sourceCodeLocation?.startTag;
const body = node.childNodes[0]?.sourceCodeLocation;
if (opening === undefined || body === undefined || body === null)
throw new Error("Missing parse5 inline script range");
return {
start: { line: opening.endLine, column: opening.endCol - 1 },
end: { line: body.endLine, column: body.endCol - 1 },
};
}
if ("childNodes" in node) {
for (const child of node.childNodes.toReversed()) pending.push(child);
}
}
throw new Error("Missing parse5 inline script");
};
it("bounds retained inline script locations and names the omitted remainder", async () => {
it("retains the first 100 HTML and SVG inline script locations in document order", async () => {
const root = await createTestTempDirectory("rea-html-many-inline-scripts-");
const count = 5_000;
await writeFile(
join(root, "index.html"),
"<script>run();</script>\n".repeat(count),
);
const scriptPair = [
"<script>run();</script>",
"<svg><script>svgRun();</script></svg>",
"",
].join("\n");
await writeFile(join(root, "index.html"), scriptPair.repeat(2_500));
const result = await reconstructJavaScriptArtifact({ input_path: root });
const gap = result.graph.nodes
@@ -353,13 +266,25 @@ it("bounds retained inline script locations and names the omitted remainder", as
unit: "items",
};
expect(gap?.properties.inline_script_count).toBe(count);
expect(gap?.properties.inline_scripts).toHaveLength(100);
expect(gap?.properties.inline_script_count).toBe(5_000);
expect(gap?.properties.inline_scripts).toEqual(
Array.from({ length: 100 }, (_, index) => {
const line = index + 1;
const svg = line % 2 === 0;
return {
script_type: "classic",
location: {
start: { line, column: svg ? 13 : 8 },
end: { line, column: svg ? 22 : 14 },
},
};
}),
);
// The gap record knows exactly which locations the bound dropped.
expect(gap?.evidence.coverage).toEqual({
status: "partial",
truncated: true,
omitted_count: count - 100,
omitted_count: 4_900,
limits: [limit],
});
// The graph is truncated too, but unanalyzed bodies hide an unknown total.
@@ -370,6 +295,6 @@ it("bounds retained inline script locations and names the omitted remainder", as
limits: expect.arrayContaining([limit]),
});
expect(result.graph.limitations).toContain(
`index.html has ${String(count)} inline JavaScript bodies starting at lines 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and ${String(count - 10)} more that were not analyzed; endpoints, storage, imports and other facts in them are absent from the evidence.`,
"index.html has 5000 inline JavaScript bodies starting at lines 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and 4990 more that were not analyzed; endpoints, storage, imports and other facts in them are absent from the evidence.",
);
});
@@ -1,151 +1,81 @@
import { mkdir, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join, relative, sep } from "node:path";
import { expect, it } from "vitest";
import { reconstructJavaScriptArtifact } from "../../support/javascriptApplicationScope.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { writeFixtureFiles } from "../../support/workspace/writeFixtureFiles.js";
const cases: readonly {
name: string;
html: string;
files: Readonly<Record<string, string>>;
expected: readonly string[];
}[] = [
{
name: "extension fallback",
html: '<script src="./app"></script>',
files: { "app.js": "globalThis.owned = true;" },
expected: [],
},
{
name: "directory index",
html: '<script src="./app"></script>',
files: { "app/index.js": "globalThis.owned = true;" },
expected: [],
},
{
name: "directory package",
html: '<script src="./app"></script>',
files: {
"app/package.json": '{"main":"entry.js"}',
"app/entry.js": "globalThis.owned = true;",
},
expected: [],
},
{
name: "base directory",
html: '<base href="assets/"><script src="./app"></script>',
files: { "assets/app.js": "globalThis.owned = true;" },
expected: [],
},
{
name: "exact base resource",
html: '<base href="assets/"><script src="./app.js?cache=1#v2"></script>',
files: {
"assets/app.js": "globalThis.owned = true;",
"app.js": "globalThis.decoy = true;",
},
expected: ["assets/app.js"],
},
{
name: "exact script resource",
html: '<script src="./app.js?cache=1#v2"></script>',
files: { "app.js": "globalThis.owned = true;" },
expected: ["app.js"],
},
{
name: "percent-encoded script letters",
html: '<script src="%61pp.js"></script>',
files: { "app.js": "globalThis.owned = true;" },
expected: ["app.js"],
},
{
name: "script URL surrounded by whitespace",
html: '<script src=" app.js "></script>',
files: { "app.js": "globalThis.owned = true;" },
expected: ["app.js"],
},
{
name: "percent-encoded base directory",
html: '<base href="%61ssets/"><script src="app.js"></script>',
files: { "assets/app.js": "globalThis.owned = true;" },
expected: ["assets/app.js"],
},
];
it.each(cases)(
"uses exact HTML resource identity for $name",
async ({ html, files, expected }) => {
const root = await createTestTempDirectory("rea-html-resources-");
await Promise.all(
Object.entries({ ...files, "index.html": html }).map(
async ([path, text]) => {
await mkdir(dirname(join(root, path)), { recursive: true });
await writeFile(join(root, path), text);
},
),
);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const loads = result.graph.edges.filter(
({ relation, properties }) =>
relation === "loads" && properties.script_path !== undefined,
);
expect(loads.map(({ properties }) => properties.resolved_path)).toEqual(
expected,
);
if (expected.length === 0) {
const reference = result.graph.nodes
.flatMap(({ observations }) => observations)
.find(
({ properties }) => properties.mechanism === "html-script-reference",
);
expect(reference).toMatchObject({
properties: {
script_path: "./app",
resolution_context: "html-reference",
resolution_status: "not-found",
resolved_path: null,
},
evidence: {
authority: "static-relationship-inference",
location: {
available: true,
value: { kind: "source-range", source: "index.html" },
},
limitations: expect.arrayContaining([
expect.stringContaining("exact HTML resource"),
]),
},
});
}
},
);
it("retains CommonJS extension resolution against Node", async () => {
const root = await createTestTempDirectory("rea-html-node-control-");
await Promise.all([
writeFile(
join(root, "main.cjs"),
'const value = require("./app"); module.exports = value;',
),
writeFile(join(root, "app.js"), 'module.exports = "actual";'),
]);
const expected = relative(
root,
createRequire(join(root, "main.cjs")).resolve("./app"),
)
.split(sep)
.join("/");
const result = await reconstructJavaScriptArtifact({ input_path: root });
const edge = result.graph.edges.find(
({ properties }) =>
properties.module_link_kind === "require" &&
properties.specifier === "./app",
);
expect(edge?.properties).toMatchObject({
resolution_status: "resolved",
resolved_path: expected,
it("requires exact HTML script paths when fallback candidates exist", async () => {
const root = await createTestTempDirectory("rea-html-resources-");
await writeFixtureFiles(root, {
"index.html": [
'<script src="./extension"></script>',
'<script src="./directory"></script>',
'<script src="./package"></script>',
].join("\n"),
"base.html": [
'<base href="%61ssets/">',
'<script src="./app"></script>',
'<script src="%61pp.js?cache=1#v2"></script>',
].join("\n"),
"extension.js": "globalThis.extensionDecoy = true;",
"directory/index.js": "globalThis.directoryDecoy = true;",
"package/package.json": '{"main":"entry.js"}',
"package/entry.js": "globalThis.packageDecoy = true;",
"app.js": "globalThis.rootDecoy = true;",
"assets/app.js": "globalThis.exactScript = true;",
});
const { graph } = await reconstructJavaScriptArtifact({ input_path: root });
const loads = graph.edges.filter(
({ relation, properties }) =>
relation === "loads" && properties.script_path !== undefined,
);
expect(loads).toMatchObject([
{
properties: {
script_path: "%61pp.js?cache=1#v2",
base_href: "%61ssets/",
resolution_status: "resolved",
resolved_path: "assets/app.js",
},
},
]);
const unresolved = graph.nodes
.flatMap(({ observations }) => observations)
.filter(
({ properties }) => properties.mechanism === "html-script-reference",
);
expect(unresolved).toHaveLength(4);
for (const [source, scriptPath, candidate, base] of [
["index.html", "./extension", "extension", null],
["index.html", "./directory", "directory", null],
["index.html", "./package", "package", null],
["base.html", "./app", "assets/app", "%61ssets/"],
] as const) {
const reference = unresolved.find(
({ properties }) => properties.script_path === scriptPath,
);
expect(reference, scriptPath).toMatchObject({
properties: {
script_path: scriptPath,
base_href: base,
resolution_context: "html-reference",
resolution_status: "not-found",
resolved_path: null,
},
evidence: {
authority: "static-relationship-inference",
location: {
available: true,
value: { kind: "source-range", source },
},
limitations: expect.arrayContaining([
expect.stringContaining(
`The exact HTML resource ${candidate} was not found`,
),
]),
},
});
}
});