-
-
Notifications
You must be signed in to change notification settings - Fork 249
/
Schema.ts
9106 lines (8394 loc) · 258 KB
/
Schema.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @since 0.67.0
*/
import * as array_ from "effect/Array"
import * as bigDecimal_ from "effect/BigDecimal"
import * as bigInt_ from "effect/BigInt"
import * as boolean_ from "effect/Boolean"
import type { Brand } from "effect/Brand"
import * as cause_ from "effect/Cause"
import * as chunk_ from "effect/Chunk"
import * as config_ from "effect/Config"
import * as configError_ from "effect/ConfigError"
import * as data_ from "effect/Data"
import * as dateTime from "effect/DateTime"
import * as duration_ from "effect/Duration"
import * as Effect from "effect/Effect"
import * as either_ from "effect/Either"
import * as Encoding from "effect/Encoding"
import * as Equal from "effect/Equal"
import * as Equivalence from "effect/Equivalence"
import * as exit_ from "effect/Exit"
import * as fiberId_ from "effect/FiberId"
import type { LazyArg } from "effect/Function"
import { dual, identity } from "effect/Function"
import * as hashMap_ from "effect/HashMap"
import * as hashSet_ from "effect/HashSet"
import * as list_ from "effect/List"
import * as number_ from "effect/Number"
import * as option_ from "effect/Option"
import type * as Order from "effect/Order"
import type { Pipeable } from "effect/Pipeable"
import { pipeArguments } from "effect/Pipeable"
import * as Predicate from "effect/Predicate"
import * as record_ from "effect/Record"
import * as redacted_ from "effect/Redacted"
import * as Request from "effect/Request"
import * as sortedSet_ from "effect/SortedSet"
import * as string_ from "effect/String"
import * as struct_ from "effect/Struct"
import type * as Types from "effect/Types"
import type { LazyArbitrary } from "./Arbitrary.js"
import * as arbitrary_ from "./Arbitrary.js"
import type { ParseOptions } from "./AST.js"
import * as AST from "./AST.js"
import * as equivalence_ from "./Equivalence.js"
import * as fastCheck_ from "./FastCheck.js"
import * as errors_ from "./internal/errors.js"
import * as filters_ from "./internal/filters.js"
import * as serializable_ from "./internal/serializable.js"
import * as util_ from "./internal/util.js"
import * as ParseResult from "./ParseResult.js"
import * as pretty_ from "./Pretty.js"
import type * as Serializable from "./Serializable.js"
import * as TreeFormatter from "./TreeFormatter.js"
/**
* @since 0.68.2
*/
export type Simplify<A> = { [K in keyof A]: A[K] } & {}
/**
* @since 0.67.0
*/
export type SimplifyMutable<A> = {
-readonly [K in keyof A]: A[K]
} extends infer B ? B : never
/**
* @since 0.67.0
* @category symbol
*/
export const TypeId: unique symbol = Symbol.for("@effect/schema/Schema")
/**
* @since 0.67.0
* @category symbol
*/
export type TypeId = typeof TypeId
/**
* @category model
* @since 0.67.0
*/
export interface Schema<in out A, in out I = A, out R = never> extends Schema.Variance<A, I, R>, Pipeable {
readonly Type: A
readonly Encoded: I
/** @since 0.69.3 */
readonly Context: R
readonly ast: AST.AST
/**
* Merges a set of new annotations with existing ones, potentially overwriting
* any duplicates.
*/
annotations(annotations: Annotations.Schema<A>): Schema<A, I, R>
}
/**
* @category model
* @since 0.67.0
*/
export interface SchemaClass<A, I = A, R = never> extends AnnotableClass<SchemaClass<A, I, R>, A, I, R> {}
/**
* @category constructors
* @since 0.67.0
*/
export const make = <A, I = A, R = never>(ast: AST.AST): SchemaClass<A, I, R> =>
class SchemaClass {
[TypeId] = variance
static Type: A
static Encoded: I
static Context: R
static [TypeId] = variance
static ast = ast
static annotations(annotations: Annotations.Schema<A>) {
return make<A, I, R>(mergeSchemaAnnotations(this.ast, annotations))
}
static pipe() {
return pipeArguments(this, arguments)
}
static toString() {
return String(ast)
}
}
const variance = {
/* c8 ignore next */
_A: (_: any) => _,
/* c8 ignore next */
_I: (_: any) => _,
/* c8 ignore next */
_R: (_: never) => _
}
interface AllAnnotations<A, TypeParameters extends ReadonlyArray<any>>
extends Annotations.Schema<A, TypeParameters>, PropertySignature.Annotations<A>
{}
const toASTAnnotations = <A, TypeParameters extends ReadonlyArray<any>>(
annotations?: AllAnnotations<A, TypeParameters>
): AST.Annotations => {
if (!annotations) {
return {}
}
const out: Types.Mutable<AST.Annotations> = {}
// symbols are reserved for custom annotations
const custom = Object.getOwnPropertySymbols(annotations)
for (const sym of custom) {
out[sym] = annotations[sym]
}
// string keys are reserved as /schema namespace
if (annotations.typeId !== undefined) {
const typeId = annotations.typeId
if (typeof typeId === "object") {
out[AST.TypeAnnotationId] = typeId.id
out[typeId.id] = typeId.annotation
} else {
out[AST.TypeAnnotationId] = typeId
}
}
const move = (from: keyof typeof annotations, to: symbol) => {
if (annotations[from] !== undefined) {
out[to] = annotations[from]
}
}
move("message", AST.MessageAnnotationId)
move("missingMessage", AST.MissingMessageAnnotationId)
move("identifier", AST.IdentifierAnnotationId)
move("title", AST.TitleAnnotationId)
move("description", AST.DescriptionAnnotationId)
move("examples", AST.ExamplesAnnotationId)
move("default", AST.DefaultAnnotationId)
move("documentation", AST.DocumentationAnnotationId)
move("jsonSchema", AST.JSONSchemaAnnotationId)
move("arbitrary", arbitrary_.ArbitraryHookId)
move("pretty", pretty_.PrettyHookId)
move("equivalence", equivalence_.EquivalenceHookId)
move("concurrency", AST.ConcurrencyAnnotationId)
move("batching", AST.BatchingAnnotationId)
move("parseIssueTitle", AST.ParseIssueTitleAnnotationId)
move("parseOptions", AST.ParseOptionsAnnotationId)
move("decodingFallback", AST.DecodingFallbackAnnotationId)
return out
}
const mergeSchemaAnnotations = <A>(ast: AST.AST, annotations: Annotations.Schema<A>): AST.AST =>
AST.annotations(ast, toASTAnnotations(annotations))
/**
* @category annotations
* @since 0.67.0
*/
export declare namespace Annotable {
/**
* @since 0.67.0
*/
export type Self<S extends All> = ReturnType<S["annotations"]>
/**
* @since 0.67.0
*/
export type Any = Annotable<any, any, any, unknown>
/**
* @since 0.67.0
*/
export type All =
| Any
| Annotable<any, any, never, unknown>
| Annotable<any, never, any, unknown>
| Annotable<any, never, never, unknown>
}
/**
* @category annotations
* @since 0.67.0
*/
export interface Annotable<Self extends Schema<A, I, R>, A, I = A, R = never> extends Schema<A, I, R> {
annotations(annotations: Annotations.Schema<A>): Self
}
/**
* @category annotations
* @since 0.67.0
*/
export interface AnnotableClass<Self extends Schema<A, I, R>, A, I = A, R = never> extends Annotable<Self, A, I, R> {
new(_: never): Schema.Variance<A, I, R>
}
/**
* @since 0.67.0
*/
export const asSchema = <S extends Schema.All>(
schema: S
): Schema<Schema.Type<S>, Schema.Encoded<S>, Schema.Context<S>> => schema as any
/**
* @category formatting
* @since 0.67.0
*/
export const format = <A, I, R>(schema: Schema<A, I, R>): string => String(schema.ast)
/**
* @since 0.67.0
*/
export declare namespace Schema {
/**
* @since 0.67.0
*/
export interface Variance<A, I, R> {
readonly [TypeId]: {
readonly _A: Types.Invariant<A>
readonly _I: Types.Invariant<I>
readonly _R: Types.Covariant<R>
}
}
/**
* @since 0.67.0
*/
export type Type<S> = S extends Schema.Variance<infer A, infer _I, infer _R> ? A : never
/**
* @since 0.67.0
*/
export type Encoded<S> = S extends Schema.Variance<infer _A, infer I, infer _R> ? I : never
/**
* @since 0.67.0
*/
export type Context<S> = S extends Schema.Variance<infer _A, infer _I, infer R> ? R : never
/**
* @since 0.67.0
*/
export type ToAsserts<S extends AnyNoContext> = (
input: unknown,
options?: AST.ParseOptions
) => asserts input is Schema.Type<S>
/**
* Any schema, except for `never`.
*
* @since 0.67.0
*/
export type Any = Schema<any, any, unknown>
/**
* Any schema with `Context = never`, except for `never`.
*
* @since 0.67.0
*/
export type AnyNoContext = Schema<any, any, never>
/**
* Any schema, including `never`.
*
* @since 0.67.0
*/
export type All =
| Any
| Schema<any, never, unknown>
| Schema<never, any, unknown>
| Schema<never, never, unknown>
/**
* Type-level counterpart of `Schema.asSchema` function.
*
* @since 0.67.0
*/
export type AsSchema<S extends All> = Schema<Type<S>, Encoded<S>, Context<S>>
}
/**
* The `encodedSchema` function allows you to extract the `Encoded` portion of a
* schema, creating a new schema that conforms to the properties defined in the
* original schema without retaining any refinements or transformations that
* were applied previously.
*
* @since 0.67.0
*/
export const encodedSchema = <A, I, R>(schema: Schema<A, I, R>): SchemaClass<I> => make(AST.encodedAST(schema.ast))
/**
* The `encodedBoundSchema` function is similar to `encodedSchema` but preserves
* the refinements up to the first transformation point in the original schema.
*
* @since 0.67.17
*/
export const encodedBoundSchema = <A, I, R>(schema: Schema<A, I, R>): SchemaClass<I> =>
make(AST.encodedBoundAST(schema.ast))
/**
* The `typeSchema` function allows you to extract the `Type` portion of a
* schema, creating a new schema that conforms to the properties defined in the
* original schema without considering the initial encoding or transformation
* processes.
*
* @since 0.67.0
*/
export const typeSchema = <A, I, R>(schema: Schema<A, I, R>): SchemaClass<A> => make(AST.typeAST(schema.ast))
/* c8 ignore start */
export {
/**
* By default the option `exact` is set to `true`.
*
* @throws `ParseError`
* @category validation
* @since 0.67.0
*/
asserts,
/**
* @category decoding
* @since 0.67.0
*/
decodeOption,
/**
* @throws `ParseError`
* @category decoding
* @since 0.67.0
*/
decodeSync,
/**
* @category decoding
* @since 0.67.0
*/
decodeUnknownOption,
/**
* @throws `ParseError`
* @category decoding
* @since 0.67.0
*/
decodeUnknownSync,
/**
* @category encoding
* @since 0.67.0
*/
encodeOption,
/**
* @throws `ParseError`
* @category encoding
* @since 0.67.0
*/
encodeSync,
/**
* @category encoding
* @since 0.67.0
*/
encodeUnknownOption,
/**
* @throws `ParseError`
* @category encoding
* @since 0.67.0
*/
encodeUnknownSync,
/**
* By default the option `exact` is set to `true`.
*
* @category validation
* @since 0.67.0
*/
is,
/**
* @category validation
* @since 0.67.0
*/
validateOption,
/**
* @throws `ParseError`
* @category validation
* @since 0.67.0
*/
validateSync
} from "./ParseResult.js"
/* c8 ignore end */
/**
* @category encoding
* @since 0.67.0
*/
export const encodeUnknown = <A, I, R>(
schema: Schema<A, I, R>,
options?: ParseOptions
) => {
const encodeUnknown = ParseResult.encodeUnknown(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): Effect.Effect<I, ParseResult.ParseError, R> =>
ParseResult.mapError(encodeUnknown(u, overrideOptions), ParseResult.parseError)
}
/**
* @category encoding
* @since 0.67.0
*/
export const encodeUnknownEither = <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => {
const encodeUnknownEither = ParseResult.encodeUnknownEither(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): either_.Either<I, ParseResult.ParseError> =>
either_.mapLeft(encodeUnknownEither(u, overrideOptions), ParseResult.parseError)
}
/**
* @category encoding
* @since 0.67.0
*/
export const encodeUnknownPromise = <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => {
const parser = encodeUnknown(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): Promise<I> => Effect.runPromise(parser(u, overrideOptions))
}
/**
* @category encoding
* @since 0.67.0
*/
export const encode: <A, I, R>(
schema: Schema<A, I, R>,
options?: ParseOptions
) => (a: A, overrideOptions?: ParseOptions) => Effect.Effect<I, ParseResult.ParseError, R> = encodeUnknown
/**
* @category encoding
* @since 0.67.0
*/
export const encodeEither: <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => (a: A, overrideOptions?: ParseOptions) => either_.Either<I, ParseResult.ParseError> = encodeUnknownEither
/**
* @category encoding
* @since 0.67.0
*/
export const encodePromise: <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => (a: A, overrideOptions?: ParseOptions) => Promise<I> = encodeUnknownPromise
/**
* @category decoding
* @since 0.67.0
*/
export const decodeUnknown = <A, I, R>(
schema: Schema<A, I, R>,
options?: ParseOptions
) => {
const decodeUnknown = ParseResult.decodeUnknown(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): Effect.Effect<A, ParseResult.ParseError, R> =>
ParseResult.mapError(decodeUnknown(u, overrideOptions), ParseResult.parseError)
}
/**
* @category decoding
* @since 0.67.0
*/
export const decodeUnknownEither = <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => {
const decodeUnknownEither = ParseResult.decodeUnknownEither(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): either_.Either<A, ParseResult.ParseError> =>
either_.mapLeft(decodeUnknownEither(u, overrideOptions), ParseResult.parseError)
}
/**
* @category decoding
* @since 0.67.0
*/
export const decodeUnknownPromise = <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => {
const parser = decodeUnknown(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): Promise<A> => Effect.runPromise(parser(u, overrideOptions))
}
/**
* @category decoding
* @since 0.67.0
*/
export const decode: <A, I, R>(
schema: Schema<A, I, R>,
options?: ParseOptions
) => (i: I, overrideOptions?: ParseOptions) => Effect.Effect<A, ParseResult.ParseError, R> = decodeUnknown
/**
* @category decoding
* @since 0.67.0
*/
export const decodeEither: <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => (i: I, overrideOptions?: ParseOptions) => either_.Either<A, ParseResult.ParseError> = decodeUnknownEither
/**
* @category decoding
* @since 0.67.0
*/
export const decodePromise: <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => (i: I, overrideOptions?: ParseOptions) => Promise<A> = decodeUnknownPromise
/**
* @category validation
* @since 0.67.0
*/
export const validate = <A, I, R>(
schema: Schema<A, I, R>,
options?: ParseOptions
) => {
const validate = ParseResult.validate(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): Effect.Effect<A, ParseResult.ParseError, R> =>
ParseResult.mapError(validate(u, overrideOptions), ParseResult.parseError)
}
/**
* @category validation
* @since 0.67.0
*/
export const validateEither = <A, I, R>(
schema: Schema<A, I, R>,
options?: ParseOptions
) => {
const validateEither = ParseResult.validateEither(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): either_.Either<A, ParseResult.ParseError> =>
either_.mapLeft(validateEither(u, overrideOptions), ParseResult.parseError)
}
/**
* @category validation
* @since 0.67.0
*/
export const validatePromise = <A, I>(
schema: Schema<A, I, never>,
options?: ParseOptions
) => {
const parser = validate(schema, options)
return (u: unknown, overrideOptions?: ParseOptions): Promise<A> => Effect.runPromise(parser(u, overrideOptions))
}
/**
* Tests if a value is a `Schema`.
*
* @category guards
* @since 0.67.0
*/
export const isSchema = (u: unknown): u is Schema.Any =>
Predicate.hasProperty(u, TypeId) && Predicate.isObject(u[TypeId])
/**
* @category api interface
* @since 0.67.0
*/
export interface Literal<Literals extends array_.NonEmptyReadonlyArray<AST.LiteralValue>>
extends AnnotableClass<Literal<Literals>, Literals[number]>
{
readonly literals: Readonly<Literals>
}
const getDefaultLiteralAST = <Literals extends array_.NonEmptyReadonlyArray<AST.LiteralValue>>(
literals: Literals
) =>
AST.isMembers(literals)
? AST.Union.make(AST.mapMembers(literals, (literal) => new AST.Literal(literal)))
: new AST.Literal(literals[0])
const makeLiteralClass = <Literals extends array_.NonEmptyReadonlyArray<AST.LiteralValue>>(
literals: Literals,
ast: AST.AST = getDefaultLiteralAST(literals)
): Literal<Literals> =>
class LiteralClass extends make<Literals[number]>(ast) {
static override annotations(annotations: Annotations.Schema<Literals[number]>): Literal<Literals> {
return makeLiteralClass(this.literals, mergeSchemaAnnotations(this.ast, annotations))
}
static literals = [...literals] as Literals
}
/**
* @category constructors
* @since 0.67.0
*/
export function Literal<Literals extends array_.NonEmptyReadonlyArray<AST.LiteralValue>>(
...literals: Literals
): Literal<Literals>
export function Literal(): Never
export function Literal<Literals extends ReadonlyArray<AST.LiteralValue>>(
...literals: Literals
): Schema<Literals[number]>
export function Literal<Literals extends ReadonlyArray<AST.LiteralValue>>(
...literals: Literals
): Schema<Literals[number]> | Never {
return array_.isNonEmptyReadonlyArray(literals) ? makeLiteralClass(literals) : Never
}
/**
* Creates a new `Schema` from a literal schema.
*
* @example
* import * as S from "@effect/schema/Schema"
* import { Either } from "effect"
*
* const schema = S.Literal("a", "b", "c").pipe(S.pickLiteral("a", "b"))
*
* assert.deepStrictEqual(S.decodeSync(schema)("a"), "a")
* assert.deepStrictEqual(S.decodeSync(schema)("b"), "b")
* assert.strictEqual(Either.isLeft(S.decodeUnknownEither(schema)("c")), true)
*
* @category constructors
* @since 0.67.0
*/
export const pickLiteral =
<A extends AST.LiteralValue, L extends array_.NonEmptyReadonlyArray<A>>(...literals: L) =>
<I, R>(_schema: Schema<A, I, R>): Literal<[...L]> => Literal(...literals)
/**
* @category constructors
* @since 0.67.0
*/
export const UniqueSymbolFromSelf = <S extends symbol>(symbol: S): SchemaClass<S> => make(new AST.UniqueSymbol(symbol))
/**
* @category api interface
* @since 0.67.0
*/
export interface Enums<A extends EnumsDefinition> extends AnnotableClass<Enums<A>, A[keyof A]> {
readonly enums: A
}
/**
* @since 0.67.0
*/
export type EnumsDefinition = { [x: string]: string | number }
const getDefaultEnumsAST = <A extends EnumsDefinition>(enums: A) =>
new AST.Enums(
Object.keys(enums).filter(
(key) => typeof enums[enums[key]] !== "number"
).map((key) => [key, enums[key]])
)
const makeEnumsClass = <A extends EnumsDefinition>(
enums: A,
ast: AST.AST = getDefaultEnumsAST(enums)
): Enums<A> =>
class EnumsClass extends make<A[keyof A]>(ast) {
static override annotations(annotations: Annotations.Schema<A[keyof A]>) {
return makeEnumsClass(this.enums, mergeSchemaAnnotations(this.ast, annotations))
}
static enums = { ...enums }
}
/**
* @category constructors
* @since 0.67.0
*/
export const Enums = <A extends EnumsDefinition>(enums: A): Enums<A> => makeEnumsClass(enums)
type Join<Params> = Params extends [infer Head, ...infer Tail] ?
`${(Head extends Schema<infer A> ? A : Head) & (AST.LiteralValue)}${Join<Tail>}`
: ""
/**
* @category API interface
* @since 0.67.17
*/
export interface TemplateLiteral<A> extends SchemaClass<A> {}
type TemplateLiteralParameter = Schema.AnyNoContext | AST.LiteralValue
/**
* @category template literal
* @since 0.67.0
*/
export const TemplateLiteral = <Params extends array_.NonEmptyReadonlyArray<TemplateLiteralParameter>>(
...[head, ...tail]: Params
): TemplateLiteral<Join<Params>> => {
let astOrs: ReadonlyArray<AST.TemplateLiteral | string> = getTemplateLiterals(
getTemplateLiteralParameterAST(head)
)
for (const span of tail) {
astOrs = array_.flatMap(
astOrs,
(a) => getTemplateLiterals(getTemplateLiteralParameterAST(span)).map((b) => combineTemplateLiterals(a, b))
)
}
return make(AST.Union.make(astOrs.map((astOr) => Predicate.isString(astOr) ? new AST.Literal(astOr) : astOr)))
}
const getTemplateLiteralParameterAST = (span: TemplateLiteralParameter): AST.AST =>
isSchema(span) ? span.ast : new AST.Literal(String(span))
const combineTemplateLiterals = (
a: AST.TemplateLiteral | string,
b: AST.TemplateLiteral | string
): AST.TemplateLiteral | string => {
if (Predicate.isString(a)) {
return Predicate.isString(b) ?
a + b :
new AST.TemplateLiteral(a + b.head, b.spans)
}
if (Predicate.isString(b)) {
return new AST.TemplateLiteral(
a.head,
array_.modifyNonEmptyLast(
a.spans,
(span) => new AST.TemplateLiteralSpan(span.type, span.literal + b)
)
)
}
return new AST.TemplateLiteral(
a.head,
array_.appendAll(
array_.modifyNonEmptyLast(
a.spans,
(span) => new AST.TemplateLiteralSpan(span.type, span.literal + String(b.head))
),
b.spans
)
)
}
const getTemplateLiterals = (
ast: AST.AST
): ReadonlyArray<AST.TemplateLiteral | string> => {
switch (ast._tag) {
case "Literal":
return [String(ast.literal)]
case "NumberKeyword":
case "StringKeyword":
return [new AST.TemplateLiteral("", [new AST.TemplateLiteralSpan(ast, "")])]
case "Union":
return array_.flatMap(ast.types, getTemplateLiterals)
}
throw new Error(errors_.getSchemaUnsupportedLiteralSpanErrorMessage(ast))
}
type TemplateLiteralParserParameters = Schema.Any | AST.LiteralValue
type TemplateLiteralParserParametersType<T> = T extends [infer Head, ...infer Tail] ?
readonly [Head extends Schema<infer A, infer _I, infer _R> ? A : Head, ...TemplateLiteralParserParametersType<Tail>]
: []
type TemplateLiteralParserParametersEncoded<T> = T extends [infer Head, ...infer Tail] ? `${
& (Head extends Schema<infer _A, infer I, infer _R> ? I : Head)
& (AST.LiteralValue)}${TemplateLiteralParserParametersEncoded<Tail>}`
: ""
/**
* @category API interface
* @since 0.70.1
*/
export interface TemplateLiteralParser<Params extends array_.NonEmptyReadonlyArray<TemplateLiteralParserParameters>>
extends
Schema<
TemplateLiteralParserParametersType<Params>,
TemplateLiteralParserParametersEncoded<Params>,
Schema.Context<Params[number]>
>
{
readonly params: Params
}
/**
* @category template literal
* @since 0.70.1
*/
export const TemplateLiteralParser = <Params extends array_.NonEmptyReadonlyArray<TemplateLiteralParserParameters>>(
...params: Params
): TemplateLiteralParser<Params> => {
const encodedSchemas: Array<Schema.Any> = []
const typeSchemas: Array<Schema.Any> = []
const numbers: Array<number> = []
for (let i = 0; i < params.length; i++) {
const p = params[i]
if (isSchema(p)) {
const encoded = encodedSchema(p)
if (AST.isNumberKeyword(encoded.ast)) {
numbers.push(i)
}
encodedSchemas.push(encoded)
typeSchemas.push(p)
} else {
const literal = Literal(p as AST.LiteralValue)
encodedSchemas.push(literal)
typeSchemas.push(literal)
}
}
const from = TemplateLiteral(...encodedSchemas as any)
const re = AST.getTemplateLiteralCapturingRegExp(from.ast as AST.TemplateLiteral)
return class TemplateLiteralParserClass extends transform(from, Tuple(...typeSchemas), {
strict: false,
decode: (s) => {
const out: Array<number | string> = re.exec(s)!.slice(1, params.length + 1)
for (let i = 0; i < numbers.length; i++) {
const index = numbers[i]
out[index] = Number(out[index])
}
return out
},
encode: (tuple) => tuple.join("")
}) {
static params = params.slice()
} as any
}
const declareConstructor = <
const TypeParameters extends ReadonlyArray<Schema.Any>,
I,
A
>(
typeParameters: TypeParameters,
options: {
readonly decode: (
...typeParameters: {
readonly [K in keyof TypeParameters]: Schema<
Schema.Type<TypeParameters[K]>,
Schema.Encoded<TypeParameters[K]>,
never
>
}
) => (
input: unknown,
options: ParseOptions,
ast: AST.Declaration
) => Effect.Effect<A, ParseResult.ParseIssue, never>
readonly encode: (
...typeParameters: {
readonly [K in keyof TypeParameters]: Schema<
Schema.Type<TypeParameters[K]>,
Schema.Encoded<TypeParameters[K]>,
never
>
}
) => (
input: unknown,
options: ParseOptions,
ast: AST.Declaration
) => Effect.Effect<I, ParseResult.ParseIssue, never>
},
annotations?: Annotations.Schema<A, TypeParameters>
): SchemaClass<A, I, Schema.Context<TypeParameters[number]>> =>
make(
new AST.Declaration(
typeParameters.map((tp) => tp.ast),
(...typeParameters) => options.decode(...typeParameters.map(make) as any),
(...typeParameters) => options.encode(...typeParameters.map(make) as any),
toASTAnnotations(annotations)
)
)
const declarePrimitive = <A>(
is: (input: unknown) => input is A,
annotations?: Annotations.Schema<A>
): SchemaClass<A> => {
const decodeUnknown = () => (input: unknown, _: ParseOptions, ast: AST.Declaration) =>
is(input) ? ParseResult.succeed(input) : ParseResult.fail(new ParseResult.Type(ast, input))
const encodeUnknown = decodeUnknown
return make(new AST.Declaration([], decodeUnknown, encodeUnknown, toASTAnnotations(annotations)))
}
/**
* The constraint `R extends Schema.Context<P[number]>` enforces dependencies solely from `typeParameters`.
* This ensures that when you call `Schema.to` or `Schema.from`, you receive a schema with a `never` context.
*
* @category constructors
* @since 0.67.0
*/
export const declare: {
<A>(
is: (input: unknown) => input is A,
annotations?: Annotations.Schema<A>
): SchemaClass<A>
<const P extends ReadonlyArray<Schema.All>, I, A>(
typeParameters: P,
options: {
readonly decode: (
...typeParameters: { readonly [K in keyof P]: Schema<Schema.Type<P[K]>, Schema.Encoded<P[K]>, never> }
) => (
input: unknown,
options: ParseOptions,
ast: AST.Declaration
) => Effect.Effect<A, ParseResult.ParseIssue, never>
readonly encode: (
...typeParameters: { readonly [K in keyof P]: Schema<Schema.Type<P[K]>, Schema.Encoded<P[K]>, never> }
) => (
input: unknown,
options: ParseOptions,
ast: AST.Declaration
) => Effect.Effect<I, ParseResult.ParseIssue, never>
},
annotations?: Annotations.Schema<A, { readonly [K in keyof P]: Schema.Type<P[K]> }>
): SchemaClass<A, I, Schema.Context<P[number]>>
} = function() {
if (Array.isArray(arguments[0])) {
const typeParameters = arguments[0]
const options = arguments[1]
const annotations = arguments[2]
return declareConstructor(typeParameters, options, annotations)
}
const is = arguments[0]
const annotations = arguments[1]
return declarePrimitive(is, annotations)
} as any
/**
* @category type id
* @since 0.67.0
*/
export const BrandTypeId: unique symbol = Symbol.for("@effect/schema/TypeId/Brand")
/**
* @category constructors
* @since 0.67.0
*/
export const fromBrand = <C extends Brand<string | symbol>, A extends Brand.Unbranded<C>>(
constructor: Brand.Constructor<C>,
annotations?: Annotations.Filter<C, A>
) =>
<I, R>(self: Schema<A, I, R>): BrandSchema<A & C, I, R> =>
makeBrandClass<Schema<A & C, I, R>, string | symbol>(
new AST.Refinement(
self.ast,
function predicate(a: A, _: ParseOptions, ast: AST.AST): option_.Option<ParseResult.ParseIssue> {
const either = constructor.either(a)
return either_.isLeft(either) ?
option_.some(new ParseResult.Type(ast, a, either.left.map((v) => v.message).join(", "))) :
option_.none()
},
toASTAnnotations({ typeId: { id: BrandTypeId, annotation: { constructor } }, ...annotations })
)
)
/**
* @category type id
* @since 0.67.0
*/
export const InstanceOfTypeId: unique symbol = Symbol.for("@effect/schema/TypeId/InstanceOf")
/**
* @category api interface
* @since 0.67.0
*/
export interface instanceOf<A> extends AnnotableClass<instanceOf<A>, A> {}
/**
* @category constructors
* @since 0.67.0
*/
export const instanceOf = <A extends abstract new(...args: any) => any>(
constructor: A,