From eb656d3b3ecdceff607b634b001a73169900e013 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Sat, 10 May 2025 10:28:39 +0200 Subject: [PATCH] add support for exclusive unions (#115) * rename makeUnsafe to makeSync * add support for "oneOf" unions * rename CodecError to SchemaError * rename issues * add OneOf issue --- packages/effect/SCHEMA.md | 32 ++ packages/effect/dtslint/Schema.tst.ts | 58 ++-- packages/effect/src/Schema.ts | 73 +++-- packages/effect/src/SchemaAST.ts | 72 +++-- packages/effect/src/SchemaCheck.ts | 4 +- packages/effect/src/SchemaFormatter.ts | 75 +++-- packages/effect/src/SchemaIssue.ts | 191 +++++++---- packages/effect/src/SchemaParser.ts | 6 +- packages/effect/src/SchemaSerializerJson.ts | 6 +- packages/effect/src/SchemaTransformation.ts | 2 +- packages/effect/src/SchemaValidator.ts | 14 +- .../effect/src/unstable/HttpClientResponse.ts | 4 +- .../src/unstable/HttpIncomingMessage.ts | 4 +- packages/effect/test/Schema.test.ts | 303 +++++++++--------- packages/effect/test/SchemaFormatter.test.ts | 52 ++- packages/effect/test/SchemaIssue.test.ts | 2 +- packages/effect/test/SchemaTest.ts | 10 +- 17 files changed, 550 insertions(+), 358 deletions(-) diff --git a/packages/effect/SCHEMA.md b/packages/effect/SCHEMA.md index 7ee90faa17..7e3c99a9b4 100644 --- a/packages/effect/SCHEMA.md +++ b/packages/effect/SCHEMA.md @@ -1290,6 +1290,38 @@ class A extends Schema.RequestClass("A")({ }) {} ``` +## Unions + +By default, unions are inclusive, meaning that the union matches if any member matches. + +Members are checked in order, and the first match is returned. + +### Exclusive Unions + +You can create an exclusive union, where the union matches if exactly one member matches, by passing the `{ mode: "oneOf" }` option. + +**Example** (Exclusive Union) + +```ts +import { Effect, Schema, SchemaFormatter } from "effect" + +const schema = Schema.Union( + [Schema.Struct({ a: Schema.String }), Schema.Struct({ b: Schema.Number })], + { mode: "oneOf" } +) + +Schema.decodeUnknown(schema)({ a: "a", b: 1 }) + .pipe( + Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), + Effect.runPromise + ) + .then(console.log, console.error) +/* +Output: +Expected exactly one successful result for { readonly "a": string } ⊻ { readonly "b": number }, actual {"a":"a","b":1} +*/ +``` + ## Transformations Redesign ### Transformations as First-Class diff --git a/packages/effect/dtslint/Schema.tst.ts b/packages/effect/dtslint/Schema.tst.ts index e45c577b9e..55c8c3e7ba 100644 --- a/packages/effect/dtslint/Schema.tst.ts +++ b/packages/effect/dtslint/Schema.tst.ts @@ -65,50 +65,50 @@ describe("Schema", () => { }) }) - describe("makeUnsafe", () => { + describe("makeSync", () => { it("Never", () => { const schema = Schema.Never - expect(schema.makeUnsafe).type.toBe<(input: never, options?: Schema.MakeOptions | undefined) => never>() + expect(schema.makeSync).type.toBe<(input: never, options?: Schema.MakeOptions | undefined) => never>() }) it("Unknown", () => { const schema = Schema.Unknown - expect(schema.makeUnsafe).type.toBe<(input: unknown, options?: Schema.MakeOptions | undefined) => unknown>() + expect(schema.makeSync).type.toBe<(input: unknown, options?: Schema.MakeOptions | undefined) => unknown>() }) it("Null", () => { const schema = Schema.Null - expect(schema.makeUnsafe).type.toBe<(input: null, options?: Schema.MakeOptions | undefined) => null>() + expect(schema.makeSync).type.toBe<(input: null, options?: Schema.MakeOptions | undefined) => null>() }) it("Undefined", () => { const schema = Schema.Undefined - expect(schema.makeUnsafe).type.toBe<(input: undefined, options?: Schema.MakeOptions | undefined) => undefined>() + expect(schema.makeSync).type.toBe<(input: undefined, options?: Schema.MakeOptions | undefined) => undefined>() }) it("String", () => { const schema = Schema.String - expect(schema.makeUnsafe).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>() + expect(schema.makeSync).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>() }) it("Number", () => { const schema = Schema.Number - expect(schema.makeUnsafe).type.toBe<(input: number, options?: Schema.MakeOptions | undefined) => number>() + expect(schema.makeSync).type.toBe<(input: number, options?: Schema.MakeOptions | undefined) => number>() }) it("check", () => { const schema = Schema.String.pipe(Schema.check(SchemaCheck.minLength(1))) - expect(schema.makeUnsafe).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>() + expect(schema.makeSync).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>() }) it("checkEncoded", () => { const schema = Schema.String.pipe(Schema.checkEncoded(SchemaCheck.minLength(1))) - expect(schema.makeUnsafe).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>() + expect(schema.makeSync).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>() }) it("brand", () => { const schema = Schema.String.pipe(Schema.brand("a")) - expect(schema.makeUnsafe).type.toBe< + expect(schema.makeSync).type.toBe< (input: string, options?: Schema.MakeOptions | undefined) => string & Brand.Brand<"a"> >() }) @@ -117,7 +117,7 @@ describe("Schema", () => { const schema = Schema.Struct({ a: Schema.String.pipe(Schema.brand("a")) }) - expect(schema.makeUnsafe).type.toBe< + expect(schema.makeSync).type.toBe< ( input: { readonly a: string }, options?: Schema.MakeOptions | undefined @@ -134,7 +134,7 @@ describe("Schema", () => { it("typeSchema", () => { const schema = Schema.String.pipe(Schema.brand("a"), Schema.typeCodec) - expect(schema.makeUnsafe).type.toBe< + expect(schema.makeSync).type.toBe< (input: string, options?: Schema.MakeOptions | undefined) => string & Brand.Brand<"a"> >() }) @@ -335,7 +335,7 @@ describe("Schema", () => { } const schema = f(Schema.Struct({ a: Schema.String, c: Schema.String })) - expect(schema.makeUnsafe).type.toBe< + expect(schema.makeSync).type.toBe< ( input: { readonly a: string; readonly c: string; readonly b: string }, options?: Schema.MakeOptions | undefined @@ -355,12 +355,12 @@ describe("Schema", () => { const schema = Schema.Struct({ a: Schema.String.pipe(Schema.setConstructorDefault(() => Result.succeedSome("c"))) }) - expect(schema.makeUnsafe).type.toBe< + expect(schema.makeSync).type.toBe< (input: { readonly a?: string }, options?: Schema.MakeOptions | undefined) => { readonly a: string } >() const flipped = schema.pipe(Schema.flip) - expect(flipped.makeUnsafe).type.toBe< + expect(flipped.makeSync).type.toBe< (input: { readonly a: string }, options?: Schema.MakeOptions | undefined) => { readonly a: string } >() @@ -495,7 +495,7 @@ describe("Schema", () => { expect().type.toBe() expect().type.toBe<{ readonly a: string }>() - expect(A.makeUnsafe({ a: 1 })).type.toBe() + expect(A.makeSync({ a: 1 })).type.toBe() expect(Schema.revealCodec(schema)).type.toBe>() expect(schema).type.toBe() @@ -503,7 +503,7 @@ describe("Schema", () => { Schema.Struct<{ readonly a: Schema.decodeTo }> >() expect(schema.ast).type.toBe() - expect(schema.makeUnsafe).type.toBe< + expect(schema.makeSync).type.toBe< (input: { readonly a: number }, options?: Schema.MakeOptions | undefined) => A >() expect(schema.fields).type.toBe<{ readonly a: Schema.decodeTo }>() @@ -511,7 +511,7 @@ describe("Schema", () => { // @ts-expect-error: Property 'a' does not exist on type 'typeof A'. const _test1 = A.a - const instance = A.makeUnsafe({ a: 1 }) + const instance = A.makeSync({ a: 1 }) // @ts-expect-error: Property 'annotate' does not exist on type 'A'. const _test2 = instance.annotate }) @@ -558,7 +558,7 @@ describe("Schema", () => { expect(schema).type.toBe>() expect(schema.annotate({})).type.toBe>() expect(schema.ast).type.toBe() - expect(schema.makeUnsafe).type.toBe< + expect(schema.makeSync).type.toBe< (input: MyError, options?: Schema.MakeOptions | undefined) => MyError >() }) @@ -712,7 +712,7 @@ describe("Schema", () => { }) {} expect(new A({ a: "a" })).type.toBe() - expect(A.makeUnsafe({ a: "a" })).type.toBe() + expect(A.makeSync({ a: "a" })).type.toBe() expect(Schema.revealCodec(A)).type.toBe>() expect(revealClass(A)).type.toBe< Schema.Class, A> @@ -726,7 +726,7 @@ describe("Schema", () => { })) {} expect(new A({ a: "a" })).type.toBe() - expect(A.makeUnsafe({ a: "a" })).type.toBe() + expect(A.makeSync({ a: "a" })).type.toBe() expect(Schema.revealCodec(A)).type.toBe>() expect(revealClass(A)).type.toBe< Schema.Class, A> @@ -769,8 +769,8 @@ describe("Schema", () => { const f = (a: A) => a - f(A.makeUnsafe({ a: "a" })) - f(B.makeUnsafe({ a: "a" })) + f(A.makeSync({ a: "a" })) + f(B.makeSync({ a: "a" })) class ABranded extends Schema.Class("ABranded")({ a: Schema.String @@ -781,15 +781,15 @@ describe("Schema", () => { const fABranded = (a: ABranded) => a - fABranded(ABranded.makeUnsafe({ a: "a" })) + fABranded(ABranded.makeSync({ a: "a" })) // @ts-expect-error - fABranded(BBranded.makeUnsafe({ a: "a" })) + fABranded(BBranded.makeSync({ a: "a" })) const fBBranded = (a: BBranded) => a // @ts-expect-error - fBBranded(ABranded.makeUnsafe({ a: "a" })) - fBBranded(BBranded.makeUnsafe({ a: "a" })) + fBBranded(ABranded.makeSync({ a: "a" })) + fBBranded(BBranded.makeSync({ a: "a" })) }) }) @@ -800,7 +800,7 @@ describe("Schema", () => { }) {} expect(new E({ a: "a" })).type.toBe() - expect(E.makeUnsafe({ a: "a" })).type.toBe() + expect(E.makeSync({ a: "a" })).type.toBe() expect(Schema.revealCodec(E)).type.toBe>() expect(Effect.gen(function*() { @@ -814,7 +814,7 @@ describe("Schema", () => { })) {} expect(new E({ a: "a" })).type.toBe() - expect(E.makeUnsafe({ a: "a" })).type.toBe() + expect(E.makeSync({ a: "a" })).type.toBe() expect(Schema.revealCodec(E)).type.toBe>() expect(Effect.gen(function*() { diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 9381e46aea..74cfac789b 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -94,7 +94,10 @@ export interface Bottom< input: this["~type.make.in"], options?: MakeOptions ): SchemaResult.SchemaResult - makeUnsafe(input: this["~type.make.in"], options?: MakeOptions): this["Type"] + /** + * @throws {Error} The issue is contained in the error cause. + */ + makeSync(input: this["~type.make.in"], options?: MakeOptions): this["Type"] } /** @@ -152,7 +155,7 @@ export abstract class Bottom$< constructor(readonly ast: Ast) { this.make = this.make.bind(this) - this.makeUnsafe = this.makeUnsafe.bind(this) + this.makeSync = this.makeSync.bind(this) } abstract rebuild(ast: this["ast"]): this["~rebuild.out"] pipe() { @@ -165,11 +168,11 @@ export abstract class Bottom$< const parseOptions: SchemaAST.ParseOptions = { "~variant": "make", ...options?.parseOptions } return SchemaValidator.validateUnknownParserResult(this)(input, parseOptions) as any } - makeUnsafe(input: this["~type.make.in"], options?: MakeOptions): this["Type"] { + makeSync(input: this["~type.make.in"], options?: MakeOptions): this["Type"] { return Result.getOrThrowWith( SchemaValidator.runSyncSchemaResult(this.make(input, options)), (issue) => - new globalThis.Error(`makeUnsafe failure, actual ${globalThis.String(input)}`, { + new globalThis.Error(`makeSync failure, actual ${globalThis.String(input)}`, { cause: issue }) ) @@ -253,7 +256,7 @@ export interface Codec extends * @since 4.0.0 * @category error */ -export class CodecError extends Data.TaggedError("CodecError")<{ +export class SchemaError extends Data.TaggedError("SchemaError")<{ readonly issue: SchemaIssue.Issue }> {} @@ -263,8 +266,8 @@ export class CodecError extends Data.TaggedError("CodecError")<{ */ export const decodeUnknown = (codec: Codec) => { const parser = SchemaValidator.decodeUnknown(codec) - return (u: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => { - return Effect.mapError(parser(u, options), (issue) => new CodecError({ issue })) + return (u: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => { + return Effect.mapError(parser(u, options), (issue) => new SchemaError({ issue })) } } @@ -274,8 +277,8 @@ export const decodeUnknown = (codec: Codec) => { */ export const decode = (codec: Codec) => { const parser = SchemaValidator.decode(codec) - return (e: E, options?: SchemaAST.ParseOptions): Effect.Effect => { - return Effect.mapError(parser(e, options), (issue) => new CodecError({ issue })) + return (e: E, options?: SchemaAST.ParseOptions): Effect.Effect => { + return Effect.mapError(parser(e, options), (issue) => new SchemaError({ issue })) } } @@ -291,8 +294,8 @@ export const decodeUnknownSync = SchemaValidator.decodeUnknownSync */ export const encodeUnknown = (codec: Codec) => { const parser = SchemaValidator.encodeUnknown(codec) - return (u: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => { - return Effect.mapError(parser(u, options), (issue) => new CodecError({ issue })) + return (u: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => { + return Effect.mapError(parser(u, options), (issue) => new SchemaError({ issue })) } } @@ -302,8 +305,8 @@ export const encodeUnknown = (codec: Codec) => { */ export const encode = (codec: Codec) => { const parser = SchemaValidator.encode(codec) - return (t: T, options?: SchemaAST.ParseOptions): Effect.Effect => { - return Effect.mapError(parser(t, options), (issue) => new CodecError({ issue })) + return (t: T, options?: SchemaAST.ParseOptions): Effect.Effect => { + return Effect.mapError(parser(t, options), (issue) => new SchemaError({ issue })) } } @@ -603,7 +606,7 @@ export const declareRefinement = ( () => (input, ast) => options.is(input) ? Result.ok(input) : - Result.err(new SchemaIssue.MismatchIssue(ast, O.some(input))), + Result.err(new SchemaIssue.InvalidType(ast, O.some(input))), options.annotations ) } @@ -1552,10 +1555,27 @@ class Union$> extends make$> i } /** + * Members are checked in order, and the first match is returned. + * + * Optionally, you can specify the `mode` to be `"anyOf"` or `"oneOf"`. + * + * - `"anyOf"` - The union matches if any member matches. + * - `"oneOf"` - The union matches if exactly one member matches. + * * @since 4.0.0 */ -export function Union>(members: Members): Union { - const ast = new SchemaAST.UnionType(members.map((type) => type.ast), undefined, undefined, undefined, undefined) +export function Union>( + members: Members, + options?: { mode?: "anyOf" | "oneOf" } +): Union { + const ast = new SchemaAST.UnionType( + members.map((type) => type.ast), + options?.mode ?? "anyOf", + undefined, + undefined, + undefined, + undefined + ) return new Union$(ast, members) } @@ -1591,6 +1611,7 @@ export function Literals>( return new Literals$( new SchemaAST.UnionType( literals.map((literal) => Literal(literal).ast), + "anyOf", undefined, undefined, undefined, @@ -1682,7 +1703,7 @@ export const refine = ( (input, ast) => is(input) ? undefined : - [new SchemaIssue.MismatchIssue(ast, O.some(input)), true], // after a refinement, we always want to abort + [new SchemaIssue.InvalidType(ast, O.some(input)), true], // after a refinement, we always want to abort annotations ) ]) @@ -1977,12 +1998,12 @@ export const Option = (value: S): Option => { onSuccess: O.some, onFailure: (issue) => { const actual = O.some(oinput) - return new SchemaIssue.CompositeIssue(ast, actual, [issue]) + return new SchemaIssue.Composite(ast, actual, [issue]) } } ) } - return Result.err(new SchemaIssue.MismatchIssue(ast, O.some(oinput))) + return Result.err(new SchemaIssue.InvalidType(ast, O.some(oinput))) }, { declaration: { @@ -2038,11 +2059,11 @@ export const Map = (key: Key, value: Value): SchemaValidator.decodeUnknownSchemaResult(array)([...input], options), { onSuccess: (array: ReadonlyArray) => new globalThis.Map(array), - onFailure: (issue) => new SchemaIssue.CompositeIssue(ast, O.some(input), [issue]) + onFailure: (issue) => new SchemaIssue.Composite(ast, O.some(input), [issue]) } ) } - return Result.err(new SchemaIssue.MismatchIssue(ast, O.some(input))) + return Result.err(new SchemaIssue.InvalidType(ast, O.some(input))) }, { declaration: { @@ -2265,7 +2286,7 @@ function makeClass< return class extends Inherited { constructor(...[input, options]: ReadonlyArray) { if (options?.skipValidation !== true) { - schema.makeUnsafe(input, options) + schema.makeSync(input, options) } super(input, { ...options, skipValidation: true }) } @@ -2313,7 +2334,7 @@ function makeClass< if (input instanceof this) { return Result.ok(input) } - return Result.err(new SchemaIssue.MismatchIssue(ast, O.some(input))) + return Result.err(new SchemaIssue.InvalidType(ast, O.some(input))) }, { serialization: { @@ -2338,7 +2359,7 @@ function makeClass< (input) => new this(input, options) ) } - static makeUnsafe(input: S["~type.make.in"], options?: MakeOptions): Self { + static makeSync(input: S["~type.make.in"], options?: MakeOptions): Self { return new this(input, options) } static extend( @@ -2367,7 +2388,7 @@ const makeDefaultClassLink = (self: new(...args: ReadonlyArray) => any) => SchemaParser.mapSome((input) => new self(input)), SchemaParser.parseSome((input) => { if (!(input instanceof self)) { - return Result.err(new SchemaIssue.MismatchIssue(ast, input)) + return Result.err(new SchemaIssue.InvalidType(ast, input)) } return Result.succeedSome(input) }) @@ -2386,7 +2407,7 @@ function getDefaultComputeAST( if (input instanceof self) { return Result.ok(input) } - return Result.err(new SchemaIssue.MismatchIssue(ast, O.some(input))) + return Result.err(new SchemaIssue.InvalidType(ast, O.some(input))) }, { serialization: { diff --git a/packages/effect/src/SchemaAST.ts b/packages/effect/src/SchemaAST.ts index ee1e176d95..8dcaf6f560 100644 --- a/packages/effect/src/SchemaAST.ts +++ b/packages/effect/src/SchemaAST.ts @@ -699,7 +699,7 @@ export class TupleType extends Extensions { // If the input is not an array, return early with an error if (!Arr.isArray(input)) { - return yield* Effect.fail(new SchemaIssue.MismatchIssue(ast, oinput)) + return yield* Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } const output: Array = [] @@ -713,24 +713,24 @@ export class TupleType extends Extensions { const parser = go(element) const r = yield* Effect.result(parser(value, options)) if (Result.isErr(r)) { - const issue = new SchemaIssue.PointerIssue([i], r.err) + const issue = new SchemaIssue.Pointer([i], r.err) if (errorsAllOption) { issues.push(issue) continue } else { - return yield* Effect.fail(new SchemaIssue.CompositeIssue(ast, oinput, [issue])) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, [issue])) } } else { if (Option.isSome(r.ok)) { output[i] = r.ok.value } else { if (!element.context?.isOptional) { - const issue = new SchemaIssue.PointerIssue([i], SchemaIssue.MissingIssue.instance) + const issue = new SchemaIssue.Pointer([i], new SchemaIssue.MissingKey()) if (errorsAllOption) { issues.push(issue) continue } else { - return yield* Effect.fail(new SchemaIssue.CompositeIssue(ast, oinput, [issue])) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, [issue])) } } } @@ -743,30 +743,30 @@ export class TupleType extends Extensions { for (; i < len - tail.length; i++) { const r = yield* Effect.result(parser(Option.some(input[i]), options)) if (Result.isErr(r)) { - const issue = new SchemaIssue.PointerIssue([i], r.err) + const issue = new SchemaIssue.Pointer([i], r.err) if (errorsAllOption) { issues.push(issue) continue } else { - return yield* Effect.fail(new SchemaIssue.CompositeIssue(ast, oinput, [issue])) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, [issue])) } } else { if (Option.isSome(r.ok)) { output[i] = r.ok.value } else { - const issue = new SchemaIssue.PointerIssue([i], SchemaIssue.MissingIssue.instance) + const issue = new SchemaIssue.Pointer([i], new SchemaIssue.MissingKey()) if (errorsAllOption) { issues.push(issue) continue } else { - return yield* Effect.fail(new SchemaIssue.CompositeIssue(ast, oinput, [issue])) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, [issue])) } } } } } if (Arr.isNonEmptyArray(issues)) { - return yield* Effect.fail(new SchemaIssue.CompositeIssue(ast, oinput, issues)) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, issues)) } return Option.some(output) }) @@ -856,7 +856,7 @@ export class TypeLiteral extends Extensions { // If the input is not a record, return early with an error if (!Predicate.isRecord(input)) { - return yield* Effect.fail(new SchemaIssue.MismatchIssue(ast, oinput)) + return yield* Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } const output: Record = {} @@ -874,13 +874,13 @@ export class TypeLiteral extends Extensions { const parser = go(type) const r = yield* Effect.result(parser(value, options)) if (Result.isErr(r)) { - const issue = new SchemaIssue.PointerIssue([name], r.err) + const issue = new SchemaIssue.Pointer([name], r.err) if (errorsAllOption) { issues.push(issue) continue } else { return yield* Effect.fail( - new SchemaIssue.CompositeIssue(ast, oinput, [issue]) + new SchemaIssue.Composite(ast, oinput, [issue]) ) } } else { @@ -888,13 +888,13 @@ export class TypeLiteral extends Extensions { output[name] = r.ok.value } else { if (!ps.type.context?.isOptional) { - const issue = new SchemaIssue.PointerIssue([name], SchemaIssue.MissingIssue.instance) + const issue = new SchemaIssue.Pointer([name], new SchemaIssue.MissingKey()) if (errorsAllOption) { issues.push(issue) continue } else { return yield* Effect.fail( - new SchemaIssue.CompositeIssue(ast, oinput, [issue]) + new SchemaIssue.Composite(ast, oinput, [issue]) ) } } @@ -910,13 +910,13 @@ export class TypeLiteral extends Extensions { SchemaIssue.Issue > if (Result.isErr(rKey)) { - const issue = new SchemaIssue.PointerIssue([key], rKey.err) + const issue = new SchemaIssue.Pointer([key], rKey.err) if (errorsAllOption) { issues.push(issue) continue } else { return yield* Effect.fail( - new SchemaIssue.CompositeIssue(ast, oinput, [issue]) + new SchemaIssue.Composite(ast, oinput, [issue]) ) } } @@ -925,13 +925,13 @@ export class TypeLiteral extends Extensions { const parserValue = go(is.type) const rValue = yield* Effect.result(parserValue(value, options)) if (Result.isErr(rValue)) { - const issue = new SchemaIssue.PointerIssue([key], rValue.err) + const issue = new SchemaIssue.Pointer([key], rValue.err) if (errorsAllOption) { issues.push(issue) continue } else { return yield* Effect.fail( - new SchemaIssue.CompositeIssue(ast, oinput, [issue]) + new SchemaIssue.Composite(ast, oinput, [issue]) ) } } else { @@ -950,7 +950,7 @@ export class TypeLiteral extends Extensions { } if (Arr.isNonEmptyArray(issues)) { - return yield* Effect.fail(new SchemaIssue.CompositeIssue(ast, oinput, issues)) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, issues)) } return Option.some(output) }) @@ -1014,7 +1014,6 @@ const getCandidateTypes = memoize((ast: AST): ReadonlyArray | Type | null case "Suspend": return null } - ast satisfies never // TODO: remove this }) function getCandidates(input: unknown, types: ReadonlyArray): ReadonlyArray { @@ -1036,6 +1035,7 @@ export class UnionType extends Extensions { readonly _tag = "UnionType" constructor( readonly types: ReadonlyArray, + readonly mode: "anyOf" | "oneOf", annotations: Annotations | undefined, checks: Checks | undefined, encoding: Encoding | undefined, @@ -1048,7 +1048,7 @@ export class UnionType extends Extensions { const types = mapOrSame(this.types, typeAST) return types === this.types ? this : - new UnionType(types, this.annotations, this.checks, undefined, this.context) + new UnionType(types, this.mode, this.annotations, this.checks, undefined, this.context) } /** @internal */ flip(): AST { @@ -1058,7 +1058,7 @@ export class UnionType extends Extensions { const types = mapOrSame(this.types, flip) return types === this.types ? this : - new UnionType(types, this.annotations, this.checks, undefined, this.context) + new UnionType(types, this.mode, this.annotations, this.checks, undefined, this.context) } /** @internal */ parser(go: (ast: AST) => SchemaValidator.Parser) { @@ -1069,29 +1069,38 @@ export class UnionType extends Extensions { return Option.none() } const input = oinput.value - + const oneOf = ast.mode === "oneOf" const candidates = getCandidates(input, ast.types) const issues: Array = [] + let out: Option.Option | undefined = undefined for (const candidate of candidates) { const parser = go(candidate) - const r = yield* Effect.result(parser(Option.some(input), options)) + const r = yield* Effect.result(parser(oinput, options)) if (Result.isErr(r)) { issues.push(r.err) continue } else { - return r.ok + if (out && oneOf) { + return yield* Effect.fail(new SchemaIssue.OneOf(ast, input)) + } + out = r.ok + if (!oneOf) { + break + } } } - if (Arr.isNonEmptyArray(issues)) { + if (out) { + return out + } else if (Arr.isNonEmptyArray(issues)) { if (candidates.length === 1) { return yield* Effect.fail(issues[0]) } else { - return yield* Effect.fail(new SchemaIssue.CompositeIssue(ast, oinput, issues)) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, issues)) } } else { - return yield* Effect.fail(new SchemaIssue.MismatchIssue(ast, oinput)) + return yield* Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } }) } @@ -1529,13 +1538,12 @@ function formatAST(ast: AST): string { if (ast.types.length === 0) { return "never" } else { - return ast.types.map(format).join(" | ") + return ast.types.map(format).join(ast.mode === "oneOf" ? " ⊻ " : " | ") } } case "Suspend": return "#" } - ast satisfies never // TODO: remove this } /** @internal */ @@ -1676,5 +1684,5 @@ export const fromPredicate = return Effect.succeedNone } const u = oinput.value - return predicate(u) ? Effect.succeed(Option.some(u)) : Effect.fail(new SchemaIssue.MismatchIssue(ast, oinput)) + return predicate(u) ? Effect.succeed(Option.some(u)) : Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } diff --git a/packages/effect/src/SchemaCheck.ts b/packages/effect/src/SchemaCheck.ts index a8937e4272..fcfc2dd331 100644 --- a/packages/effect/src/SchemaCheck.ts +++ b/packages/effect/src/SchemaCheck.ts @@ -74,10 +74,10 @@ export function make( return undefined } if (Predicate.isBoolean(out)) { - return out ? undefined : [new SchemaIssue.InvalidIssue(Option.some(input)), false] + return out ? undefined : [new SchemaIssue.InvalidData(Option.some(input)), false] } if (Predicate.isString(out)) { - return [new SchemaIssue.InvalidIssue(Option.some(input), out), false] + return [new SchemaIssue.InvalidData(Option.some(input), out), false] } return out }, diff --git a/packages/effect/src/SchemaFormatter.ts b/packages/effect/src/SchemaFormatter.ts index 93b7bc4088..5df6c1c9b8 100644 --- a/packages/effect/src/SchemaFormatter.ts +++ b/packages/effect/src/SchemaFormatter.ts @@ -42,17 +42,17 @@ const draw = (indentation: string, forest: Forest): string => { return r } -function formatInvalidIssue(issue: SchemaIssue.InvalidIssue): string { +function formatInvalidData(issue: SchemaIssue.InvalidData): string { if (issue.message !== undefined) { return issue.message } if (Option.isNone(issue.actual)) { return "No value provided" } - return `Invalid value ${formatUnknown(issue.actual.value)}` + return `Invalid data ${formatUnknown(issue.actual.value)}` } -function formatMismatchIssue(issue: SchemaIssue.MismatchIssue): string { +function formatInvalidType(issue: SchemaIssue.InvalidType): string { if (issue.message !== undefined) { return issue.message } @@ -62,7 +62,13 @@ function formatMismatchIssue(issue: SchemaIssue.MismatchIssue): string { return `Expected ${SchemaAST.format(issue.ast)}, actual ${formatUnknown(issue.actual.value)}` } -function formatForbiddenIssue(issue: SchemaIssue.ForbiddenIssue): string { +function formatOneOf(issue: SchemaIssue.OneOf): string { + return `Expected exactly one successful result for ${SchemaAST.format(issue.ast)}, actual ${ + formatUnknown(issue.actual) + }` +} + +function formatForbidden(issue: SchemaIssue.Forbidden): string { if (issue.message !== undefined) { return issue.message } @@ -71,24 +77,25 @@ function formatForbiddenIssue(issue: SchemaIssue.ForbiddenIssue): string { function formatTree(issue: SchemaIssue.Issue): Tree { switch (issue._tag) { - case "MismatchIssue": - return makeTree(formatMismatchIssue(issue)) - case "InvalidIssue": - return makeTree(formatInvalidIssue(issue)) - case "CompositeIssue": + case "InvalidType": + return makeTree(formatInvalidType(issue)) + case "InvalidData": + return makeTree(formatInvalidData(issue)) + case "Composite": return makeTree(SchemaAST.format(issue.ast), issue.issues.map(formatTree)) - case "PointerIssue": + case "Pointer": return makeTree(formatPath(issue.path), [formatTree(issue.issue)]) - case "CheckIssue": + case "Check": return makeTree(SchemaAST.formatCheck(issue.check), [formatTree(issue.issue)]) - case "TransformationIssue": + case "Transformation": return makeTree(SchemaAST.formatParser(issue.parser), [formatTree(issue.issue)]) - case "MissingIssue": - return makeTree("Missing value") - case "ForbiddenIssue": - return makeTree(formatForbiddenIssue(issue)) + case "MissingKey": + return makeTree("Missing key") + case "Forbidden": + return makeTree(formatForbidden(issue)) + case "OneOf": + return makeTree(formatOneOf(issue)) } - issue satisfies never // TODO: remove this } /** @@ -104,7 +111,7 @@ export const TreeFormatter: SchemaFormatter = { * @since 4.0.0 */ export interface StructuredIssue { - readonly _tag: "MismatchIssue" | "InvalidIssue" | "MissingIssue" | "ForbiddenIssue" + readonly _tag: "InvalidType" | "InvalidData" | "MissingKey" | "Forbidden" | "OneOf" readonly expected: string readonly actual: Option.Option readonly path: SchemaIssue.PropertyKeyPath @@ -127,27 +134,27 @@ function formatStructured( expected: string | undefined ): Array { switch (issue._tag) { - case "MismatchIssue": + case "InvalidType": return [ { _tag: issue._tag, expected: expected ?? SchemaAST.format(issue.ast), actual: issue.actual, path, - message: formatMismatchIssue(issue) + message: formatInvalidType(issue) } ] - case "InvalidIssue": + case "InvalidData": return [ { _tag: issue._tag, expected: expected ?? "unknown", actual: issue.actual, path, - message: formatInvalidIssue(issue) + message: formatInvalidData(issue) } ] - case "MissingIssue": + case "MissingKey": return [ { _tag: issue._tag, @@ -157,17 +164,27 @@ function formatStructured( message: "Missing value" } ] - case "ForbiddenIssue": + case "Forbidden": return [ { _tag: issue._tag, expected: expected ?? "unknown", actual: issue.actual, path, - message: formatForbiddenIssue(issue) + message: formatForbidden(issue) } ] - case "CheckIssue": { + case "OneOf": + return [ + { + _tag: issue._tag, + expected: expected ?? SchemaAST.format(issue.ast), + actual: Option.some(issue.actual), + path, + message: formatOneOf(issue) + } + ] + case "Check": { expected = expected ?? SchemaAST.formatCheck(issue.check) return formatStructured(issue.issue, path, expected).map((structured) => ({ ...structured, @@ -175,13 +192,13 @@ function formatStructured( meta: issue.check.annotations?.meta })) } - case "TransformationIssue": { + case "Transformation": { expected = expected ?? SchemaAST.formatParser(issue.parser) return formatStructured(issue.issue, path, expected) } - case "PointerIssue": + case "Pointer": return formatStructured(issue.issue, [...path, ...issue.path], expected) - case "CompositeIssue": { + case "Composite": { expected = expected ?? SchemaAST.format(issue.ast) return issue.issues.flatMap((issue) => formatStructured(issue, path, expected)) } diff --git a/packages/effect/src/SchemaIssue.ts b/packages/effect/src/SchemaIssue.ts index 96263febd8..eeb0664e8e 100644 --- a/packages/effect/src/SchemaIssue.ts +++ b/packages/effect/src/SchemaIssue.ts @@ -2,7 +2,6 @@ * @since 4.0.0 */ -import type * as Arr from "./Array.js" import type * as Option from "./Option.js" import { hasProperty } from "./Predicate.js" import type * as SchemaAST from "./SchemaAST.js" @@ -33,30 +32,37 @@ export function isIssue(u: unknown): u is Issue { */ export type Issue = // leaf - | MismatchIssue - | InvalidIssue - | MissingIssue - | ForbiddenIssue + | InvalidType + | InvalidData + | MissingKey + | Forbidden + | OneOf // composite - | CheckIssue - | TransformationIssue - | PointerIssue - | CompositeIssue + | Check + | Transformation + | Pointer + | Composite class Base { readonly [TypeId] = TypeId } /** - * Error that occurs when a transformation has an error. + * Issue that occurs when a transformation has an issue. * * @category model * @since 4.0.0 */ -export class TransformationIssue extends Base { - readonly _tag = "TransformationIssue" +export class Transformation extends Base { + readonly _tag = "Transformation" constructor( + /** + * The parser contained in the transformation that failed. + */ readonly parser: SchemaAST.Transformation["decode"], + /** + * The issue that occurred. + */ readonly issue: Issue ) { super() @@ -64,16 +70,25 @@ export class TransformationIssue extends Base { } /** - * Error that occurs when a check has an error. + * Issue that occurs when a check has an issue. * * @category model * @since 4.0.0 */ -export class CheckIssue extends Base { - readonly _tag = "CheckIssue" +export class Check extends Base { + readonly _tag = "Check" constructor( + /** + * The check that failed. + */ readonly check: SchemaCheck.Check, + /** + * The issue that occurred. + */ readonly issue: Issue, + /** + * Whether the decoding process has been aborted after this check has failed. + */ readonly abort: boolean ) { super() @@ -92,10 +107,16 @@ export type PropertyKeyPath = ReadonlyArray * @category model * @since 4.0.0 */ -export class PointerIssue extends Base { - readonly _tag = "PointerIssue" +export class Pointer extends Base { + readonly _tag = "Pointer" constructor( + /** + * The path to the location in the input that caused the issue. + */ readonly path: PropertyKeyPath, + /** + * The issue that occurred. + */ readonly issue: Issue ) { super() @@ -108,12 +129,8 @@ export class PointerIssue extends Base { * @category model * @since 4.0.0 */ -export class MissingIssue extends Base { - static readonly instance = new MissingIssue() - readonly _tag = "MissingIssue" - private constructor() { - super() - } +export class MissingKey extends Base { + readonly _tag = "MissingKey" } /** @@ -122,58 +139,116 @@ export class MissingIssue extends Base { * @category model * @since 4.0.0 */ -export class CompositeIssue extends Base { - readonly _tag = "CompositeIssue" +export class Composite extends Base { + readonly _tag = "Composite" constructor( + /** + * The schema that caused the issue. + */ readonly ast: SchemaAST.AST, + /** + * The actual value that caused the issue. + */ readonly actual: Option.Option, - readonly issues: Arr.NonEmptyReadonlyArray + /** + * The issues that occurred. + */ + readonly issues: readonly [Issue, ...ReadonlyArray] ) { super() } } /** - * @category model - * @since 4.0.0 - */ -export class MismatchIssue extends Base { - readonly _tag = "MismatchIssue" - constructor( - readonly ast: SchemaAST.AST, - readonly actual: Option.Option, - readonly message?: string - ) { - super() - } -} - -/** - * @category model - * @since 4.0.0 - */ -export class InvalidIssue extends Base { - readonly _tag = "InvalidIssue" - constructor( - readonly actual: Option.Option, - readonly message?: string - ) { - super() - } -} - -/** - * The `Forbidden` variant of the `Issue` type represents a forbidden operation, such as when encountering an Effect that is not allowed to execute (e.g., using `runSync`). + * Issue that occurs when the type of the input is invalid. * * @category model * @since 4.0.0 */ -export class ForbiddenIssue extends Base { - readonly _tag = "ForbiddenIssue" +export class InvalidType extends Base { + readonly _tag = "InvalidType" constructor( + /** + * The schema that caused the issue. + */ + readonly ast: SchemaAST.AST, + /** + * The actual value that caused the issue. + */ readonly actual: Option.Option, + /** + * The message to display by default. + */ readonly message?: string ) { super() } } + +/** + * Issue that occurs when the data of the input is invalid. + * + * @category model + * @since 4.0.0 + */ +export class InvalidData extends Base { + readonly _tag = "InvalidData" + constructor( + /** + * The actual value that caused the issue. + */ + readonly actual: Option.Option, + /** + * The message to display by default. + */ + readonly message?: string + ) { + super() + } +} + +/** + * Issue that occurs when a forbidden operation is encountered, such as when + * encountering an Effect that is not allowed to execute (e.g., using `runSync`). + * + * @category model + * @since 4.0.0 + */ +export class Forbidden extends Base { + readonly _tag = "Forbidden" + constructor( + /** + * The actual value that caused the issue. + */ + readonly actual: Option.Option, + /** + * The message to display by default. + */ + readonly message?: string + ) { + super() + } +} + +/** + * Issue that occurs when a value matches multiple union members but the + * schema is configured to only allow one. + * + * @category model + * @since 4.0.0 + */ +export class OneOf extends Base { + readonly _tag = "OneOf" + constructor( + /** + * The schema that caused the issue. + */ + readonly ast: SchemaAST.UnionType, + /** + * The actual value that caused the issue. + */ + readonly actual: unknown + ) { + super() + } +} diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index eb153c6909..d19da67f72 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -109,7 +109,7 @@ export function withDefault(defaultValue: () => T, annotations?: Annotations) * @since 4.0.0 */ export function required(annotations?: Annotations): Parser { - return parseNone(() => SchemaResult.fail(SchemaIssue.MissingIssue.instance), { + return parseNone(() => SchemaResult.fail(new SchemaIssue.MissingKey()), { title: "required", ...annotations }) @@ -232,7 +232,7 @@ export function parseJson(options?: { Result.try({ try: () => Option.some(JSON.parse(input, options?.options?.reviver)), catch: (e) => - new SchemaIssue.InvalidIssue(Option.some(input), e instanceof Error ? e.message : globalThis.String(e)) + new SchemaIssue.InvalidData(Option.some(input), e instanceof Error ? e.message : globalThis.String(e)) }), { title: "parseJson", ...options?.annotations }) } @@ -256,6 +256,6 @@ export function stringifyJson(options?: { Result.try({ try: () => Option.some(JSON.stringify(input, options?.options?.replacer, options?.options?.space)), catch: (e) => - new SchemaIssue.InvalidIssue(Option.some(input), e instanceof Error ? e.message : globalThis.String(e)) + new SchemaIssue.InvalidData(Option.some(input), e instanceof Error ? e.message : globalThis.String(e)) }), { title: "stringifyJson", ...options?.annotations }) } diff --git a/packages/effect/src/SchemaSerializerJson.ts b/packages/effect/src/SchemaSerializerJson.ts index 2e9684eaa2..148b2e5c3c 100644 --- a/packages/effect/src/SchemaSerializerJson.ts +++ b/packages/effect/src/SchemaSerializerJson.ts @@ -97,6 +97,7 @@ const go = SchemaAST.memoize((ast: SchemaAST.AST): SchemaAST.AST => { case "UnionType": return new SchemaAST.UnionType( ast.types.map(go), + ast.mode, ast.annotations, ast.checks, undefined, @@ -111,7 +112,6 @@ const go = SchemaAST.memoize((ast: SchemaAST.AST): SchemaAST.AST => { ast.context ) } - ast satisfies never // TODO: remove this }) const forbiddenLink = new SchemaAST.Link( @@ -131,9 +131,9 @@ const symbolLink = new SchemaAST.Link( if (Symbol.for(description) === sym) { return SchemaResult.succeed(Option.some(description)) } - return SchemaResult.fail(new SchemaIssue.ForbiddenIssue(Option.some(sym), "Symbol is not registered")) + return SchemaResult.fail(new SchemaIssue.Forbidden(Option.some(sym), "Symbol is not registered")) } - return SchemaResult.fail(new SchemaIssue.ForbiddenIssue(Option.some(sym), "Symbol has no description")) + return SchemaResult.fail(new SchemaIssue.Forbidden(Option.some(sym), "Symbol has no description")) }, { title: "symbol encoding" }) ) ) diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index 50ef87e0f8..d7b462c218 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -87,7 +87,7 @@ export function transformOrFail( * @since 4.0.0 */ export function fail(message: string, annotations?: SchemaAST.Annotations.Documentation): Transformation { - const fail = SchemaParser.fail((o) => new SchemaIssue.ForbiddenIssue(o, message), annotations) + const fail = SchemaParser.fail((o) => new SchemaIssue.Forbidden(o, message), annotations) return new Transformation(fail, fail) } diff --git a/packages/effect/src/SchemaValidator.ts b/packages/effect/src/SchemaValidator.ts index 7376950742..bd12f2a709 100644 --- a/packages/effect/src/SchemaValidator.ts +++ b/packages/effect/src/SchemaValidator.ts @@ -119,12 +119,12 @@ export const runSyncSchemaResult = ( } } // The effect executed synchronously but failed due to a defect (e.g., a missing dependency) - return Result.err(new SchemaIssue.ForbiddenIssue(Option.none(), cause.failures.map(String).join("\n"))) + return Result.err(new SchemaIssue.Forbidden(Option.none(), cause.failures.map(String).join("\n"))) } // The effect could not be resolved synchronously, meaning it performs async work return Result.err( - new SchemaIssue.ForbiddenIssue( + new SchemaIssue.Forbidden( Option.none(), "cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work" ) @@ -141,7 +141,7 @@ export const fromASTSchemaResult = (ast: SchemaAST.AST) => { const oa = parser(oinput, options ?? defaultParseOptions) return Effect.flatMap(oa, (oa) => { if (Option.isNone(oa)) { - return Effect.fail(new SchemaIssue.MismatchIssue(ast, oinput)) + return Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } return Effect.succeed(oa.value) }) @@ -185,7 +185,7 @@ const go = SchemaAST.memoize((ast: SchemaAST.AST): Parser => { (ou) => SchemaResult.mapError( parser.run(ou, ast, options), - (e) => new SchemaIssue.TransformationIssue(parser, e) + (e) => new SchemaIssue.Transformation(parser, e) ) ) } else { @@ -194,7 +194,7 @@ const go = SchemaAST.memoize((ast: SchemaAST.AST): Parser => { } srou = SchemaResult.mapError( srou, - (e) => new SchemaIssue.CompositeIssue(ast, ou, [e]) + (e) => new SchemaIssue.Composite(ast, ou, [e]) ) } @@ -215,7 +215,7 @@ const go = SchemaAST.memoize((ast: SchemaAST.AST): Parser => { const iu = check.run(value, ast, options) if (iu) { const [issue, abort] = iu - issues.push(new SchemaIssue.CheckIssue(check, issue, abort)) + issues.push(new SchemaIssue.Check(check, issue, abort)) if (abort || !errorsAllOption) { return } @@ -232,7 +232,7 @@ const go = SchemaAST.memoize((ast: SchemaAST.AST): Parser => { runChecks(checks) if (Arr.isNonEmptyArray(issues)) { - return Effect.fail(new SchemaIssue.CompositeIssue(ast, oa, issues)) + return Effect.fail(new SchemaIssue.Composite(ast, oa, issues)) } } return Effect.succeed(oa) diff --git a/packages/effect/src/unstable/HttpClientResponse.ts b/packages/effect/src/unstable/HttpClientResponse.ts index 1a3a29fd3b..41666023bf 100644 --- a/packages/effect/src/unstable/HttpClientResponse.ts +++ b/packages/effect/src/unstable/HttpClientResponse.ts @@ -85,7 +85,7 @@ export const schemaJson = < const decode = Schema.decodeUnknown(schema) return ( self: HttpClientResponse - ): Effect.Effect => + ): Effect.Effect => Effect.flatMap(self.json, (body) => decode({ status: self.status, @@ -111,7 +111,7 @@ export const schemaNoBody = < options?: ParseOptions | undefined ) => { const decode = Schema.decodeUnknown(schema) - return (self: HttpClientResponse): Effect.Effect => + return (self: HttpClientResponse): Effect.Effect => decode({ status: self.status, headers: self.headers diff --git a/packages/effect/src/unstable/HttpIncomingMessage.ts b/packages/effect/src/unstable/HttpIncomingMessage.ts index 0b31b9ac5b..dfb195e054 100644 --- a/packages/effect/src/unstable/HttpIncomingMessage.ts +++ b/packages/effect/src/unstable/HttpIncomingMessage.ts @@ -48,7 +48,7 @@ export const schemaBodyJson = >(schema: S, options? const decode = Schema.decodeUnknown(schema) return ( self: HttpIncomingMessage - ): Effect.Effect => + ): Effect.Effect => Effect.flatMap(self.json, (_) => decode(_, options)) } @@ -78,7 +78,7 @@ export const schemaHeaders = { const decode = Schema.decodeUnknown(schema) - return (self: HttpIncomingMessage): Effect.Effect => decode(self.headers, options) + return (self: HttpIncomingMessage): Effect.Effect => decode(self.headers, options) } /** diff --git a/packages/effect/test/Schema.test.ts b/packages/effect/test/Schema.test.ts index 2fb3b7fe76..1e69c638e8 100644 --- a/packages/effect/test/Schema.test.ts +++ b/packages/effect/test/Schema.test.ts @@ -70,8 +70,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, "a") await assertions.make.fail(schema, null as any, `Expected "a", actual null`) - assertions.makeUnsafe.succeed(schema, "a") - assertions.makeUnsafe.fail(schema, null as any, `makeUnsafe failure, actual null`) + assertions.makeSync.succeed(schema, "a") + assertions.makeSync.fail(schema, null as any, `makeSync failure, actual null`) await assertions.decoding.succeed(schema, "a") await assertions.decoding.fail(schema, 1, `Expected "a", actual 1`) @@ -131,7 +131,7 @@ describe("Schema", () => { const schema = Schema.Never await assertions.make.fail(schema, null as never, `Expected never, actual null`) - assertions.makeUnsafe.fail(schema, null as never, `makeUnsafe failure, actual null`) + assertions.makeSync.fail(schema, null as never, `makeSync failure, actual null`) strictEqual(SchemaAST.format(schema.ast), `never`) @@ -145,7 +145,7 @@ describe("Schema", () => { strictEqual(SchemaAST.format(schema.ast), `unknown`) await assertions.make.succeed(schema, "a") - assertions.makeUnsafe.succeed(schema, "a") + assertions.makeSync.succeed(schema, "a") await assertions.decoding.succeed(schema, "a") }) @@ -157,8 +157,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, null) await assertions.make.fail(schema, undefined as any, `Expected null, actual undefined`) - assertions.makeUnsafe.succeed(schema, null) - assertions.makeUnsafe.fail(schema, undefined as any, `makeUnsafe failure, actual undefined`) + assertions.makeSync.succeed(schema, null) + assertions.makeSync.fail(schema, undefined as any, `makeSync failure, actual undefined`) }) it("Undefined", async () => { @@ -168,8 +168,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, undefined) await assertions.make.fail(schema, null as any, `Expected undefined, actual null`) - assertions.makeUnsafe.succeed(schema, undefined) - assertions.makeUnsafe.fail(schema, null as any, `makeUnsafe failure, actual null`) + assertions.makeSync.succeed(schema, undefined) + assertions.makeSync.fail(schema, null as any, `makeSync failure, actual null`) }) it("String", async () => { @@ -179,8 +179,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, "a") await assertions.make.fail(schema, null as any, `Expected string, actual null`) - assertions.makeUnsafe.succeed(schema, "a") - assertions.makeUnsafe.fail(schema, null as any, `makeUnsafe failure, actual null`) + assertions.makeSync.succeed(schema, "a") + assertions.makeSync.fail(schema, null as any, `makeSync failure, actual null`) await assertions.decoding.succeed(schema, "a") await assertions.decoding.fail(schema, 1, "Expected string, actual 1") @@ -196,8 +196,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, 1) await assertions.make.fail(schema, null as any, `Expected number, actual null`) - assertions.makeUnsafe.succeed(schema, 1) - assertions.makeUnsafe.fail(schema, null as any, `makeUnsafe failure, actual null`) + assertions.makeSync.succeed(schema, 1) + assertions.makeSync.fail(schema, null as any, `makeSync failure, actual null`) await assertions.decoding.succeed(schema, 1) await assertions.decoding.fail(schema, "a", `Expected number, actual "a"`) @@ -214,8 +214,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, a) await assertions.make.fail(schema, Symbol("b") as any, `Expected Symbol(a), actual Symbol(b)`) - assertions.makeUnsafe.succeed(schema, a) - assertions.makeUnsafe.fail(schema, Symbol("b") as any, `makeUnsafe failure, actual Symbol(b)`) + assertions.makeSync.succeed(schema, a) + assertions.makeSync.fail(schema, Symbol("b") as any, `makeSync failure, actual Symbol(b)`) await assertions.decoding.succeed(schema, a) await assertions.decoding.fail(schema, Symbol("b"), `Expected Symbol(a), actual Symbol(b)`) @@ -228,8 +228,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, 1n) await assertions.make.fail(schema, null as any, `Expected bigint, actual null`) - assertions.makeUnsafe.succeed(schema, 1n) - assertions.makeUnsafe.fail(schema, null as any, `makeUnsafe failure, actual null`) + assertions.makeSync.succeed(schema, 1n) + assertions.makeSync.fail(schema, null as any, `makeSync failure, actual null`) await assertions.decoding.succeed(schema, 1n) await assertions.decoding.fail(schema, "1" as any, `Expected bigint, actual "1"`) @@ -251,8 +251,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, { a: "a" }) await assertions.make.fail(schema, null as any, `Expected { readonly "a": string }, actual null`) - assertions.makeUnsafe.succeed(schema, { a: "a" }) - assertions.makeUnsafe.fail(schema, null as any, `makeUnsafe failure, actual null`) + assertions.makeSync.succeed(schema, { a: "a" }) + assertions.makeSync.fail(schema, null as any, `makeSync failure, actual null`) await assertions.decoding.succeed(schema, { a: "a" }) await assertions.decoding.fail( @@ -260,7 +260,7 @@ describe("Schema", () => { {}, `{ readonly "a": string } └─ ["a"] - └─ Missing value` + └─ Missing key` ) await assertions.decoding.fail( schema, @@ -276,7 +276,7 @@ describe("Schema", () => { {} as any, `{ readonly "a": string } └─ ["a"] - └─ Missing value` + └─ Missing key` ) await assertions.encoding.fail( schema, @@ -299,9 +299,9 @@ describe("Schema", () => { {} as any, `{ readonly "a": string; readonly "b": number } ├─ ["a"] -│ └─ Missing value +│ └─ Missing key └─ ["b"] - └─ Missing value`, + └─ Missing key`, { parseOptions: { errors: "all" } } ) @@ -310,9 +310,9 @@ describe("Schema", () => { {}, `{ readonly "a": string; readonly "b": number } ├─ ["a"] -│ └─ Missing value +│ └─ Missing key └─ ["b"] - └─ Missing value`, + └─ Missing key`, { parseOptions: { errors: "all" } } ) @@ -321,9 +321,9 @@ describe("Schema", () => { {} as any, `{ readonly "a": string; readonly "b": number } ├─ ["a"] -│ └─ Missing value +│ └─ Missing key └─ ["b"] - └─ Missing value`, + └─ Missing key`, { parseOptions: { errors: "all" } } ) }) @@ -344,7 +344,7 @@ describe("Schema", () => { └─ ["a"] └─ number & finite <-> string └─ finite - └─ Invalid value NaN` + └─ Invalid data NaN` ) await assertions.encoding.succeed(schema, { a: 1 }, { expected: { a: "1" } }) @@ -368,8 +368,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, { a: "a" }) await assertions.make.succeed(schema, {}) - assertions.makeUnsafe.succeed(schema, { a: "a" }) - assertions.makeUnsafe.succeed(schema, {}) + assertions.makeSync.succeed(schema, { a: "a" }) + assertions.makeSync.succeed(schema, {}) await assertions.decoding.succeed(schema, { a: "a" }) await assertions.decoding.succeed(schema, {}) @@ -406,14 +406,14 @@ describe("Schema", () => { { b: "b" }, `{ readonly "a": string; readonly "b": string } └─ ["a"] - └─ Missing value` + └─ Missing key` ) await assertions.decoding.fail( schema, { a: "a" }, `{ readonly "a": string; readonly "b": string } └─ ["b"] - └─ Missing value` + └─ Missing key` ) }) @@ -451,7 +451,7 @@ describe("Schema", () => { { a: "", b: "b" }, `{ readonly "a": string; readonly "b": string } & └─ - └─ Invalid value {"a":"","b":"b"}` + └─ Invalid data {"a":"","b":"b"}` ) }) }) @@ -496,10 +496,10 @@ describe("Schema", () => { └─ [0] └─ string & minLength(1) └─ minLength(1) - └─ Invalid value ""` + └─ Invalid data ""` ) - assertions.makeUnsafe.succeed(schema, ["a"]) - assertions.makeUnsafe.fail(schema, [""], `makeUnsafe failure, actual `) + assertions.makeSync.succeed(schema, ["a"]) + assertions.makeSync.fail(schema, [""], `makeSync failure, actual `) await assertions.decoding.succeed(schema, ["a"]) await assertions.decoding.fail( @@ -507,7 +507,7 @@ describe("Schema", () => { [], `readonly [string & minLength(1)] └─ [0] - └─ Missing value` + └─ Missing key` ) await assertions.decoding.fail( schema, @@ -523,14 +523,14 @@ describe("Schema", () => { [] as any, `readonly [string & minLength(1)] └─ [0] - └─ Missing value` + └─ Missing key` ) await assertions.decoding.fail( schema, [], `readonly [string & minLength(1)] └─ [0] - └─ Missing value` + └─ Missing key` ) await assertions.encoding.fail( schema, @@ -546,8 +546,8 @@ describe("Schema", () => { strictEqual(SchemaAST.format(schema.ast), `readonly [string?]`) - assertions.makeUnsafe.succeed(schema, ["a"]) - assertions.makeUnsafe.succeed(schema, []) + assertions.makeSync.succeed(schema, ["a"]) + assertions.makeSync.succeed(schema, []) await assertions.decoding.succeed(schema, ["a"]) await assertions.decoding.succeed(schema, []) @@ -564,7 +564,7 @@ describe("Schema", () => { strictEqual(SchemaAST.format(schema.ast), `ReadonlyArray`) await assertions.make.succeed(schema, ["a", "b"]) - assertions.makeUnsafe.succeed(schema, ["a", "b"]) + assertions.makeSync.succeed(schema, ["a", "b"]) await assertions.decoding.succeed(schema, ["a", "b"]) await assertions.decoding.fail( @@ -599,7 +599,7 @@ describe("Schema", () => { "ab", `string & minLength(3) └─ minLength(3) - └─ Invalid value "ab"` + └─ Invalid data "ab"` ) }) @@ -615,16 +615,16 @@ describe("Schema", () => { "ab", `string & minLength(3) & includes("c") └─ minLength(3) - └─ Invalid value "ab"` + └─ Invalid data "ab"` ) await assertions.decoding.fail( schema, "ab", `string & minLength(3) & includes("c") ├─ minLength(3) -│ └─ Invalid value "ab" +│ └─ Invalid data "ab" └─ includes("c") - └─ Invalid value "ab"`, + └─ Invalid data "ab"`, { parseOptions: { errors: "all" } } ) }) @@ -640,7 +640,7 @@ describe("Schema", () => { "a", `string & minLength(2) & includes("b") └─ minLength(2) - └─ Invalid value "a"` + └─ Invalid data "a"` ) }) }) @@ -659,7 +659,7 @@ describe("Schema", () => { 12, `string & minLength(3) <-> number & finite └─ minLength(3) - └─ Invalid value "12"` + └─ Invalid data "12"` ) }) @@ -676,14 +676,14 @@ describe("Schema", () => { 12, `string & minLength(3) & includes("1") <-> number & finite └─ minLength(3) - └─ Invalid value "12"` + └─ Invalid data "12"` ) await assertions.encoding.fail( schema, 234, `string & minLength(3) & includes("1") <-> number & finite └─ includes("1") - └─ Invalid value "234"` + └─ Invalid data "234"` ) }) }) @@ -702,7 +702,7 @@ describe("Schema", () => { Option.some(""), `Option & Some & length > 0 └─ length > 0 - └─ Invalid value { + └─ Invalid data { "_id": "Option", "_tag": "Some", "value": "" @@ -732,7 +732,7 @@ describe("Schema", () => { "b", `string & regex(^a) └─ regex(^a) - └─ Invalid value "b"` + └─ Invalid data "b"` ) await assertions.encoding.succeed(schema, "a") @@ -741,7 +741,7 @@ describe("Schema", () => { "b", `string & regex(^a) └─ regex(^a) - └─ Invalid value "b"` + └─ Invalid data "b"` ) }) @@ -756,7 +756,7 @@ describe("Schema", () => { "b", `string & startsWith("a") └─ startsWith("a") - └─ Invalid value "b"` + └─ Invalid data "b"` ) await assertions.encoding.succeed(schema, "a") @@ -765,7 +765,7 @@ describe("Schema", () => { "b", `string & startsWith("a") └─ startsWith("a") - └─ Invalid value "b"` + └─ Invalid data "b"` ) }) @@ -780,7 +780,7 @@ describe("Schema", () => { "b", `string & endsWith("a") └─ endsWith("a") - └─ Invalid value "b"` + └─ Invalid data "b"` ) await assertions.encoding.succeed(schema, "a") @@ -789,7 +789,7 @@ describe("Schema", () => { "b", `string & endsWith("a") └─ endsWith("a") - └─ Invalid value "b"` + └─ Invalid data "b"` ) }) @@ -804,7 +804,7 @@ describe("Schema", () => { "A", `string & lowercased └─ lowercased - └─ Invalid value "A"` + └─ Invalid data "A"` ) await assertions.encoding.succeed(schema, "a") @@ -813,7 +813,7 @@ describe("Schema", () => { "A", `string & lowercased └─ lowercased - └─ Invalid value "A"` + └─ Invalid data "A"` ) }) @@ -828,7 +828,7 @@ describe("Schema", () => { "a", `string & uppercased └─ uppercased - └─ Invalid value "a"` + └─ Invalid data "a"` ) await assertions.encoding.succeed(schema, "A") @@ -837,7 +837,7 @@ describe("Schema", () => { "a", `string & uppercased └─ uppercased - └─ Invalid value "a"` + └─ Invalid data "a"` ) }) @@ -852,7 +852,7 @@ describe("Schema", () => { " a ", `string & trimmed └─ trimmed - └─ Invalid value " a "` + └─ Invalid data " a "` ) }) @@ -867,7 +867,7 @@ describe("Schema", () => { "", `string & minLength(1) └─ minLength(1) - └─ Invalid value ""` + └─ Invalid data ""` ) await assertions.encoding.succeed(schema, "a") @@ -876,7 +876,7 @@ describe("Schema", () => { "", `string & minLength(1) └─ minLength(1) - └─ Invalid value ""` + └─ Invalid data ""` ) }) }) @@ -893,7 +893,7 @@ describe("Schema", () => { 1, `number & greaterThan(1) └─ greaterThan(1) - └─ Invalid value 1` + └─ Invalid data 1` ) await assertions.encoding.succeed(schema, 2) @@ -902,7 +902,7 @@ describe("Schema", () => { 1, `number & greaterThan(1) └─ greaterThan(1) - └─ Invalid value 1` + └─ Invalid data 1` ) }) @@ -917,7 +917,7 @@ describe("Schema", () => { 0, `number & between(1, 3) └─ between(1, 3) - └─ Invalid value 0` + └─ Invalid data 0` ) await assertions.encoding.succeed(schema, 2) @@ -926,7 +926,7 @@ describe("Schema", () => { 0, `number & between(1, 3) └─ between(1, 3) - └─ Invalid value 0` + └─ Invalid data 0` ) }) }) @@ -942,7 +942,7 @@ describe("Schema", () => { 1.1, `number & int └─ int - └─ Invalid value 1.1` + └─ Invalid data 1.1` ) await assertions.encoding.succeed(schema, 1) @@ -951,7 +951,7 @@ describe("Schema", () => { 1.1, `number & int └─ int - └─ Invalid value 1.1` + └─ Invalid data 1.1` ) }) @@ -966,23 +966,23 @@ describe("Schema", () => { 1.1, `number & int32 └─ int - └─ Invalid value 1.1` + └─ Invalid data 1.1` ) await assertions.decoding.fail( schema, Number.MAX_SAFE_INTEGER + 1, `number & int32 └─ int - └─ Invalid value 9007199254740992` + └─ Invalid data 9007199254740992` ) await assertions.decoding.fail( schema, Number.MAX_SAFE_INTEGER + 1, `number & int32 ├─ int -│ └─ Invalid value 9007199254740992 +│ └─ Invalid data 9007199254740992 └─ between(-2147483648, 2147483647) - └─ Invalid value 9007199254740992`, + └─ Invalid data 9007199254740992`, { parseOptions: { errors: "all" } } ) @@ -992,14 +992,14 @@ describe("Schema", () => { 1.1, `number & int32 └─ int - └─ Invalid value 1.1` + └─ Invalid data 1.1` ) await assertions.encoding.fail( schema, Number.MAX_SAFE_INTEGER + 1, `number & int32 └─ int - └─ Invalid value 9007199254740992` + └─ Invalid data 9007199254740992` ) }) }) @@ -1010,8 +1010,8 @@ describe("Schema", () => { Schema.decodeTo( Schema.String, new SchemaTransformation.Transformation( - SchemaParser.fail((o) => new SchemaIssue.InvalidIssue(o, "err decoding")), - SchemaParser.fail((o) => new SchemaIssue.InvalidIssue(o, "err encoding")) + SchemaParser.fail((o) => new SchemaIssue.InvalidData(o, "err decoding")), + SchemaParser.fail((o) => new SchemaIssue.InvalidData(o, "err encoding")) ) ) ) @@ -1062,7 +1062,7 @@ describe("Schema", () => { "a", `number & finite <-> string └─ finite - └─ Invalid value NaN` + └─ Invalid data NaN` ) await assertions.encoding.succeed(schema, 1, { expected: "1" }) @@ -1085,7 +1085,7 @@ describe("Schema", () => { "1", `number & finite & greaterThan(2) <-> string └─ greaterThan(2) - └─ Invalid value 1` + └─ Invalid data 1` ) await assertions.encoding.succeed(schema, 3, { expected: "3" }) @@ -1095,7 +1095,7 @@ describe("Schema", () => { `string <-> number & finite & greaterThan(2) └─ number & finite & greaterThan(2) └─ greaterThan(2) - └─ Invalid value 1` + └─ Invalid data 1` ) }) }) @@ -1137,7 +1137,7 @@ describe("Schema", () => { {}, `{ readonly "a": string <-> string } └─ ["a"] - └─ Missing value` + └─ Missing key` ) await assertions.encoding.succeed(schema, { a: "a" }) @@ -1146,7 +1146,7 @@ describe("Schema", () => { {} as any, `{ readonly "a": string <-> string } └─ ["a"] - └─ Missing value` + └─ Missing key` ) }) @@ -1170,7 +1170,7 @@ describe("Schema", () => { └─ ["a"] └─ string <-> string └─ required - └─ Missing value` + └─ Missing key` ) await assertions.encoding.succeed(schema, { a: "a" }) @@ -1200,7 +1200,7 @@ describe("Schema", () => { └─ ["a"] └─ string <-> string └─ required - └─ Missing value` + └─ Missing key` ) }) @@ -1215,7 +1215,7 @@ describe("Schema", () => { " a2 ", `number & finite <-> string └─ finite - └─ Invalid value NaN` + └─ Invalid data NaN` ) await assertions.encoding.succeed(schema, 2, { expected: "2" }) @@ -1244,7 +1244,7 @@ describe("Schema", () => { └─ string <-> string & minLength(2) └─ string & minLength(3) <-> string & minLength(2) └─ minLength(3) - └─ Invalid value "aa"` + └─ Invalid data "aa"` ) await assertions.encoding.succeed(schema, { a: "aaa" }) @@ -1256,7 +1256,7 @@ describe("Schema", () => { └─ string & minLength(2) <-> string └─ string & minLength(3) └─ minLength(3) - └─ Invalid value "aa"` + └─ Invalid data "aa"` ) }) @@ -1297,7 +1297,7 @@ describe("Schema", () => { {}, `{ readonly "a": string <-> string } └─ ["a"] - └─ Missing value` + └─ Missing key` ) await assertions.encoding.succeed(schema, { a: "a" }) @@ -1306,7 +1306,7 @@ describe("Schema", () => { {} as any, `{ readonly "a": string <-> string } └─ ["a"] - └─ Missing value` + └─ Missing key` ) }) @@ -1333,7 +1333,7 @@ describe("Schema", () => { └─ ["a"] └─ string <-> string └─ required - └─ Missing value` + └─ Missing key` ) }) @@ -1355,7 +1355,7 @@ describe("Schema", () => { └─ ["a"] └─ string <-> string └─ required - └─ Missing value` + └─ Missing key` ) await assertions.encoding.succeed(schema, { a: "a" }) @@ -1373,7 +1373,7 @@ describe("Schema", () => { " a2 ", `number & finite <-> string └─ finite - └─ Invalid value NaN` + └─ Invalid data NaN` ) await assertions.encoding.succeed(schema, 2, { expected: "2" }) @@ -1401,7 +1401,7 @@ describe("Schema", () => { └─ string <-> string & minLength(2) └─ string & minLength(3) └─ minLength(3) - └─ Invalid value "aa"` + └─ Invalid data "aa"` ) await assertions.encoding.succeed(schema, { a: "aaa" }) @@ -1413,7 +1413,7 @@ describe("Schema", () => { └─ string & minLength(2) <-> string └─ string & minLength(3) └─ minLength(3) - └─ Invalid value "aa"` + └─ Invalid data "aa"` ) }) }) @@ -1434,14 +1434,14 @@ describe("Schema", () => { `string & minLength(3) <-> number & finite & greaterThan(2) └─ number & finite & greaterThan(2) └─ greaterThan(2) - └─ Invalid value 2` + └─ Invalid data 2` ) await assertions.decoding.fail( schema, 3, `string & minLength(3) <-> number & finite & greaterThan(2) └─ minLength(3) - └─ Invalid value "3"` + └─ Invalid data "3"` ) }) @@ -1450,17 +1450,17 @@ describe("Schema", () => { a: FiniteFromString.pipe(Schema.setConstructorDefault(() => Result.succeedSome(-1))) }) - assertions.makeUnsafe.succeed(schema, { a: 1 }) - assertions.makeUnsafe.succeed(schema, {}, { a: -1 }) + assertions.makeSync.succeed(schema, { a: 1 }) + assertions.makeSync.succeed(schema, {}, { a: -1 }) const flipped = schema.pipe(Schema.flip) - throws(() => flipped.makeUnsafe({} as any)) - assertions.makeUnsafe.succeed(flipped, { a: "1" }) + throws(() => flipped.makeSync({} as any)) + assertions.makeSync.succeed(flipped, { a: "1" }) const flipped2 = flipped.pipe(Schema.flip) deepStrictEqual(flipped2.fields, schema.fields) - assertions.makeUnsafe.succeed(flipped2, { a: 1 }) - assertions.makeUnsafe.succeed(flipped2, {}, { a: -1 }) + assertions.makeSync.succeed(flipped2, { a: 1 }) + assertions.makeSync.succeed(flipped2, {}, { a: -1 }) }) }) @@ -1536,7 +1536,7 @@ describe("Schema", () => { └─ ["a"] └─ number & finite & greaterThan(0) <-> string └─ finite - └─ Invalid value NaN` + └─ Invalid data NaN` ) await assertions.encoding.succeed(schema, { a: 1, categories: [] }, { expected: { a: "1", categories: [] } }) @@ -1555,7 +1555,7 @@ describe("Schema", () => { └─ string <-> number & finite & greaterThan(0) └─ number & finite & greaterThan(0) └─ greaterThan(0) - └─ Invalid value -1` + └─ Invalid data -1` ) }) }) @@ -1575,8 +1575,8 @@ describe("Schema", () => { a: FiniteFromString.pipe(Schema.setConstructorDefault(() => Result.succeedSome(-1))) }) - assertions.makeUnsafe.succeed(schema, { a: 1 }) - assertions.makeUnsafe.succeed(schema, {}, { a: -1 }) + assertions.makeSync.succeed(schema, { a: 1 }) + assertions.makeSync.succeed(schema, {}, { a: -1 }) }) it("nested defaults", () => { @@ -1586,8 +1586,8 @@ describe("Schema", () => { }).pipe(Schema.setConstructorDefault(() => Result.succeedSome({}))) }) - assertions.makeUnsafe.succeed(schema, { a: { b: 1 } }) - assertions.makeUnsafe.succeed(schema, {}, { a: { b: -1 } }) + assertions.makeSync.succeed(schema, { a: { b: 1 } }) + assertions.makeSync.succeed(schema, {}, { a: { b: -1 } }) }) it("Struct & Effect sync", () => { @@ -1595,8 +1595,8 @@ describe("Schema", () => { a: FiniteFromString.pipe(Schema.setConstructorDefault(() => Effect.succeed(Option.some(-1)))) }) - assertions.makeUnsafe.succeed(schema, { a: 1 }) - assertions.makeUnsafe.succeed(schema, {}, { a: -1 }) + assertions.makeSync.succeed(schema, { a: 1 }) + assertions.makeSync.succeed(schema, {}, { a: -1 }) }) it("Struct & Effect async", async () => { @@ -1649,8 +1649,8 @@ describe("Schema", () => { await assertions.make.succeed(schema, { a: 1 }) await assertions.make.fail(schema, null as any, `Expected { readonly [x: string]: number }, actual null`) - assertions.makeUnsafe.succeed(schema, { a: 1 }) - assertions.makeUnsafe.fail(schema, null as any, `makeUnsafe failure, actual null`) + assertions.makeSync.succeed(schema, { a: 1 }) + assertions.makeSync.fail(schema, null as any, `makeSync failure, actual null`) await assertions.decoding.succeed(schema, { a: 1 }) await assertions.decoding.fail(schema, null, "Expected { readonly [x: string]: number }, actual null") @@ -1760,14 +1760,31 @@ describe("Schema", () => { "", `string & minLength(1) └─ minLength(1) - └─ Invalid value ""` + └─ Invalid data ""` ) await assertions.decoding.fail( schema, -1, `number & greaterThan(0) └─ greaterThan(0) - └─ Invalid value -1` + └─ Invalid data -1` + ) + }) + + it(`mode: "oneOf"`, async () => { + const schema = Schema.Union([ + Schema.Struct({ a: Schema.String }), + Schema.Struct({ b: Schema.Number }) + ], { mode: "oneOf" }) + + strictEqual(SchemaAST.format(schema.ast), `{ readonly "a": string } ⊻ { readonly "b": number }`) + + await assertions.decoding.succeed(schema, { a: "a" }) + await assertions.decoding.succeed(schema, { b: 1 }) + await assertions.decoding.fail( + schema, + { a: "a", b: 1 }, + `Expected exactly one successful result for { readonly "a": string } ⊻ { readonly "b": number }, actual {"a":"a","b":1}` ) }) }) @@ -1807,7 +1824,7 @@ describe("Schema", () => { "", `string & minLength(1) └─ minLength(1) - └─ Invalid value ""` + └─ Invalid data ""` ) }) }) @@ -1826,7 +1843,7 @@ describe("Schema", () => { "", `string & minLength(1) └─ minLength(1) - └─ Invalid value ""` + └─ Invalid data ""` ) }) }) @@ -1892,7 +1909,7 @@ describe("Schema", () => { strictEqual(SchemaAST.format(schema.ast), `{ readonly "a": string }`) - const instance = schema.makeUnsafe({ a: "a" }) + const instance = schema.makeSync({ a: "a" }) strictEqual(instance.a, "a") deepStrictEqual(A.fields, { a: Schema.String }) }) @@ -1945,7 +1962,7 @@ describe("Schema", () => { await assertions.decoding.succeed(schema, { _tag: "a", a: "1" }, { expected: { _tag: "a", a: 1 } }) await assertions.encoding.succeed(schema, { _tag: "a", a: 1 }, { expected: { _tag: "a", a: "1" } }) - assertions.makeUnsafe.succeed(schema, { _tag: "a", a: 1 }) + assertions.makeSync.succeed(schema, { _tag: "a", a: 1 }) }) it("decoding: required & encoding: required & constructor: optional", async () => { @@ -1956,8 +1973,8 @@ describe("Schema", () => { await assertions.decoding.succeed(schema, { _tag: "a", a: "1" }, { expected: { _tag: "a", a: 1 } }) await assertions.encoding.succeed(schema, { _tag: "a", a: 1 }, { expected: { _tag: "a", a: "1" } }) - assertions.makeUnsafe.succeed(schema, { _tag: "a", a: 1 }) - assertions.makeUnsafe.succeed(schema, { a: 1 }, { _tag: "a", a: 1 }) + assertions.makeSync.succeed(schema, { _tag: "a", a: 1 }) + assertions.makeSync.succeed(schema, { a: 1 }, { _tag: "a", a: 1 }) }) it("decoding: default & encoding: never & constructor: optional", async () => { @@ -1977,8 +1994,8 @@ describe("Schema", () => { await assertions.decoding.succeed(schema, { _tag: "a", a: "1" }, { expected: { _tag: "a", a: 1 } }) await assertions.decoding.succeed(schema, { a: "1" }, { expected: { _tag: "a", a: 1 } }) await assertions.encoding.succeed(schema, { _tag: "a", a: 1 }, { expected: { a: "1" } }) - assertions.makeUnsafe.succeed(schema, { _tag: "a", a: 1 }) - assertions.makeUnsafe.succeed(schema, { a: 1 }, { _tag: "a", a: 1 }) + assertions.makeSync.succeed(schema, { _tag: "a", a: 1 }) + assertions.makeSync.succeed(schema, { a: 1 }, { _tag: "a", a: 1 }) }) }) @@ -2014,7 +2031,7 @@ describe("Schema", () => { `{"a":null}`, `{ readonly "b": number } <-> string └─ ["b"] - └─ Missing value` + └─ Missing key` ) }) @@ -2036,7 +2053,7 @@ describe("Schema", () => { └─ ["a"] └─ { readonly "b": number } <-> string └─ ["b"] - └─ Missing value` + └─ Missing key` ) }) }) @@ -2048,11 +2065,11 @@ describe("Schema", () => { SchemaTransformation.transformOrFail( (s) => s === "a" - ? SchemaResult.fail(new SchemaIssue.ForbiddenIssue(Option.some(s), "not a")) + ? SchemaResult.fail(new SchemaIssue.Forbidden(Option.some(s), "not a")) : SchemaResult.succeedSome(s), (s) => s === "b" - ? SchemaResult.fail(new SchemaIssue.ForbiddenIssue(Option.some(s), "not b")) + ? SchemaResult.fail(new SchemaIssue.Forbidden(Option.some(s), "not b")) : SchemaResult.succeedSome(s) ) ) @@ -2355,11 +2372,11 @@ describe("Schema", () => { strictEqual(SchemaAST.format(A.ast), `A <-> { readonly "a": string }`) assertTrue(new A({ a: "a" }) instanceof A) - assertTrue(A.makeUnsafe({ a: "a" }) instanceof A) + assertTrue(A.makeSync({ a: "a" }) instanceof A) // test additional fields strictEqual(new A({ a: "a" })._a, 1) - strictEqual(A.makeUnsafe({ a: "a" })._a, 1) + strictEqual(A.makeSync({ a: "a" })._a, 1) // test Equal.equals assertTrue(Equal.equals(new A({ a: "a" }), new A({ a: "a" }))) @@ -2408,11 +2425,11 @@ describe("Schema", () => { strictEqual(SchemaAST.format(A.ast), `A <-> { readonly "a": string }`) assertTrue(new A({ a: "a" }) instanceof A) - assertTrue(A.makeUnsafe({ a: "a" }) instanceof A) + assertTrue(A.makeSync({ a: "a" }) instanceof A) // test additional fields strictEqual(new A({ a: "a" })._a, 1) - strictEqual(A.makeUnsafe({ a: "a" })._a, 1) + strictEqual(A.makeSync({ a: "a" })._a, 1) // test Equal.equals assertTrue(Equal.equals(new A({ a: "a" }), new A({ a: "a" }))) @@ -2460,11 +2477,11 @@ describe("Schema", () => { strictEqual(SchemaAST.format(A.ast), `B <-> { readonly "a": string }`) assertTrue(new A({ a: "a" }) instanceof A) - assertTrue(A.makeUnsafe({ a: "a" }) instanceof A) + assertTrue(A.makeSync({ a: "a" }) instanceof A) // test additional fields strictEqual(new A({ a: "a" })._a, 1) - strictEqual(A.makeUnsafe({ a: "a" })._a, 1) + strictEqual(A.makeSync({ a: "a" })._a, 1) // test Equal.equals assertTrue(Equal.equals(new A({ a: "a" }), new A({ a: "a" }))) @@ -2513,11 +2530,11 @@ describe("Schema", () => { strictEqual(SchemaAST.format(A.ast), `A & <-> { readonly "a": string }`) assertTrue(new A({ a: "a" }) instanceof A) - assertTrue(A.makeUnsafe({ a: "a" }) instanceof A) + assertTrue(A.makeSync({ a: "a" }) instanceof A) // test additional fields strictEqual(new A({ a: "a" })._a, 1) - strictEqual(A.makeUnsafe({ a: "a" })._a, 1) + strictEqual(A.makeSync({ a: "a" })._a, 1) // test Equal.equals assertTrue(Equal.equals(new A({ a: "a" }), new A({ a: "a" }))) @@ -2566,9 +2583,9 @@ describe("Schema", () => { const instance = new B({ a: "a", b: 2 }) assertTrue(instance instanceof A) - assertTrue(B.makeUnsafe({ a: "a", b: 2 }) instanceof A) + assertTrue(B.makeSync({ a: "a", b: 2 }) instanceof A) assertTrue(instance instanceof B) - assertTrue(B.makeUnsafe({ a: "a", b: 2 }) instanceof B) + assertTrue(B.makeSync({ a: "a", b: 2 }) instanceof B) strictEqual(instance.a, "a") strictEqual(instance._a, 1) @@ -2625,9 +2642,9 @@ describe("Schema", () => { strictEqual(SchemaAST.format(B.ast), `B <-> { readonly "a": string; readonly "b": number }`) assertTrue(instance instanceof A) - assertTrue(B.makeUnsafe({ a: "a", b: 2 }) instanceof A) + assertTrue(B.makeSync({ a: "a", b: 2 }) instanceof A) assertTrue(instance instanceof B) - assertTrue(B.makeUnsafe({ a: "a", b: 2 }) instanceof B) + assertTrue(B.makeSync({ a: "a", b: 2 }) instanceof B) strictEqual(instance.a, "a") strictEqual(instance._a, 1) @@ -2746,7 +2763,7 @@ describe("Schema", () => { "", `string & minLength(1) <-> string └─ minLength(1) - └─ Invalid value ""` + └─ Invalid data ""` ) await assertions.encoding.succeed(schema, "a") @@ -2814,7 +2831,7 @@ describe("Schema", () => { it("forced failure", async () => { const schema = Schema.String.pipe( - Schema.decodingMiddleware(() => SchemaResult.fail(new SchemaIssue.ForbiddenIssue(Option.none(), "my message"))) + Schema.decodingMiddleware(() => SchemaResult.fail(new SchemaIssue.Forbidden(Option.none(), "my message"))) ) await assertions.decoding.fail( @@ -2852,7 +2869,7 @@ describe("Schema", () => { it("forced failure", async () => { const schema = Schema.String.pipe( - Schema.encodingMiddleware(() => SchemaResult.fail(new SchemaIssue.ForbiddenIssue(Option.none(), "my message"))) + Schema.encodingMiddleware(() => SchemaResult.fail(new SchemaIssue.Forbidden(Option.none(), "my message"))) ) await assertions.encoding.fail( @@ -2869,7 +2886,7 @@ describe("Schema", () => { Schema.checkEffect((s) => Effect.gen(function*() { if (s.length === 0) { - return new SchemaIssue.InvalidIssue(Option.some(s), "length > 0") + return new SchemaIssue.InvalidData(Option.some(s), "length > 0") } }).pipe(Effect.delay(100)) ) @@ -2892,7 +2909,7 @@ describe("Schema", () => { Effect.gen(function*() { yield* Service if (s.length === 0) { - return new SchemaIssue.InvalidIssue(Option.some(s), "length > 0") + return new SchemaIssue.InvalidData(Option.some(s), "length > 0") } }) ) diff --git a/packages/effect/test/SchemaFormatter.test.ts b/packages/effect/test/SchemaFormatter.test.ts index eb92e4b448..d73c6122ac 100644 --- a/packages/effect/test/SchemaFormatter.test.ts +++ b/packages/effect/test/SchemaFormatter.test.ts @@ -25,14 +25,14 @@ const assertStructuredIssue = async ( } describe("StructuredFormatter", () => { - it("MismatchIssue", async () => { + it("single InvalidType", async () => { const schema = Schema.Struct({ a: Schema.String }) assertStructuredIssue(schema, { a: null }, [ { - _tag: "MismatchIssue", + _tag: "InvalidType", expected: `{ readonly "a": string }`, path: ["a"], actual: Option.some(null), @@ -41,7 +41,7 @@ describe("StructuredFormatter", () => { ]) }) - it("MismatchIssues", async () => { + it("multiple InvalidTypes", async () => { const schema = Schema.Struct({ a: Schema.String, b: Schema.Number @@ -49,14 +49,14 @@ describe("StructuredFormatter", () => { assertStructuredIssue(schema, { a: null, b: null }, [ { - _tag: "MismatchIssue", + _tag: "InvalidType", expected: `{ readonly "a": string; readonly "b": number }`, path: ["a"], actual: Option.some(null), message: "Expected string, actual null" }, { - _tag: "MismatchIssue", + _tag: "InvalidType", expected: `{ readonly "a": string; readonly "b": number }`, path: ["b"], actual: Option.some(null), @@ -65,18 +65,18 @@ describe("StructuredFormatter", () => { ]) }) - it("InvalidIssue", async () => { + it("InvalidData", async () => { const schema = Schema.Struct({ a: Schema.String.pipe(Schema.check(SchemaCheck.nonEmpty)) }) assertStructuredIssue(schema, { a: "" }, [ { - _tag: "InvalidIssue", + _tag: "InvalidData", expected: `{ readonly "a": string & minLength(1) }`, path: ["a"], actual: Option.some(""), - message: `Invalid value ""`, + message: `Invalid data ""`, abort: false, meta: { id: "minLength", @@ -86,14 +86,14 @@ describe("StructuredFormatter", () => { ]) }) - it("MissingIssue", async () => { + it("single MissingKey", async () => { const schema = Schema.Struct({ a: Schema.String }) assertStructuredIssue(schema, {}, [ { - _tag: "MissingIssue", + _tag: "MissingKey", expected: `{ readonly "a": string }`, path: ["a"], message: "Missing value", @@ -102,7 +102,7 @@ describe("StructuredFormatter", () => { ]) }) - it("MissingIssues", async () => { + it("multiple MissingKeys", async () => { const schema = Schema.Struct({ a: Schema.String, b: Schema.Number @@ -110,14 +110,14 @@ describe("StructuredFormatter", () => { assertStructuredIssue(schema, {}, [ { - _tag: "MissingIssue", + _tag: "MissingKey", expected: `{ readonly "a": string; readonly "b": number }`, path: ["a"], message: "Missing value", actual: Option.none() }, { - _tag: "MissingIssue", + _tag: "MissingKey", expected: `{ readonly "a": string; readonly "b": number }`, path: ["b"], message: "Missing value", @@ -126,14 +126,14 @@ describe("StructuredFormatter", () => { ]) }) - it("ForbiddenIssue", async () => { + it("Forbidden", async () => { const schema = Schema.Struct({ a: Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.fail("my message"))) }) assertStructuredIssue(schema, { a: "a" }, [ { - _tag: "ForbiddenIssue", + _tag: "Forbidden", expected: `{ readonly "a": string <-> string }`, path: ["a"], message: "my message", @@ -141,4 +141,26 @@ describe("StructuredFormatter", () => { } ]) }) + + it("Union", async () => { + const schema = Schema.Union([ + Schema.Struct({ + a: Schema.String + }), + Schema.Struct({ + b: Schema.Number + }) + ], { mode: "oneOf" }) + + assertStructuredIssue(schema, { a: "a", b: 1 }, [ + { + _tag: "OneOf", + expected: `{ readonly "a": string } ⊻ { readonly "b": number }`, + path: [], + message: + `Expected exactly one successful result for { readonly "a": string } ⊻ { readonly "b": number }, actual {"a":"a","b":1}`, + actual: Option.some({ a: "a", b: 1 }) + } + ]) + }) }) diff --git a/packages/effect/test/SchemaIssue.test.ts b/packages/effect/test/SchemaIssue.test.ts index bd106299a6..2f404caefc 100644 --- a/packages/effect/test/SchemaIssue.test.ts +++ b/packages/effect/test/SchemaIssue.test.ts @@ -4,6 +4,6 @@ import { assertTrue } from "./utils/assert.js" describe("SchemaIssue", () => { it("isIssue", () => { - assertTrue(SchemaIssue.isIssue(SchemaIssue.MissingIssue.instance)) + assertTrue(SchemaIssue.isIssue(new SchemaIssue.MissingKey())) }) }) diff --git a/packages/effect/test/SchemaTest.ts b/packages/effect/test/SchemaTest.ts index 3fc2a3cf8d..7c1b15e262 100644 --- a/packages/effect/test/SchemaTest.ts +++ b/packages/effect/test/SchemaTest.ts @@ -50,17 +50,17 @@ export const assertions = (asserts: { } }, - makeUnsafe: { + makeSync: { /** * Ensures that the given constructor produces the expected value. */ succeed( // Destructure to verify that "this" type is bound - { makeUnsafe }: { readonly makeUnsafe: (a: A) => A }, + { makeSync }: { readonly makeSync: (a: A) => A }, input: A, expected?: A ) { - deepStrictEqual(makeUnsafe(input), expected === undefined ? input : expected) + deepStrictEqual(makeSync(input), expected === undefined ? input : expected) }, /** @@ -68,11 +68,11 @@ export const assertions = (asserts: { */ fail( // Destructure to verify that "this" type is bound - { makeUnsafe }: { readonly makeUnsafe: (a: A, options?: Schema.MakeOptions) => A }, + { makeSync }: { readonly makeSync: (a: A, options?: Schema.MakeOptions) => A }, input: A, message: string ) { - throws(() => makeUnsafe(input), (err) => { + throws(() => makeSync(input), (err) => { assertInstanceOf(err, Error) strictEqual(err.message, message) })