feat(domain): add versioned JavaScript Application Graph

This commit is contained in:
N0zoM1z0
2026-07-16 05:08:52 +09:00
committed by N0zoM1z0
parent d8321defd7
commit 2ca56724e4
65 changed files with 3630 additions and 57 deletions
@@ -0,0 +1,435 @@
import { z } from "zod";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
const boundedKeySchema = z.string().min(1).max(512);
const unsafePathSegments = new Set(["", ".", ".."]);
const isSafeRelativePath = (path: string): boolean => {
if (path.startsWith("/") || path.includes("\\")) return false;
return path.split("/").every((part) => !unsafePathSegments.has(part));
};
const relativePathSchema = z
.string()
.min(1)
.max(4_096)
.refine(
isSafeRelativePath,
"Expected a normalized relative POSIX path without traversal",
);
/** Authority that produced one node observation or relationship. */
const applicationEvidenceAuthoritySchema = z.enum([
"artifact-bytes",
"ast-static-analysis",
"static-relationship-inference",
"passive-cdp-runtime",
"controlled-replay",
"native-analysis-provider",
"historical-reference",
"user-assertion",
"unknown",
]);
/** Epistemic state kept separate from the evidence source. */
const applicationFactStateSchema = z.enum([
"observed",
"inferred",
"unknown",
"unavailable",
]);
/** Confidence assigned without promoting inference into observation. */
const applicationConfidenceSchema = z.enum([
"exact",
"high",
"medium",
"low",
"unknown",
]);
/** Why an artifact or source location was not available to an extractor. */
const applicationUnavailableReasonSchema = z.enum([
"not-applicable",
"not-observed",
"not-approved",
"truncated",
"provider-unavailable",
"unresolved",
"unknown",
]);
const unavailableFactSchema = z.strictObject({
available: z.literal(false),
reason: applicationUnavailableReasonSchema,
detail: boundedTextSchema,
});
const availableArtifactSchema = z
.strictObject({
available: z.literal(true),
artifact_id: z.string().regex(/^art_[a-f0-9]{64}$/u),
sha256: digestSchema,
})
.superRefine((artifact, context) => {
if (artifact.artifact_id !== `art_${artifact.sha256}`)
context.addIssue({
code: "custom",
path: ["artifact_id"],
message: "Artifact identifier must commit the same SHA-256 digest",
});
});
/** Explicit content-addressed artifact availability for one graph fact. */
const applicationArtifactReferenceSchema = z.discriminatedUnion("available", [
availableArtifactSchema,
unavailableFactSchema,
]);
const sourceRangeSchema = z
.strictObject({
kind: z.literal("source-range"),
source: boundedTextSchema,
start: z.strictObject({
line: z.number().int().min(1),
column: z.number().int().min(0),
}),
end: z.strictObject({
line: z.number().int().min(1),
column: z.number().int().min(0),
}),
})
.superRefine((location, context) => {
if (
location.end.line < location.start.line ||
(location.end.line === location.start.line &&
location.end.column < location.start.column)
)
context.addIssue({
code: "custom",
path: ["end"],
message: "Source range end must not precede its start",
});
});
const fileOffsetRangeSchema = z
.strictObject({
kind: z.literal("file-offset-range"),
start: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
end: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
})
.superRefine((location, context) => {
if (location.end < location.start)
context.addIssue({
code: "custom",
path: ["end"],
message: "File offset range end must not precede its start",
});
});
/** A deterministic artifact, source, runtime, package, or native location. */
const applicationLocationSchema = z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("artifact-path"),
path: relativePathSchema,
}),
sourceRangeSchema,
fileOffsetRangeSchema,
z.strictObject({
kind: z.literal("url"),
url: z.string().min(1).max(16_384),
}),
z.strictObject({
kind: z.literal("runtime"),
capture_sha256: digestSchema,
target_key: boundedKeySchema,
frame_key: boundedKeySchema.nullable(),
script_key: boundedKeySchema.nullable(),
}),
z.strictObject({
kind: z.literal("native-address"),
address: boundedKeySchema,
symbol: boundedTextSchema.nullable(),
}),
z.strictObject({
kind: z.literal("package-export"),
package_name: boundedKeySchema,
export_path: boundedTextSchema,
}),
]);
/** Explicit source-location availability for one graph fact. */
const applicationLocationReferenceSchema = z.discriminatedUnion("available", [
z.strictObject({
available: z.literal(true),
value: applicationLocationSchema,
}),
unavailableFactSchema,
]);
/** Versioned extractor coordinates attached to every graph fact. */
const applicationExtractorSchema = z.strictObject({
name: z.string().min(1).max(128),
version: z.string().min(1).max(128),
operation: z.string().min(1).max(256),
executable_sha256: digestSchema.nullable(),
});
const applicationLimitSchema = z.strictObject({
name: z.string().min(1).max(128),
value: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
unit: z.enum([
"items",
"bytes",
"milliseconds",
"depth",
"characters",
"instructions",
"other",
]),
});
/** Bounded collection coverage without treating omission as absence. */
export const applicationCoverageSchema = z
.strictObject({
status: z.enum(["complete", "partial", "unknown", "unavailable"]),
truncated: z.boolean(),
omitted_count: z
.number()
.int()
.min(0)
.max(Number.MAX_SAFE_INTEGER)
.nullable(),
limits: z.array(applicationLimitSchema).max(32),
})
.superRefine((coverage, context) => {
if (
coverage.status === "complete" &&
(coverage.truncated || coverage.omitted_count !== 0)
)
context.addIssue({
code: "custom",
message: "Complete coverage cannot be truncated or omit items",
});
if (
coverage.truncated &&
(coverage.status !== "partial" ||
coverage.limits.length === 0 ||
coverage.omitted_count === 0)
)
context.addIssue({
code: "custom",
message:
"Truncated coverage must be partial, name a limit, and not claim zero omissions",
});
if (
["unknown", "unavailable"].includes(coverage.status) &&
(coverage.truncated || coverage.omitted_count !== null)
)
context.addIssue({
code: "custom",
message:
"Unknown or unavailable coverage cannot invent truncation counts",
});
});
const applicationGraphEvidenceBaseSchema = z.strictObject({
authority: applicationEvidenceAuthoritySchema,
state: applicationFactStateSchema,
confidence: applicationConfidenceSchema,
artifact: applicationArtifactReferenceSchema,
location: applicationLocationReferenceSchema,
extractor: applicationExtractorSchema,
coverage: applicationCoverageSchema,
limitations: z.array(boundedTextSchema).max(100),
evidence_ids: z.array(z.string().regex(/^ev_[a-f0-9]{64}$/u)).max(100),
});
type EvidenceValue = z.infer<typeof applicationGraphEvidenceBaseSchema>;
const checkAuthorityState = (
evidence: EvidenceValue,
context: z.RefinementCtx,
): void => {
if (
evidence.authority === "static-relationship-inference" &&
evidence.state !== "inferred"
)
context.addIssue({
code: "custom",
path: ["state"],
message: "Static relationship authority must remain inferred",
});
if (
evidence.authority === "unknown" &&
!["unknown", "unavailable"].includes(evidence.state)
)
context.addIssue({
code: "custom",
path: ["state"],
message: "Unknown authority cannot claim an observed fact",
});
};
const checkStateConfidence = (
evidence: EvidenceValue,
context: z.RefinementCtx,
): void => {
if (
["unknown", "unavailable"].includes(evidence.state) &&
(evidence.confidence !== "unknown" || evidence.limitations.length === 0)
)
context.addIssue({
code: "custom",
message:
"Unknown and unavailable facts require unknown confidence and an explicit limitation",
});
if (evidence.state === "observed" && evidence.confidence === "unknown")
context.addIssue({
code: "custom",
path: ["confidence"],
message: "Observed facts require a bounded non-unknown confidence",
});
if (
evidence.state === "inferred" &&
!["high", "medium", "low"].includes(evidence.confidence)
)
context.addIssue({
code: "custom",
path: ["confidence"],
message: "Inferred facts require high, medium, or low confidence",
});
if (evidence.confidence === "exact" && evidence.state !== "observed")
context.addIssue({
code: "custom",
path: ["confidence"],
message: "Exact confidence is reserved for observed facts",
});
};
const checkTraceability = (
evidence: EvidenceValue,
context: z.RefinementCtx,
): void => {
if (evidence.state === "observed" && !evidence.location.available)
context.addIssue({
code: "custom",
path: ["location"],
message: "Observed facts require an actionable location",
});
if (evidence.state === "inferred" && evidence.limitations.length === 0)
context.addIssue({
code: "custom",
path: ["limitations"],
message: "Inferred facts require an explicit limitation",
});
if (
evidence.coverage.status !== "complete" &&
evidence.limitations.length === 0
)
context.addIssue({
code: "custom",
path: ["limitations"],
message: "Non-complete coverage requires an explicit limitation",
});
};
const checkArtifactBacking = (
evidence: EvidenceValue,
context: z.RefinementCtx,
): void => {
const artifactBacked = [
"artifact-bytes",
"ast-static-analysis",
"controlled-replay",
"native-analysis-provider",
].includes(evidence.authority);
if (
artifactBacked &&
evidence.state !== "unavailable" &&
!evidence.artifact.available
)
context.addIssue({
code: "custom",
path: ["artifact"],
message: "Artifact-backed facts require a content digest",
});
};
/** Provenance, authority, uncertainty, and bounds for one graph fact. */
export const applicationGraphEvidenceSchema =
applicationGraphEvidenceBaseSchema.superRefine((evidence, context) => {
checkAuthorityState(evidence, context);
checkStateConfidence(evidence, context);
checkTraceability(evidence, context);
checkArtifactBacking(evidence, context);
});
/** Stable node identifier strategies and their explicit scope. */
export const applicationNodeIdentitySchema = z.discriminatedUnion("strategy", [
z.strictObject({
strategy: z.literal("content-digest"),
stability: z.literal("global-exact"),
sha256: digestSchema,
}),
z.strictObject({
strategy: z.literal("source-map-original"),
stability: z.literal("source-map-exact"),
source_map_sha256: digestSchema,
original_source: boundedTextSchema,
source_sha256: digestSchema.nullable(),
}),
z.strictObject({
strategy: z.literal("canonical-path"),
stability: z.literal("artifact-version"),
artifact_sha256: digestSchema,
path: relativePathSchema,
}),
z.strictObject({
strategy: z.literal("structural-fingerprint"),
stability: z.literal("cross-version-inference"),
algorithm: z.string().min(1).max(128),
fingerprint_sha256: digestSchema,
basis: z
.array(
z.enum([
"syntax-tree",
"control-flow",
"imports",
"exports",
"literals",
"api-usage",
]),
)
.min(1)
.max(6),
}),
z.strictObject({
strategy: z.literal("artifact-local-key"),
stability: z.literal("artifact-version"),
artifact_sha256: digestSchema,
namespace: boundedKeySchema,
key: boundedTextSchema,
}),
z.strictObject({
strategy: z.literal("runtime-instance"),
stability: z.literal("capture-only"),
capture_sha256: digestSchema,
runtime_key: boundedTextSchema,
}),
z.strictObject({
strategy: z.literal("observation-fingerprint"),
stability: z.literal("observation-only"),
observation_sha256: digestSchema,
scope: boundedTextSchema,
}),
]);
/** Evidence coordinates attached to one graph observation or edge. */
export type ApplicationGraphEvidence = z.infer<
typeof applicationGraphEvidenceSchema
>;
/** Explicit stable identity strategy for one application entity. */
export type ApplicationNodeIdentity = z.infer<
typeof applicationNodeIdentitySchema
>;
+495
View File
@@ -0,0 +1,495 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import type {
ApplicationGraphEvidence,
ApplicationNodeIdentity,
} from "./javascriptApplicationEvidenceSchemas.js";
import {
applicationEdgeInputSchema,
applicationEdgeSchema,
applicationNodeInputSchema,
applicationNodeObservationSchema,
applicationNodeSchema,
javascriptApplicationGraphInputSchema,
javascriptApplicationGraphRecordSchema,
type ApplicationEdge,
type ApplicationNode,
type JavaScriptApplicationGraphInput,
} from "./javascriptApplicationGraphSchemas.js";
const compareCodePoints = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const canonicalJson = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(
"JavaScript Application Graph could not canonicalize data",
);
return encoded;
};
const digestCanonical = (value: unknown): string =>
createHash("sha256").update(canonicalJson(value)).digest("hex");
const OBSERVATION_IDENTIFIER_STRATEGY = {
strategy: "semantic-content-sha256" as const,
stability: "observation-exact" as const,
};
const EDGE_IDENTIFIER_STRATEGY = {
strategy: "semantic-content-sha256" as const,
stability: "relationship-exact" as const,
};
const uniqueSorted = <Value extends string>(
values: readonly Value[],
): Value[] => [...new Set(values)].sort(compareCodePoints);
const limitKey = (
limit: ApplicationGraphEvidence["coverage"]["limits"][number],
) => canonicalJson(limit);
const normalizeLimits = (
limits: ApplicationGraphEvidence["coverage"]["limits"],
): ApplicationGraphEvidence["coverage"]["limits"] =>
[...new Map(limits.map((limit) => [limitKey(limit), limit])).values()].sort(
(left, right) => compareCodePoints(limitKey(left), limitKey(right)),
);
const normalizeEvidence = (
evidence: ApplicationGraphEvidence,
): ApplicationGraphEvidence => ({
...evidence,
coverage: {
...evidence.coverage,
limits: normalizeLimits(evidence.coverage.limits),
},
limitations: uniqueSorted(evidence.limitations),
evidence_ids: uniqueSorted(evidence.evidence_ids),
});
const normalizeIdentity = (
identity: ApplicationNodeIdentity,
): ApplicationNodeIdentity =>
identity.strategy === "structural-fingerprint"
? { ...identity, basis: uniqueSorted(identity.basis) }
: identity;
const nodeSemantic = (node: Pick<ApplicationNode, "kind" | "identity">) => ({
kind: node.kind,
identity: node.identity,
});
const nodeId = (node: Pick<ApplicationNode, "kind" | "identity">): string =>
`jag_node_${digestCanonical(nodeSemantic(node))}`;
const observationSemantic = (
nodeIdentifier: string,
observation: Omit<
z.infer<typeof applicationNodeObservationSchema>,
"observation_id"
>,
) => ({ node_id: nodeIdentifier, ...observation });
const observationId = (
nodeIdentifier: string,
observation: Omit<
z.infer<typeof applicationNodeObservationSchema>,
"observation_id"
>,
): string =>
`jag_observation_${digestCanonical(
observationSemantic(nodeIdentifier, observation),
)}`;
type EdgeSemantic = Omit<ApplicationEdge, "edge_id">;
const edgeId = (edge: EdgeSemantic): string =>
`jag_edge_${digestCanonical(edge)}`;
const sortedUniqueIssue = (
values: readonly string[],
path: PropertyKey[],
label: string,
context: z.RefinementCtx,
): void => {
for (let index = 1; index < values.length; index += 1) {
if (compareCodePoints(values[index - 1] ?? "", values[index] ?? "") < 0)
continue;
context.addIssue({
code: "custom",
message: `${label} must be sorted and unique by Unicode code point`,
path: [...path, index],
});
return;
}
};
const checkEvidenceNormalization = (
evidence: ApplicationGraphEvidence,
path: PropertyKey[],
context: z.RefinementCtx,
): void => {
sortedUniqueIssue(
evidence.limitations,
[...path, "limitations"],
"Evidence limitations",
context,
);
sortedUniqueIssue(
evidence.evidence_ids,
[...path, "evidence_ids"],
"Evidence identifiers",
context,
);
sortedUniqueIssue(
evidence.coverage.limits.map(limitKey),
[...path, "coverage", "limits"],
"Evidence limits",
context,
);
const runtimeLocation =
evidence.location.available && evidence.location.value.kind === "runtime";
const staticAuthority = [
"artifact-bytes",
"ast-static-analysis",
"static-relationship-inference",
"native-analysis-provider",
].includes(evidence.authority);
if (runtimeLocation && staticAuthority)
context.addIssue({
code: "custom",
message: "Static and native authorities cannot claim a runtime location",
path: [...path, "location"],
});
};
const observationMatchesIdentity = (
node: ApplicationNode,
observation: ApplicationNode["observations"][number],
): boolean => {
const { identity } = node;
const { evidence } = observation;
if (identity.strategy === "content-digest")
return (
evidence.state === "observed" &&
evidence.artifact.available &&
evidence.artifact.sha256 === identity.sha256
);
if (identity.strategy === "source-map-original")
return (
evidence.state === "observed" &&
evidence.artifact.available &&
evidence.artifact.sha256 === identity.source_map_sha256
);
if (identity.strategy === "canonical-path")
return (
evidence.artifact.available &&
evidence.artifact.sha256 === identity.artifact_sha256 &&
evidence.location.available &&
evidence.location.value.kind === "artifact-path" &&
evidence.location.value.path === identity.path
);
if (identity.strategy === "artifact-local-key")
return (
evidence.artifact.available &&
evidence.artifact.sha256 === identity.artifact_sha256
);
if (identity.strategy === "runtime-instance") {
if (
!["passive-cdp-runtime", "controlled-replay"].includes(
evidence.authority,
) ||
!evidence.location.available ||
evidence.location.value.kind !== "runtime"
)
return false;
const location = evidence.location.value;
return (
location.capture_sha256 === identity.capture_sha256 &&
[location.target_key, location.frame_key, location.script_key].includes(
identity.runtime_key,
)
);
}
if (identity.strategy === "structural-fingerprint")
return evidence.state === "inferred";
return evidence.state === "observed";
};
const checkNode = (
node: ApplicationNode,
index: number,
context: z.RefinementCtx,
): void => {
if (node.node_id !== nodeId(node))
context.addIssue({
code: "custom",
message: "Node identifier does not match its kind and identity",
path: ["nodes", index, "node_id"],
});
if (
node.identity.strategy === "structural-fingerprint" &&
canonicalJson(node.identity.basis) !==
canonicalJson(uniqueSorted(node.identity.basis))
)
context.addIssue({
code: "custom",
message: "Structural fingerprint basis must be sorted and unique",
path: ["nodes", index, "identity", "basis"],
});
sortedUniqueIssue(
node.observations.map(({ observation_id: id }) => id),
["nodes", index, "observations"],
"Node observations",
context,
);
for (const [observationIndex, observation] of node.observations.entries()) {
const { observation_id: identifier, ...semantic } = observation;
if (identifier !== observationId(node.node_id, semantic))
context.addIssue({
code: "custom",
message: "Observation identifier does not match its semantic content",
path: [
"nodes",
index,
"observations",
observationIndex,
"observation_id",
],
});
checkEvidenceNormalization(
observation.evidence,
["nodes", index, "observations", observationIndex, "evidence"],
context,
);
}
if (
!node.observations.some((observation) =>
observationMatchesIdentity(node, observation),
)
)
context.addIssue({
code: "custom",
message: "Node identity is not supported by a compatible observation",
path: ["nodes", index, "identity"],
});
};
type GraphRecord = z.infer<typeof javascriptApplicationGraphRecordSchema>;
const checkGraphInvariants = (
graph: GraphRecord,
context: z.RefinementCtx,
): void => {
sortedUniqueIssue(
graph.root_node_ids,
["root_node_ids"],
"Root nodes",
context,
);
sortedUniqueIssue(
graph.nodes.map(({ node_id: id }) => id),
["nodes"],
"Nodes",
context,
);
sortedUniqueIssue(
graph.edges.map(({ edge_id: id }) => id),
["edges"],
"Edges",
context,
);
sortedUniqueIssue(
graph.limitations,
["limitations"],
"Graph limitations",
context,
);
sortedUniqueIssue(
graph.coverage.limits.map(limitKey),
["coverage", "limits"],
"Graph limits",
context,
);
if (graph.coverage.status !== "complete" && graph.limitations.length === 0)
context.addIssue({
code: "custom",
message: "Non-complete graph coverage requires an explicit limitation",
path: ["limitations"],
});
const nodesById = new Map(graph.nodes.map((node) => [node.node_id, node]));
for (const root of graph.root_node_ids)
if (!nodesById.has(root))
context.addIssue({
code: "custom",
message: "Root identifier must name a graph node",
path: ["root_node_ids"],
});
for (const [index, node] of graph.nodes.entries())
checkNode(node, index, context);
for (const [index, edge] of graph.edges.entries()) {
const { edge_id: identifier, ...semantic } = edge;
if (identifier !== edgeId(semantic))
context.addIssue({
code: "custom",
message: "Edge identifier does not match its semantic content",
path: ["edges", index, "edge_id"],
});
if (
!nodesById.has(edge.source_node_id) ||
!nodesById.has(edge.target_node_id)
)
context.addIssue({
code: "custom",
message: "Edge endpoints must name graph nodes",
path: ["edges", index],
});
if (edge.source_node_id === edge.target_node_id)
context.addIssue({
code: "custom",
message: "Application graph edges cannot be self-referential",
path: ["edges", index],
});
if (
edge.relation === "changed_from" &&
nodesById.get(edge.source_node_id)?.kind !==
nodesById.get(edge.target_node_id)?.kind
)
context.addIssue({
code: "custom",
message: "changed_from endpoints must have the same node kind",
path: ["edges", index, "relation"],
});
checkEvidenceNormalization(
edge.evidence,
["edges", index, "evidence"],
context,
);
}
const { graph_id: identifier, ...semantic } = graph;
if (identifier !== `jag_${digestCanonical(semantic)}`)
context.addIssue({
code: "custom",
message: "Graph identifier does not match its semantic content",
path: ["graph_id"],
});
};
/** Strict versioned JavaScript Application Graph with verified commitments. */
export const javascriptApplicationGraphSchema =
javascriptApplicationGraphRecordSchema.superRefine(checkGraphInvariants);
/** Fully validated JavaScript Application Graph v1. */
export type JavaScriptApplicationGraph = z.infer<
typeof javascriptApplicationGraphSchema
>;
/** Build one normalized application entity and derive all semantic IDs. */
export const createJavaScriptApplicationNode = (
input: unknown,
): ApplicationNode => {
const parsed = applicationNodeInputSchema.parse(input);
const identity = normalizeIdentity(parsed.identity);
const identifier = nodeId({ kind: parsed.kind, identity });
const observations = parsed.observations
.map((observation) => {
const semantic = {
...observation,
evidence: normalizeEvidence(observation.evidence),
identifier_strategy: OBSERVATION_IDENTIFIER_STRATEGY,
};
return applicationNodeObservationSchema.parse({
...semantic,
observation_id: observationId(identifier, semantic),
});
})
.sort((left, right) =>
compareCodePoints(left.observation_id, right.observation_id),
);
return applicationNodeSchema.parse({
node_id: identifier,
kind: parsed.kind,
identity,
observations,
});
};
/** Build one normalized directed relationship and derive its semantic ID. */
export const createJavaScriptApplicationEdge = (
input: unknown,
): ApplicationEdge => {
const parsed = applicationEdgeInputSchema.parse(input);
const semantic = {
...parsed,
evidence: normalizeEvidence(parsed.evidence),
identifier_strategy: EDGE_IDENTIFIER_STRATEGY,
};
return applicationEdgeSchema.parse({
...semantic,
edge_id: edgeId(semantic),
});
};
/** Normalize a complete graph and derive its top-level semantic ID. */
export const createJavaScriptApplicationGraph = (
input: unknown,
): JavaScriptApplicationGraph => {
const parsed = javascriptApplicationGraphInputSchema.parse(input);
const semantic: JavaScriptApplicationGraphInput = {
...parsed,
root_node_ids: uniqueSorted(parsed.root_node_ids),
nodes: [...parsed.nodes].sort((left, right) =>
compareCodePoints(left.node_id, right.node_id),
),
edges: [...parsed.edges].sort((left, right) =>
compareCodePoints(left.edge_id, right.edge_id),
),
coverage: {
...parsed.coverage,
limits: normalizeLimits(parsed.coverage.limits),
},
limitations: uniqueSorted(parsed.limitations),
};
return javascriptApplicationGraphSchema.parse({
...semantic,
graph_id: `jag_${digestCanonical(semantic)}`,
});
};
/** Parse a stored graph, rejecting unsupported versions and stale IDs. */
export const parseJavaScriptApplicationGraph = (
input: unknown,
): JavaScriptApplicationGraph => {
const envelope = z
.object({ schema: z.string(), schema_version: z.number() })
.passthrough()
.safeParse(input);
if (
envelope.success &&
envelope.data.schema === "JavaScriptApplicationGraph" &&
envelope.data.schema_version !== 1
)
throw new TypeError(
`Unsupported JavaScript Application Graph schema version: ${String(envelope.data.schema_version)}`,
);
return javascriptApplicationGraphSchema.parse(input);
};
/** Compute the byte-stable SHA-256 commitment of a verified graph. */
export const computeJavaScriptApplicationGraphSha256 = (
input: unknown,
): string => digestCanonical(parseJavaScriptApplicationGraph(input));
/** Serialize a verified graph as RFC 8785 canonical JSON. */
export const serializeJavaScriptApplicationGraph = (input: unknown): string =>
canonicalJson(parseJavaScriptApplicationGraph(input));
export type { ApplicationEdge, ApplicationGraphEvidence, ApplicationNode };
@@ -0,0 +1,164 @@
import { z } from "zod";
import {
applicationCoverageSchema,
applicationGraphEvidenceSchema,
applicationNodeIdentitySchema,
} from "./javascriptApplicationEvidenceSchemas.js";
import { isJsonWithinLimits } from "./jsonLimits.js";
import { jsonValueSchema } from "./jsonValue.js";
const boundedTextSchema = z.string().min(1).max(4_096);
/** Node kinds admitted by JavaScript Application Graph v1. */
export const JAVASCRIPT_APPLICATION_NODE_KINDS = [
"package",
"installer",
"artifact",
"asar-entry",
"electron-main",
"electron-preload",
"electron-renderer",
"electron-utility",
"javascript-asset",
"javascript-chunk",
"javascript-module",
"source-map",
"source-module",
"browser-window",
"frame",
"target",
"context-bridge-api",
"ipc-channel",
"ipc-handler",
"worker",
"service-worker",
"endpoint",
"storage",
"native-addon",
"native-export",
"runtime-script-instance",
"unknown",
] as const;
/** Provider-neutral application entity categories. */
const applicationNodeKindSchema = z.enum(JAVASCRIPT_APPLICATION_NODE_KINDS);
/** Directed relations admitted by JavaScript Application Graph v1. */
export const JAVASCRIPT_APPLICATION_RELATIONS = [
"contains",
"loads",
"imports",
"maps_to",
"exposes",
"sends",
"invokes",
"handles",
"calls",
"persists_to",
"observed_as",
"changed_from",
] as const;
/** Provider-neutral relation categories. */
const applicationRelationSchema = z.enum(JAVASCRIPT_APPLICATION_RELATIONS);
const applicationPropertiesSchema = z
.record(z.string().min(1).max(128), jsonValueSchema)
.superRefine((properties, context) => {
if (Object.keys(properties).length > 64)
context.addIssue({
code: "custom",
message: "Application graph properties exceed 64 keys",
});
if (
!isJsonWithinLimits(properties, {
maxDepth: 6,
maxNodes: 512,
maxStringLength: 4_096,
})
)
context.addIssue({
code: "custom",
message: "Application graph properties exceed structural limits",
});
});
/** One node observation before its semantic identifier is derived. */
const applicationNodeObservationInputSchema = z.strictObject({
label: z.string().min(1).max(1_024).nullable(),
properties: applicationPropertiesSchema,
evidence: applicationGraphEvidenceSchema,
});
/** One immutable, evidence-bearing observation attached to an entity. */
export const applicationNodeObservationSchema =
applicationNodeObservationInputSchema.extend({
observation_id: z.string().regex(/^jag_observation_[a-f0-9]{64}$/u),
identifier_strategy: z.strictObject({
strategy: z.literal("semantic-content-sha256"),
stability: z.literal("observation-exact"),
}),
});
/** One application entity before its stable identifier is derived. */
export const applicationNodeInputSchema = z.strictObject({
kind: applicationNodeKindSchema,
identity: applicationNodeIdentitySchema,
observations: z.array(applicationNodeObservationInputSchema).min(1).max(64),
});
/** One stable application entity with one or more bounded observations. */
export const applicationNodeSchema = z.strictObject({
node_id: z.string().regex(/^jag_node_[a-f0-9]{64}$/u),
kind: applicationNodeKindSchema,
identity: applicationNodeIdentitySchema,
observations: z.array(applicationNodeObservationSchema).min(1).max(64),
});
/** One directed relationship before its semantic identifier is derived. */
export const applicationEdgeInputSchema = z.strictObject({
source_node_id: z.string().regex(/^jag_node_[a-f0-9]{64}$/u),
target_node_id: z.string().regex(/^jag_node_[a-f0-9]{64}$/u),
relation: applicationRelationSchema,
properties: applicationPropertiesSchema,
evidence: applicationGraphEvidenceSchema,
});
/** One directed, evidence-bearing application relationship. */
export const applicationEdgeSchema = applicationEdgeInputSchema.extend({
edge_id: z.string().regex(/^jag_edge_[a-f0-9]{64}$/u),
identifier_strategy: z.strictObject({
strategy: z.literal("semantic-content-sha256"),
stability: z.literal("relationship-exact"),
}),
});
/** Graph content before its top-level semantic identifier is derived. */
export const javascriptApplicationGraphInputSchema = z.strictObject({
schema: z.literal("JavaScriptApplicationGraph"),
schema_version: z.literal(1),
root_node_ids: z
.array(z.string().regex(/^jag_node_[a-f0-9]{64}$/u))
.min(1)
.max(1_000),
nodes: z.array(applicationNodeSchema).min(1).max(100_000),
edges: z.array(applicationEdgeSchema).max(200_000),
coverage: applicationCoverageSchema,
limitations: z.array(boundedTextSchema).max(1_000),
});
/** Strict stored shape for JavaScript Application Graph v1. */
export const javascriptApplicationGraphRecordSchema =
javascriptApplicationGraphInputSchema.extend({
graph_id: z.string().regex(/^jag_[a-f0-9]{64}$/u),
});
/** Immutable entity in a JavaScript Application Graph. */
export type ApplicationNode = z.infer<typeof applicationNodeSchema>;
/** Immutable relationship in a JavaScript Application Graph. */
export type ApplicationEdge = z.infer<typeof applicationEdgeSchema>;
/** Complete v1 graph content before its graph identifier is derived. */
export type JavaScriptApplicationGraphInput = z.infer<
typeof javascriptApplicationGraphInputSchema
>;