@silverprotocol/core 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.
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./agjson.js";
2
+ export * from "./ingest.js";
3
+ export * from "./reduce.js";
4
+ export * from "./stream-assembler.js";
5
+ export * from "./wire.js";
package/src/ingest.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Consumer-ingestion posture (SPEC §0.2 / §12; audit B5).
3
+ *
4
+ * A consumer validating incoming events MUST parse-known-else-skip and pass
5
+ * unknown fields through, so additive-minor spec revisions survive. This is
6
+ * DISTINCT from producer conformance (`AgEvent.parse`), which rejects anything
7
+ * outside the schema.
8
+ *
9
+ * Field-passthrough scope: unknown TOP-LEVEL fields are preserved verbatim.
10
+ * Nested structured sub-objects are returned in validated form; the opaque
11
+ * channels (`_meta`, `providerMetadata`, provider payload fields) are typed as
12
+ * opaque bags and therefore pass through in full by construction.
13
+ */
14
+ import { AgEvent, type JsonValue } from "./agjson.js";
15
+
16
+ export function ingestAgEvent(v: JsonValue): AgEvent | undefined {
17
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return undefined;
18
+ const r = AgEvent.safeParse(v);
19
+ if (!r.success) return undefined;
20
+ // Preserve unknown top-level fields: validated keys win, unknown keys ride along.
21
+ return Object.assign({}, v, r.data);
22
+ }
23
+
24
+ export function ingestAgEvents(vs: JsonValue[]): AgEvent[] {
25
+ const out: AgEvent[] = [];
26
+ for (const v of vs) {
27
+ const e = ingestAgEvent(v);
28
+ if (e !== undefined) out.push(e);
29
+ }
30
+ return out;
31
+ }
@@ -0,0 +1,456 @@
1
+ import type { JsonValue } from "./agjson.js";
2
+
3
+ // ─────────────────────────────────────────────────────────────────────────────
4
+ // Inline RFC-6902 JSON-Patch applier (reduce R6).
5
+ //
6
+ // Contract: applyPatch(doc, patch) → { ok: true; value: JsonValue } | { ok: false }
7
+ //
8
+ // Design rules:
9
+ // • NEVER throws — all failure paths return { ok: false }.
10
+ // • PURE — returns a NEW document; never mutates `doc`.
11
+ // • ATOMIC — applies to a working clone; returns { ok: true, value } only if
12
+ // EVERY op succeeds; otherwise returns { ok: false } and `doc` is untouched.
13
+ // • Signals (ok:false) on: malformed patch, malformed op, absent path for
14
+ // replace/remove/move/copy-from, failed test op, out-of-bounds index.
15
+ //
16
+ // RFC-6901 pointer parsing:
17
+ // • split on "/"; unescape "~1" → "/" then "~0" → "~" (ORDER MATTERS).
18
+ // • "" (empty pointer) = the whole document (root replacement).
19
+ // ─────────────────────────────────────────────────────────────────────────────
20
+
21
+ /** Result type returned by applyPatch. */
22
+ export type PatchResult = { ok: true; value: JsonValue } | { ok: false };
23
+
24
+ /** Failure sentinel — used internally to signal any error without throwing. */
25
+ const FAIL: { ok: false } = { ok: false };
26
+
27
+ /**
28
+ * Discriminated result for internal pointer helpers.
29
+ * Using a distinct wrapper avoids overloading `null` as both a valid JsonValue
30
+ * (e.g. the document IS null) and a failure sentinel — which is the root cause
31
+ * of the null-at-root silent corruption bug (R6 fix 1).
32
+ */
33
+ type PointerResult = { ok: true; doc: JsonValue } | { ok: false };
34
+
35
+ const POINTER_FAIL: PointerResult = { ok: false };
36
+
37
+ // ── Type guards ────────────────────────────────────────────────────────────────
38
+
39
+ /** Narrow JsonValue to a plain JSON object (non-array, non-null). */
40
+ function isJsonObject(v: JsonValue): v is { [k: string]: JsonValue } {
41
+ return typeof v === "object" && v !== null && !Array.isArray(v);
42
+ }
43
+
44
+ /** Narrow JsonValue to a JSON array. */
45
+ function isJsonArray(v: JsonValue): v is JsonValue[] {
46
+ return Array.isArray(v);
47
+ }
48
+
49
+ // ── RFC-6901 pointer helpers ──────────────────────────────────────────────────
50
+
51
+ /**
52
+ * Parse a RFC-6901 JSON Pointer string into its reference-token array.
53
+ * Empty string → [] (root).
54
+ * "/foo/bar" → ["foo", "bar"].
55
+ * Unescaping: "~1" → "/" then "~0" → "~" (order mandated by spec).
56
+ */
57
+ function parsePointer(ptr: string): string[] | null {
58
+ if (ptr === "") return [];
59
+ if (!ptr.startsWith("/")) return null; // malformed — must start with "/"
60
+ return ptr
61
+ .slice(1)
62
+ .split("/")
63
+ .map((tok) => tok.replace(/~1/g, "/").replace(/~0/g, "~"));
64
+ }
65
+
66
+ /**
67
+ * Resolve a JSON Pointer in a document, returning { parent, key, value } on
68
+ * success, or null on failure (absent path, wrong type at an intermediate node).
69
+ *
70
+ * `parent` is the object/array containing `key`; for the root pointer ([])
71
+ * there is no parent, so parent=null and key="" are returned (callers handle
72
+ * root as a special case).
73
+ */
74
+ function resolve(
75
+ doc: JsonValue,
76
+ tokens: string[],
77
+ ): { parent: { [k: string]: JsonValue } | JsonValue[]; key: string; value: JsonValue } | { parent: null; key: ""; value: JsonValue } | null {
78
+ if (tokens.length === 0) {
79
+ return { parent: null, key: "", value: doc };
80
+ }
81
+
82
+ let node: JsonValue = doc;
83
+ for (let i = 0; i < tokens.length - 1; i++) {
84
+ const tok = tokens[i];
85
+ if (tok === undefined) return null;
86
+ if (isJsonArray(node)) {
87
+ const idx = arrayIndex(tok, node.length, false);
88
+ if (idx === null) return null;
89
+ const child = node[idx];
90
+ if (child === undefined) return null;
91
+ node = child;
92
+ } else if (isJsonObject(node)) {
93
+ const child = node[tok];
94
+ if (child === undefined) return null;
95
+ node = child;
96
+ } else {
97
+ return null; // scalar — can't descend further
98
+ }
99
+ }
100
+
101
+ const lastTok = tokens[tokens.length - 1];
102
+ if (lastTok === undefined) return null;
103
+
104
+ if (isJsonArray(node)) {
105
+ const idx = arrayIndex(lastTok, node.length, false);
106
+ if (idx === null) return null;
107
+ const value = node[idx];
108
+ if (value === undefined) return null;
109
+ return { parent: node, key: String(idx), value };
110
+ } else if (isJsonObject(node)) {
111
+ const value = node[lastTok];
112
+ if (value === undefined) return null;
113
+ return { parent: node, key: lastTok, value };
114
+ }
115
+ return null;
116
+ }
117
+
118
+ /**
119
+ * Convert a JSON Pointer token to a numeric array index.
120
+ * - "0".."n" are valid non-negative integers.
121
+ * - "-" is the append-sentinel (only valid for `add`).
122
+ * - Out-of-bounds for the given length → null.
123
+ *
124
+ * @param tok The token string.
125
+ * @param len Current array length.
126
+ * @param allowDash If true, "-" maps to `len` (append position for `add`).
127
+ */
128
+ function arrayIndex(tok: string, len: number, allowDash: boolean): number | null {
129
+ if (tok === "-") {
130
+ return allowDash ? len : null;
131
+ }
132
+ // RFC-6902: leading zeros are disallowed except for "0" itself.
133
+ if (!/^\d+$/.test(tok)) return null;
134
+ if (tok.length > 1 && tok.startsWith("0")) return null;
135
+ const n = Number(tok);
136
+ // For non-add ops: must be within [0, len-1]; for add, [0, len] is handled by the caller.
137
+ if (n > len) return null;
138
+ return n;
139
+ }
140
+
141
+ // ── Structural set/remove helpers (operate on a working clone) ────────────────
142
+
143
+ /**
144
+ * Set a value at the given pointer tokens in `doc`.
145
+ * For `add` semantics pass `isAdd=true` — enables "-" sentinel and insertion.
146
+ * For `replace` semantics pass `isAdd=false` — target must already exist.
147
+ * Returns a PointerResult: { ok: true; doc: JsonValue } on success, { ok: false }
148
+ * on failure. Uses a discriminated wrapper (not null) so that a legitimate null
149
+ * document value (e.g. root replacement with null) is never confused with failure.
150
+ */
151
+ function pointerSet(
152
+ doc: JsonValue,
153
+ tokens: string[],
154
+ value: JsonValue,
155
+ isAdd: boolean,
156
+ ): PointerResult {
157
+ if (tokens.length === 0) {
158
+ // Root replacement: always ok. value may legally be null.
159
+ return { ok: true, doc: value };
160
+ }
161
+
162
+ // Recurse to find the parent container.
163
+ if (tokens.length === 1) {
164
+ const tok = tokens[0];
165
+ if (tok === undefined) return POINTER_FAIL;
166
+
167
+ if (isJsonArray(doc)) {
168
+ const idx = arrayIndex(tok, doc.length, isAdd);
169
+ if (idx === null) return POINTER_FAIL;
170
+ if (!isAdd && idx >= doc.length) return POINTER_FAIL; // replace requires existing
171
+ const copy: JsonValue[] = [...doc];
172
+ if (isAdd) {
173
+ copy.splice(idx, 0, value);
174
+ } else {
175
+ copy[idx] = value;
176
+ }
177
+ return { ok: true, doc: copy };
178
+ } else if (isJsonObject(doc)) {
179
+ // Object: add creates/replaces; replace requires the key to exist.
180
+ if (!isAdd && !(tok in doc)) return POINTER_FAIL; // replace: key must exist
181
+ return { ok: true, doc: { ...doc, [tok]: value } };
182
+ }
183
+ return POINTER_FAIL; // scalar — cannot descend
184
+ }
185
+
186
+ // Multi-segment: recurse into the next node.
187
+ const tok = tokens[0];
188
+ if (tok === undefined) return POINTER_FAIL;
189
+ const rest = tokens.slice(1);
190
+
191
+ if (isJsonArray(doc)) {
192
+ const idx = arrayIndex(tok, doc.length, false);
193
+ if (idx === null || idx >= doc.length) return POINTER_FAIL;
194
+ const child = doc[idx];
195
+ if (child === undefined) return POINTER_FAIL;
196
+ const childResult = pointerSet(child, rest, value, isAdd);
197
+ if (!childResult.ok) return POINTER_FAIL;
198
+ const copy: JsonValue[] = [...doc];
199
+ copy[idx] = childResult.doc;
200
+ return { ok: true, doc: copy };
201
+ } else if (isJsonObject(doc)) {
202
+ const child = doc[tok];
203
+ if (child === undefined) return POINTER_FAIL;
204
+ const childResult = pointerSet(child, rest, value, isAdd);
205
+ if (!childResult.ok) return POINTER_FAIL;
206
+ return { ok: true, doc: { ...doc, [tok]: childResult.doc } };
207
+ }
208
+ return POINTER_FAIL; // scalar — cannot descend
209
+ }
210
+
211
+ /**
212
+ * Remove the value at the given pointer tokens in `doc`.
213
+ * Returns a PointerResult: { ok: true; doc: JsonValue } on success, { ok: false }
214
+ * on failure. Uses a discriminated wrapper (not null) so that legitimate null
215
+ * values in the document are never confused with failure.
216
+ */
217
+ function pointerRemove(doc: JsonValue, tokens: string[]): PointerResult {
218
+ if (tokens.length === 0) {
219
+ // RFC-6902: removing the root is invalid.
220
+ return POINTER_FAIL;
221
+ }
222
+
223
+ if (tokens.length === 1) {
224
+ const tok = tokens[0];
225
+ if (tok === undefined) return POINTER_FAIL;
226
+
227
+ if (isJsonArray(doc)) {
228
+ // "-" is not a valid remove target (append-only sentinel).
229
+ const idx = arrayIndex(tok, doc.length, false);
230
+ if (idx === null || idx >= doc.length) return POINTER_FAIL;
231
+ const copy: JsonValue[] = [...doc];
232
+ copy.splice(idx, 1);
233
+ return { ok: true, doc: copy };
234
+ } else if (isJsonObject(doc)) {
235
+ if (!(tok in doc)) return POINTER_FAIL;
236
+ const { [tok]: _removed, ...rest } = doc;
237
+ return { ok: true, doc: rest };
238
+ }
239
+ return POINTER_FAIL;
240
+ }
241
+
242
+ // Multi-segment: recurse.
243
+ const tok = tokens[0];
244
+ if (tok === undefined) return POINTER_FAIL;
245
+ const rest = tokens.slice(1);
246
+
247
+ if (isJsonArray(doc)) {
248
+ const idx = arrayIndex(tok, doc.length, false);
249
+ if (idx === null || idx >= doc.length) return POINTER_FAIL;
250
+ const child = doc[idx];
251
+ if (child === undefined) return POINTER_FAIL;
252
+ const childResult = pointerRemove(child, rest);
253
+ if (!childResult.ok) return POINTER_FAIL;
254
+ const copy: JsonValue[] = [...doc];
255
+ copy[idx] = childResult.doc;
256
+ return { ok: true, doc: copy };
257
+ } else if (isJsonObject(doc)) {
258
+ const child = doc[tok];
259
+ if (child === undefined) return POINTER_FAIL;
260
+ const childResult = pointerRemove(child, rest);
261
+ if (!childResult.ok) return POINTER_FAIL;
262
+ return { ok: true, doc: { ...doc, [tok]: childResult.doc } };
263
+ }
264
+ return POINTER_FAIL;
265
+ }
266
+
267
+ // ── Deep-equality for `test` op ───────────────────────────────────────────────
268
+
269
+ /** RFC-6902 §4.6 deep equality — structural JSON equality (no undefined, no NaN). */
270
+ function deepEqual(a: JsonValue, b: JsonValue): boolean {
271
+ if (a === b) return true;
272
+ if (a === null || b === null) return false;
273
+ if (typeof a !== typeof b) return false;
274
+ if (isJsonArray(a) && isJsonArray(b)) {
275
+ if (a.length !== b.length) return false;
276
+ for (let i = 0; i < a.length; i++) {
277
+ const ai = a[i];
278
+ const bi = b[i];
279
+ if (ai === undefined || bi === undefined) return false;
280
+ if (!deepEqual(ai, bi)) return false;
281
+ }
282
+ return true;
283
+ }
284
+ if (isJsonArray(a) || isJsonArray(b)) return false;
285
+ if (isJsonObject(a) && isJsonObject(b)) {
286
+ const aKeys = Object.keys(a);
287
+ const bKeys = Object.keys(b);
288
+ if (aKeys.length !== bKeys.length) return false;
289
+ for (const k of aKeys) {
290
+ if (!(k in b)) return false;
291
+ const av = a[k];
292
+ const bv = b[k];
293
+ if (av === undefined || bv === undefined) return false;
294
+ if (!deepEqual(av, bv)) return false;
295
+ }
296
+ return true;
297
+ }
298
+ return false;
299
+ }
300
+
301
+ // ── Op shape guards ───────────────────────────────────────────────────────────
302
+
303
+ /** Narrow an op entry to the expected shape before dispatching. */
304
+ function isObj(v: JsonValue): v is { [k: string]: JsonValue } {
305
+ return isJsonObject(v);
306
+ }
307
+
308
+ function getString(obj: { [k: string]: JsonValue }, key: string): string | null {
309
+ const v = obj[key];
310
+ return typeof v === "string" ? v : null;
311
+ }
312
+
313
+ // ── applyPatch ────────────────────────────────────────────────────────────────
314
+
315
+ /**
316
+ * Apply an RFC-6902 JSON Patch to `doc`.
317
+ *
318
+ * PURE: returns a new document; never mutates `doc`.
319
+ * ATOMIC: if any op fails, returns { ok: false } — no partial result is ever
320
+ * returned.
321
+ * NEVER THROWS: all error paths return { ok: false }.
322
+ *
323
+ * @param doc The document to patch (not mutated).
324
+ * @param patch The patch — must be a JSON array of op objects.
325
+ * @returns { ok: true; value: JsonValue } | { ok: false }
326
+ */
327
+ export function applyPatch(doc: JsonValue, patch: JsonValue): PatchResult {
328
+ try {
329
+ // Reject non-array patch.
330
+ if (!Array.isArray(patch)) return FAIL;
331
+
332
+ // Apply all ops to a working copy (structuredClone for isolation from `doc`).
333
+ let working: JsonValue = structuredClone(doc);
334
+
335
+ for (const rawOp of patch) {
336
+ if (rawOp === undefined) return FAIL;
337
+ if (!isObj(rawOp)) return FAIL;
338
+
339
+ const op = getString(rawOp, "op");
340
+ const pathStr = getString(rawOp, "path");
341
+ if (op === null || pathStr === null) return FAIL;
342
+
343
+ const pathTokens = parsePointer(pathStr);
344
+ if (pathTokens === null) return FAIL;
345
+
346
+ switch (op) {
347
+ case "add": {
348
+ const value = rawOp["value"];
349
+ if (value === undefined) return FAIL;
350
+ const result = pointerSet(working, pathTokens, value, true);
351
+ if (!result.ok) return FAIL;
352
+ working = result.doc;
353
+ break;
354
+ }
355
+
356
+ case "remove": {
357
+ const result = pointerRemove(working, pathTokens);
358
+ if (!result.ok) return FAIL;
359
+ working = result.doc;
360
+ break;
361
+ }
362
+
363
+ case "replace": {
364
+ const value = rawOp["value"];
365
+ if (value === undefined) return FAIL;
366
+ const result = pointerSet(working, pathTokens, value, false);
367
+ if (!result.ok) return FAIL;
368
+ working = result.doc;
369
+ break;
370
+ }
371
+
372
+ case "move": {
373
+ const fromStr = getString(rawOp, "from");
374
+ if (fromStr === null) return FAIL;
375
+ const fromTokens = parsePointer(fromStr);
376
+ if (fromTokens === null) return FAIL;
377
+
378
+ // A move into one of its own descendants is illegal.
379
+ if (isProperPrefix(fromTokens, pathTokens)) return FAIL;
380
+
381
+ // Identity move (from === path): no-op per RFC-6902 §4.4 semantics.
382
+ if (fromStr === pathStr) break;
383
+
384
+ // Get the value at `from`.
385
+ const resolved = resolve(working, fromTokens);
386
+ if (resolved === null) return FAIL;
387
+ const movedValue = resolved.value;
388
+
389
+ // Remove from `from`.
390
+ const afterRemove = pointerRemove(working, fromTokens);
391
+ if (!afterRemove.ok) return FAIL;
392
+
393
+ // Add at `path`.
394
+ const afterAdd = pointerSet(afterRemove.doc, pathTokens, movedValue, true);
395
+ if (!afterAdd.ok) return FAIL;
396
+ working = afterAdd.doc;
397
+ break;
398
+ }
399
+
400
+ case "copy": {
401
+ const fromStr = getString(rawOp, "from");
402
+ if (fromStr === null) return FAIL;
403
+ const fromTokens = parsePointer(fromStr);
404
+ if (fromTokens === null) return FAIL;
405
+
406
+ // Get the value at `from`.
407
+ const resolved = resolve(working, fromTokens);
408
+ if (resolved === null) return FAIL;
409
+ // Deep-clone the copied value to keep the patch pure.
410
+ const copiedValue: JsonValue = structuredClone(resolved.value);
411
+
412
+ // Add at `path`.
413
+ const result = pointerSet(working, pathTokens, copiedValue, true);
414
+ if (!result.ok) return FAIL;
415
+ working = result.doc;
416
+ break;
417
+ }
418
+
419
+ case "test": {
420
+ const value = rawOp["value"];
421
+ if (value === undefined) return FAIL;
422
+
423
+ const resolved = resolve(working, pathTokens);
424
+ if (resolved === null) return FAIL;
425
+ if (!deepEqual(resolved.value, value)) return FAIL;
426
+ // `test` op does not modify the document.
427
+ break;
428
+ }
429
+
430
+ default:
431
+ // Unknown op → fail.
432
+ return FAIL;
433
+ }
434
+ }
435
+
436
+ return { ok: true, value: working };
437
+ } catch {
438
+ // Catch-all: structuredClone or anything unexpected — never propagate.
439
+ return FAIL;
440
+ }
441
+ }
442
+
443
+ // ── Utility ───────────────────────────────────────────────────────────────────
444
+
445
+ /**
446
+ * Returns true if `prefix` is a proper prefix of `tokens`
447
+ * (i.e., every element of prefix equals the corresponding element of tokens,
448
+ * and tokens is strictly longer). Used to detect illegal move-into-descendant.
449
+ */
450
+ function isProperPrefix(prefix: string[], tokens: string[]): boolean {
451
+ if (prefix.length >= tokens.length) return false;
452
+ for (let i = 0; i < prefix.length; i++) {
453
+ if (prefix[i] !== tokens[i]) return false;
454
+ }
455
+ return true;
456
+ }