-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathz.ts
More file actions
368 lines (347 loc) · 18.7 KB
/
z.ts
File metadata and controls
368 lines (347 loc) · 18.7 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// deno-lint-ignore-file no-explicit-any
export const isNotEmpty: Rule<string> = (str, msg) => msg && msg('cannot be empty') || str !== '';
export const isValidTimestamp: Rule<string> = (str, msg) => msg && msg('must be a valid timestamp') || tryParseDate(str)?.toISOString() === str;
export const isValidUuid: Rule<string> = (str, msg) => msg && msg('must be a valid uuid') || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(str);
export const isValidUrl: Rule<string> = (str, msg) => msg && msg('must be a valid URL') || tryParseUrl(str) !== undefined;
export const isArrayDistinct: Rule<unknown[]> = (arr, msg) => msg && msg('must have distinct elements') || arr.every((v, index) => arr.indexOf(v) === index);
export const isStringRecord = (obj: unknown): obj is Record<string, unknown> => typeof obj === 'object' && obj !== null && !Array.isArray(obj) && obj.constructor === Object && Object.keys(obj).every(v => typeof v === 'string');
export const tryParseDate = (str: string): Date | undefined => { try { return new Date(str); } catch { /* noop */} };
export const tryParseUrl = (str: string): URL | undefined => { try { return URL.parse(str) || undefined; } catch { /* noop */} };
//
export type ParseOpts = string /* name */ | { name?: string, strict?: boolean };
export type Schema<TValue> = {
parse(input: unknown, opts?: ParseOpts): TValue,
}
export type Builder<TValue> = TValue & Schema<TValue> & {
default: (value: TValue) => Builder<TValue>,
optional: () => Builder<TValue | undefined>,
nullable: () => Builder<TValue | null>,
}
export type NumberBuilder<TValue> = TValue & Schema<TValue> & {
default: (value: TValue) => NumberBuilder<TValue>,
optional: () => NumberBuilder<TValue | undefined>,
nullable: () => NumberBuilder<TValue | null>,
convertString: () => NumberBuilder<TValue>,
min: (value: TValue) => NumberBuilder<TValue>,
gt: (value: TValue) => NumberBuilder<TValue>,
max: (value: TValue) => NumberBuilder<TValue>,
lt: (value: TValue) => NumberBuilder<TValue>,
}
export type ArrayBuilder<TValueArray> = TValueArray & Schema<TValueArray> & {
default: (value: TValueArray) => ArrayBuilder<TValueArray>,
optional: () => ArrayBuilder<TValueArray | undefined>,
nullable: () => ArrayBuilder<TValueArray | null>,
distinct: () => ArrayBuilder<TValueArray>,
min: (numItems: number) => ArrayBuilder<TValueArray>,
gt: (numItems: number) => ArrayBuilder<TValueArray>,
max: (numItems: number) => ArrayBuilder<TValueArray>,
lt: (numItems: number) => ArrayBuilder<TValueArray>,
}
export type Rule<T> = (input: T, msg?: (message: string) => false) => boolean;
// deno-lint-ignore ban-types
export type BasicObject<T> = T extends Function | Array<any> ? never : (T extends object ? T : never);
export type Z = {
boolean: (...rules: Rule<boolean>[]) => NumberBuilder<boolean>,
number: (...rules: Rule<number>[]) => NumberBuilder<number>,
integer: (...rules: Rule<number>[]) => NumberBuilder<number>,
unknown: (...rules: Rule<unknown>[]) => Builder<unknown>,
array: <T>(item: T, ...rules: Rule<T[]>[]) => ArrayBuilder<T[]>,
string: (...rules: (RegExp | Rule<string>)[]) => Builder<string>,
timestamp: (...rules: (RegExp | Rule<string>)[]) => Builder<string>,
uuid: (...rules: (RegExp | Rule<string>)[]) => Builder<string>,
url: (...rules: (RegExp | Rule<URL>)[]) => Builder<string>,
record: <K extends string | number | symbol, V>(key: K, value: V, ...rules: Rule<Record<K, V>>[]) => any, // TODO
object: <T>(type: BasicObject<T>, ...rules: Rule<T>[]) => Builder<T>,
literal: <T>(value: T, ...rules: Rule<T>[]) => Builder<T>,
union: <A, B>(lhs: A, rhs: B, ...rules: Rule<A | B>[]) => Builder<A | B>,
}
export const z: Z = {
boolean: (...rules) => {
return newBuilder({ schemaType: 'boolean', rules });
},
number: (...rules) => {
return newBuilder({ schemaType: 'number', rules });
},
integer: (...rules) => {
return z.number(...[ Number.isSafeInteger, ...rules ]);
},
unknown: (...rules) => {
return newBuilder({ schemaType: 'unknown', rules });
},
string: (...rulesOrRegexes) => {
const rules: Rule<string>[] = rulesOrRegexes.map(v => typeof v === 'function' ? v : p => v.test(p));
return newBuilder({ schemaType: 'string', rules });
},
timestamp: (...rules) => {
return z.string(...[ isValidTimestamp, ...rules ]);
},
uuid: (...rules) => {
return z.string(...[ isValidUuid, ...rules ]);
},
url: (...rulesOrRegexes) => {
const rules: Rule<string>[] = rulesOrRegexes.map(v => typeof v === 'function' ? (s=> v(URL.parse(s)!)) : p => v.test(p));
rules.unshift(isValidUrl);
return newBuilder({ schemaType: 'string', rules });
},
array: (arrayItemSchema, ...rules) => {
return newBuilder({ schemaType: 'array', rules, arrayItemSchema });
},
record: (recordKeySchema, recordValueSchema, ...rules) => {
return newBuilder({ schemaType: 'record', rules, recordKeySchema, recordValueSchema });
},
object: (objectSchema, ...rules) => {
return newBuilder({ schemaType: 'object', rules, objectSchema });
},
literal: (literalValue, ...rules) => {
return newBuilder({ schemaType: 'literal', rules, literalValue });
},
union: (lhsSchema, rhsSchema, ...rules) => {
return newBuilder({ schemaType: 'union', rules, lhsSchema, rhsSchema });
},
}
//
const stateSymbol = Symbol();
type SchemaType = 'boolean' | 'number' | 'string' | 'unknown' | 'array' | 'record' | 'object' | 'literal' | 'union';
type BuilderState<TValue> = {
schemaType: SchemaType | undefined, rules: Rule<TValue>[], arrayItemSchema?: any, recordKeySchema?: any, recordValueSchema?: any,
distinct?: boolean, defaultValue?: unknown, convertString?: boolean, minValue?: unknown, gtValue?: unknown, maxValue?: unknown, ltValue?: unknown, optional?: boolean,
objectSchema?: any, literalValue?: any, lhsSchema?: any, rhsSchema?: any, nullable?: boolean,
};
function computeLiteralDescription(value: unknown): string {
return typeof value === 'string' ? `'${value}'`
: `${value}`;
}
function computeSchemaDescriptionFromObject(obj: Record<string, unknown>): string {
if (!isStringRecord(obj)) throw new Error(`Unable to compute description for ${obj}`);
const computeValueType = (obj: unknown): string => Array.isArray(obj) ? 'any[]'
: isStringRecord(obj) ? computeSchemaDescriptionFromObject(obj)
: obj === null ? 'null'
: typeof obj;
const props: string[] = [];
for (const [ name, value ] of Object.entries(obj)) {
props.push(`${name}: ${computeValueType(value)}`);
}
return props.length === 0 ? '{}' : `{ ${props.join(', ')} }`;
}
function computeSchemaDescription(schema: any): string {
const {
schemaType, arrayItemSchema, recordKeySchema, recordValueSchema,
optional, nullable, objectSchema, literalValue, lhsSchema, rhsSchema
} = (schema[stateSymbol] ?? {}) as BuilderState<unknown>;
const base = schemaType === undefined && isStringRecord(schema) ? computeSchemaDescriptionFromObject(schema)
: (schemaType === 'boolean' || schemaType === 'number' || schemaType === 'string' || schemaType === 'unknown') ? schemaType
: schemaType === 'union' ? `${computeSchemaDescription(lhsSchema)} | ${computeSchemaDescription(rhsSchema)}`
: schemaType === 'array' ? `Array<${computeSchemaDescription(arrayItemSchema)}>`
: schemaType === 'literal' ? computeLiteralDescription(literalValue)
: schemaType === 'object' ? computeSchemaDescription(objectSchema)
: schemaType === 'record' ? `Record<${computeSchemaDescription(recordKeySchema)}, ${computeSchemaDescription(recordValueSchema)}>`
: undefined;
if (base === undefined) throw new Error(`TODO implement: ${schemaType}`);
let rt = base;
if (nullable) rt = `(${rt} | null)`;
if (optional) rt += '?';
return rt;
}
function newBuilder<TValue>(state: BuilderState<TValue>): any {
const { schemaType } = state;
const rt = {
[stateSymbol]: state,
default: (value: unknown) => {
state.defaultValue = value;
return rt;
},
optional: () => {
state.optional = true;
return rt;
},
nullable: () => {
state.nullable = true;
return rt;
},
convertString: () => {
if (schemaType !== 'number') throw new Error();
state.convertString = true;
return rt;
},
min: (value: unknown) => {
if (schemaType === 'array') {
state.minValue = z.integer().min(0).parse(value, { name: 'numItems' });
} else if (schemaType === 'number') {
state.minValue = value;
} else {
throw new Error();
}
return rt;
},
gt: (value: unknown) => {
if (schemaType === 'array') {
state.gtValue = z.integer().min(0).parse(value, { name: 'numItems' });
} else if (schemaType === 'number') {
state.gtValue = value;
} else {
throw new Error();
}
return rt;
},
max: (value: unknown) => {
if (schemaType === 'array') {
state.maxValue = z.integer().min(0).parse(value, { name: 'numItems' });
} else if (schemaType === 'number') {
state.maxValue = value;
} else {
throw new Error();
}
return rt;
},
lt: (value: unknown) => {
if (schemaType === 'array') {
state.ltValue = z.integer().min(0).parse(value, { name: 'numItems' });
} else if (schemaType === 'number') {
state.ltValue = value;
} else {
throw new Error();
}
return rt;
},
distinct: () => {
if (schemaType !== 'array') throw new Error();
state.distinct = true;
return rt;
},
parse: (input: unknown, opts: ParseOpts = {}) => {
const name = typeof opts === 'string' ? opts : isStringRecord(opts) && typeof opts.name === 'string' ? opts.name : 'input';
const strict = isStringRecord(opts) ? !!opts.strict : undefined;
const path: (string | number)[] = [ name ];
const applySchema = (input: unknown, schema: any, fail: (path: (string | number)[], value: unknown, message?: string) => void) => {
const {
schemaType, rules, arrayItemSchema, convertString, distinct, recordKeySchema, recordValueSchema,
defaultValue, minValue, gtValue, maxValue, ltValue, optional, objectSchema, literalValue, lhsSchema, rhsSchema,
nullable,
} = (schema[stateSymbol] ?? {}) as BuilderState<unknown>;
const checkRules = (value: unknown) => {
let allRules = rules;
if (minValue !== undefined || gtValue !== undefined || maxValue !== undefined || ltValue !== undefined) allRules = [ ...allRules ];
if (schemaType === 'array') {
if (minValue !== undefined) allRules.unshift((v, msg) => msg && msg(`must be at least ${minValue} items`) || (v as unknown[]).length >= (minValue as number));
if (gtValue !== undefined) allRules.unshift((v, msg) => msg && msg(`must be greater than ${gtValue} items`) || (v as unknown[]).length > (gtValue as number));
if (maxValue !== undefined) allRules.unshift((v, msg) => msg && msg(`must be at most ${maxValue} items`) || (v as unknown[]).length <= (maxValue as number));
if (ltValue !== undefined) allRules.unshift((v, msg) => msg && msg(`must be less than ${ltValue} items`) || (v as unknown[]).length < (ltValue as number));
} else {
if (minValue !== undefined) allRules.unshift((v, msg) => msg && msg(`must be at least ${minValue}`) || v as any >= (minValue as any));
if (gtValue !== undefined) allRules.unshift((v, msg) => msg && msg(`must be greater than ${gtValue}`) || v as any > (gtValue as any));
if (maxValue !== undefined) allRules.unshift((v, msg) => msg && msg(`must be at most ${maxValue}`) || v as any <= (maxValue as any));
if (ltValue !== undefined) allRules.unshift((v, msg) => msg && msg(`must be less than ${ltValue}`) || v as any < (ltValue as any));
}
let outMessage: string | undefined;
for (const rule of allRules) {
outMessage = undefined;
if (!rule(value, msg => { outMessage = msg; return false })) return fail(path, value, outMessage);
}
}
if (optional && input === undefined) return;
if (nullable && input === null) return;
if (schemaType === undefined || schemaType === 'object') {
if (!isStringRecord(input)) return fail(path, input, 'expected object');
const allowedKeys = strict ? new Set<string>() : undefined;
for (const [ propName, propDef ] of Object.entries(objectSchema ?? schema)) {
const propValue = input[propName];
path.push(propName);
const converted = applySchema(propValue, propDef, fail);
if (converted !== undefined) {
input[propName] = converted;
}
if (input[propName] === undefined) delete input[propName];
path.pop();
allowedKeys?.add(propName);
}
if (allowedKeys) {
const unexpectedKeys = Object.keys(input).filter(v => !allowedKeys.has(v));
if (unexpectedKeys.length > 0) {
return fail(path, input, `Unexpected key${unexpectedKeys.length > 1 ? 's' : ''}: ${unexpectedKeys.join(', ')}`);
}
}
checkRules(input);
} else if (schemaType === 'number') {
let value: number;
if (typeof input === 'number') {
value = input;
} else if (input === undefined && typeof defaultValue === 'number') {
value = defaultValue;
} else if (typeof input === 'string' && convertString) {
const converted = Number(input);
if (Number.isNaN(converted)) return fail(path, input, 'unable to convert to number');
value = converted;
} else {
return fail(path, input, 'expected number');
}
checkRules(value);
if (value !== input) return value;
} else if (schemaType === 'string') {
let value: string;
if (typeof input === 'string') {
value = input;
} else if (input === undefined && typeof defaultValue === 'string') {
value = defaultValue;
} else {
return fail(path, input, 'expected string');
}
checkRules(value);
if (value !== input) return value;
} else if (schemaType === 'array') {
if (!arrayItemSchema) throw new Error();
if (!Array.isArray(input)) return fail(path, input, 'expected array');
for (let i = 0; i < input.length; i++) {
path.push(i);
const converted = applySchema(input[i], arrayItemSchema, fail);
if (converted !== undefined) {
input[i] = converted;
}
path.pop();
}
checkRules(input);
if (distinct && !isArrayDistinct(input)) return Array.from(new Set(input));
} else if (schemaType === 'record') {
if (!recordKeySchema || !recordValueSchema) throw new Error();
const { schemaType: keySchemaType } = recordKeySchema[stateSymbol] ?? {} as BuilderState<unknown>;
if (keySchemaType !== 'string') return fail(path, input, 'only string-keyed objects are supported');
if (!isStringRecord(input)) return fail(path, input, 'expected object');
for (const [ inputKey, inputValue ] of Object.entries(input)) {
applySchema(inputKey, recordKeySchema, fail);
path.push(inputKey);
applySchema(inputValue, recordValueSchema, fail);
if (inputValue === undefined) delete input[inputKey];
path.pop();
}
checkRules(input);
} else if (schemaType === 'literal') {
if (literalValue === undefined) throw new Error();
if (input !== literalValue) return fail(path, input, 'unexpected literal value');
checkRules(input);
} else if (schemaType === 'boolean') {
if (typeof input !== 'boolean') return fail(path, input, 'expected boolean');
checkRules(input);
} else if (schemaType === 'unknown') {
checkRules(input);
} else if (schemaType === 'union') {
if (!lhsSchema || !rhsSchema) throw new Error();
let failed = false;
applySchema(input, lhsSchema, () => { failed = true });
if (failed) {
failed = false;
applySchema(input, rhsSchema, () => { failed = true });
if (failed) return fail(path, input, `expected ${computeSchemaDescription(lhsSchema)} | ${computeSchemaDescription(rhsSchema)}`);
}
checkRules(input);
} else {
throw new Error();
}
};
applySchema(input, rt, (path, value, message) => { throw new Error(`Bad ${path.join('.')}: ${typeof value === 'object' ? JSON.stringify(value) : value}${message ? `, ${message}` : ''}`); });
return input;
},
toString: () => {
return computeSchemaDescription(rt);
},
}
return rt;
}