feat(javascript): report observed export property presence (#1160)

* feat(javascript): report observed export property presence

Extend compare_javascript_export_shapes so each retained return variant
lists observed property names and each change reports presence independently
of value resolution. Complete parent coverage classifies one-sided names as
added or removed even when static values stay unknown.

Fixes #725

* test(javascript): match unknown export-shape values by availability

Nested availability objects include a reason when values stay unresolved.
Assert availability through objectContaining so presence-only added and
removed rows still verify unknown values.

* fix(javascript): preserve uncertain export property presence and locations

* fix(javascript): normalize presence and preserve local property coverage

* fix(javascript): require present discriminants for return pairing

* fix(javascript): normalize retained shapes before comparison

* refactor(javascript): share return projection with executable examples

* fix(javascript): localize uncertainty for missing mutated slots

* fix(javascript): bind advertised export examples to exact artifacts

* fix(javascript): keep uncertain property flow as candidates

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Matt Van Horn
2026-10-09 18:30:31 +08:00
committed by GitHub
co-authored by morluto
parent 04aef6df33
commit 45e3edc17f
25 changed files with 1552 additions and 113 deletions
@@ -32,7 +32,7 @@ import {
resolveArtifactPathByContext,
type ArtifactPathResolution,
} from "./JavaScriptArtifactPathResolution.js";
import { projectJavaScriptExportReturnShapes } from "./JavaScriptReturnShapeProjection.js";
import { projectJavaScriptExportReturnShapes } from "../../domain/javascript/javascriptExportReturnShapeProjection.js";
import type { JavaScriptModuleSemanticIr } from "./JavaScriptArtifactAnalysisTypes.js";
@@ -69,7 +69,10 @@ const projectValue = (input: ValueProjectionInput): void => {
source: target,
target: slot,
relation: "writes-property",
resolution: value.unknownProperties ? "candidate" : "resolved",
resolution:
value.unknownProperties || property.presence === "unknown-coverage"
? "candidate"
: "resolved",
});
projectValue({
context,
+3 -2
View File
@@ -155,13 +155,14 @@ export const APPLICATION_TOOL_CONTRACTS = [
name: "compare_javascript_export_shapes",
...toolContractMetadata("compare_javascript_export_shapes"),
description:
"Compare static return shapes for one exact module/export selector on each authenticated JavaScript Application Graph supplied as inline Evidence or exact same-session retained references. Variants pair only by reciprocal unique literal discriminants; dynamic values, incomplete properties, and ambiguous variants remain unknown. Reports JSON Pointer changes without executing JavaScript; runtime behavior requires a separate agent-run probe.",
"Compare static return shapes for one exact module/export selector on each authenticated JavaScript Application Graph supplied as inline Evidence or exact same-session retained references. Variants pair only by reciprocal unique literal discriminants. Each retained variant lists observed return-property names even when values stay unknown. Presence (present, absent, or unknown-coverage) is separate from value resolution: a name present on only one paired shape is added or removed when parent-property coverage is complete on both sides, including when the static value is unresolved. Dynamic values, incomplete parent coverage, and unpaired variants remain unknown. Reports JSON Pointer changes without executing JavaScript; runtime behavior requires a separate agent-run probe.",
kind: "application",
inputSchema: compareJavaScriptExportShapesRequestSchema,
outputSchema: exportShapeComparisonOutputSchema,
examples: [
{
title: "Compare one exact parser export without execution",
title:
"Report observed return-property presence when static values stay unknown",
input: JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE,
},
{
@@ -102,15 +102,7 @@ export const SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE = {
application: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE,
};
/** Exact static return-shape comparison with both Evidence records inline. */
export const JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE = {
left: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE,
right: reconciliationEvidence,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
};
export { JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE } from "./javascriptExportShapeComparisonExample.js";
/** Full-Evidence compatibility fixture used by pure domain and adapter tests. */
export const JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE = {
@@ -0,0 +1,270 @@
import { createEvidence } from "../../domain/evidence.js";
import { createWebTextArtifact } from "../../domain/webContentArtifact.js";
import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
import { projectJavaScriptExportReturnShapes } from "../../domain/javascript/javascriptExportReturnShapeProjection.js";
import {
completeApplicationCoverage,
partialApplicationCoverage,
} from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "../../domain/javascript/javascriptApplicationGraph.js";
import {
createJavaScriptSemanticGraph,
createJavaScriptSemanticGraphNode,
} from "../../domain/javascript/javascriptSemanticGraph.js";
import { JAVASCRIPT_SEMANTIC_RELATION_FAMILIES } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
// Inventory identities/counters captured from real analysis of these two sources.
// The inline example retains only source-derived export facts, with explicit gaps.
const captures = {
count: {
input_path: "/examples/javascript-export-presence/left",
root_artifact_sha256:
"5005ebc2f35719a2fc014f19a81c669f3a1ab471b7245ef6985a111b6845a747",
inventory_manifest_id:
"agm_f30ded9a83d43a3980417bbe63dfad569e83386f243c4d6a01af0166372cb9e6",
inventory_graph_sha256:
"4b8aceaf67e43fd8317ec1f5fd1df5235f8fa402335accf011683e008c6bc62c",
},
total: {
input_path: "/examples/javascript-export-presence/right",
root_artifact_sha256:
"269ae72a601ad5ac02f1c2dda6ff9accffa2d2e4f4a9e406facee0d5a78a5377",
inventory_manifest_id:
"agm_d3ceaa1af38fb3474070ca25c0d4644282e5fb7d5824cee3e3a81391481e9fc1",
inventory_graph_sha256:
"3e9bc926951480c35385efe5650d9d781631bd74c37a523d543b5fbe06b01ce6",
},
};
const summary = {
browser_windows: 0,
explicit_web_preferences: 0,
preload_entrypoints: 0,
context_bridge_apis: 0,
exposed_api_members: 0,
ipc: {
operations: 0,
literal_channels: 0,
dynamic_channel_operations: 0,
renderer_transmissions: 0,
renderer_listeners: 0,
main_handlers: 0,
paired_renderer_transmissions: 0,
ambiguous_renderer_transmissions: 0,
unpaired_literal_renderer_transmissions: 0,
},
sender_validation_observations: 0,
utility_processes: 0,
resolved_utility_entrypoints: 0,
native_addon_bindings: 0,
resolved_native_addon_bindings: 0,
};
const statistics = {
relevant_files: 1,
nested_asar_containers: 0,
text_bytes_read: 60,
invalid_utf8_files: 0,
parsed_javascript_files: 1,
visited_ast_nodes: 12,
findings: 1,
modules: 0,
parse_failures: 0,
truncated_scopes: 0,
};
const modulePath = "parser.mjs";
const limitations = [
"This example retains export and return-shape facts only; other application and semantic relationships are omitted.",
];
const exampleEvidence = (property: "count" | "total") => {
const metadata = captures[property];
const source = `export default () => ({ kind: "results", ${property}: query() });\n`;
const artifact = createWebTextArtifact(source, "text/javascript");
const ir = analyzeJavaScriptSemantics(source);
const link = ir.moduleLinks.find(
({ exportedName }) => exportedName === "default",
);
if (link === undefined)
throw new Error("Example source must define a default export");
const coverage =
ir.coverage.status === "complete"
? completeApplicationCoverage()
: partialApplicationCoverage([], ir.coverage.omittedCount);
const projection = projectJavaScriptExportReturnShapes({
ir,
link,
modulePath,
baseCoverage: coverage,
});
if (projection === null)
throw new Error("Example export must retain return shapes");
const evidence = {
artifact: {
available: true,
artifact_id: `art_${artifact.sha256}`,
sha256: artifact.sha256,
},
location: {
available: true,
value: { kind: "source-range", source: modulePath, ...link.location },
},
extractor: {
name: "rea-javascript-artifact-reconstruction",
version: "1",
operation: "recover-module-export",
executable_sha256: null,
},
coverage,
limitations: ir.limitations,
evidence_ids: [],
};
const exported = createJavaScriptApplicationNode({
kind: "javascript-module",
identity: {
strategy: "artifact-local-key",
stability: "artifact-version",
artifact_sha256: artifact.sha256,
namespace: "module-export",
key: `${metadata.root_artifact_sha256}:${modulePath}:default`,
},
observations: [
{
label: `${modulePath}:default`,
properties: {
semantic_role: "export-binding",
module_path: modulePath,
relationship_kind: link.kind,
exported_name: link.exportedName,
local_name: link.localName,
imported_name: link.importedName,
declared_specifier: link.specifier,
},
evidence: {
...evidence,
authority: "ast-static-analysis",
state: "observed",
confidence: "exact",
},
},
{
label: `${modulePath}:default:return-shapes`,
properties: projection.properties,
evidence: {
...evidence,
authority: "static-relationship-inference",
state: "inferred",
confidence: "high",
location: {
available: true,
value: {
kind: "source-range",
source: modulePath,
...projection.range,
},
},
extractor: {
...evidence.extractor,
operation: "recover-export-return-shapes",
},
coverage: projection.coverage,
limitations: projection.limitations,
},
},
],
});
const graph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: [exported.node_id],
nodes: [exported],
edges: [],
coverage: partialApplicationCoverage([], null),
limitations,
});
const module = createJavaScriptSemanticGraphNode({
kind: "module",
identity: {
artifact_sha256: artifact.sha256,
module_path: modulePath,
source_range: null,
role_key: "example-module",
},
function_node_id: null,
application_node_ids: [exported.node_id],
label: modulePath,
properties: {},
evidence: {
...evidence,
authority: "ast-static-analysis",
state: "observed",
confidence: "exact",
},
});
const semanticGraph = createJavaScriptSemanticGraph({
schema: "JavaScriptSemanticRelationGraph",
root_artifact_sha256: metadata.root_artifact_sha256,
application_graph_id: graph.graph_id,
root_node_ids: [module.node_id],
nodes: [module],
relations: [],
fingerprints: [],
unknowns: [],
coverage: {
status: "unknown",
truncated: false,
omitted_nodes: null,
omitted_relations: null,
limits: [],
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
family,
status: "unknown",
retained_relations: 0,
omitted_relations: null,
unknown_ids: [],
})),
},
limitations,
});
const result = javascriptApplicationAnalysisResultSchema.parse({
...metadata,
format: "directory",
graph,
semantic_graph: semanticGraph,
summary,
statistics,
limitations,
});
return createEvidence(
{
path: result.input_path,
sha256: result.root_artifact_sha256,
format: "directory",
},
{
id: "rea-javascript-application",
name: "REA JavaScript application analyzer",
version: "1",
},
{
predicateType: "rea.javascript-application-analysis",
operation: "analyze_javascript_application",
parameters: {},
result,
confidence: "derived",
authority: "shipped-artifact",
limitations,
},
);
};
/** Source-derived tagged exports with known presence and unresolved values. */
export const JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE = {
left: exampleEvidence("count"),
right: exampleEvidence("total"),
left_module_path: modulePath,
left_export_name: "default",
right_module_path: modulePath,
right_export_name: "default",
};
@@ -1,30 +1,31 @@
import { jsonObjectSchema, jsonValueSchema } from "../../domain/jsonValue.js";
import { jsonObjectSchema, jsonValueSchema } from "../jsonValue.js";
import {
partialApplicationCoverage,
truncatedApplicationCoverage,
} from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
type ApplicationCoverage,
} from "./javascriptApplicationEvidenceSchemas.js";
import type {
JavaScriptSemanticCallable,
JavaScriptSemanticModuleLink,
} from "../../domain/javascript/javascriptSemanticIr.js";
import { flattenSemanticReturnValue } from "../../domain/javascript/javascriptSemanticReturns.js";
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactGraphCoverage } from "./JavaScriptArtifactGraphContext.js";
import type { JavaScriptModuleSemanticIr } from "./JavaScriptArtifactAnalysisTypes.js";
JavaScriptSemanticIr,
} from "./javascriptSemanticIr.js";
import { flattenSemanticReturnValue } from "./javascriptSemanticReturns.js";
import type { JavaScriptSourceRange } from "./javascriptStaticAnalysisTypes.js";
/** Return-shape facts and coverage inferred for one exported callable. */
export interface JavaScriptReturnShapeProjection {
readonly properties: ReturnType<typeof jsonObjectSchema.parse>;
readonly range: JavaScriptSourceRange;
readonly coverage: JavaScriptArtifactGraphCoverage;
readonly coverage: ApplicationCoverage;
readonly limitations: readonly string[];
}
/** Project one exact export/callable link into shallow bounded graph values. */
/** Project one exact export/callable link into inert return-shape observations. */
export const projectJavaScriptExportReturnShapes = (input: {
readonly ir: JavaScriptModuleSemanticIr;
readonly ir: Pick<JavaScriptSemanticIr, "callables" | "limitations">;
readonly link: JavaScriptSemanticModuleLink;
readonly modulePath: string;
readonly baseCoverage: JavaScriptArtifactGraphCoverage;
readonly baseCoverage: ApplicationCoverage;
}): JavaScriptReturnShapeProjection | null => {
if (input.link.callableId === null || input.link.exportedName === null)
return null;
@@ -17,6 +17,7 @@ import {
} from "./javascriptExportShapeSelection.js";
import {
buildJavaScriptExportShapeChanges,
buildJavaScriptExportShapeInventories,
hasPartialJavaScriptExportPropertyCoverage,
pairJavaScriptExportShapeVariants,
type JavaScriptExportShapePairing,
@@ -56,6 +57,11 @@ export const compareJavaScriptExportShapes = (
);
const changes = allChanges;
const omittedChanges = 0;
const propertyInventories = buildJavaScriptExportShapeInventories({
pairing,
leftShapes: leftRetained.shapes,
rightShapes: rightRetained.shapes,
});
const coverage = comparisonCoverage({
input,
left,
@@ -70,6 +76,7 @@ export const compareJavaScriptExportShapes = (
const semantic = {
left: left.selection,
right: right.selection,
property_inventories: propertyInventories,
summary: summarize(allChanges),
changes,
coverage,
@@ -2,7 +2,12 @@ import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
/** Canonically encode one export-shape comparison value. */
/**
* Canonically encode one export-shape comparison value.
*
* Comparison identifiers hash the full result semantics, including each
* change's presence object and the per-variant property inventories.
*/
export const canonicalExportShapeValue = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
@@ -1,6 +1,9 @@
import { expect, it } from "vitest";
import { projectedExportReturnShapesSchema } from "./javascriptExportShapeComparisonSchemas.js";
import {
javaScriptExportShapeComparisonChangeSchema,
projectedExportReturnShapesSchema,
} from "./javascriptExportShapeComparisonSchemas.js";
const projectionWithField = (field: unknown) => ({
semantic_role: "export-return-shapes",
@@ -29,6 +32,40 @@ const projectionWithField = (field: unknown) => ({
},
});
it("rejects a comparison change object missing presence", () => {
const digest = "a".repeat(64);
const change = {
change_id: `jesc_change_${digest}`,
status: "added",
path: "/total",
discriminant: { path: "/kind", value: "results" },
left: { availability: "absent" },
right: {
availability: "unknown",
reason: "Static field value is unknown.",
},
left_source_range: {
start: { line: 4, column: 9 },
end: { line: 4, column: 48 },
},
right_source_range: {
start: { line: 4, column: 9 },
end: { line: 4, column: 62 },
},
evidence_links: [`ev_${digest}`, `ev_${"b".repeat(64)}`],
limitations: [],
};
expect(
javaScriptExportShapeComparisonChangeSchema.safeParse(change).success,
).toBe(false);
expect(
javaScriptExportShapeComparisonChangeSchema.safeParse({
...change,
presence: { left: "absent", right: "present" },
}).success,
).toBe(true);
});
it("parses projected fields into literal, union, or unknown values", () => {
expect(
projectedExportReturnShapesSchema.safeParse(
@@ -73,7 +73,10 @@ export const compareJavaScriptExportShapesInputSchema = z
});
});
const projectedReturnFieldShape = { path: jsonPointerSchema };
const projectedReturnFieldShape = {
path: jsonPointerSchema,
presence: z.enum(["present", "absent", "unknown-coverage"]).optional(),
};
const projectedReturnFieldSchema = z.discriminatedUnion("state", [
z.strictObject({
...projectedReturnFieldShape,
@@ -229,11 +232,21 @@ const discriminantSchema = z.strictObject({
value: semanticPrimitiveSchema,
});
const propertyPresenceSchema = z.enum([
"present",
"absent",
"unknown-coverage",
]);
const comparisonChangeSchema = z.strictObject({
change_id: prefixedDigestSchema("jesc_change"),
status: z.enum(["added", "removed", "changed", "unknown"]),
path: jsonPointerSchema,
discriminant: discriminantSchema.nullable(),
presence: z.strictObject({
left: propertyPresenceSchema,
right: propertyPresenceSchema,
}),
left: valueAvailabilitySchema,
right: valueAvailabilitySchema,
left_source_range: sourceRangeSchema.nullable(),
@@ -242,11 +255,31 @@ const comparisonChangeSchema = z.strictObject({
limitations: z.array(textSchema),
});
/** One change row; presence is required even when values stay unknown. */
export const javaScriptExportShapeComparisonChangeSchema =
comparisonChangeSchema;
const inventoryPropertyCoverageSchema = z.strictObject({
path: jsonPointerSchema,
status: z.enum(["complete", "partial"]),
});
const propertyInventorySchema = z.strictObject({
side: z.enum(["left", "right"]),
variant_index: z.number().int().nonnegative(),
discriminant: discriminantSchema.nullable(),
paired: z.boolean(),
source_range: sourceRangeSchema,
properties: z.array(jsonPointerSchema),
property_coverage: z.array(inventoryPropertyCoverageSchema),
});
/** Static export-return comparison with explicit unknown semantics. */
export const javaScriptExportShapeComparisonResultSchema = z.strictObject({
comparison_id: prefixedDigestSchema("jesc"),
left: selectorResultSchema,
right: selectorResultSchema,
property_inventories: z.array(propertyInventorySchema),
summary: z.strictObject({
added: z.number().int().min(0),
removed: z.number().int().min(0),
@@ -295,3 +328,6 @@ export type JavaScriptExportShapeComparisonResult = z.output<
export type JavaScriptExportShapeComparisonChange = z.output<
typeof comparisonChangeSchema
>;
export type JavaScriptExportShapePropertyInventory = z.output<
typeof propertyInventorySchema
>;
@@ -10,6 +10,9 @@ import {
import { compareCodePoints } from "../canonicalOrdering.js";
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
type Field = Shape["fields"][number];
type NormalizedField = Field & { presence: NonNullable<Field["presence"]> };
type NormalizedShape = Omit<Shape, "fields"> & { fields: NormalizedField[] };
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
type SelectorBase = Omit<SelectorResult, "status" | "selected_node_id">;
type ReturnShapeSelection =
@@ -55,7 +58,7 @@ export type SelectedJavaScriptExport =
/** Complete return-shape inventory retained from an authenticated projection. */
export interface RetainedJavaScriptExportShapes {
readonly shapes: readonly Shape[];
readonly shapes: readonly NormalizedShape[];
readonly omitted: number;
}
@@ -126,11 +129,22 @@ export const selectJavaScriptExport = (
};
};
/** Retain every projected return variant. */
/** Retain every variant and normalize legacy presence on comparison-owned copies. */
export const retainJavaScriptExportShapes = (
selection: SelectedJavaScriptExport,
): RetainedJavaScriptExportShapes => {
const shapes = selection.projection?.static_return_shapes ?? [];
const shapes = (
selection.projection?.static_return_shapes ?? []
).map<NormalizedShape>((shape) => ({
...shape,
fields: shape.fields.map<NormalizedField>((field) => ({
...field,
// Legacy unknown fields did not distinguish values from uncertain slots.
presence:
field.presence ??
(field.state === "unknown" ? "unknown-coverage" : "present"),
})),
}));
return { shapes, omitted: 0 };
};
@@ -5,19 +5,28 @@ import {
import type {
JavaScriptExportShapeComparisonChange,
JavaScriptExportShapeComparisonResult,
ProjectedExportReturnShapes,
JavaScriptExportShapePropertyInventory,
} from "./javascriptExportShapeComparisonSchemas.js";
import { compareCodePoints, uniqueSorted } from "../canonicalOrdering.js";
import type { SelectedJavaScriptExport } from "./javascriptExportShapeSelection.js";
import type {
SelectedJavaScriptExport,
RetainedJavaScriptExportShapes,
} from "./javascriptExportShapeSelection.js";
type Primitive = string | number | boolean | null;
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
type Shape = RetainedJavaScriptExportShapes["shapes"][number];
type Field = Shape["fields"][number];
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
type ValueAvailability = JavaScriptExportShapeComparisonChange["left"];
type PropertyPresence =
JavaScriptExportShapeComparisonChange["presence"]["left"];
type Discriminant = NonNullable<
JavaScriptExportShapeComparisonChange["discriminant"]
>;
const UNKNOWN_COVERAGE_PRESENCE = {
left: "unknown-coverage",
right: "unknown-coverage",
} as const satisfies JavaScriptExportShapeComparisonChange["presence"];
interface VariantPair {
readonly leftIndex: number;
@@ -112,12 +121,62 @@ export const buildJavaScriptExportShapeChanges = (
return [...paired, ...unpairedLeft, ...unpairedRight];
};
/** List observed property names per retained variant, including unknown values. */
export const buildJavaScriptExportShapeInventories = (input: {
readonly pairing: JavaScriptExportShapePairing;
readonly leftShapes: readonly Shape[];
readonly rightShapes: readonly Shape[];
}): JavaScriptExportShapePropertyInventory[] => {
const leftPairs = new Map(
input.pairing.pairs.map((pair) => [pair.leftIndex, pair]),
);
const rightPairs = new Map(
input.pairing.pairs.map((pair) => [pair.rightIndex, pair]),
);
return [
...input.leftShapes.map((shape, index) =>
inventoryFor("left", index, shape, leftPairs.get(index)),
),
...input.rightShapes.map((shape, index) =>
inventoryFor("right", index, shape, rightPairs.get(index)),
),
];
};
const inventoryFor = (
side: JavaScriptExportShapePropertyInventory["side"],
variantIndex: number,
shape: Shape,
pair: VariantPair | undefined,
): JavaScriptExportShapePropertyInventory => ({
side,
variant_index: variantIndex,
discriminant: pair?.discriminant ?? null,
paired: pair !== undefined,
source_range: shape.source_range,
properties: uniqueSorted([
...shape.fields
.filter((field) => fieldPresence(shape, field, field.path) === "present")
.map(({ path }) => path),
...shape.property_coverage.map(({ path }) => path),
]).filter((path) => path !== ""),
property_coverage: shape.property_coverage.map(({ path, status }) => ({
path,
status,
})),
});
/** Report whether any retained shape lacks complete property coverage. */
export const hasPartialJavaScriptExportPropertyCoverage = (
shapes: readonly Shape[],
): boolean =>
shapes.some((shape) =>
shape.property_coverage.some(({ status }) => status === "partial"),
shapes.some(
(shape) =>
shape.property_coverage.some(({ status }) => status === "partial") ||
shape.fields.some(
(field) =>
fieldPresence(shape, field, field.path) === "unknown-coverage",
),
);
interface DiscriminantOccurrence {
@@ -131,6 +190,7 @@ const discriminantOccurrences = (
const output = new Map<string, DiscriminantOccurrence>();
shapes.forEach((shape, index) => {
for (const field of shape.fields) {
if (fieldPresence(shape, field, field.path) !== "present") continue;
const value = literalValue(field);
if (!value.found) continue;
const discriminant = { path: field.path, value: value.value };
@@ -204,6 +264,7 @@ const selectionUnknownChange = (
status: "unknown",
path: "",
discriminant: null,
presence: UNKNOWN_COVERAGE_PRESENCE,
left: selectionAvailability(input.leftSelection.selection, "left"),
right: selectionAvailability(input.rightSelection.selection, "right"),
left_source_range: null,
@@ -221,6 +282,7 @@ const emptyShapeUnknownChange = (
status: "unknown",
path: "",
discriminant: null,
presence: UNKNOWN_COVERAGE_PRESENCE,
left: emptyShapeAvailability(input.leftShapes, "left"),
right: emptyShapeAvailability(input.rightShapes, "right"),
left_source_range: null,
@@ -261,6 +323,10 @@ const diffPair = (
status,
path,
discriminant,
presence: {
left: fieldPresence(left, leftField, path),
right: fieldPresence(right, rightField, path),
},
left: fieldAvailability(leftField),
right: fieldAvailability(rightField),
left_source_range: left.source_range,
@@ -288,6 +354,7 @@ const fieldAtPath = (
return undefined;
return {
path,
presence: "present",
state: "unknown",
value: null,
reason:
@@ -312,24 +379,40 @@ const fieldChangeStatus = ({
}: FieldChangeInput):
| JavaScriptExportShapeComparisonChange["status"]
| null => {
if (leftField !== undefined && rightField !== undefined) {
if (
canonicalExportShapeValue(leftField) ===
const leftPresence = fieldPresence(leftShape, leftField, path);
const rightPresence = fieldPresence(rightShape, rightField, path);
if (
leftField !== undefined &&
rightField !== undefined &&
canonicalExportShapeValue(leftField) ===
canonicalExportShapeValue(rightField)
)
return null;
)
return null;
if (leftPresence === "absent" && rightPresence === "absent") return null;
if (
leftPresence === "unknown-coverage" ||
rightPresence === "unknown-coverage"
)
return "unknown";
if (leftPresence === "absent") return "added";
if (rightPresence === "absent") return "removed";
if (leftField !== undefined && rightField !== undefined) {
return leftField.state === "unknown" || rightField.state === "unknown"
? "unknown"
: "changed";
}
const present = leftField ?? rightField;
if (present === undefined) return null;
const parent = parentPointer(path);
const parentsComplete =
propertyCoverageComplete(leftShape, parent) &&
propertyCoverageComplete(rightShape, parent);
if (present.state === "unknown" || !parentsComplete) return "unknown";
return leftField === undefined ? "added" : "removed";
return null;
};
const fieldPresence = (
shape: Shape,
field: Field | undefined,
path: string,
): PropertyPresence => {
if (field !== undefined) return field.presence;
return propertyCoverageComplete(shape, parentPointer(path))
? "absent"
: "unknown-coverage";
};
const propertyCoverageComplete = (shape: Shape, path: string | null): boolean =>
@@ -345,7 +428,8 @@ const parentPointer = (path: string): string | null => {
};
const fieldAvailability = (field: Field | undefined): ValueAvailability => {
if (field === undefined) return { availability: "absent" };
if (field === undefined || field.presence === "absent")
return { availability: "absent" };
if (field.state === "unknown")
return {
availability: "unknown",
@@ -390,6 +474,7 @@ const unpairedChange = (
status: "unknown",
path: "",
discriminant: null,
presence: UNKNOWN_COVERAGE_PRESENCE,
left: {
availability: "unknown",
reason:
@@ -63,9 +63,17 @@ it("invalidates a deep mutation while retaining unrelated literal properties", (
status: "object",
properties: [
{ name: "untouched", value: { status: "literal", value: "retained" } },
{
name: "next",
presence: "unknown-coverage",
value: {
status: "unknown",
reason: "This property may have been mutated.",
},
},
],
unknownProperties: true,
omittedProperties: null,
unknownProperties: false,
omittedProperties: 0,
});
expect(onlyBinding(ir, "value").value).toEqual({
status: "literal",
@@ -20,23 +20,16 @@ export const invalidateSemanticMutationPath = (
property.name === name
? {
...property,
...(remaining.length === 0
? { presence: "unknown-coverage" as const }
: {}),
value: invalidateSemanticMutationPath(property.value, remaining),
}
: property,
);
return value.unknownProperties || !observed
? {
status: "object",
properties,
unknownProperties: true,
omittedProperties: observed ? value.omittedProperties : null,
}
: {
status: "object",
properties,
unknownProperties: false,
omittedProperties: 0,
};
if (!observed)
properties.push({ name, value: unknown, presence: "unknown-coverage" });
return { ...value, properties };
}
if (value.status === "array") {
const index = typeof key === "number" ? key : Number(key);
@@ -46,20 +39,18 @@ export const invalidateSemanticMutationPath = (
String(index) !== String(key)
)
return unknown;
const observed = value.items[index] !== undefined;
const items = value.items.map((item, position) =>
position === index
? invalidateSemanticMutationPath(item, remaining)
: item,
);
return value.unknownItems || !observed
? {
status: "array",
items,
unknownItems: true,
omittedItems: observed ? value.omittedItems : null,
}
: { status: "array", items, unknownItems: false, omittedItems: 0 };
const itemPresence = {
...value.itemPresence,
...(remaining.length === 0 || value.items[index] === undefined
? { [index]: "unknown-coverage" as const }
: {}),
};
return { ...value, items, itemPresence };
}
return unknown;
};
@@ -211,14 +211,33 @@ const flattenValue = (
path: string,
fields: ProjectedReturnField[],
coverage: ProjectedPropertyCoverage[],
presence: "present" | "absent" | "unknown-coverage" = "present",
): void => {
if (presence !== "present") {
fields.push({
path,
presence,
state: "unknown",
value: null,
reason:
"reason" in value ? value.reason : "Property presence is uncertain.",
});
return;
}
if (value.status === "literal") {
fields.push({ path, state: "literal", value: value.value, reason: null });
fields.push({
path,
presence,
state: "literal",
value: value.value,
reason: null,
});
return;
}
if (value.status === "union") {
fields.push({
path,
presence,
state: "union",
value: [...value.values],
reason: null,
@@ -237,6 +256,7 @@ const flattenValue = (
`${path}/${escapePointer(property.name)}`,
fields,
coverage,
property.presence ?? "present",
);
return;
}
@@ -247,11 +267,30 @@ const flattenValue = (
: { path, status: "complete", omitted: 0 },
);
value.items.forEach((item, index) =>
flattenValue(item, `${path}/${String(index)}`, fields, coverage),
flattenValue(
item,
`${path}/${String(index)}`,
fields,
coverage,
value.itemPresence?.[index] ?? "present",
),
);
// Sparse mutation metadata retains uncertain slots without expanding arrays.
for (const [index, itemPresence] of Object.entries(
value.itemPresence ?? {},
)) {
if (Number(index) < value.items.length) continue;
flattenValue(value, `${path}/${index}`, fields, coverage, itemPresence);
}
return;
}
fields.push({ path, state: "unknown", value: null, reason: value.reason });
fields.push({
path,
presence,
state: "unknown",
value: null,
reason: value.reason,
});
};
const escapePointer = (value: string): string =>
@@ -24,6 +24,9 @@ type JavaScriptSemanticObjectValue = {
type JavaScriptSemanticArrayValue = {
readonly status: "array";
readonly items: readonly JavaScriptSemanticValue[];
readonly itemPresence?: Readonly<
Record<number, "absent" | "unknown-coverage">
>;
} & (
| {
readonly unknownItems: false;
@@ -57,4 +60,5 @@ export type JavaScriptSemanticValue =
export interface JavaScriptSemanticProperty {
readonly name: string;
readonly value: JavaScriptSemanticValue;
readonly presence?: "unknown-coverage";
}
@@ -299,6 +299,7 @@ const evaluateArray = (
context: EvaluationContext,
): JavaScriptSemanticValue => {
const items: JavaScriptSemanticValue[] = [];
const itemPresence: Record<number, "absent"> = {};
let unknownItems = false;
let omittedItems: number | null = 0;
for (const element of node.elements) {
@@ -309,8 +310,7 @@ const evaluateArray = (
break;
}
if (element === null) {
unknownItems = true;
if (omittedItems !== null) omittedItems += 1;
itemPresence[items.length] = "absent";
items.push({
status: "unknown",
reason: "Array hole has no primitive value.",
@@ -320,8 +320,14 @@ const evaluateArray = (
items.push(evaluateExpression(element, nestedContext(context)));
}
return unknownItems
? { status: "array", items, unknownItems: true, omittedItems }
: { status: "array", items, unknownItems: false, omittedItems: 0 };
? { status: "array", items, itemPresence, unknownItems: true, omittedItems }
: {
status: "array",
items,
itemPresence,
unknownItems: false,
omittedItems: 0,
};
};
const evaluateMember = (