Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

change-facts.ts

116 lines3.7 KB

1/**
2 * Whether two model snapshots are the same fact.
3 *
4 * A source hash, an extract time, object key order, the operand order of
5 * `+`, and the order of an input's `values` are not facts. Everything else
6 * in the snapshot is, including `expiresAt` and a rate.
7 */
8import { stableStringify } from '#/server/kv.ts'
9​
10function isRecord(value: unknown): value is Record<string, unknown> {
11 return typeof value === 'object' && value !== null && !Array.isArray(value)
13​
14/** `Array.isArray` types the elements as `any`. Copy them as `unknown`. */
15function copyArray(value: unknown): Array<unknown> | null {
16 if (!Array.isArray(value)) return null
17 return (value as Array<unknown>).slice()
19​
20function compareValue(a: unknown, b: unknown): number {
21 const as = typeof a === 'string' ? a : stableStringify(a)
22 const bs = typeof b === 'string' ? b : stableStringify(b)
23 return as < bs ? -1 : as > bs ? 1 : 0
25​
26/** Drop the clock and the text hash. The URL and `expiresAt` stay. */
27function stripSource(source: unknown): void {
28 if (!isRecord(source)) return
29 delete source.hash
30 delete source.extractedAt
32​
33function normalizeInputs(inputs: unknown): void {
34 if (!isRecord(inputs)) return
35 for (const input of Object.values(inputs)) {
36 if (!isRecord(input)) continue
37 const values = copyArray(input.values)
38 if (values) input.values = values.sort(compareValue)
39 if (isRecord(input.estimate)) {
40 stripSource(input.estimate.source)
41 normalizeInputs(input.estimate.inputs)
42 }
43 }
45​
46/** Sort every `+` after its operands are themselves canonical. */
47function sortPlus(value: unknown): unknown {
48 if (Array.isArray(value)) return value.map(sortPlus)
49 if (!isRecord(value)) return value
50 const out: Record<string, unknown> = {}
51 for (const [key, child] of Object.entries(value)) {
52 const sorted = sortPlus(child)
53 const operands = key === '+' ? copyArray(sorted) : null
54 out[key] = operands ? operands.sort(compareValue) : sorted
55 }
56 return out
58​
59function normalizePricing(pricing: unknown): void {
60 if (!isRecord(pricing)) return
61 stripSource(pricing.source)
62 normalizeInputs(pricing.inputs)
63 if ('price' in pricing) pricing.price = sortPlus(pricing.price)
65​
66/** Snapshot reduced to facts. The argument is not mutated. */
67function facts(snapshot: unknown): unknown {
68 const copy: unknown = structuredClone(snapshot)
69 if (isRecord(copy)) normalizePricing(copy.pricing)
70 return copy
72​
73function diff(a: unknown, b: unknown, path: string, out: Array<string>): void {
74 if (stableStringify(a) === stableStringify(b)) return
75 if (isRecord(a) && isRecord(b)) {
76 const keys = new Set([...Object.keys(a), ...Object.keys(b)])
77 for (const key of [...keys].sort()) {
78 diff(a[key], b[key], path === '' ? key : `${path}.${key}`, out)
79 }
80 return
81 }
82 if (Array.isArray(a) && Array.isArray(b)) {
83 const length = Math.max(a.length, b.length)
84 for (let index = 0; index < length; index++) {
85 diff(a[index], b[index], `${path}.${String(index)}`, out)
86 }
87 return
88 }
89 if (path !== '') out.push(path)
91​
92/** Field paths that differ between the fact forms. Sorted. Empty when equal. */
93export function changedFactPaths(
94 before: unknown,
95 after: unknown,
96): Array<string> {
97 const paths: Array<string> = []
98 diff(facts(before), facts(after), '', paths)
99 paths.sort()
100 return paths
102​
103/**
104 * The `model.updated` payload. Refuses an empty `changed` list: an event
105 * with nothing to report is not written.
106 */
107export function modelUpdatedPayload(
108 before: unknown,
109 after: unknown,
110 changed: ReadonlyArray<string>,
111): { before: unknown; after: unknown; changed: Array<string> } {
112 if (changed.length === 0) {
113 throw new Error('model.updated requires a changed fact')
114 }
115 return { before, after, changed: [...changed] }