@flyingrobots/parley-read 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ // Validation, under spec §4.5 and §4.6. Three rules do all the work here:
2
+ //
3
+ // 1. Full validation is against the schema for the **exact** advertised `(id, version)` pair.
4
+ // Another version's schema, even the latest of the same major, is not validation.
5
+ // 2. With no schema for the exact pair, a reader MAY check the version-independent core — the
6
+ // §1.3 envelope and the shape of `_schema` — and MUST report that as *partial*.
7
+ // 3. A line whose `_schema.id` is not ours at all, such as a tool's own result type, is parsed
8
+ // and passed through, and the reader says it did not validate it.
9
+ //
10
+ // `_schema.id` and `_schema.version` are identifiers, not fetch instructions: the pair resolves
11
+ // against the schemas this package ships (`src/schemas.ts`, pinned by commit and digest) and
12
+ // nothing is fetched.
13
+ import Ajv2020, { type ErrorObject, type ValidateFunction } from "ajv/dist/2020.js";
14
+ import addFormats from "ajv-formats";
15
+ import { SCHEMAS } from "./schemas.ts";
16
+
17
+ export interface SchemaRef { readonly id: string; readonly version: string }
18
+
19
+ /** The fields §1.3 puts on every line. */
20
+ export const ENVELOPE = ["event", "t", "seq", "run", "_schema"] as const;
21
+ /** A `_schema.id` outside this prefix belongs to a tool, not to the protocol (§4.6). */
22
+ export const PROTOCOL_PREFIX = "parley.";
23
+
24
+ export type Validation =
25
+ /** Validated against the schema for this exact pair. */
26
+ | { readonly state: "validated"; readonly schema: SchemaRef }
27
+ /** The exact pair's schema rejected the line. */
28
+ | { readonly state: "invalid"; readonly schema: SchemaRef; readonly errors: readonly string[] }
29
+ /** A `parley.*` pair this reader ships no schema for: the core was checked, the contract was not (§4.5). */
30
+ | { readonly state: "partial"; readonly schema: SchemaRef; readonly missing: readonly string[] }
31
+ /** Not validated at all: a tool's own type, or a line that advertises no pair. */
32
+ | { readonly state: "unvalidated"; readonly schema: SchemaRef | null; readonly why: "tool_owned" | "no_schema_ref" };
33
+
34
+ export interface Validator {
35
+ /** True when this reader ships the schema for exactly this pair. */
36
+ has(id: string, version: string): boolean;
37
+ validate(record: Record<string, unknown>): Validation;
38
+ }
39
+
40
+ function describe(errors: ErrorObject[] | null | undefined): string[] {
41
+ return (errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message ?? ""}`.trim());
42
+ }
43
+
44
+ /** The §1.3 envelope fields a line is missing or has malformed; `[]` when the core is sound. */
45
+ export function envelopeGaps(record: Record<string, unknown>): string[] {
46
+ const missing: string[] = [];
47
+ for (const key of ENVELOPE) if (!(key in record)) missing.push(key);
48
+ if ("t" in record && !(Number.isInteger(record.t) && (record.t as number) >= 0)) missing.push("t");
49
+ if ("seq" in record && !(Number.isInteger(record.seq) && (record.seq as number) >= 0)) missing.push("seq");
50
+ if ("run" in record && !(typeof record.run === "string" && record.run.length > 0)) missing.push("run");
51
+ if ("event" in record && typeof record.event !== "string") missing.push("event");
52
+ const stamp = record._schema as Record<string, unknown> | undefined;
53
+ if (stamp !== undefined && !(typeof stamp.id === "string" && typeof stamp.version === "string")) missing.push("_schema");
54
+ return [...new Set(missing)];
55
+ }
56
+
57
+ /** Read a line's advertised pair, or null when it advertises none. */
58
+ export function schemaRef(record: Record<string, unknown>): SchemaRef | null {
59
+ const stamp = record._schema as { id?: unknown; version?: unknown } | undefined;
60
+ if (!stamp || typeof stamp.id !== "string" || typeof stamp.version !== "string") return null;
61
+ if (!stamp.id || !stamp.version) return null;
62
+ return { id: stamp.id, version: stamp.version };
63
+ }
64
+
65
+ /**
66
+ * A validator over the schemas this package ships. Compilation is lazy and cached, so a load of a
67
+ * thousand receipts compiles each schema once.
68
+ */
69
+ export function validator(schemas: ReadonlyArray<{ id: string; version: string; schema: Record<string, unknown> }> = SCHEMAS): Validator {
70
+ const byPair = new Map<string, Record<string, unknown>>();
71
+ for (const s of schemas) byPair.set(`${s.id}@${s.version}`, s.schema);
72
+ const ajv = new Ajv2020({ strict: false, allErrors: true });
73
+ addFormats(ajv);
74
+ const compiled = new Map<string, ValidateFunction>();
75
+
76
+ const compile = (pair: string): ValidateFunction => {
77
+ let fn = compiled.get(pair);
78
+ if (!fn) { fn = ajv.compile(byPair.get(pair)!); compiled.set(pair, fn); }
79
+ return fn;
80
+ };
81
+
82
+ return {
83
+ has: (id, version) => byPair.has(`${id}@${version}`),
84
+ validate(record) {
85
+ const schema = schemaRef(record);
86
+ if (!schema) return { state: "unvalidated", schema: null, why: "no_schema_ref" };
87
+ if (!schema.id.startsWith(PROTOCOL_PREFIX)) return { state: "unvalidated", schema, why: "tool_owned" };
88
+ const pair = `${schema.id}@${schema.version}`;
89
+ if (!byPair.has(pair)) return { state: "partial", schema, missing: envelopeGaps(record) };
90
+ const fn = compile(pair);
91
+ return fn(record) ? { state: "validated", schema } : { state: "invalid", schema, errors: describe(fn.errors) };
92
+ },
93
+ };
94
+ }