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

@@ -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" },
]);
},
);