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();