-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
384 lines (316 loc) · 8.37 KB
/
utils.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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import { Context, Describe, Infer, Result, Struct } from "./struct.ts";
import { Failure } from "./error.ts";
/**
* Check if a value is an iterator.
*/
function isIterable<T>(x: unknown): x is Iterable<T> {
return isObject(x) && typeof (x as any)[Symbol.iterator] === "function";
}
/**
* Check if a value is a plain object.
*/
export function isObject(x: unknown): x is object {
return typeof x === "object" && x != null;
}
/**
* Check if a value is a plain object.
*/
export function isPlainObject(x: unknown): x is { [key: string]: any } {
if (Object.prototype.toString.call(x) !== "[object Object]") {
return false;
}
const prototype = Object.getPrototypeOf(x);
return prototype === null || prototype === Object.prototype;
}
/**
* Return a value as a printable string.
*/
export function print(value: any): string {
return typeof value === "string" ? JSON.stringify(value) : `${value}`;
}
/**
* Shifts (removes and returns) the first value from the `input` iterator.
* Like `Array.prototype.shift()` but for an `Iterator`.
*/
export function shiftIterator<T>(input: Iterator<T>): T | undefined {
const { done, value } = input.next();
return done ? undefined : value;
}
/**
* Convert a single validation result to a failure.
*/
export function toFailure<T, S>(
result: string | boolean | Partial<Failure>,
context: Context,
struct: Struct<T, S>,
value: any,
): Failure | undefined {
if (result === true) {
return;
} else if (result === false) {
result = {};
} else if (typeof result === "string") {
result = { message: result };
}
const { path, branch } = context;
const { type } = struct;
const {
refinement,
message = `Expected a value of type \`${type}\`${
refinement ? ` with refinement \`${refinement}\`` : ""
}, but received: \`${print(value)}\``,
} = result;
return {
value,
type,
refinement,
key: path[path.length - 1],
path,
branch,
...result,
message,
};
}
/**
* Convert a validation result to an iterable of failures.
*/
export function* toFailures<T, S>(
result: Result,
context: Context,
struct: Struct<T, S>,
value: any,
): IterableIterator<Failure> {
if (!isIterable(result)) {
result = [result];
}
for (const r of result) {
const failure = toFailure(r, context, struct, value);
if (failure) {
yield failure;
}
}
}
/**
* Check a value against a struct, traversing deeply into nested values, and
* returning an iterator of failures or success.
*/
export function* run<T, S>(
value: unknown,
struct: Struct<T, S>,
options: {
path?: any[];
branch?: any[];
coerce?: boolean;
mask?: boolean;
} = {},
): IterableIterator<[Failure, undefined] | [undefined, T]> {
const { path = [], branch = [value], coerce = false, mask = false } = options;
const ctx: Context = { path, branch };
if (coerce) {
value = struct.coercer(value, ctx);
if (
mask &&
struct.type !== "type" &&
isObject(struct.schema) &&
isObject(value) &&
!Array.isArray(value)
) {
for (const key in value) {
if ((struct.schema as any)[key] === undefined) {
delete (value as any)[key];
}
}
}
}
let valid = true;
for (const failure of struct.validator(value, ctx)) {
valid = false;
yield [failure, undefined];
}
for (let [k, v, s] of struct.entries(value, ctx)) {
const ts = run(v, s as Struct, {
path: k === undefined ? path : [...path, k],
branch: k === undefined ? branch : [...branch, v],
coerce,
mask,
});
for (const t of ts) {
if (t[0]) {
valid = false;
yield [t[0], undefined];
} else if (coerce) {
v = t[1];
if (k === undefined) {
value = v;
} else if (value instanceof Map) {
value.set(k, v);
} else if (value instanceof Set) {
value.add(v);
} else if (isObject(value)) {
(value as any)[k] = v;
}
}
}
}
if (valid) {
for (const failure of struct.refiner(value as T, ctx)) {
valid = false;
yield [failure, undefined];
}
}
if (valid) {
yield [undefined, value as T];
}
}
/**
* Convert a union of type to an intersection.
*/
export type UnionToIntersection<U> = (
U extends any ? (arg: U) => any : never
) extends (arg: infer I) => void ? I
: never;
/**
* Assign properties from one type to another, overwriting existing.
*/
export type Assign<T, U> = Simplify<U & Omit<T, keyof U>>;
/**
* A schema for enum structs.
*/
export type EnumSchema<T extends string | number | undefined> = {
[K in NonNullable<T>]: K;
};
/**
* Check if a type is a match for another whilst treating overlapping
* unions as a match.
*/
export type IsMatch<T, G> = T extends G ? (G extends T ? T : never) : never;
/**
* Check if a type is an exact match.
*/
export type IsExactMatch<T, U> = (<G>() => G extends T ? 1 : 2) extends <
G,
>() => G extends U ? 1 : 2 ? T
: never;
/**
* Check if a type is a record type.
*/
export type IsRecord<T> = T extends object ? string extends keyof T ? T
: never
: never;
/**
* Check if a type is a tuple.
*/
export type IsTuple<T> = T extends [any] ? T
: T extends [any, any] ? T
: T extends [any, any, any] ? T
: T extends [any, any, any, any] ? T
: T extends [any, any, any, any, any] ? T
: never;
/**
* Check if a type is a union.
*/
export type IsUnion<T, U extends T = T> = (
T extends any ? (U extends T ? false : true) : false
) extends false ? never
: T;
/**
* A schema for object structs.
*/
export type ObjectSchema = Record<string, Struct<any, any>>;
/**
* Infer a type from an object struct schema.
*/
export type ObjectType<S extends ObjectSchema> = Simplify<
Optionalize<{ [K in keyof S]: Infer<S[K]> }>
>;
/**
* Omit properties from a type that extend from a specific type.
*/
export type OmitBy<T, V> = Omit<
T,
{ [K in keyof T]: V extends Extract<T[K], V> ? K : never }[keyof T]
>;
/**
* Normalize properties of a type that allow `undefined` to make them optional.
*/
export type Optionalize<S extends object> =
& OmitBy<S, undefined>
& Partial<PickBy<S, undefined>>;
/**
* Transform an object schema type to represent a partial.
*/
export type PartialObjectSchema<S extends ObjectSchema> = {
[K in keyof S]: Struct<Infer<S[K]> | undefined>;
};
/**
* Pick properties from a type that extend from a specific type.
*/
export type PickBy<T, V> = Pick<
T,
{ [K in keyof T]: V extends Extract<T[K], V> ? K : never }[keyof T]
>;
/**
* Simplifies a type definition to its most basic representation.
*/
export type Simplify<T> = T extends any[] | Date ? T
: { [K in keyof T]: T[K] } & {};
export type If<B extends Boolean, Then, Else> = B extends true ? Then : Else;
/**
* A schema for any type of struct.
*/
export type StructSchema<T> = [T] extends [string | undefined]
? [T] extends [IsMatch<T, string | undefined>] ? null
: [T] extends [IsUnion<T>] ? EnumSchema<T>
: T
: [T] extends [number | undefined]
? [T] extends [IsMatch<T, number | undefined>] ? null
: [T] extends [IsUnion<T>] ? EnumSchema<T>
: T
: [T] extends [boolean] ? [T] extends [IsExactMatch<T, boolean>] ? null
: T
: T extends
| bigint
| symbol
| undefined
| null
| Function
| Date
| Error
| RegExp
| Map<any, any>
| WeakMap<any, any>
| Set<any>
| WeakSet<any>
| Promise<any> ? null
: T extends Array<infer E> ? T extends IsTuple<T> ? null
: Struct<E>
: T extends object ? T extends IsRecord<T> ? null
: { [K in keyof T]: Describe<T[K]> }
: null;
/**
* A schema for tuple structs.
*/
export type TupleSchema<T> = { [K in keyof T]: Struct<T[K]> };
/**
* Shorthand type for matching any `Struct`.
*/
export type AnyStruct = Struct<any, any>;
/**
* Infer a tuple of types from a tuple of `Struct`s.
*
* This is used to recursively retrieve the type from `union` `intersection` and
* `tuple` structs.
*/
export type InferStructTuple<
Tuple extends AnyStruct[],
Length extends number = Tuple["length"],
> = Length extends Length ? number extends Length ? Tuple
: _InferTuple<Tuple, Length, []>
: never;
type _InferTuple<
Tuple extends AnyStruct[],
Length extends number,
Accumulated extends unknown[],
Index extends number = Accumulated["length"],
> = Index extends Length ? Accumulated
: _InferTuple<Tuple, Length, [...Accumulated, Infer<Tuple[Index]>]>;