Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(reference): resolve runtime imports from their owning syntax
morlutoc0d550b231f5
diff --git a/src/application/ReferenceSourceImportEntries.test.ts b/src/application/ReferenceSourceImportEntries.test.tsindex e0fbf2434..876c15fe9 100644--- a/src/application/ReferenceSourceImportEntries.test.ts+++ b/src/application/ReferenceSourceImportEntries.test.ts@@ -116,3 +116,140 @@ it("retains Kotlin source identity and language across the inventory projection"expect(parsed.parseFailures).toEqual([]);expect(parsed.relationships).toEqual([]);});++it("resolves runtime require package mains without an index and before typed indexes", () => {+ const files = [+ ["main.cjs", 'require("./pkg");\nrequire("./dep");\n'],+ [+ "main.ts",+ 'import dep = require("./typed");\n' ++ 'require("./typed");\n' ++ 'import data = require("./json-package");\n' ++ 'require("./emitted.js");\n',+ ],+ ["pkg/package.json", '{"main":"actual.js"}\n'],+ ["pkg/actual.js", 'module.exports = "package main";\n'],+ ["dep.js", 'module.exports = "file";\n'],+ ["dep/index.ts", 'export const value = "index";\n'],+ ["typed.js", 'module.exports = "runtime file";\n'],+ ["typed/index.ts", 'export const value = "source index";\n'],+ ["json-package/package.json", '{"main":"data"}\n'],+ ["json-package/data.json", '{"value":"package main"}\n'],+ ["json-package/index.js", 'module.exports = "fallback index";\n'],+ ["emitted.ts", 'export const value = "source counterpart";\n'],+ ] as const;+ const read: ReferenceSourceRead = {+ root: "/selected/source",+ entries: files.map(([path, content]) => ({+ status: "read",+ kind: "file",+ path,+ bytes: Buffer.from(content),+ size: Buffer.byteLength(content),+ })),+ bytesRead: files.reduce(+ (sum, [, content]) => sum + Buffer.byteLength(content),+ 0,+ ),+ limitations: [],+ };++ const parsed = parseReferenceSourceEntries(+ read,+ new Set(files.map(([path]) => path)),+ );++ expect(parsed.relationships).toContainEqual({+ from_path: "main.cjs",+ to: "pkg/actual.js",+ kind: "requires",+ resolution: "internal",+ parse_state: "parsed",+ });+ expect(parsed.relationships).toContainEqual({+ from_path: "main.cjs",+ to: "dep.js",+ kind: "requires",+ resolution: "internal",+ parse_state: "parsed",+ });+ expect(parsed.relationships).toContainEqual({+ from_path: "main.ts",+ to: "typed/index.ts",+ kind: "requires",+ resolution: "internal",+ parse_state: "parsed",+ });+ expect(parsed.relationships).toContainEqual({+ from_path: "main.ts",+ to: "typed.js",+ kind: "requires",+ resolution: "internal",+ parse_state: "parsed",+ });+ expect(parsed.relationships).toContainEqual({+ from_path: "main.ts",+ to: "json-package/data.json",+ kind: "requires",+ resolution: "internal",+ parse_state: "parsed",+ });+ expect(parsed.relationships).toContainEqual({+ from_path: "main.ts",+ to: "emitted.ts",+ kind: "requires",+ resolution: "internal",+ parse_state: "parsed",+ });+});++it("matches package manifests by exact or unique canonical directory identity", () => {+ const composed = "caf\u00e9";+ const decomposed = "cafe\u0301";+ const composedTwin = "r\u00e9sum\u00e9";+ const decomposedTwin = "re\u0301sume\u0301";+ const files = [+ [+ "main.cjs",+ [composed, composedTwin, decomposedTwin]+ .map((name) => `require(${JSON.stringify(`./${name}`)});`)+ .join("\n"),+ ],+ [`${decomposed}/package.json`, '{"main":"unique.js"}\n'],+ [`${decomposed}/unique.js`, 'module.exports = "unique";\n'],+ [`${composed}/unique.js`, 'module.exports = "unrelated exact spelling";\n'],+ [`${composedTwin}/package.json`, '{"main":"exact-composed.js"}\n'],+ [`${composedTwin}/exact-composed.js`, 'module.exports = "composed";\n'],+ [`${decomposedTwin}/package.json`, '{"main":"exact-decomposed.js"}\n'],+ [+ `${decomposedTwin}/exact-decomposed.js`,+ 'module.exports = "decomposed";\n',+ ],+ ] as const;+ const read: ReferenceSourceRead = {+ root: "/selected/source",+ entries: files.map(([path, content]) => ({+ status: "read",+ kind: "file",+ path,+ bytes: Buffer.from(content),+ size: Buffer.byteLength(content),+ })),+ bytesRead: files.reduce(+ (sum, [, content]) => sum + Buffer.byteLength(content),+ 0,+ ),+ limitations: [],+ };++ const parsed = parseReferenceSourceEntries(+ read,+ new Set(files.map(([path]) => path)),+ );++ expect(parsed.relationships.map(({ to }) => to)).toEqual([+ `${decomposed}/unique.js`,+ `${composedTwin}/exact-composed.js`,+ `${decomposedTwin}/exact-decomposed.js`,+ ]);+});diff --git a/src/application/ReferenceSourceImportEntries.ts b/src/application/ReferenceSourceImportEntries.tsindex 13b866272..7c21913d9 100644--- a/src/application/ReferenceSourceImportEntries.ts+++ b/src/application/ReferenceSourceImportEntries.ts@@ -107,11 +107,20 @@ type PackageMain =*/const readPackageMains = (read: ReferenceSourceRead,-): ReadonlyMap<string, PackageMain> => {+): {+ readonly mains: ReadonlyMap<string, PackageMain>;+ readonly pathLookup: ReferenceSourcePathLookup;+} => {const mains = new Map<string, PackageMain>();+ const manifestPaths: string[] = [];for (const entry of read.entries) {if (posix.basename(entry.path) !== "package.json") continue;+ manifestPaths.push(entry.path);const directory = posix.dirname(entry.path);+ if (mains.has(directory)) {+ mains.set(directory, { state: "unknown" });+ continue;+ }if (entry.status !== "read" || entry.kind !== "file") {mains.set(directory, { state: "unknown" });continue;@@ -134,7 +143,10 @@ const readPackageMains = (mains.set(directory, { state: "unknown" });}}- return mains;+ return {+ mains,+ pathLookup: createReferenceSourcePathLookup(manifestPaths),+ };};/**@@ -154,54 +166,109 @@ const RESOLUTION_SUFFIXES: readonly (readonly string[])[] = [const REQUIRE_RESOLUTION_SUFFIXES = RESOLUTION_SUFFIXES.map((slot) =>slot.includes(".js") ? [...slot, ".json"] : slot,);+const NODE_REQUIRE_SUFFIXES = ["", ".js", ".json", ".node"] as const;++type InternalSpecifierResolutionMode =+ | "source-import"+ | "source-require"+ | "runtime-require";++const resolutionSuffixes = (+ mode: InternalSpecifierResolutionMode,+): readonly (readonly string[])[] =>+ mode === "source-require" ? REQUIRE_RESOLUTION_SUFFIXES : RESOLUTION_SUFFIXES;++const nodeRequireFileCandidates = (path: string): string[] =>+ NODE_REQUIRE_SUFFIXES.map((suffix) => `${path}${suffix}`);++const nodeRequireIndexCandidates = (directory: string): string[] =>+ NODE_REQUIRE_SUFFIXES.filter((suffix) => suffix !== "").map((suffix) =>+ posix.join(directory, `index${suffix}`),+ );/** Inventory facts an internal specifier resolves against. */interface SpecifierContext {readonly lookupPath: ReferenceSourcePathLookup;readonly packageMains: ReadonlyMap<string, PackageMain>;+ readonly packageManifestPathLookup: ReferenceSourcePathLookup;}-/**- * Apply a package `main` to a directory resolved through its index. Node loads- * the declared entry as a file, then as a directory index, and falls back to- * the package's own index only when neither exists.- */+const packageMainForDirectory = (+ directory: string,+ context: SpecifierContext,+): { readonly directory: string; readonly main: PackageMain } | undefined => {+ const manifestPath = context.packageManifestPathLookup.resolve(+ posix.join(directory, "package.json"),+ );+ if (manifestPath !== undefined) {+ const manifestDirectory = posix.dirname(manifestPath);+ const main = context.packageMains.get(manifestDirectory);+ return main === undefined+ ? undefined+ : { directory: manifestDirectory, main };+ }+ return context.packageManifestPathLookup.has(+ posix.join(directory, "package.json"),+ )+ ? { directory, main: { state: "unknown" } }+ : undefined;+};++/** Apply a package main, retaining an existing index as the fallback target. */const selectPackageMain = (- index: string,+ directory: string,+ indexFallback: string | undefined,context: SpecifierContext,- slots: readonly (readonly string[])[],+ mode: InternalSpecifierResolutionMode,): { to: string; resolution: "internal" | "unresolved" } => {- const directory = posix.dirname(index);- const manifest = context.packageMains.get(directory);+ const packageSelection = packageMainForDirectory(directory, context);+ const packageDirectory = packageSelection?.directory ?? directory;+ const manifest = packageSelection?.main;if (manifest === undefined || manifest.state === "none")- return { to: index, resolution: "internal" };+ return indexFallback === undefined+ ? { to: directory, resolution: "unresolved" }+ : { to: indexFallback, resolution: "internal" };if (manifest.state === "unknown")- return { to: directory, resolution: "unresolved" };+ return { to: packageDirectory, resolution: "unresolved" };// Node resolves `main` with path.resolve: an absolute main leaves the// package, and a trailing separator does not make the entry a directory.if (posix.isAbsolute(manifest.main))return { to: posix.normalize(manifest.main), resolution: "unresolved" };const target = posix- .normalize(posix.join(directory, manifest.main))+ .normalize(posix.join(packageDirectory, manifest.main)).replace(/(?<=.)\/+$/u, "");// Node would load a declared entry outside the imported root.if (logicalPathEscapesRoot(target))return { to: target, resolution: "unresolved" };- const suffixes = slots.flat();- const selected = context.lookupPath.resolveCandidates([- ...suffixes.map((suffix) => `${target}${suffix}`),- ...suffixes- .filter((suffix) => suffix !== "")- .map((suffix) => posix.join(target, `index${suffix}`)),- ]);- return { to: selected ?? index, resolution: "internal" };+ const slots = resolutionSuffixes(mode);+ const candidates =+ mode === "runtime-require"+ ? [+ ...nodeRequireFileCandidates(target),+ ...nodeRequireIndexCandidates(target),+ ]+ : [+ ...slots.flatMap((slot) =>+ slot.map((suffix) => `${target}${suffix}`),+ ),+ ...slots+ .flat()+ .filter((suffix) => suffix !== "")+ .map((suffix) => posix.join(target, `index${suffix}`)),+ ];+ const selected = context.lookupPath.resolveCandidates(candidates);+ return selected === undefined+ ? indexFallback === undefined+ ? { to: packageDirectory, resolution: "unresolved" }+ : { to: indexFallback, resolution: "internal" }+ : { to: selected, resolution: "internal" };};const resolveInternalSpecifier = (fromPath: string,specifier: string,context: SpecifierContext,- slots: readonly (readonly string[])[],+ mode: InternalSpecifierResolutionMode,): { to: string; resolution: "internal" | "unresolved" } => {if (posix.isAbsolute(specifier))return { to: specifier, resolution: "unresolved" };@@ -215,14 +282,21 @@ const resolveInternalSpecifier = (specifier.endsWith("/") || [".", ".."].includes(posix.basename(specifier));// A directory resolves only to an index with an extension; neither Node nor// TypeScript selects an extensionless `index` file.- const candidates = slots.flatMap((slot) => [- ...(directoryReference- ? []- : slot.map((suffix) => `${normalized}${suffix}`)),- ...slot- .filter((suffix) => suffix !== "")- .map((suffix) => posix.join(normalized, `index${suffix}`)),- ]);+ const slots = resolutionSuffixes(mode);+ const candidates =+ mode === "runtime-require"+ ? [+ ...(directoryReference ? [] : nodeRequireFileCandidates(normalized)),+ ...nodeRequireIndexCandidates(normalized),+ ]+ : slots.flatMap((slot) => [+ ...(directoryReference+ ? []+ : slot.map((suffix) => `${normalized}${suffix}`)),+ ...slot+ .filter((suffix) => suffix !== "")+ .map((suffix) => posix.join(normalized, `index${suffix}`)),+ ]);// Retain present runtime files first; substitute only a missing counterpart.// Counterparts cover explicit filenames, not directory/index resolution.if (!directoryReference)@@ -232,12 +306,15 @@ const resolveInternalSpecifier = (),);const match = context.lookupPath.resolveCandidates(candidates);- if (match === undefined) return { to: normalized, resolution: "unresolved" };+ if (match === undefined)+ return packageMainForDirectory(normalized, context) !== undefined+ ? selectPackageMain(normalized, undefined, context, mode)+ : { to: normalized, resolution: "unresolved" };const resolvedThroughIndex =posix.basename(match).startsWith("index.") &&posix.dirname(match).normalize("NFC") === normalized.normalize("NFC");return resolvedThroughIndex- ? selectPackageMain(match, context, slots)+ ? selectPackageMain(posix.dirname(match), match, context, mode): { to: match, resolution: "internal" };};@@ -265,20 +342,25 @@ const appendFile = (});if (parsed === undefined) return;for (const relationship of parsed.relationships) {- if (relationship.resolution !== "internal") {- output.relationships.push(relationship);+ const { resolutionStrategy, ...graphRelationship } = relationship;+ if (graphRelationship.resolution !== "internal") {+ output.relationships.push(graphRelationship);continue;}+ const mode: InternalSpecifierResolutionMode =+ resolutionStrategy === "runtime-require"+ ? "runtime-require"+ : graphRelationship.kind === "requires"+ ? "source-require"+ : "source-import";const resolved = resolveInternalSpecifier(- relationship.from_path,- relationship.to,+ graphRelationship.from_path,+ graphRelationship.to,context,- relationship.kind === "requires"- ? REQUIRE_RESOLUTION_SUFFIXES- : RESOLUTION_SUFFIXES,+ mode,);output.relationships.push({- ...relationship,+ ...graphRelationship,to: resolved.to,resolution: resolved.resolution,});@@ -335,9 +417,11 @@ export const parseReferenceSourceEntries = (parseFailures: [],limitations: [...read.limitations],};+ const packageMainInventory = readPackageMains(read);const context: SpecifierContext = {lookupPath: createReferenceSourcePathLookup(filePaths),- packageMains: readPackageMains(read),+ packageMains: packageMainInventory.mains,+ packageManifestPathLookup: packageMainInventory.pathLookup,};for (const entry of read.entries) {if (signal?.aborted === true) break;diff --git a/src/domain/referenceSourceImportParsing.ts b/src/domain/referenceSourceImportParsing.tsindex 18f76a358..5d4af98da 100644--- a/src/domain/referenceSourceImportParsing.ts+++ b/src/domain/referenceSourceImportParsing.ts@@ -47,6 +47,8 @@ interface ReferenceSourceImportRelationship {readonly kind: ReferenceSourceImportKind;readonly resolution: ReferenceSourceImportResolution;readonly parse_state: ReferenceSourceImportParseState;+ /** Distinguishes call-form CommonJS require from TS import-equals `requires`. */+ readonly resolutionStrategy?: "runtime-require";}interface ReferenceSourceParseFailure {@@ -114,6 +116,7 @@ const appendRelationship = (readonly kind: ReferenceSourceImportKind;readonly parseState: ReferenceSourceImportParseState;readonly resolution?: ReferenceSourceImportResolution;+ readonly resolutionStrategy?: "runtime-require";},): void => {if (input.to === undefined) return;@@ -123,6 +126,9 @@ const appendRelationship = (kind: input.kind,resolution: input.resolution ?? resolveSpecifier(input.to),parse_state: input.parseState,+ ...(input.resolutionStrategy === undefined+ ? {}+ : { resolutionStrategy: input.resolutionStrategy }),});};@@ -253,6 +259,7 @@ const extractRequireAndDynamicImports = (to: result.specifier,kind: "requires",parseState: result.parseState,+ resolutionStrategy: "runtime-require",});}continue;diff --git a/src/domain/referenceSourcePathIdentity.test.ts b/src/domain/referenceSourcePathIdentity.test.tsnew file mode 100644index 000000000..56b177562--- /dev/null+++ b/src/domain/referenceSourcePathIdentity.test.ts@@ -0,0 +1,15 @@+import { expect, it } from "vitest";++import { createReferenceSourcePathLookup } from "./referenceSourcePathIdentity.js";++it("reports ambiguous canonical identities while preserving exact paths", () => {+ const first = "package/a\u0301\u0323/package.json";+ const second = "package/a\u0323\u0301/package.json";+ const third = "package/\u1ea1\u0301/package.json";+ const lookup = createReferenceSourcePathLookup([first, second]);++ expect(lookup.has(third)).toBe(true);+ expect(lookup.resolve(third)).toBeUndefined();+ expect(lookup.resolve(first)).toBe(first);+ expect(lookup.resolve(second)).toBe(second);+});diff --git a/src/domain/referenceSourcePathIdentity.ts b/src/domain/referenceSourcePathIdentity.tsindex 4ac6963cf..76404c83b 100644--- a/src/domain/referenceSourcePathIdentity.ts+++ b/src/domain/referenceSourcePathIdentity.ts@@ -1,6 +1,8 @@import { posix } from "node:path";export interface ReferenceSourcePathLookup {+ /** Whether an exact or canonical identity exists, including ambiguous ones. */+ readonly has: (path: string) => boolean;readonly resolve: (path: string) => string | undefined;readonly resolveCandidates: (paths: readonly string[]) => string | undefined;/** Resolve a path to the closest recorded parent identity. */@@ -22,9 +24,12 @@ export const createReferenceSourcePathLookup = (}const equivalent = (path: string): string | undefined =>canonical.get(path.normalize("NFC")) ?? undefined;+ const has = (path: string): boolean =>+ exact.has(path) || canonical.has(path.normalize("NFC"));const resolve = (path: string): string | undefined =>exact.has(path) ? path : equivalent(path);return {+ has,resolve,resolveCandidates: (candidates) =>candidates.find((path) => exact.has(path)) ??diff --git a/tests/boundary/cli/referenceSourceDirectoryImports.test.ts b/tests/boundary/cli/referenceSourceDirectoryImports.test.tsindex 8bf5d94e5..491722c68 100644--- a/tests/boundary/cli/referenceSourceDirectoryImports.test.ts+++ b/tests/boundary/cli/referenceSourceDirectoryImports.test.ts@@ -8,6 +8,169 @@ import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceimport { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";import { cliTest } from "../../support/cli/cliFixture.js";+type ResolutionCase = readonly [from: string, specifier: string, to: string];++interface ReferenceSourceDirectoryFixture {+ readonly workspace: string;+ readonly root: string;+ readonly outside: string;+ readonly imports: readonly ResolutionCase[];+ readonly unresolved: readonly ResolutionCase[];+}++const prepareReferenceSourceDirectoryFixture =+ async (): Promise<ReferenceSourceDirectoryFixture> => {+ const workspace = await createTestTempDirectory(+ "rea-reference-directory-imports-",+ );+ const root = join(workspace, "source");+ const outside = join(workspace, "outside", "index.js");+ const imports = [+ ["slash.cjs", "./lib/", "lib/index.js"],+ ["dot.cjs", "./lib/.", "lib/index.js"],+ ["self.cjs", ".", "index.js"],+ ["self-slash.cjs", "./", "index.js"],+ ["nested/parent.cjs", "..", "index.js"],+ ["nested/parent-slash.cjs", "../", "index.js"],+ ["direct.cjs", "./lib.js", "lib.js"],+ ["fallback.cjs", "./fallback", "fallback/index.js"],+ ["legacy-order.cjs", "./dep", "dep/index.js"],+ ["bare-index.cjs", "./bare", "bare.js"],+ ["package-main.cjs", "./pkg", "pkg/actual.js"],+ ["package-main-no-index.cjs", "./no-index-pkg", "no-index-pkg/actual.js"],+ ["package-main-fallback.cjs", "./stale", "stale/index.js"],+ ["typed-index-collision.cjs", "./typed", "typed.js"],+ ["package-main-slash.cjs", "./slashed", "slashed/lib.js"],+ ["json.cjs", "./data", "data.json"],+ ["json-explicit.cjs", "./data.json", "data.json"],+ ["json-before-index.cjs", "./conf", "conf.json"],+ ["js-before-json.cjs", "./both", "both.js"],+ ["json-index.cjs", "./settings", "settings/index.json"],+ ["json-main.cjs", "./jpkg", "jpkg/config.json"],+ ] as const satisfies readonly ResolutionCase[];+ const unresolved = [+ ["missing.cjs", "./missing/", "missing/"],+ ["escape.cjs", "../outside/", "../outside/"],+ ["main.ts", "./folder.js/.", "folder.js"],+ ["only-bare.cjs", "./only/", "only/"],+ ["invalid-manifest.cjs", "./broken", "broken"],+ ["absolute-main.cjs", "./absolute", outside],+ ] as const satisfies readonly ResolutionCase[];+ const files = new Map<string, string>([+ ["index.js", 'module.exports = "root index";\n'],+ ["lib/index.js", 'module.exports = "library index";\n'],+ ["lib.js", 'module.exports = "sibling JavaScript file";\n'],+ ["lib.ts", 'export const value = "sibling TypeScript file";\n'],+ ["fallback/index.js", 'module.exports = "fallback index";\n'],+ ["dep/index.js", 'module.exports = "existing index priority";\n'],+ ["dep.cjs", 'module.exports = "later CommonJS candidate";\n'],+ ["folder.ts", 'export const value = "emitted filename counterpart";\n'],+ ["missing.js", 'module.exports = "not a directory";\n'],+ ["bare.js", 'module.exports = "file before directory";\n'],+ ["bare/index", 'module.exports = "extensionless index";\n'],+ ["only/index", 'module.exports = "extensionless index";\n'],+ ["pkg/package.json", '{"main":"actual.js"}\n'],+ ["pkg/actual.js", 'module.exports = "declared main";\n'],+ ["pkg/index.js", 'module.exports = "ignored index";\n'],+ ["no-index-pkg/package.json", '{"main":"actual.js"}\n'],+ [+ "no-index-pkg/actual.js",+ 'module.exports = "declared main without index";\n',+ ],+ ["typed.js", 'module.exports = "runtime file";\n'],+ ["typed/index.ts", 'export const value = "source index";\n'],+ ["stale/package.json", '{"main":"gone.js"}\n'],+ ["stale/index.js", 'module.exports = "legacy fallback";\n'],+ ["broken/package.json", '{"main":\n'],+ ["broken/index.js", 'module.exports = "unknown selection";\n'],+ ["slashed/package.json", '{"main":"lib/"}\n'],+ ["slashed/lib.js", 'module.exports = "file main";\n'],+ ["slashed/lib/index.js", 'module.exports = "not selected";\n'],+ ["slashed/index.js", 'module.exports = "not selected";\n'],+ ["absolute/package.json", `${JSON.stringify({ main: outside })}\n`],+ ["absolute/index.js", 'module.exports = "not selected";\n'],+ ["data.json", '{"value":1}\n'],+ ["conf.json", '{"value":"file before index"}\n'],+ ["conf/index.js", 'module.exports = "not selected";\n'],+ ["both.js", 'module.exports = "JavaScript first";\n'],+ ["both.json", '{"value":"not selected"}\n'],+ ["settings/index.json", '{"value":"JSON index"}\n'],+ ["jpkg/package.json", '{"main":"config"}\n'],+ ["jpkg/config.json", '{"value":"JSON main"}\n'],+ ["jpkg/index.js", 'module.exports = "not selected";\n'],+ ...[...imports, ...unresolved].map(+ ([path, specifier]) =>+ [path, `require(${JSON.stringify(specifier)});\n`] as const,+ ),+ ]);+ await Promise.all(+ [...files].map(async ([path, contents]) => {+ const target = join(root, path);+ await mkdir(dirname(target), { recursive: true });+ await writeFile(target, contents);+ }),+ );+ await mkdir(dirname(outside), { recursive: true });+ await writeFile(outside, 'module.exports = "outside import root";\n');+ return { workspace, root, outside, imports, unresolved };+ };++const assertNodeResolutionControls = (+ fixture: ReferenceSourceDirectoryFixture,+): void => {+ const { root, outside, imports } = fixture;+ for (const [path, specifier, target] of imports)+ expect(createRequire(join(root, path)).resolve(specifier)).toBe(+ join(root, target),+ );+ expect(() =>+ createRequire(join(root, "missing.cjs")).resolve("./missing/"),+ ).toThrow();+ expect(() =>+ createRequire(join(root, "main.ts")).resolve("./folder.js/."),+ ).toThrow();+ expect(() =>+ createRequire(join(root, "only-bare.cjs")).resolve("./only/"),+ ).toThrow();+ expect(() =>+ createRequire(join(root, "invalid-manifest.cjs")).resolve("./broken"),+ ).toThrow();+ expect(createRequire(join(root, "escape.cjs")).resolve("../outside/")).toBe(+ outside,+ );+ expect(+ createRequire(join(root, "absolute-main.cjs")).resolve("./absolute"),+ ).toBe(outside);+};++const assertGraphResolution = (+ graph: ReturnType<typeof historicalSourceGraphSchema.parse>,+ fixture: ReferenceSourceDirectoryFixture,+): void => {+ const { imports, unresolved } = fixture;+ expect(graph.parse_failures).toEqual([]);+ expect(graph.relationships).toHaveLength(imports.length + unresolved.length);+ for (const [from, , to] of imports)+ expect.soft(graph.relationships, from).toContainEqual({+ from_path: from,+ to,+ kind: "requires",+ resolution: "internal",+ parse_state: "parsed",+ });+ for (const [from, , to] of unresolved)+ expect.soft(graph.relationships, from).toContainEqual({+ from_path: from,+ to,+ kind: "requires",+ resolution: "unresolved",+ parse_state: "parsed",+ });+ expect(graph.entries.some((entry) => entry.path.includes("outside"))).toBe(+ false,+ );+};+// Reference-source reads require no-follow opens; Windows reports unsupported.describe.skipIf(process.platform === "win32")("compiled reference-source directory imports",@@ -15,154 +178,21 @@ describe.skipIf(process.platform === "win32")(cliTest("resolves directory spellings without selecting similarly named files",async ({ cli }) => {- const workspace = await createTestTempDirectory(- "rea-reference-directory-imports-",- );- const root = join(workspace, "source");- const outside = join(workspace, "outside", "index.js");- const imports = [- ["slash.cjs", "./lib/", "lib/index.js"],- ["dot.cjs", "./lib/.", "lib/index.js"],- ["self.cjs", ".", "index.js"],- ["self-slash.cjs", "./", "index.js"],- ["nested/parent.cjs", "..", "index.js"],- ["nested/parent-slash.cjs", "../", "index.js"],- ["direct.cjs", "./lib.js", "lib.js"],- ["fallback.cjs", "./fallback", "fallback/index.js"],- ["legacy-order.cjs", "./dep", "dep/index.js"],- ["bare-index.cjs", "./bare", "bare.js"],- ["package-main.cjs", "./pkg", "pkg/actual.js"],- ["package-main-fallback.cjs", "./stale", "stale/index.js"],- ["package-main-slash.cjs", "./slashed", "slashed/lib.js"],- ["json.cjs", "./data", "data.json"],- ["json-explicit.cjs", "./data.json", "data.json"],- ["json-before-index.cjs", "./conf", "conf.json"],- ["js-before-json.cjs", "./both", "both.js"],- ["json-index.cjs", "./settings", "settings/index.json"],- ["json-main.cjs", "./jpkg", "jpkg/config.json"],- ] as const;- const unresolved = [- ["missing.cjs", "./missing/", "missing/"],- ["escape.cjs", "../outside/", "../outside/"],- ["main.ts", "./folder.js/.", "folder.js"],- ["only-bare.cjs", "./only/", "only/"],- ["invalid-manifest.cjs", "./broken", "broken"],- ["absolute-main.cjs", "./absolute", outside],- ] as const;- const files = new Map<string, string>([- ["index.js", 'module.exports = "root index";\n'],- ["lib/index.js", 'module.exports = "library index";\n'],- ["lib.js", 'module.exports = "sibling JavaScript file";\n'],- ["lib.ts", 'export const value = "sibling TypeScript file";\n'],- ["fallback/index.js", 'module.exports = "fallback index";\n'],- ["dep/index.js", 'module.exports = "existing index priority";\n'],- ["dep.cjs", 'module.exports = "later CommonJS candidate";\n'],- [- "folder.ts",- 'export const value = "emitted filename counterpart";\n',- ],- ["missing.js", 'module.exports = "not a directory";\n'],- ["bare.js", 'module.exports = "file before directory";\n'],- ["bare/index", 'module.exports = "extensionless index";\n'],- ["only/index", 'module.exports = "extensionless index";\n'],- // A package main outranks the index; a missing main falls back to it.- ["pkg/package.json", '{"main":"actual.js"}\n'],- ["pkg/actual.js", 'module.exports = "declared main";\n'],- ["pkg/index.js", 'module.exports = "ignored index";\n'],- ["stale/package.json", '{"main":"gone.js"}\n'],- ["stale/index.js", 'module.exports = "legacy fallback";\n'],- ["broken/package.json", '{"main":\n'],- ["broken/index.js", 'module.exports = "unknown selection";\n'],- // Node resolves main with path.resolve: no trailing-slash directory- // intent, and an absolute main leaves the imported root.- ["slashed/package.json", '{"main":"lib/"}\n'],- ["slashed/lib.js", 'module.exports = "file main";\n'],- ["slashed/lib/index.js", 'module.exports = "not selected";\n'],- ["slashed/index.js", 'module.exports = "not selected";\n'],- ["absolute/package.json", `${JSON.stringify({ main: outside })}\n`],- ["absolute/index.js", 'module.exports = "not selected";\n'],- // CommonJS loads X.json after X.js and before any directory index.- ["data.json", '{"value":1}\n'],- ["conf.json", '{"value":"file before index"}\n'],- ["conf/index.js", 'module.exports = "not selected";\n'],- ["both.js", 'module.exports = "JavaScript first";\n'],- ["both.json", '{"value":"not selected"}\n'],- ["settings/index.json", '{"value":"JSON index"}\n'],- ["jpkg/package.json", '{"main":"config"}\n'],- ["jpkg/config.json", '{"value":"JSON main"}\n'],- ["jpkg/index.js", 'module.exports = "not selected";\n'],- ...[...imports, ...unresolved].map(- ([path, specifier]) =>- [path, `require(${JSON.stringify(specifier)});\n`] as const,- ),- ]);- await Promise.all(- [...files].map(async ([path, contents]) => {- const target = join(root, path);- await mkdir(dirname(target), { recursive: true });- await writeFile(target, contents);- }),- );- await mkdir(dirname(outside), { recursive: true });- await writeFile(outside, 'module.exports = "outside import root";\n');-- // Node's loader establishes each fixture's meaning independently.- for (const [path, specifier, target] of imports)- expect(createRequire(join(root, path)).resolve(specifier)).toBe(- join(root, target),- );- expect(() =>- createRequire(join(root, "missing.cjs")).resolve("./missing/"),- ).toThrow();- expect(() =>- createRequire(join(root, "main.ts")).resolve("./folder.js/."),- ).toThrow();- expect(() =>- createRequire(join(root, "only-bare.cjs")).resolve("./only/"),- ).toThrow();- expect(() =>- createRequire(join(root, "invalid-manifest.cjs")).resolve("./broken"),- ).toThrow();- expect(- createRequire(join(root, "escape.cjs")).resolve("../outside/"),- ).toBe(outside);- expect(- createRequire(join(root, "absolute-main.cjs")).resolve("./absolute"),- ).toBe(outside);-+ const fixture = await prepareReferenceSourceDirectoryFixture();+ assertNodeResolutionControls(fixture);const result = await cli.run({- arguments: ["import-reference-source", root, "--json"],+ arguments: ["import-reference-source", fixture.root, "--json"],environment: {- HOME: workspace,- XDG_CONFIG_HOME: workspace,- XDG_CACHE_HOME: workspace,+ HOME: fixture.workspace,+ XDG_CONFIG_HOME: fixture.workspace,+ XDG_CACHE_HOME: fixture.workspace,},});expect(result.exitCode).toBe(0);- const graph = historicalSourceGraphSchema.parse(result.json);- expect(graph.parse_failures).toEqual([]);- expect(graph.relationships).toHaveLength(- imports.length + unresolved.length,+ assertGraphResolution(+ historicalSourceGraphSchema.parse(result.json),+ fixture,);- for (const [from, , to] of imports)- expect.soft(graph.relationships, from).toContainEqual({- from_path: from,- to,- kind: "requires",- resolution: "internal",- parse_state: "parsed",- });- for (const [from, , to] of unresolved)- expect.soft(graph.relationships, from).toContainEqual({- from_path: from,- to,- kind: "requires",- resolution: "unresolved",- parse_state: "parsed",- });- expect(- graph.entries.some((entry) => entry.path.includes("outside")),- ).toBe(false);},);},