-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTypeBuilder.ts
More file actions
348 lines (302 loc) · 10.4 KB
/
TypeBuilder.ts
File metadata and controls
348 lines (302 loc) · 10.4 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
import * as schema from '../schema';
import * as classes from './classes';
import type {Type} from './types';
import type {TypeSystem} from '../system/TypeSystem';
import type {TypeAlias} from '../system/TypeAlias';
import type {TypeOfAlias} from '../system/types';
const {s} = schema;
type UnionToIntersection<U> = (U extends never ? never : (arg: U) => never) extends (arg: infer I) => void ? I : never;
type UnionToTuple<T> = UnionToIntersection<T extends never ? never : (t: T) => T> extends (_: never) => infer W
? [...UnionToTuple<Exclude<T, W>>, W]
: [];
type ObjValueTuple<T, KS extends any[] = UnionToTuple<keyof T>, R extends any[] = []> = KS extends [
infer K,
...infer KT,
]
? ObjValueTuple<T, KT, [...R, T[K & keyof T]]>
: R;
type RecordToFields<O extends Record<string, Type>> = ObjValueTuple<{
[K in keyof O]: classes.ObjectFieldType<K extends string ? K : never, O[K]>;
}>;
export class TypeBuilder {
constructor(public system?: TypeSystem) {}
// -------------------------------------------------------------- empty types
get any() {
return this.Any();
}
get undef() {
return this.Const<undefined>(undefined);
}
get nil() {
return this.Const<null>(null);
}
get bool() {
return this.Boolean();
}
get num() {
return this.Number();
}
get str() {
return this.String();
}
get bin() {
return this.Binary(this.any);
}
get arr() {
return this.Array(this.any);
}
get obj() {
return this.Object();
}
get map() {
return this.Map(this.any);
}
get fn() {
return this.Function(this.undef, this.undef);
}
get fn$() {
return this.Function$(this.undef, this.undef);
}
// --------------------------------------------------------------- shorthands
public readonly undefined = () => this.undef;
public readonly null = () => this.nil;
public readonly boolean = () => this.bool;
public readonly number = () => this.num;
public readonly string = () => this.str;
public readonly binary = () => this.bin;
public readonly con = <V>(value: schema.Narrow<V>, options?: schema.Optional<schema.ConstSchema>) =>
this.Const(value, options);
public readonly literal = this.con;
public readonly array = <T>(type?: T, options?: schema.Optional<schema.ArraySchema>) =>
this.Array<T extends Type ? T : classes.AnyType>(
(type ?? this.any) as T extends Type ? T : classes.AnyType,
options,
);
public readonly tuple = <F extends (Type | classes.ObjectFieldType<any, any>)[]>(...types: F) => this.Tuple(...types);
/**
* Creates an object type with the specified properties. This is a shorthand for
* `t.Object(t.prop(key, value), ...)`.
*
* Importantly, this method does not allow to specify object field order,
* so the order of properties in the resulting type is not guaranteed.
*
* Example:
*
* ```ts
* t.object({
* id: t.str,
* name: t.string(),
* age: t.num,
* verified: t.bool,
* });
* ```
*
* @param record A mapping of property names to types.
* @returns An object type.
*/
public readonly object = <R extends Record<string, Type>>(record: R): classes.ObjType<RecordToFields<R>> => {
const fields: classes.ObjectFieldType<any, any>[] = [];
for (const [key, value] of Object.entries(record)) fields.push(this.prop(key, value));
const obj = new classes.ObjType<RecordToFields<R>>(fields as any);
obj.system = this.system;
return obj;
};
/**
* Creates a type that represents a value that may be present or absent. The
* value is `undefined` if absent. This is a shorthand for `t.Or(type, t.undef)`.
*/
public readonly maybe = <T extends Type>(type: T) => this.Or(type, this.undef);
/**
* Creates a union type from a list of values. This is a shorthand for
* `t.Or(t.Const(value1), t.Const(value2), ...)`. For example, the below
* are equivalent:
*
* ```ts
* t.enum('red', 'green', 'blue');
* t.Or(t.Const('red'), t.Const('green'), t.Const('blue'));
* ```
*
* @param values The values to include in the union.
* @returns A union type representing the values.
*/
public readonly enum = <const T extends (string | number | boolean | null)[]>(
...values: T
): classes.OrType<{[K in keyof T]: classes.ConType<schema.Narrow<T[K]>>}> =>
this.Or(...values.map((type) => this.Const(type as any))) as any;
// --------------------------------------------------- base node constructors
public Any(options?: schema.Optional<schema.AnySchema>) {
const type = new classes.AnyType(s.Any(options));
type.system = this.system;
return type;
}
public Const<V>(value: schema.Narrow<V>, options?: schema.Optional<schema.ConstSchema>) {
type V2 = string extends V
? never
: number extends V
? never
: boolean extends V
? never
: any[] extends V
? never
: V;
const type = new classes.ConType<V2>(schema.s.Const(value, options));
type.system = this.system;
return type;
}
public Boolean(options?: schema.Optional<schema.BooleanSchema>) {
const type = new classes.BoolType(s.Boolean(options));
type.system = this.system;
return type;
}
public Number(options?: schema.Optional<schema.NumberSchema>) {
const type = new classes.NumType(s.Number(options));
type.system = this.system;
return type;
}
public String(options?: schema.Optional<schema.StringSchema>) {
const type = new classes.StrType(s.String(options));
type.system = this.system;
return type;
}
public Binary<T extends Type>(type: T, options: schema.Optional<schema.BinarySchema> = {}) {
const bin = new classes.BinType(type, options);
bin.system = this.system;
return bin;
}
public Array<T extends Type>(type: T, options?: schema.Optional<schema.ArraySchema>) {
const arr = new classes.ArrType<T>(type, options);
arr.system = this.system;
return arr;
}
public Tuple<F extends (Type | classes.ObjectFieldType<any, any>)[]>(...types: F) {
const tup = new classes.TupType<F>(types);
tup.system = this.system;
return tup;
}
public Object<F extends classes.ObjectFieldType<any, any>[]>(...fields: F) {
const obj = new classes.ObjType<F>(fields);
obj.system = this.system;
return obj;
}
public prop<K extends string, V extends Type>(key: K, value: V) {
const field = new classes.ObjectFieldType<K, V>(key, value);
field.system = this.system;
return field;
}
public propOpt<K extends string, V extends Type>(key: K, value: V) {
const field = new classes.ObjectOptionalFieldType<K, V>(key, value);
field.system = this.system;
return field;
}
public Map<T extends Type>(val: T, key?: Type, options?: schema.Optional<schema.MapSchema>) {
const map = new classes.MapType<T>(val, key, options);
map.system = this.system;
return map;
}
public Or<F extends Type[]>(...types: F) {
const or = new classes.OrType<F>(types);
or.system = this.system;
return or;
}
public Ref<T extends Type | TypeAlias<any, any>>(ref: string) {
const type = new classes.RefType<TypeOfAlias<T>>(ref);
type.system = this.system;
return type;
}
public Function<Req extends Type, Res extends Type, Ctx = unknown>(
req: Req,
res: Res,
options?: schema.Optional<schema.FunctionSchema>,
) {
const fn = new classes.FnType<Req, Res, Ctx>(req, res, options);
fn.system = this.system;
return fn;
}
public Function$<Req extends Type, Res extends Type, Ctx = unknown>(
req: Req,
res: Res,
options?: schema.Optional<schema.FunctionStreamingSchema>,
) {
const fn = new classes.FnRxType<Req, Res, Ctx>(req, res, options);
fn.system = this.system;
return fn;
}
public import(node: schema.Schema): Type {
switch (node.kind) {
case 'any':
return this.Any(node);
case 'bool':
return this.Boolean(node);
case 'num':
return this.Number(node);
case 'str':
return this.String(node);
case 'bin':
return this.Binary(this.import(node.type), node);
case 'arr':
return this.Array(this.import(node.type), node);
case 'tup':
return this.Tuple(...node.types.map((t: schema.Schema) => this.import(t))).options(node);
case 'obj': {
return this.Object(
...node.fields.map((f: any) =>
f.optional
? this.propOpt(f.key, this.import(f.value)).options(f)
: this.prop(f.key, this.import(f.value)).options(f),
),
).options(node);
}
case 'map':
return this.Map(this.import(node.value), node.key ? this.import(node.key) : undefined, node);
case 'con':
return this.Const(node.value).options(node);
case 'or':
return this.Or(...node.types.map((t) => this.import(t as schema.Schema))).options(node);
case 'ref':
return this.Ref(node.ref).options(node);
case 'fn':
return this.Function(this.import(node.req as schema.Schema), this.import(node.res as schema.Schema)).options(
node,
);
case 'fn$':
return this.Function$(this.import(node.req as schema.Schema), this.import(node.res as schema.Schema)).options(
node,
);
}
throw new Error(`UNKNOWN_NODE [${node.kind}]`);
}
public from(value: unknown): Type {
switch (typeof value) {
case 'undefined':
return this.undef;
case 'boolean':
return this.bool;
case 'number':
return this.num;
case 'string':
return this.str;
case 'object':
if (value === null) return this.nil;
if (Array.isArray(value)) {
if (value.length === 0) return this.arr;
const getType = (v: unknown): string => {
switch (typeof v) {
case 'object':
if (v === null) return 'nil';
if (Array.isArray(v)) return 'arr';
return 'obj';
default:
return typeof v;
}
};
const allElementsOfTheSameType = value.every((v) => getType(v) === getType(value[0]));
return allElementsOfTheSameType
? this.Array(this.from(value[0]))
: this.Tuple(...value.map((v) => this.from(v)));
}
return this.Object(...Object.entries(value).map(([key, value]) => this.prop(key, this.from(value))));
default:
return this.any;
}
}
}