Files
rea/tests/boundary/filesystem/javascript-applications/javascriptApplicationService.test.ts
T
6f267022ed fix(errors)!: raise container reader byte faults as malformed or truncated targets (#14265)
* feat(errors)!: add the TargetFailure model, its projection table and conformance registry

Introduce one domain-owned TargetFailure value whose kind alone derives
the public code, category, retryability, recovery and details, for CLI
and MCP alike. Selected-file malformed and truncated refusals are the
first area on it: AnalysisMalformedTargetError is replaced by
AnalysisTargetFailureError, and ParseFailure's byte-structure variants
are TargetFailure variants rather than a parallel type.

The shared stableArtifactParserFailureCli loop is replaced by a
declarative registry (tests/support/targetFailure/readers/*.ts) and one
generated suite that runs every registered case through the CLI and MCP.

BREAKING CHANGE: selected-file malformed and truncated refusals add
details.failure_kind, and a truncated target's remediation now says to
re-acquire the complete file instead of choosing another target. Codes
are unchanged. Affected operations: every operation that refuses a
selected file's malformed or truncated bytes, including the ELF, PE,
Mach-O, DWARF, Go, Rust, BEAM, pyc, devicetree, Apple IPS, kernel
module, binary hardening, managed PE/CLI and IL2CPP readers.

* test(managed): name the target failure error in the merged status test

* docs(reference): name the error CSV instead of linking a non-page file

* fix(tests): expect the path reason for non-regular dyld inputs

#14225 refuses a non-regular dyld input as ArtifactReaderFailure("path");
dylibFileLifetime still expected "format" and fails on main's shard 9.

* fix(tests): expect io, invariant and path where #14225 reclassified

stableArtifact expected "format" for an impossible descriptor byte count
(now io) and an invalid chunk size (now InternalInvariantError);
directoryArtifactReaderOpen expected "format" for a non-file entry (now
path, the same change as #14238). All three fail on main.

* fix(errors)!: raise container reader byte faults as malformed or truncated targets

Delete the ambiguous `format` reason from ArtifactReaderFailure and
ArtifactOperationError. Each container reader now raises its owner's
fact once, through malformedArtifact / truncatedArtifact, with format,
offset, field and measured extents. Short reads inside a measured extent
are read-coverage integrity failures, path-kind refusals are `path`,
foreign or recovery-requiring inputs are `unsupported`, host tool output
is `io`, and REA defects are InternalInvariantError.

The trace, NTFS journal, release exposure, web capture, native macOS and
web artifact adapters project the reader's parsed facts as
AnalysisTargetFailureError instead of invalid_request. Inventory
malformed, truncated, unsupported and cancelled reasons take their code
from the TargetFailure projection table, so a truncated container is
unsupported_target with failure_kind "truncated" on both paths.

BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact,
analyze_javascript_application, inspect_desktop_application,
inspect_keyed_archive, inspect_asset_catalog, inspect_nuget_nupkg,
trace_dylib_resolution, trace_web_module_imports and
trace_web_source_location report damaged container bytes as
unsupported_target (details.reason "malformed" or "truncated", with
failure_kind and format) instead of artifact_operation_failed with
reason "format", and a truncated container as unsupported_target instead
of truncated. inspect_playwright_trace, inspect_ntfs_journal,
audit_release_exposure, the web capture inspection operations and the
caller-selected import and source maps report damaged selected bytes as
unsupported_target instead of invalid_request. The `format` reason no
longer appears in details.reason.

* test(artifacts): expect target failure codes in compiled CLI and MCP suites

* fix(errors): give the integrity kind a schema-valid code and list the reference page

artifact_integrity_mismatch's projection schema requires declared and
calculated digests, which a TargetFailure of kind integrity does not
carry, so the kind now projects artifact_operation_failed with category
integrity_mismatch. The model test validates every kind's projection
against analysisErrorProjectionSchema. The reference page joins the
documentation sidebar.

* fix(artifacts): report a short carrier read as a changed file and keep unsupported desktop probes local

A Bun or Node SEA short read inside a range already checked against the
measured size meant the file changed, not that it was truncated. The
carrier range reader and Bun's readExact now raise read-coverage
integrity for it, and keep 'outside the file' as the truncated case.
DesktopFileInspection records an unsupported managed-metadata probe as a
row issue again, so later file checks still run.

* test(errors): register PE DOS-signature and truncated IPS refusals and drop their per-command copies

The non-MZ PE imports and load-config cases (PE32/PE32+, ZZ and high-bit
signatures) and the truncated Apple IPS body move into the conformance
registry, which runs them through the CLI and MCP and now also checks
that a refusal leaves the selected file unchanged. The per-command tests
keep only their valid-image controls.

* feat(errors)!: make failure_kind the identifier and derive code and retry from it

Apply the owner review on #14239 to the TargetFailure model:
- remove details.format_failure; failure_kind is the only identifier;
- give integrity, conflict and io their own codes
  (target_integrity_mismatch, input_conflict, host_io_failed) and derive
  inventory malformed, truncated and unsupported codes from the same table;
- add a retry hint (none, backoff, after_change) derived from the kind,
  with io refined by its transient errno fact; retryable stays the
  unchanged-retry flag and is true exactly for backoff;
- rename the limit-cut result code and category truncated to partial;
- drop cancelled and resource from the target kinds and spell
  identifiers in American English (unrecognized);
- return a target failure a tool handler throws as a projected isError
  result instead of letting the SDK flatten it to text.

BREAKING CHANGE: details.format_failure is removed (read
details.failure_kind). The truncated result code and category are now
partial. Target integrity failures report target_integrity_mismatch,
host read failures host_io_failed and disagreeing inputs input_conflict.
Inventory operations (inventory_artifact, inspect_artifact,
extract_artifact and the other inventory callers) report truncated
container bytes as unsupported_target. Every target failure carries a
top-level retry hint.

* fix(artifacts): keep changed-file short reads, invalid offsets and EOF declarations apart

PyInstaller reads inside the measured size, and .NET bundle manifest
refills, now raise read-coverage integrity on a zero-byte read instead of
truncated. A .NET bundle field and a Godot PCK directory entry that extend
past the file are truncated (with offset and extents) instead of
malformed. An absent or invalid ASAR packed offset is malformed; only a
valid range past the archive is truncated. The .NET manifest string
offset is reported in file coordinates.

* fix(artifacts): verify the carrier before blaming a short read on the bytes

The NTFS $MFT decoder, positional members (FIT, uImage, Bun, Deno) and
.NET bundle members now re-verify the source before reporting a short
stream as malformed, so a file that changed during the read reports the
change. The truncation site builds the model's measured extent.

* docs(android): name unsupported_target for truncated boot image structures

* fix(errors)!: report a target that changed during the read as failure_kind changed

Inventory integrity failures whose check means the target moved under the
read (container, member and unpacked-entry identity, read coverage,
traversal coverage) now take the model's changed projection: code
artifact_changed, retry backoff and details.failure_kind changed. A
selected target that no longer matches the one the session admitted gets
its own admitted-identity check and keeps its reopen recovery.

BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and
the other inventory operations report a target that changed during the
read as artifact_changed (retryable, failure_kind changed) instead of
artifact_operation_failed. Admission-identity refusals report
integrity_check admitted-identity instead of container-identity.

* test(artifacts): expect admitted-identity for selections replaced before admission

A selected source replaced before admission fails the admitted-identity check rather than container-identity since the changed/admitted split.

* test(go): name the fixture and result when an MZ carrier is not refused through MCP

* test(web): expect the partial code for a refused source-map admission

The limit-cut code is partial; this Windows-lane test arrived from main with the old truncated spelling.

* test(errors): check the MCP target failure as the text clients receive

The stdio transport removes the private structured carrier from every isError result, so the conformance suite asserted a field that never reaches clients and failed every case. The projected diagnostic is checked from the JSON text instead.

* test(artifacts): expect artifact_changed when selected bytes change after inventory

Bundle resources replaced after open and unselected JavaScript sources rewritten after inventory now fail a change check, so they report artifact_changed with retry backoff rather than artifact_operation_failed.

* fix(errors): report a session digest mismatch as admitted-identity

The digest the session admitted does not change when the same request is
repeated, so targetDigestChangedFailure was inviting a backoff retry that
fails the same way. It now names admitted-identity, which stays
artifact_operation_failed and not retryable, and tells the caller to reopen.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(artifacts): classify unused PyInstaller compressed input as layout

zlib stops at the first complete stream, so a declared span that arrives
intact but is not fully consumed is trailing junk or a second stream, not
a file that changed. A source that ends before that span stays read-coverage.
The cached-carrier test replaces the file with a different size so a shared
timestamp cannot hide the rewrite.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* test(applications): expect unsupported_target for a damaged trace stream

A trace member whose CRC fails is a malformed zip target. The partial
Evidence assertion now checks that code, failure_kind and format.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* test(dylib): expect admitted-identity when the opened target is replaced

The session keeps the digest it admitted, so replacing the executable and
repeating trace_dylib_resolution is not a retryable container change.

Co-authored-by: morluto <morluto@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-11-24 21:17:43 -05:00

612 lines
22 KiB
TypeScript

import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { parseEvidence } from "../../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { writeJavaScriptSourceSelectionFixture } from "../../../fixtures/javascriptSourceSelection.js";
import { ArtifactReaderFailure } from "../../../../src/resources/ArtifactReader.js";
import { scanCanonicalArtifactInventory } from "../../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
import {
analyzeJavaScriptApplication,
readJavaScriptArtifactFiles,
} from "../../../support/javascriptApplicationScope.js";
import { createJavaScriptArtifactReader } from "../../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
import { createJavaScriptSourceAnalysis } from "../../../../src/javascript/analysis/JavaScriptSourceAnalysis.js";
import { analyzeAndAdoptJavaScriptArtifactFiles } from "../../../../src/application/javascript/JavaScriptArtifactAnalysis.js";
import { createJavaScriptSemanticGraphProjection } from "../../../../src/application/javascript/JavaScriptSemanticGraphBuilder.js";
import { immutableArtifactGraph } from "../../../fixtures/javascriptArtifactGraph.js";
import type { JavaScriptApplicationGraph } from "../../../../src/domain/javascript/javascriptApplicationGraph.js";
import { writeFixtureFiles } from "../../../support/javascriptApplicationFixture.js";
describe("JavaScript source selection cancellation boundary", () => {
it("keeps unselected files outside scope when the real worker cancels after the last selected file", async () => {
const root = await createTestTempDirectory(
"rea-js-selected-last-cancellation-",
);
await writeJavaScriptSourceSelectionFixture(root);
const snapshot = await scanCanonicalArtifactInventory(root, {});
const reader = createJavaScriptArtifactReader(root, "directory");
const controller = new AbortController();
const reason = { request: "caller cancelled selected sources" };
const sourcePaths = ["main.mjs"];
try {
const files = await readJavaScriptArtifactFiles(
reader,
snapshot,
controller.signal,
sourcePaths,
);
const worker = await createJavaScriptSourceAnalysis(
{ heapMb: 512, timeoutMs: 30_000 },
1,
);
let outcome: Awaited<
ReturnType<typeof analyzeAndAdoptJavaScriptArtifactFiles>
>;
try {
const realWorker = worker.analyze.bind(worker);
outcome = await analyzeAndAdoptJavaScriptArtifactFiles(
files,
{
analyze: async (...args) => {
const result = await realWorker(...args);
controller.abort(reason);
return result;
},
},
createJavaScriptSemanticGraphProjection(),
async () => {},
controller.signal,
);
} finally {
await worker.close();
}
expect(outcome.interruption).toBeInstanceOf(AnalysisCancelledError);
expect(outcome.interruption?.cause).toBe(reason);
const unselected = outcome.analysis.files.filter(
({ file }) =>
!file.text.included && file.text.reason === "outside-analysis-scope",
);
expect(unselected).toHaveLength(5);
expect(
unselected.every(
({ analysis_failure }) => analysis_failure === undefined,
),
).toBe(true);
expect(
outcome.analysis.files.find(({ file }) => file.path === "main.mjs")
?.javascript,
).toMatchObject({ parse_status: "complete" });
} finally {
await reader.close();
}
});
});
it("resolves lazy package and JSON facts without completing their skipped observations", async () => {
const root = await createTestTempDirectory("rea-js-lazy-json-facts-");
await writeFixtureFiles(root, {
"app/first.cjs": 'require("late-pkg"); require("./config.json");\n',
"app/second.cjs": "module.exports = 2;\n",
"app/config.json": "true",
"app/node_modules/late-pkg/package.json": JSON.stringify({
main: "index.cjs",
}),
"app/node_modules/late-pkg/index.cjs": "module.exports = 1;\n",
"app/vendor/package.json": JSON.stringify({ main: "vendor.cjs" }),
});
const snapshot = await scanCanonicalArtifactInventory(root, {});
const reader = createJavaScriptArtifactReader(root, "directory");
const controller = new AbortController();
const reason = { request: "stop before structured files" };
const sourcePaths = [
"app/first.cjs",
"app/second.cjs",
"app/node_modules/late-pkg/package.json",
"app/node_modules/late-pkg/index.cjs",
"app/config.json",
];
try {
const files = await readJavaScriptArtifactFiles(
reader,
snapshot,
controller.signal,
sourcePaths,
);
const worker = await createJavaScriptSourceAnalysis(
{ heapMb: 512, timeoutMs: 30_000 },
1,
);
let outcome: Awaited<
ReturnType<typeof analyzeAndAdoptJavaScriptArtifactFiles>
>;
let completedWorkers = 0;
const projection = createJavaScriptSemanticGraphProjection();
try {
const realWorker = worker.analyze.bind(worker);
outcome = await analyzeAndAdoptJavaScriptArtifactFiles(
files,
{
analyze: async (...args) => {
const result = await realWorker(...args);
completedWorkers += 1;
if (completedWorkers === 2) controller.abort(reason);
return result;
},
},
projection,
async () => {},
controller.signal,
);
} finally {
await worker.close();
}
expect(completedWorkers).toBe(2);
expect(outcome.interruption).toBeInstanceOf(AnalysisCancelledError);
expect(outcome.interruption?.cause).toBe(reason);
const analysisByPath = new Map(
outcome.analysis.files.map((entry) => [entry.file.path, entry]),
);
for (const path of sourcePaths.slice(0, 2))
expect(analysisByPath.get(path)?.javascript).toMatchObject({
parse_status: "complete",
});
for (const path of [
"app/node_modules/late-pkg/package.json",
"app/config.json",
])
expect(analysisByPath.get(path)?.analysis_failure?.status).toBe(
"not-started",
);
expect(
outcome.analysis.packages.some(
({ path }) => path === "app/node_modules/late-pkg/package.json",
),
).toBe(false);
expect(
outcome.analysis.json_modules.some(
({ path }) => path === "app/config.json",
),
).toBe(false);
const graph = await immutableArtifactGraph(
snapshot,
files,
outcome.analysis,
);
expect(graph.coverage.status).toBe("partial");
const packageRelationships = graph.edges.filter(
({ relation, properties }) =>
relation === "imports" &&
properties.module_link_kind === "require" &&
properties.specifier === "late-pkg",
);
expect(packageRelationships).toHaveLength(1);
expect(packageRelationships[0]?.properties).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/late-pkg/index.cjs",
});
const jsonRelationships = graph.edges.filter(
({ relation, properties }) =>
relation === "imports" &&
properties.module_link_kind === "require" &&
properties.specifier === "./config.json",
);
expect(jsonRelationships).toHaveLength(1);
expect(jsonRelationships[0]?.properties).toMatchObject({
target_file_kind: "json",
target_json_status: "included",
});
for (const [path, operation] of [
["app/node_modules/late-pkg/package.json", "parse-package-json"],
["app/config.json", "parse-json-module"],
] as const)
expectSkippedStructuredSource(graph, path, operation);
const excluded = analysisByPath.get("app/vendor/package.json");
expect(excluded?.file.text).toMatchObject({
included: false,
reason: "outside-analysis-scope",
});
expect(excluded?.analysis_failure).toBeUndefined();
expect(
unknownScopeObservation(graph, "app/vendor/package.json"),
).toMatchObject({
properties: { operation: "select-javascript-sources" },
evidence: { confidence: "unknown", state: "unavailable" },
});
} finally {
await reader.close();
}
});
const unknownScopeObservation = (
graph: JavaScriptApplicationGraph,
path: string,
) =>
graph.nodes
.filter(({ kind }) => kind === "unknown")
.flatMap(({ observations }) => observations)
.find(({ properties }) => properties.path === path);
const expectSkippedStructuredSource = (
graph: JavaScriptApplicationGraph,
path: string,
operation: string,
): void => {
expect(
graph.nodes.some(
({ kind, observations }) =>
kind === "package" &&
observations.some(({ properties }) => properties.path === path),
),
).toBe(false);
expect(
graph.nodes
.filter(({ kind }) => kind === "artifact")
.flatMap(({ observations }) => observations)
.find(({ properties }) => properties.path === path),
).toMatchObject({ properties: { json_parse_status: null } });
expect(unknownScopeObservation(graph, path)).toMatchObject({
properties: { operation, analysis_status: "not-started" },
});
};
describe("Selected JavaScript source failure diagnostics", () => {
it("analyzes selected files in first-request order and reports only selected progress", async () => {
const root = await createTestTempDirectory("rea-js-selected-priority-");
await writeJavaScriptSourceSelectionFixture(root);
await writeFile(join(root, "z-later.mjs"), "export const later = 1;\n");
const progress: string[] = [];
const result = await analyzeJavaScriptApplication(
{
input_path: root,
source_paths: ["z-later.mjs", "main.mjs", "z-later.mjs"],
},
{
progress: {
report: async (event) => {
if (event.phase === "parse_javascript_source")
progress.push(event.message);
},
},
},
);
if (!result.ok) throw result.error;
const analysis = javascriptApplicationAnalysisResultSchema.parse(
result.value.normalized_result,
);
expect(analysis.source_selection).toEqual({
requested_paths: ["z-later.mjs", "main.mjs", "z-later.mjs"],
unselected_files: 5,
});
expect(analysis.statistics.parsed_javascript_files).toBe(2);
expect(progress).toEqual([
expect.stringContaining("z-later.mjs"),
expect.stringContaining("main.mjs"),
]);
});
it("verifies unselected bytes against the inventoried identity without decoding them", async () => {
const root = await createTestTempDirectory("rea-js-unselected-integrity-");
await writeJavaScriptSourceSelectionFixture(root);
const result = await analyzeJavaScriptApplication(
{ input_path: root, source_paths: ["main.mjs"] },
{
progress: {
report: async (event) => {
if (event.phase === "read_javascript_artifacts")
await writeFile(
join(root, "vendor.js"),
"changed after inventory\n",
);
},
},
},
);
if (result.ok)
throw new Error(
"Unselected content changes must still fail integrity verification",
);
expect(projectAnalysisError(result.error)).toMatchObject({
code: "artifact_changed",
retry: "backoff",
details: { reason: "integrity", failure_kind: "changed" },
});
});
it("retains selected facts and unselected scope after cancellation between selected sources", async () => {
const root = await createTestTempDirectory("rea-js-selected-cancellation-");
await writeJavaScriptSourceSelectionFixture(root);
await writeFile(join(root, "z-later.mjs"), "export const later = 1;\n");
const controller = new AbortController();
const reason = { request: "caller cancelled selected sources" };
const source_paths = ["main.mjs", "z-later.mjs"];
const result = await analyzeJavaScriptApplication(
{ input_path: root, source_paths },
{
signal: controller.signal,
progress: {
report: async (event) => {
if (
event.phase === "parse_javascript_source" &&
event.message.includes("z-later.mjs")
)
controller.abort(reason);
},
},
},
);
if (result.ok) throw new Error("Expected selected-source cancellation");
expect(result.error.cause).toBe(reason);
expect(projectAnalysisError(result.error).code).toBe("cancelled");
const evidence = parseEvidence(result.error.partialObservation);
const partial = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
);
expect(partial.source_selection).toEqual({
requested_paths: source_paths,
unselected_files: 5,
});
expect(
partial.semantic_graph.nodes.some(
({ kind, label }) => kind === "function" && label === "selected",
),
).toBe(true);
expect(partial.statistics.parsed_javascript_files).toBe(1);
expect(partial.graph.coverage.status).toBe("partial");
expect(
partial.graph.nodes
.flatMap(({ observations }) =>
observations.map(({ properties }) => properties),
)
.filter(
(properties) => properties.text_status === "outside-analysis-scope",
),
).toHaveLength(5);
});
});
describe("JavaScript application failure diagnostics", () => {
it("identifies the rejected result field in caller-visible diagnostics", async () => {
const inputPath = await createTestTempDirectory("rea-js-schema-failure-");
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
const cause = new z.ZodError([
{
code: "custom",
path: ["semantic_graph", "nodes", 42, "application_node_ids", 0],
message: "Semantic node references an absent application node",
},
]);
const result = await analyzeJavaScriptApplication(
{ input_path: inputPath, format: "directory" },
{
progress: {
report: async (event) => {
if (event.terminal) throw cause;
},
},
},
);
if (result.ok) throw new Error("Expected analysis failure");
expect(result.error.cause).toBe(cause);
expect(projectAnalysisError(result.error)).toMatchObject({
code: "unreadable_output",
details: {
operation: "analyze_javascript_application",
reason: expect.stringMatching(
/schema.*1 issue.*\/semantic_graph\/nodes\/42\/application_node_ids\/0.*custom/i,
),
},
});
});
it("retains unexpected failures and their input identity in caller-visible diagnostics", async () => {
const inputPath = await createTestTempDirectory("rea-js-failure-");
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
const cause = new RangeError("Invalid string length");
// Retain the original failure locally, but never serialize its object graph.
cause.cause = cause;
const result = await analyzeJavaScriptApplication(
{ input_path: inputPath, format: "directory" },
{
progress: {
report: async (event) => {
if (event.terminal) throw cause;
},
},
},
);
if (result.ok) throw new Error("Expected analysis failure");
expect(result.error.cause).toBe(cause);
expect(projectAnalysisError(result.error)).toMatchObject({
code: "execution_failure",
details: {
provider_id: "rea-javascript-application",
operation: "analyze_javascript_application",
diagnostics: {
input_path: inputPath,
error_name: "RangeError",
error_message: "Invalid string length",
},
},
});
const projection = projectAnalysisError(result.error);
expect(JSON.parse(JSON.stringify(projection))).toEqual(projection);
});
it("reports a missing selection as invalid input, not an engine failure", async () => {
const root = await createTestTempDirectory("rea-js-missing-");
const result = await analyzeJavaScriptApplication({
input_path: join(root, "missing"),
format: "directory",
});
if (result.ok) throw new Error("Expected missing artifact failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
details: {
operation: "analyze_javascript_application",
issues: [{ path: ["input_path"], reason: "invalid_value" }],
},
});
});
it.each(["reported failure", null])(
"retains non-Error failures (%s)",
async (cause) => {
const inputPath = await createTestTempDirectory("rea-js-non-error-");
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
const result = await analyzeJavaScriptApplication(
{ input_path: inputPath, format: "directory" },
{
progress: {
report: async (event) => {
if (event.terminal) throw cause;
},
},
},
);
if (result.ok) throw new Error("Expected analysis failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "execution_failure",
details: {
diagnostics: {
error_name: "UnknownError",
error_message:
typeof cause === "string"
? cause
: "JavaScript analysis failed with a non-Error value",
},
},
});
},
);
it.each([new Error("x".repeat(10_000)), "y".repeat(10_000)])(
"preserves long failure messages through JSON projection (%#)",
async (cause) => {
const inputPath = await createTestTempDirectory("rea-js-oversized-");
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
const message = cause instanceof Error ? cause.message : cause;
const result = await analyzeJavaScriptApplication(
{ input_path: inputPath, format: "directory" },
{
progress: {
report: async (event) => {
if (event.terminal) throw cause;
},
},
},
);
if (result.ok) throw new Error("Expected analysis failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "execution_failure",
details: {
diagnostics: {
error_message: message,
},
},
});
const projection = projectAnalysisError(result.error);
expect(JSON.parse(JSON.stringify(projection))).toEqual(projection);
},
);
});
describe("JavaScript application cleanup diagnostics", () => {
it("preserves cleanup and a complete inventory when translating reader failures", async () => {
const inputPath = await createTestTempDirectory("rea-js-cleanup-failure-");
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
const inventory = await scanCanonicalArtifactInventory(inputPath);
const cleanup = {
reason: "reader remains open",
resources: [`JavaScript artifact reader for ${inputPath}`],
};
const partialObservation = {
kind: "artifact-inventory" as const,
inventory,
};
const failure = new ArtifactReaderFailure("io", "Reader cleanup failed", {
cleanup,
partialObservation,
});
const result = await analyzeJavaScriptApplication(
{ input_path: inputPath, format: "directory" },
{
progress: {
report: async () => {
throw failure;
},
},
},
);
if (result.ok) throw new Error("Expected reader failure");
expect(result.error).toMatchObject({
_tag: "ArtifactOperationError",
cleanup,
partialObservation,
});
});
});
describe("JavaScript application symbolic coverage", () => {
it("analyzes sources spreading recursive call results while preserving coverage limits and independent endpoints", async () => {
const root = await createTestTempDirectory("rea-js-recursive-spread-");
await writeFile(
join(root, "self.js"),
'function f(o) { const stay = f(o); return { ...stay, c: stay.sc.startsWith("k") }; }\nfetch("/kept-self");\n',
);
await writeFile(
join(root, "mutual.js"),
'function a(o) { const stay = b(o); return { ...stay, c: stay.sc.startsWith("k") }; }\nfunction b(o) { const stay = a(o); return { ...stay, c: stay.sc.startsWith("k") }; }\nfetch("/kept-mutual");\n',
);
const result = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
source_paths: ["self.js", "mutual.js"],
});
if (!result.ok) throw result.error;
const normalized = javascriptApplicationAnalysisResultSchema.parse(
result.value.normalized_result,
);
expect(normalized.statistics).toMatchObject({
parsed_javascript_files: 2,
parse_failures: 0,
});
const endpoints = normalized.graph.nodes
.filter(({ kind }) => kind === "endpoint")
.flatMap(({ observations }) =>
observations.map(({ properties }) => properties.value),
)
.sort();
expect(endpoints).toEqual(["/kept-mutual", "/kept-self"]);
const assetObservations = normalized.graph.nodes
.filter(({ kind }) => kind === "javascript-asset")
.flatMap(({ observations }) => observations);
for (const path of ["self.js", "mutual.js"]) {
const observation = assetObservations.find(
({ properties }) => properties.path === path,
);
expect(observation?.properties).toMatchObject({
parse_status: "partial",
analysis_coverage: {
examination: {
status: "limited",
electron_call_paths_limited: true,
},
},
});
}
});
});