/
index.ts
148 lines (141 loc) · 4.38 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/* eslint-disable complexity, @typescript-eslint/no-explicit-any */
import * as rt from "runtypes";
const nevAssert = (_: never, msg: string) => {
throw new Error(msg);
};
const isPojo = (x: unknown): x is object =>
x !== null &&
typeof x === "object" &&
Number.isInteger(Object.keys(x).length);
const childValue = (parent: unknown, key: string | number) =>
parent == null ? undefined : (parent as any)[key];
export type ArrayIndexedStructuralValidationResult = {
index: number;
result: StructuralValidationResult;
};
export type StringIndexedStructuralValidationResult = {
[key: string]: StructuralValidationResult;
};
export type StructuralValidationResult =
| string
| undefined
| ArrayIndexedStructuralValidationResult[]
| StringIndexedStructuralValidationResult;
export function validate<S extends rt.Runtype>(
schema: S,
value: unknown,
opts: {
useFirstUnionSchemaOnFail?: boolean;
useHighestKeyMatchRecordFailure?: boolean;
} = {
useFirstUnionSchemaOnFail: false,
useHighestKeyMatchRecordFailure: false,
}
): StructuralValidationResult {
const r = schema.reflect;
switch (r.tag) {
case "dictionary": {
if (isPojo(value)) {
return Object.entries(value).reduce((acc, [k, v]) => {
const child = validate(r.value, v, opts);
return child === undefined ? acc : { ...acc, [k]: child };
}, {});
} else {
return `Expected object, got ${value === null ? "null" : typeof value}`;
}
}
case "record": {
if (isPojo(value)) {
return Object.entries(r.fields).reduce((acc, [k, v]) => {
const child = validate(v, childValue(value, k), opts);
return child === undefined ? acc : { ...(acc || {}), [k]: child };
}, undefined as undefined | { [key: string]: StructuralValidationResult });
} else {
return `Expected object, got "${
value === null ? "null" : typeof value
}"`;
}
}
case "union": {
const firstSchema = r.alternatives[0];
const highestMatchRecordFailure: {
numKeysMatch: number;
result: StructuralValidationResult;
} = {
numKeysMatch: 0,
result: undefined,
};
const isValid = r.alternatives.some((subschema) => {
const result = validate(subschema, value, opts);
const isOk = result === undefined;
// discern highest matching record failure
if (!isOk && subschema.reflect.tag === "record") {
const fieldNames = new Set(Object.keys(subschema.reflect.fields));
const numKeysMatched = isPojo(value)
? Object.keys(value).reduce(
(acc, key) => acc + (fieldNames.has(key) ? 1 : 0),
0
)
: 0;
if (numKeysMatched > highestMatchRecordFailure.numKeysMatch) {
highestMatchRecordFailure.numKeysMatch = numKeysMatched;
highestMatchRecordFailure.result = result;
}
}
return isOk;
});
return isValid
? undefined
: opts.useHighestKeyMatchRecordFailure &&
highestMatchRecordFailure?.result
? highestMatchRecordFailure?.result
: opts?.useFirstUnionSchemaOnFail && firstSchema
? validate(firstSchema, value, opts)
: `No alternative schemas in the union matched "${typeof value}"`;
}
case "tuple": {
const results = r.components
.map((subschema, i) => {
const result = validate(subschema, childValue(value, i), opts);
return result
? undefined
: {
index: i,
result,
};
})
.filter(Boolean) as ArrayIndexedStructuralValidationResult[];
return results.length ? undefined : results;
}
case "array":
case "bigint":
case "boolean":
case "brand":
case "constraint":
case "function":
case "instanceof":
case "literal":
case "never":
case "number":
case "optional":
case "string":
case "symbol":
case "template":
case "void":
case "unknown": {
try {
r.check(value);
return undefined;
} catch (err) {
return err instanceof Error ? err.message : "invalid data";
}
}
case "intersect": {
throw new Error("unsupported");
}
default: {
nevAssert(r, `unhandled ${r}`);
}
}
throw new Error("unhandled");
}