Files
effect/packages/schema/CHANGELOG.md
T
github-actions[bot]andgithub-actions[bot] c3fddb3c78 Version Packages (#2806)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-22 14:04:01 +12:00

204 KiB

@effect/schema

0.67.11

Patch Changes

  • #2803 5af633e Thanks @tim-smart! - update dependencies

  • Updated dependencies [45578e8]:

    • effect@3.2.3

0.67.10

Patch Changes

0.67.9

Patch Changes

0.67.8

Patch Changes

  • Updated dependencies [c1e991d]:
    • effect@3.2.1

0.67.7

Patch Changes

0.67.6

Patch Changes

0.67.5

Patch Changes

0.67.4

Patch Changes

  • #2756 ee08593 Thanks @gcanti! - Improving Predicate Usability of Schema.is

    Before this update, the Schema.is(mySchema) function couldn't be easily used as a predicate or refinement in common array methods like filter or find. This was because the function's signature was:

    (value: unknown, overrideOptions?: AST.ParseOptions) => value is A
    

    Meanwhile, the function expected by methods like filter has the following signature:

    (value: unknown, index: number) => value is A
    

    To make Schema.is compatible with these array methods, we've adjusted the function's signature to accept number as a possible value for the second parameter, in which case it is ignored:

    -(value: unknown, overrideOptions?: AST.ParseOptions) => value is A
    +(value: unknown, overrideOptions?: AST.ParseOptions | number) => value is A
    

    Here's a practical example comparing the behavior before and after the change:

    Before:

    import { Schema } from "@effect/schema";
    
    declare const array: Array<string | number>;
    
    /*
    Throws an error:
    No overload matches this call.
    ...
    Types of parameters 'overrideOptions' and 'index' are incompatible.
    */
    const strings = array.filter(Schema.is(Schema.String));
    

    Now:

    import { Schema } from "@effect/schema";
    
    declare const array: Array<string | number>;
    
    // const strings: string[]
    const strings = array.filter(Schema.is(Schema.String));
    

    Note that the result has been correctly narrowed to string[].

  • #2746 da6d7d8 Thanks @gcanti! - pick: do not return a ComposeTransformation if none of the picked keys are related to a property signature transformation, closes #2743

0.67.3

Patch Changes

  • Updated dependencies [6ac4847]:
    • effect@3.1.5

0.67.2

Patch Changes

  • #2738 89a3afb Thanks @gcanti! - add cause in errors thrown by asserts, closes #2729

  • #2741 992c8e2 Thanks @gcanti! - Schema.optional: the default option now allows setting a default value for both the decoding phase and the default constructor. Previously, it only set the decoding default. Closes #2740.

    Example

    import { Schema } from "@effect/schema";
    
    const Product = Schema.Struct({
      name: Schema.String,
      price: Schema.NumberFromString,
      quantity: Schema.optional(Schema.NumberFromString, { default: () => 1 }),
    });
    
    // Applying defaults in the decoding phase
    console.log(
      Schema.decodeUnknownSync(Product)({ name: "Laptop", price: "999" }),
    ); // { name: 'Laptop', price: 999, quantity: 1 }
    console.log(
      Schema.decodeUnknownSync(Product)({
        name: "Laptop",
        price: "999",
        quantity: "2",
      }),
    ); // { name: 'Laptop', price: 999, quantity: 2 }
    
    // Applying defaults in the constructor
    console.log(Product.make({ name: "Laptop", price: 999 })); // { name: 'Laptop', price: 999, quantity: 1 }
    console.log(Product.make({ name: "Laptop", price: 999, quantity: 2 })); // { name: 'Laptop', price: 999, quantity: 2 }
    

0.67.1

Patch Changes

  • Updated dependencies [e41e911]:
    • effect@3.1.4

0.67.0

Minor Changes

  • #2634 d7e4997 Thanks @gcanti! - ## Simplifying Type Extraction

    When we work with schemas, it's common to need to extract their types automatically. To make this easier, we've made some changes to the Schema interface. Now, you can easily access Type and Encoded directly from a schema without the need for Schema.Schema.Type and Schema.Schema.Encoded.

    import { Schema } from "@effect/schema";
    
    const PersonSchema = Schema.Struct({
      name: Schema.String,
      age: Schema.NumberFromString,
    });
    
    // same as type PersonType = Schema.Schema.Type<typeof PersonSchema>
    type PersonType = typeof PersonSchema.Type;
    
    // same as Schema.Schema.Encoded<typeof PersonSchema>
    type PersonEncoded = typeof PersonSchema.Encoded;
    

    Default Constructors

    When dealing with data, creating values that match a specific schema is crucial. To simplify this process, we've introduced default constructors for various types of schemas: Structs, filters, and brands.

    Note

    Default constructors associated with a schema Schema<A, I, R> are specifically related to the A type, not the I type.

    Let's dive into each of them with some examples to understand better how they work.

    Example (Struct)

    import { Schema } from "@effect/schema";
    
    const MyStruct = Schema.Struct({
      name: Schema.NonEmpty,
    });
    
    MyStruct.make({ name: "a" }); // ok
    MyStruct.make({ name: "" });
    /*
    throws
    Error: { name: NonEmpty }
    └─ ["name"]
       └─ NonEmpty
          └─ Predicate refinement failure
             └─ Expected NonEmpty (a non empty string), actual ""
    */
    

    Example (filter)

    import { Schema } from "@effect/schema";
    
    const MyNumber = Schema.Number.pipe(Schema.between(1, 10));
    
    // const n: number
    const n = MyNumber.make(5); // ok
    MyNumber.make(20);
    /*
    throws
    Error: a number between 1 and 10
    └─ Predicate refinement failure
      └─ Expected a number between 1 and 10, actual 20
    */
    

    Example (brand)

    import { Schema } from "@effect/schema";
    
    const MyBrand = Schema.Number.pipe(
      Schema.between(1, 10),
      Schema.brand("MyNumber"),
    );
    
    // const n: number & Brand<"MyNumber">
    const n = MyBrand.make(5); // ok
    MyBrand.make(20);
    /*
    throws
    Error: a number between 1 and 10
    └─ Predicate refinement failure
      └─ Expected a number between 1 and 10, actual 20
    */
    

    When utilizing our default constructors, it's important to grasp the type of value they generate. In the MyBrand example, the return type of the constructor is number & Brand<"MyNumber">, indicating that the resulting value is a number with the added branding "MyNumber".

    This differs from the filter example where the return type is simply number. The branding offers additional insights about the type, facilitating the identification and manipulation of your data.

    Note that default constructors are "unsafe" in the sense that if the input does not conform to the schema, the constructor throws an error containing a description of what is wrong. This is because the goal of default constructors is to provide a quick way to create compliant values (for example, for writing tests or configurations, or in any situation where it is assumed that the input passed to the constructors is valid and the opposite situation is exceptional).

    To have a "safe" constructor, you can use Schema.validateEither:

    import { Schema } from "@effect/schema";
    
    const MyNumber = Schema.Number.pipe(Schema.between(1, 10));
    
    const ctor = Schema.validateEither(MyNumber);
    
    console.log(ctor(5));
    /*
    { _id: 'Either', _tag: 'Right', right: 5 }
    */
    
    console.log(ctor(20));
    /*
    {
      _id: 'Either',
      _tag: 'Left',
      left: {
        _id: 'ParseError',
        message: 'a number between 1 and 10\n' +
          '└─ Predicate refinement failure\n' +
          '   └─ Expected a number between 1 and 10, actual 20'
      }
    }
    */
    

    Default Constructor Values

    When constructing objects, it's common to want to assign default values to certain fields to simplify the creation of new instances. Our new Schema.withConstructorDefault combinator allows you to effortlessly manage the optionality of a field in your default constructor.

    Example

    import { Schema } from "@effect/schema";
    
    const PersonSchema = Schema.Struct({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0),
      ),
    });
    
    // The age field is optional and defaults to 0
    console.log(PersonSchema.make({ name: "John" }));
    // => { age: 0, name: 'John' }
    

    Defaults are lazily evaluated, meaning that a new instance of the default is generated every time the constructor is called:

    import { Schema } from "@effect/schema";
    
    const PersonSchema = Schema.Struct({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0),
      ),
      timestamp: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => new Date().getTime()),
      ),
    });
    
    console.log(PersonSchema.make({ name: "name1" }));
    // => { age: 0, timestamp: 1714232909221, name: 'name1' }
    console.log(PersonSchema.make({ name: "name2" }));
    // => { age: 0, timestamp: 1714232909227, name: 'name2' }
    

    Note how the timestamp field varies.

    Defaults can also be applied using the Class API:

    import { Schema } from "@effect/schema";
    
    class Person extends Schema.Class<Person>("Person")({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0),
      ),
      timestamp: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => new Date().getTime()),
      ),
    }) {}
    
    console.log(new Person({ name: "name1" }));
    // => Person { age: 0, timestamp: 1714400867208, name: 'name1' }
    console.log(new Person({ name: "name2" }));
    // => Person { age: 0, timestamp: 1714400867215, name: 'name2' }
    

    Default values are also "portable", meaning that if you reuse the same property signature in another schema, the default is carried over:

    import { Schema } from "@effect/schema";
    
    const PersonSchema = Schema.Struct({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0),
      ),
      timestamp: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => new Date().getTime()),
      ),
    });
    
    const AnotherSchema = Schema.Struct({
      foo: Schema.String,
      age: PersonSchema.fields.age,
    });
    
    console.log(AnotherSchema.make({ foo: "bar" })); // => { foo: 'bar', age: 0 }
    

    Defaults can also be applied using the Class API:

    import { Schema } from "@effect/schema";
    
    class Person extends Schema.Class<Person>("Person")({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0),
      ),
      timestamp: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => new Date().getTime()),
      ),
    }) {}
    
    console.log(new Person({ name: "name1" })); // Person { age: 0, timestamp: 1714400867208, name: 'name1' }
    console.log(new Person({ name: "name2" })); // Person { age: 0, timestamp: 1714400867215, name: 'name2' }
    

    Default Decoding Values

    Our new Schema.withDecodingDefault combinator makes it easy to handle the optionality of a field during the decoding process.

    import { Schema } from "@effect/schema";
    
    const MySchema = Schema.Struct({
      a: Schema.optional(Schema.String).pipe(
        Schema.withDecodingDefault(() => ""),
      ),
    });
    
    console.log(Schema.decodeUnknownSync(MySchema)({}));
    // => { a: '' }
    console.log(Schema.decodeUnknownSync(MySchema)({ a: undefined }));
    // => { a: '' }
    console.log(Schema.decodeUnknownSync(MySchema)({ a: "a" }));
    // => { a: 'a' }
    

    If you want to set default values both for the decoding phase and for the default constructor, you can use Schema.withDefaults:

    import { Schema } from "@effect/schema";
    
    const MySchema = Schema.Struct({
      a: Schema.optional(Schema.String).pipe(
        Schema.withDefaults({
          decoding: () => "",
          constructor: () => "-",
        }),
      ),
    });
    
    console.log(Schema.decodeUnknownSync(MySchema)({}));
    // => { a: '' }
    console.log(Schema.decodeUnknownSync(MySchema)({ a: undefined }));
    // => { a: '' }
    console.log(Schema.decodeUnknownSync(MySchema)({ a: "a" }));
    // => { a: 'a' }
    
    console.log(MySchema.make({})); // => { a: '-' }
    console.log(MySchema.make({ a: "a" })); // => { a: 'a' }
    

    Refactoring of Custom Message System

    We've refactored the system that handles user-defined custom messages to make it more intuitive.

    Now, custom messages no longer have absolute precedence by default. Instead, it becomes an opt-in behavior by explicitly setting a new flag override with the value true. Let's see an example:

    Previous Approach

    import { Schema } from "@effect/schema";
    
    const MyString = Schema.String.pipe(
      Schema.minLength(1),
      Schema.maxLength(2),
    ).annotations({
      // This message always takes precedence
      // So, for any error, the same message will always be shown
      message: () => "my custom message",
    });
    
    const decode = Schema.decodeUnknownEither(MyString);
    
    console.log(decode(null)); // "my custom message"
    console.log(decode("")); // "my custom message"
    console.log(decode("abc")); // "my custom message"
    

    As you can see, no matter where the decoding error is raised, the same error message will always be presented because in the previous version, the custom message by default overrides those generated by previous filters.

    Now, let's see how the same schema works with the new system.

    Current Approach

    import { Schema } from "@effect/schema";
    
    const MyString = Schema.String.pipe(
      Schema.minLength(1),
      Schema.maxLength(2),
    ).annotations({
      // This message is shown only if the maxLength filter fails
      message: () => "my custom message",
    });
    
    const decode = Schema.decodeUnknownEither(MyString);
    
    console.log(decode(null)); // "Expected a string, actual null"
    console.log(decode("")); // `Expected a string at least 1 character(s) long, actual ""`
    console.log(decode("abc")); // "my custom message"
    

    To restore the old behavior (for example, to address the scenario where a user wants to define a single cumulative custom message describing the properties that a valid value must have and does not want to see default messages), you need to set the override flag to true:

    import { Schema } from "@effect/schema";
    
    const MyString = Schema.String.pipe(
      Schema.minLength(1),
      Schema.maxLength(2),
    ).annotations({
      // By setting the `override` flag to `true`
      // this message will always be shown for any error
      message: () => ({ message: "my custom message", override: true }),
    });
    
    const decode = Schema.decodeUnknownEither(MyString);
    
    console.log(decode(null)); // "my custom message"
    console.log(decode("")); // "my custom message"
    console.log(decode("abc")); // "my custom message"
    

    The new system is particularly useful when the schema on which custom messages are defined is more complex than a scalar value (like string or number), for example, if it's a struct containing a field that is an array of structs. Let's see an example that illustrates how convenient it is to rely on default messages when the decoding error occurs in a nested structure:

    import { Schema } from "@effect/schema";
    import { pipe } from "effect";
    
    const schema = Schema.Struct({
      outcomes: pipe(
        Schema.Array(
          Schema.Struct({
            id: Schema.String,
            text: pipe(
              Schema.String,
              Schema.message(() => "error_invalid_outcome_type"),
              Schema.minLength(1, { message: () => "error_required_field" }),
              Schema.maxLength(50, { message: () => "error_max_length_field" }),
            ),
          }),
        ),
        Schema.minItems(1, { message: () => "error_min_length_field" }),
      ),
    });
    
    Schema.decodeUnknownSync(schema, { errors: "all" })({
      outcomes: [],
    });
    /*
    throws
    Error: { outcomes: an array of at least 1 items }
    └─ ["outcomes"]
       └─ error_min_length_field
    */
    
    Schema.decodeUnknownSync(schema, { errors: "all" })({
      outcomes: [
        { id: "1", text: "" },
        { id: "2", text: "this one is valid" },
        { id: "3", text: "1234567890".repeat(6) },
      ],
    });
    /*
    throws
    Error: { outcomes: an array of at least 1 items }
    └─ ["outcomes"]
       └─ an array of at least 1 items
          └─ From side refinement failure
             └─ ReadonlyArray<{ id: string; text: a string at most 50 character(s) long }>
                ├─ [0]
                │  └─ { id: string; text: a string at most 50 character(s) long }
                │     └─ ["text"]
                │        └─ error_required_field
                └─ [2]
                   └─ { id: string; text: a string at most 50 character(s) long }
                      └─ ["text"]
                         └─ error_max_length_field
    */
    

    In the previous version, we would have received the message "error_min_length_field" for any decoding error, which is evidently suboptimal and has now been corrected.

    Filter API Interface

    We've introduced a new API interface to the filter API. This allows you to access the refined schema using the exposed from field:

    import { Schema } from "@effect/schema";
    
    const MyFilter = Schema.Struct({
      a: Schema.String,
    }).pipe(Schema.filter(() => /* some filter... */ true));
    
    // const aField: typeof Schema.String
    const aField = MyFilter.from.fields.a;
    

    The signature of the filter function has been simplified and streamlined to be more ergonomic when setting a default message. In the new signature of filter, the type of the predicate passed as an argument is as follows:

    predicate: (a: A, options: ParseOptions, self: AST.Refinement) =>
      undefined | boolean | string | ParseResult.ParseIssue;
    

    with the following semantics:

    • true means the filter is successful.
    • false or undefined means the filter fails and no default message is set.
    • string means the filter fails and the returned string is used as the default message.
    • ParseIssue means the filter fails and the returned ParseIssue is used as an error.

    Let's see an example of how it worked before and how it works now.

    Before

    import { Schema, ParseResult } from "@effect/schema";
    import { Option } from "effect";
    
    const Positive = Schema.Number.pipe(
      Schema.filter((n, _, ast) =>
        n > 0
          ? Option.none()
          : Option.some(new ParseResult.Type(ast, n, "must be positive")),
      ),
    );
    
    Schema.decodeUnknownSync(Positive)(-1);
    /*
    throws
    Error: <refinement schema>
    └─ Predicate refinement failure
       └─ must be positive
    */
    

    Now

    import { Schema } from "@effect/schema";
    
    const Positive = Schema.Number.pipe(
      Schema.filter((n) => (n > 0 ? undefined : "must be positive")),
    );
    
    Schema.decodeUnknownSync(Positive)(-1);
    /*
    throws
    Error: { number | filter }
    └─ Predicate refinement failure
       └─ must be positive
    */
    

    JSON Schema Compiler Refactoring

    The JSON Schema compiler has been refactored to be more user-friendly. Now, the make API attempts to produce the optimal JSON Schema for the input part of the decoding phase. This means that starting from the most nested schema, it traverses the chain, including each refinement, and stops at the first transformation found.

    Let's see an example:

    import { JSONSchema, Schema } from "@effect/schema";
    
    const schema = Schema.Struct({
      foo: Schema.String.pipe(Schema.minLength(2)),
      bar: Schema.optional(Schema.NumberFromString, {
        default: () => 0,
      }),
    });
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2));
    

    Now, let's compare the JSON Schemas produced in both the previous and new versions.

    Before

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "required": ["bar", "foo"],
      "properties": {
        "bar": {
          "type": "number",
          "description": "a number",
          "title": "number"
        },
        "foo": {
          "type": "string",
          "description": "a string at least 2 character(s) long",
          "title": "string",
          "minLength": 2
        }
      },
      "additionalProperties": false,
      "title": "Struct (Type side)"
    }
    

    As you can see, the JSON Schema produced has:

    • a required foo field, correctly modeled with a constraint ("minLength": 2)
    • a required numeric bar field

    This happens because in the previous version, the JSONSchema.make API by default produces a JSON Schema for the Type part of the schema. That is:

    type Type = Schema.Schema.Type<typeof schema>;
    /*
    type Type = {
        readonly foo: string;
        readonly bar: number;
    }
    */
    

    However, typically, we are interested in generating a JSON Schema for the input part of the decoding process, i.e., in this case for:

    type Encoded = Schema.Schema.Encoded<typeof schema>;
    /*
    type Encoded = {
        readonly foo: string;
        readonly bar?: string | undefined;
    }
    */
    

    At first glance, a possible solution might be to generate the JSON Schema of Schema.encodedSchema(schema):

    console.log(
      JSON.stringify(JSONSchema.make(Schema.encodedSchema(schema)), null, 2),
    );
    

    But here's what the result would be:

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "required": ["foo"],
      "properties": {
        "foo": {
          "type": "string",
          "description": "a string",
          "title": "string"
        },
        "bar": {
          "type": "string",
          "description": "a string",
          "title": "string"
        }
      },
      "additionalProperties": false
    }
    

    As you can see, we lost the "minLength": 2 constraint, which is the useful part of precisely defining our schemas using refinements.

    After

    Now, let's see what JSONSchema.make API produces by default for the same schema:

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "required": ["foo"],
      "properties": {
        "foo": {
          "type": "string",
          "description": "a string at least 2 character(s) long",
          "title": "string",
          "minLength": 2
        },
        "bar": {
          "type": "string",
          "description": "a string",
          "title": "string"
        }
      },
      "additionalProperties": false,
      "title": "Struct (Encoded side)"
    }
    

    As you can verify, the refinement has been preserved.

    Improve extend to support refinements and suspended schemas

    Now extend supports extending refinements, so you can do something like this:

    import { Schema } from "@effect/schema";
    
    const RefinedStruct = Schema.Struct({
      a: Schema.Number,
      b: Schema.Number,
    }).pipe(
      Schema.filter((value) => {
        if (value.a !== value.b) {
          return "`a` must be equal to `b`";
        }
      }),
    );
    
    const AnotherStruct = Schema.Struct({
      c: Schema.String,
      d: Schema.String,
    });
    
    // in the previous version you would receive an error:
    // Extend: cannot extend `<refinement schema>` with `{ c: string; d: string }` (path [])
    const Extended = Schema.extend(RefinedStruct, AnotherStruct);
    
    console.log(String(Extended));
    
    console.log(
      Schema.decodeUnknownSync(Extended)({ a: 1, b: 1, c: "c", d: "d" }),
    );
    // => { a: 1, b: 1, c: 'c', d: 'd' }
    console.log(
      Schema.decodeUnknownSync(Extended)({ a: 1, b: 2, c: "c", d: "d" }),
    );
    /*
    throws
    Error: { { readonly a: number; readonly b: number; readonly c: string; readonly d: string } | filter }
    └─ Predicate refinement failure
       └─ `a` must be equal to `b`
    */
    

    We've also added support for Schema.suspend. Here's an example:

    import { Arbitrary, FastCheck, Schema } from "@effect/schema";
    
    // Define a recursive list type
    type List =
      | {
          readonly type: "nil";
        }
      | {
          readonly type: "cons";
          readonly tail: {
            readonly value: number;
          } & List; // extend
        };
    
    // Define a schema for the list type
    const List: Schema.Schema<List> = Schema.Union(
      Schema.Struct({ type: Schema.Literal("nil") }),
      Schema.Struct({
        type: Schema.Literal("cons"),
        tail: Schema.extend(
          Schema.Struct({ value: Schema.Number }),
          Schema.suspend(() => List), // extend
        ),
      }),
    );
    
    console.log(
      JSON.stringify(FastCheck.sample(Arbitrary.make(List), 5), null, 2),
    );
    /*
    [
      {
        "type": "cons",
        "tail": {
          "type": "cons",
          "value": 4.8301839079380824e+36,
          "tail": {
            "type": "cons",
            "value": 1.5771055128598197e-29,
            "tail": {
              "type": "nil",
              "value": -15237.7763671875
            }
          }
        }
      },
      {
        "type": "cons",
        "tail": {
          "type": "nil",
          "value": 5.808463088527973e-18
        }
      },
      {
        "type": "nil"
      },
      {
        "type": "nil"
      },
      {
        "type": "cons",
        "tail": {
          "type": "cons",
          "value": -0.7920627593994141,
          "tail": {
            "type": "nil",
            "value": 63.837738037109375
          }
        }
      }
    ]
    */
    

    Patches

    AST

    • fix AST.toString to honor readonly modifiers
    • improve AST.toString for refinements

    Schema

    • return BrandSchema from fromBrand
    • add SchemaClass interface
    • add AnnotableClass interface
    • extend: add support for refinements, closes #2642
    • add pattern json schema annotation to Trimmed
    • add parseNumber number transformation
    • add TaggedClass api interface (exposing a _tag field)
    • add TaggedErrorClass api interface (exposing a _tag field)
    • add TaggedRequestClass api interface (exposing a _tag field)
    • add DateFromNumber schema
    • add Schema.Schema.AsSchema type-level helper to facilitate working with generic schemas.

    Other Breaking Changes

    • move fast-check from peerDependencies to dependencies

    AST

    • add path argument to Compiler API

      -export type Compiler<A> = (ast: AST) => A
      +export type Compiler<A> = (ast: AST, path: ReadonlyArray<PropertyKey>) => A
      
    • remove hash function, you can replace it with the following code:

      import { Hash } from "effect";
      import { AST } from "@effect/schema";
      
      export const hash = (ast: AST.AST): number =>
        Hash.string(JSON.stringify(ast, null, 2));
      

    JSONSchema

    • extend all interfaces with JsonSchemaAnnotations

      export interface JsonSchemaAnnotations {
        title?: string;
        description?: string;
        default?: unknown;
        examples?: Array<unknown>;
      }
      

    Schema

    • replace numerous API interfaces with class-based schema definitions

    • rename $Array API interface to `Array# @effect/schema

    • rename $Record API interface to `Record# @effect/schema

    • rename $ReadonlyMap API interface to `ReadonlyMap# @effect/schema

    • rename $Map API interface to `Map# @effect/schema

    • rename $ReadonlySet API interface to `ReadonlySet# @effect/schema

    • rename $Set API interface to `Set# @effect/schema

    • remove asBrandSchema utility

    • change BrandSchema interface

    • remove hash function

      from

      export interface BrandSchema<A extends brand_.Brand<any>, I>
        extends Annotable<BrandSchema<A, I>, A, I>,
          Brand.Constructor<A> {}
      

      to

      export interface BrandSchema<A extends Brand<any>, I, R>
        extends AnnotableClass<BrandSchema<A, I, R>, A, I, R> {
        make(a: Brand.Unbranded<A>): A;
      }
      

      Previously, you could directly use the Brand.Constructor, but now you need to use its make constructor:

      Before

      import { Schema } from "@effect/schema";
      
      const UserId = Schema.Number.pipe(Schema.brand("UserId"));
      
      console.log(UserId(1)); // 1
      

      Now

      import { Schema } from "@effect/schema";
      
      const UserId = Schema.Number.pipe(Schema.brand("UserId"));
      
      console.log(UserId.make(1)); // 1
      

0.66.16

Patch Changes

  • Updated dependencies [1f6dc96]:
    • effect@3.1.3

0.66.15

Patch Changes

  • #2710 121d6d9 Thanks @gcanti! - Class API: avoid access before initialization when creating a class with suspended props, closes #2709

0.66.14

Patch Changes

0.66.13

Patch Changes

  • Updated dependencies [e5e56d1]:
    • effect@3.1.1

0.66.12

Patch Changes

0.66.11

Patch Changes

0.66.10

Patch Changes

  • Updated dependencies [18de56b]:
    • effect@3.0.7

0.66.9

Patch Changes

  • #2626 027418e Thanks @fubhy! - Reintroduce custom NoInfer type

  • #2631 8206529 Thanks @gcanti! - add support for data-last subtype overloads in compose

    Before

    import { Schema as S } from "@effect/schema";
    
    S.Union(S.Null, S.String).pipe(S.compose(S.NumberFromString)); // ts error
    S.NumberFromString.pipe(S.compose(S.Union(S.Null, S.Number))); // ts error
    

    Now

    import { Schema as S } from "@effect/schema";
    
    // $ExpectType Schema<number, string | null, never>
    S.Union(S.Null, S.String).pipe(S.compose(S.NumberFromString)); // ok
    // $ExpectType Schema<number | null, string, never>
    S.NumberFromString.pipe(S.compose(S.Union(S.Null, S.Number))); // ok
    
  • Updated dependencies [ffe4f4e, 027418e, ac1898e, ffe4f4e]:

    • effect@3.0.6

0.66.8

Patch Changes

0.66.7

Patch Changes

  • #2595 dd41c6c Thanks @gcanti! - Remove excessive constraint from the pipeable overload of attachPropertySignature, closes #2593

  • Updated dependencies [9a24667]:

    • effect@3.0.4

0.66.6

Patch Changes

  • #2586 9dfc156 Thanks @gcanti! - remove non-tree-shakable compiler dependencies from the Schema module:

    • remove dependency from Arbitrary compiler
    • remove dependency from Equivalence compiler
    • remove dependency from Pretty compiler
  • #2583 80271bd Thanks @suddenlyGiovanni! - - Fixed a typo in the JSDoc comment of the BooleanFromUnknown boolean constructors in Schema.ts

    • Fixed a typo in the JSDoc comment of the split string transformations combinator in Schema.ts
  • #2585 e4ba97d Thanks @gcanti! - JSONSchema: rearrange handling of surrogate annotations to occur after JSON schema annotations

0.66.5

Patch Changes

  • #2582 b3fe829 Thanks @gcanti! - Add default title annotations to both sides of Struct transformations.

    This simple addition helps make error messages shorter and more understandable.

    Before

    import { Schema } from "@effect/schema";
    
    const schema = Schema.Struct({
      a: Schema.optional(Schema.String, { exact: true, default: () => "" }),
      b: Schema.String,
      c: Schema.String,
      d: Schema.String,
      e: Schema.String,
      f: Schema.String,
    });
    
    Schema.decodeUnknownSync(schema)({ a: 1 });
    /*
    throws
    Error: ({ a?: string; b: string; c: string; d: string; e: string; f: string } <-> { a: string; b: string; c: string; d: string; e: string; f: string })
    └─ Encoded side transformation failure
       └─ { a?: string; b: string; c: string; d: string; e: string; f: string }
          └─ ["a"]
             └─ Expected a string, actual 1
    */
    

    Now

    import { Schema } from "@effect/schema";
    
    const schema = Schema.Struct({
      a: Schema.optional(Schema.String, { exact: true, default: () => "" }),
      b: Schema.String,
      c: Schema.String,
      d: Schema.String,
      e: Schema.String,
      f: Schema.String,
    });
    
    Schema.decodeUnknownSync(schema)({ a: 1 });
    /*
    throws
    Error: (Struct (Encoded side) <-> Struct (Type side))
    └─ Encoded side transformation failure
       └─ Struct (Encoded side)
          └─ ["a"]
             └─ Expected a string, actual 1
    */
    
  • #2581 a58b7de Thanks @gcanti! - Fix formatting for Class and brands AST.

  • #2579 d90e8c3 Thanks @gcanti! - Schema: JSONSchema should support make(Class)

    Before

    import { JSONSchema, Schema } from "@effect/schema";
    
    class A extends Schema.Class<A>("A")({
      a: Schema.String,
    }) {}
    
    console.log(JSONSchema.make(A)); // throws MissingAnnotation: cannot build a JSON Schema for a declaration without a JSON Schema annotation
    

    Now

    console.log(JSONSchema.make(A));
    /*
    Output:
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      required: [ 'a' ],
      properties: { a: { type: 'string', description: 'a string', title: 'string' } },
      additionalProperties: false
    }
    */
    

0.66.4

Patch Changes

  • #2577 773b8e0 Thanks @gcanti! - partial / required: add support for renaming property keys in property signature transformations

    Before

    import { Schema } from "@effect/schema";
    
    const TestType = Schema.Struct({
      a: Schema.String,
      b: Schema.propertySignature(Schema.String).pipe(Schema.fromKey("c")),
    });
    
    const PartialTestType = Schema.partial(TestType);
    // throws Error: Partial: cannot handle transformations
    

    Now

    import { Schema } from "@effect/schema";
    
    const TestType = Schema.Struct({
      a: Schema.String,
      b: Schema.propertySignature(Schema.String).pipe(Schema.fromKey("c")),
    });
    
    const PartialTestType = Schema.partial(TestType);
    
    console.log(Schema.decodeUnknownSync(PartialTestType)({ a: "a", c: "c" })); // { a: 'a', b: 'c' }
    console.log(Schema.decodeUnknownSync(PartialTestType)({ a: "a" })); // { a: 'a' }
    
    const RequiredTestType = Schema.required(PartialTestType);
    
    console.log(Schema.decodeUnknownSync(RequiredTestType)({ a: "a", c: "c" })); // { a: 'a', b: 'c' }
    console.log(Schema.decodeUnknownSync(RequiredTestType)({ a: "a" })); // { a: 'a', b: undefined }
    

0.66.3

Patch Changes

  • Updated dependencies [a7b4b84]:
    • effect@3.0.3

0.66.2

Patch Changes

0.66.1

Patch Changes

  • #2550 b2b5d66 Thanks @gcanti! - Fix transformOrFail and transformOrFailFrom signatures in the exported Class interface by adding the missing annotations optional argument

  • #2555 8edacca Thanks @tim-smart! - prevent use of Array as import name to solve bundler issues

  • Updated dependencies [3da0cfa, 570e8d8, 8edacca]:

    • effect@3.0.1

0.66.0

Minor Changes

Patch Changes

0.65.0

Minor Changes

For the updates mentioned below, we've released a codemod to simplify the migration process.

To run it, use the following command:

npx @effect/codemod schema-0.65 src/**/*

The codemod is designed to automate many of the changes needed. However, it might not catch everything, so please let us know if you run into any issues (https://github.com/Effect-TS/codemod/issues). Remember to commit your code changes before running the codemod, just in case you need to undo anything.

  • #2505 0aee906 Thanks @mikearnaldi! - Re-export FastCheck to simplify usage and to resolve long term issues with ESM/CJS

  • #2440 b3acf47 Thanks @gcanti! - ## AST module

    • rename isTransform to isTransformation

    ParseResult module

    • rename Tuple to TupleType

    TreeFormatter module

    • rename formatIssue to formatIssueSync (This change was made to maintain consistency in API naming across all decoding and encoding APIs.)
    • rename formatIssueEffect to formatIssue
    • rename formatError to formatErrorSync
    • rename formatErrorEffect to formatError

    ArrayFormatter module

    • rename formatIssue to formatIssueSync
    • rename formatIssueEffect to formatIssue
    • rename formatError to formatErrorSync
    • rename formatErrorEffect to formatError

    Schema module

    • consolidate transform and transformOrFail parameters into an options object, #2434
    • consolidate Class.transformOrFail and Class.transformOrFailFrom parameters into an options object
    • consolidate declare parameters into an options object
    • consolidate optionalToRequired parameters into an options object
    • consolidate optionalToOptional parameters into an options object
    • Removed negateBigDecimal function (This cleanup was prompted by the realization that numerous functions can be derived from transformations such as negation, Math.abs, increment, etc. However, including all of them in the library is not feasible. Therefore, negateBigDecimal was removed)

    Renaming

    • rename uniqueSymbolFromSelf to UniqueSymbolFromSelf
    • rename undefined to Undefined
    • rename void to Void
    • rename null to Null
    • rename never to Never
    • rename unknown to Unknown
    • rename any to Any
    • rename string to String
    • rename number to Number
    • rename boolean to Boolean
    • rename /bigint/ig to BigInt
    • rename symbolFromSelf to SymbolFromSelf
    • rename object to Object
    • rename union to Union
    • rename nullable to NullOr
    • rename orUndefined to UndefinedOr
    • rename nullish to NullishOr
    • rename tuple to Tuple
    • rename array to Array
    • rename nonEmptyArray to NonEmptyArray
    • rename struct to Struct
    • rename record to Record
    • rename symbol to Symbol
    • rename optionFromSelf to OptionFromSelf
    • rename option to Option
    • rename optionFromNullable to OptionFromNullOr
    • rename optionFromNullish to OptionFromNullishOr
    • rename optionFromOrUndefined to OptionFromUndefinedOr
    • rename eitherFromSelf to EitherFromSelf
    • rename either to Either
    • rename eitherFromUnion to EitherFromUnion
    • rename readonlyMapFromSelf to ReadonlyMapFromSelf
    • rename mapFromSelf to MapFromSelf
    • rename readonlyMap to ReadonlyMap
    • rename map to Map
    • rename readonlySetFromSelf to ReadonlySetFromSelf
    • rename setFromSelf to SetFromSelf
    • rename readonlySet to ReadonlySet
    • rename set to Set
    • rename chunkFromSelf to ChunkFromSelf
    • rename chunk to Chunk
    • rename dataFromSelf to DataFromSelf
    • rename data to Data
    • rename causeFromSelf to CauseFromSelf
    • rename causeDefectUnknown to CauseDefectUnknown
    • rename cause to Cause
    • rename exitFromSelf to ExitFromSelf
    • rename exit to Exit
    • rename hashSetFromSelf to HashSetFromSelf
    • rename hashSet to HashSet
    • rename hashMapFromSelf to HashMapFromSelf
    • rename hashMap to HashMap
    • rename listFromSelf to ListFromSelf
    • rename list to List
    • rename sortedSetFromSelf to SortedSetFromSelf
    • rename sortedSet to SortedSet
    • rename literal to Literal
    • rename enums to Enums
    • rename templateLiteral to TemplateLiteral
  • #2511 0d3231a Thanks @gcanti! - make AST.pick correctly handle key renames

  • #2508 c22b019 Thanks @mikearnaldi! - Rename Arbitrary.Arbitrary to Arbitrary.LazyArbitrary, rename Arbitrary.make to Arbitrary.makeLazy and introduce Arbitrary.make

    Before

    import { Arbitrary, Schema } from "@effect/schema";
    import * as fc from "fast-check";
    
    const Person = Schema.struct({
      name: Schema.string,
      age: Schema.string.pipe(
        Schema.compose(Schema.NumberFromString),
        Schema.int(),
      ),
    });
    
    const arb = Arbitrary.make(Person)(fc);
    
    console.log(fc.sample(arb, 2));
    

    Now

    import { Arbitrary, FastCheck, Schema } from "@effect/schema";
    
    const Person = Schema.Struct({
      name: Schema.String,
      age: Schema.String.pipe(
        Schema.compose(Schema.NumberFromString),
        Schema.int(),
      ),
    });
    
    const arb = Arbitrary.make(Person);
    
    console.log(FastCheck.sample(arb, 2));
    

Patch Changes

0.64.20

Patch Changes

  • #2483 42b3651 Thanks @gcanti! - Add ParseIssueTitle annotation, closes #2482

    When a decoding or encoding operation fails, it's useful to have additional details in the default error message returned by TreeFormatter to understand exactly which value caused the operation to fail. To achieve this, you can set an annotation that depends on the value undergoing the operation and can return an excerpt of it, making it easier to identify the problematic value. A common scenario is when the entity being validated has an id field. The ParseIssueTitle annotation facilitates this kind of analysis during error handling.

    The type of the annotation is:

    export type ParseIssueTitleAnnotation = (
      issue: ParseIssue,
    ) => string | undefined;
    

    If you set this annotation on a schema and the provided function returns a string, then that string is used as the title by TreeFormatter, unless a message annotation (which has the highest priority) has also been set. If the function returns undefined, then the default title used by TreeFormatter is determined with the following priorities:

    • identifier
    • title
    • description
    • ast.toString()

    Example

    import type { ParseIssue } from "@effect/schema/ParseResult";
    import * as S from "@effect/schema/Schema";
    
    const getOrderItemId = ({ actual }: ParseIssue) => {
      if (S.is(S.struct({ id: S.string }))(actual)) {
        return `OrderItem with id: ${actual.id}`;
      }
    };
    
    const OrderItem = S.struct({
      id: S.string,
      name: S.string,
      price: S.number,
    }).annotations({
      identifier: "OrderItem",
      parseIssueTitle: getOrderItemId,
    });
    
    const getOrderId = ({ actual }: ParseIssue) => {
      if (S.is(S.struct({ id: S.number }))(actual)) {
        return `Order with id: ${actual.id}`;
      }
    };
    
    const Order = S.struct({
      id: S.number,
      name: S.string,
      items: S.array(OrderItem),
    }).annotations({
      identifier: "Order",
      parseIssueTitle: getOrderId,
    });
    
    const decode = S.decodeUnknownSync(Order, { errors: "all" });
    
    // No id available, so the `identifier` annotation is used as the title
    decode({});
    /*
    throws
    Error: Order
    ├─ ["id"]
    │  └─ is missing
    ├─ ["name"]
    │  └─ is missing
    └─ ["items"]
       └─ is missing
    */
    
    // An id is available, so the `parseIssueTitle` annotation is used as the title
    decode({ id: 1 });
    /*
    throws
    Error: Order with id: 1
    ├─ ["name"]
    │  └─ is missing
    └─ ["items"]
       └─ is missing
    */
    
    decode({ id: 1, items: [{ id: "22b", price: "100" }] });
    /*
    throws
    Error: Order with id: 1
    ├─ ["name"]
    │  └─ is missing
    └─ ["items"]
       └─ ReadonlyArray<OrderItem>
          └─ [0]
             └─ OrderItem with id: 22b
                ├─ ["name"]
                │  └─ is missing
                └─ ["price"]
                   └─ Expected a number, actual "100"
    */
    

    In the examples above, we can see how the parseIssueTitle annotation helps provide meaningful error messages when decoding fails.

0.64.19

Patch Changes

  • #2471 58f66fe Thanks @gcanti! - Class API: Added default title annotation to the encoded side.

    Before:

    import * as S from "@effect/schema/Schema";
    
    class MySchema extends S.Class<MySchema>("MySchema")({
      a: S.string,
      b: S.number,
    }) {}
    
    S.decodeUnknownSync(MySchema)({}, { errors: "all" });
    /*
    Error: ({ a: string; b: number } <-> MySchema)
    └─ Encoded side transformation failure
       └─ { a: string; b: number }
          ├─ ["a"]
          │  └─ is missing
          └─ ["b"]
             └─ is missing
    */
    

    After:

    import * as S from "@effect/schema/Schema";
    
    class MySchema extends S.Class<MySchema>("MySchema")({
      a: S.string,
      b: S.number,
    }) {}
    
    S.decodeUnknownSync(MySchema)({}, { errors: "all" });
    /*
    Error: (MySchema (Encoded side) <-> MySchema)
    └─ Encoded side transformation failure
       └─ MySchema (Encoded side)
          ├─ ["a"]
          │  └─ is missing
          └─ ["b"]
             └─ is missing
    */
    
  • #2465 3cad21d Thanks @gcanti! - length now allows expressing a range

    Example

    import * as S from "@effect/schema/Schema";
    
    const schema = S.string.pipe(
      S.length({ min: 2, max: 4 }, { identifier: "MyRange" }),
    );
    
    S.decodeUnknownSync(schema)("");
    /*
    throws:
    Error: MyRange
    └─ Predicate refinement failure
       └─ Expected MyRange (a string at least 2 character(s) and at most 4 character(s) long), actual ""
    */
    
  • Updated dependencies [dadc690]:

    • effect@2.4.18

0.64.18

Patch Changes

0.64.17

Patch Changes

  • #2446 62a7f23 Thanks @gcanti! - ParseResult: Add output field to TupleType and TypeLiteral. While the operation may not be entirely successful, it still provides some useful output or information.

    Examples (Tuple)

    import * as S from "@effect/schema/Schema";
    import * as Either from "effect/Either";
    
    const schema = S.array(S.number);
    const result = S.decodeUnknownEither(schema)([1, "a", 2, "b"], {
      errors: "all",
    });
    if (Either.isLeft(result)) {
      const issue = result.left.error;
      if (issue._tag === "TupleType") {
        console.log(issue.output); // [1, 2]
      }
    }
    

    Examples (TypeLiteral)

    import * as S from "@effect/schema/Schema";
    import * as Either from "effect/Either";
    
    const schema = S.record(S.string, S.number);
    const result = S.decodeUnknownEither(schema)(
      { a: 1, b: "b", c: 2, d: "d" },
      { errors: "all" },
    );
    if (Either.isLeft(result)) {
      const issue = result.left.error;
      if (issue._tag === "TypeLiteral") {
        console.log(issue.output); // { a: 1, c: 2 }
      }
    }
    
  • #2453 7cc2b41 Thanks @jessekelly881! - added Schema.BooleanFromUnknown

  • #2456 8b46fde Thanks @gcanti! - add set, setFromSelf, map, mapFromSelf

  • Updated dependencies [5170ce7]:

    • effect@2.4.16

0.64.16

Patch Changes

  • #2428 a31917a Thanks @gcanti! - export null from the AST module

  • #2436 4cd2bed Thanks @patroza! - fix: Schema JSDOC and editor click-follow for fields on struct and class

  • #2442 6cc6267 Thanks @gcanti! - Enums are now exposed under an enums property of the schema, closes #2441:

    enum Fruits {
      Apple,
      Banana,
    }
    
    // $ExpectType enums<typeof Fruits>
    S.enums(Fruits);
    
    // $ExpectType typeof Fruits
    S.enums(Fruits).enums;
    
    // $ExpectType Fruits.Apple
    S.enums(Fruits).enums.Apple;
    
    // $ExpectType Fruits.Banana
    S.enums(Fruits).enums.Banana;
    

0.64.15

Patch Changes

0.64.14

Patch Changes

0.64.13

Patch Changes

0.64.12

Patch Changes

  • #2359 9392de6 Thanks @tim-smart! - preserve defect information in Cause.Die

  • #2385 3307729 Thanks @tim-smart! - align runtime tuple behaviour to ts 5.4:

    from

    // ts 5.3
    type A = readonly [string, ...number[], boolean];
    type B = Required<A>; // readonly [string, ...(number | boolean)[], number | boolean]
    

    to

    // ts 5.4
    type A = readonly [string, ...number[], boolean];
    type B = Required<A>; // readonly [string, ...number[], boolean]
    
  • #2359 9392de6 Thanks @tim-smart! - use provided message in Schema.TaggedError .toString

  • #2385 3307729 Thanks @tim-smart! - update typescript to 5.4

  • #2396 d17a427 Thanks @sukovanej! - Fix extend with nested union.

  • Updated dependencies [3307729]:

    • effect@2.4.12

0.64.11

Patch Changes

0.64.10

Patch Changes

0.64.9

Patch Changes

0.64.8

Patch Changes

0.64.7

Patch Changes

  • Updated dependencies [71fd528]:
    • effect@2.4.9

0.64.6

Patch Changes

  • #2347 595140a Thanks @gcanti! - add back BrandSchema and introduce asBrandSchema utility

  • #2353 5f5fcd9 Thanks @tim-smart! - make optional dual:

    import * as S from "@effect/schema/Schema";
    
    const schema = S.struct({
      a: S.string.pipe(S.optional()),
    });
    
    // same as:
    const schema2 = S.struct({
      a: S.optional(S.string),
    });
    
  • #2356 7a45ad0 Thanks @gcanti! - make partial dual:

    import * as S from "@effect/schema/Schema";
    
    const schema = S.struct({ a: S.string }).pipe(S.partial());
    
    // same as:
    const schema2 = S.partial(S.struct({ a: S.string }));
    
  • #2339 5c3b1cc Thanks @gcanti! - use Simplify from effect/Types in TaggedClass, TaggedError and TaggedRequest to avoid errors in Schema.d.ts, closes #1841

  • #2343 6f7dfc9 Thanks @gcanti! - improve pick/omit and add support for Class

  • #2337 88b8583 Thanks @gcanti! - JSONSchema: allow overrides through annotations, closes #1823

  • #2348 cb20824 Thanks @gcanti! - feedback: expose Class API identifiers

  • #2350 a45a525 Thanks @gcanti! - refactor unions: remove sorting, flattening, and unification

  • Updated dependencies [bb0b69e, 6b20bad, 4e64e9b, 3851a02, 5f5fcd9, 814e5b8]:

    • effect@2.4.8

0.64.5

Patch Changes

  • #2332 d0f56c6 Thanks @gcanti! - add missing Date api interfaces:

    • DateFromSelf
    • ValidDateFromSelf
    • DateFromString
    • $Date

0.64.4

Patch Changes

  • Updated dependencies [eb93283]:
    • effect@2.4.7

0.64.3

Patch Changes

  • #2320 cfef6ec Thanks @gcanti! - feedback: remove array overload to restore pipeability to the API

0.64.2

Patch Changes

  • #2310 89748c9 Thanks @gcanti! - merge Parser module into ParseResult:

    • remove Parser module
    • remove internal/parseResult internal module
  • Updated dependencies [4f35a7e, 9971186]:

    • effect@2.4.6

0.64.1

Patch Changes

0.64.0

Minor Changes

Breaking Changes

  • The Format module has been removed

AST module

  • Tuple has been refactored to TupleType, and its _tag has consequently been renamed. The type of its rest property has changed from Option.Option<ReadonlyArray.NonEmptyReadonlyArray<AST>> to ReadonlyArray<AST>.

  • Transform has been refactored to Transformation, and its _tag property has consequently been renamed. Its property transformation has now the type TransformationKind = FinalTransformation | ComposeTransformation | TypeLiteralTransformation.

  • createRecord has been removed

  • AST.to has been renamed to AST.typeAST

  • AST.from has been renamed to AST.encodedAST

  • ExamplesAnnotation and DefaultAnnotation now accept a type parameter

  • format has been removed: Before

    AST.format(ast, verbose?)
    

    Now

    ast.toString(verbose?)
    
  • setAnnotation has been removed (use annotations instead)

  • mergeAnnotations has been renamed to annotations

  • move defaultParseOption from Parser.ts to AST.ts

ParseResult module

  • The ParseResult module now uses classes and custom constructors have been removed: Before

    import * as ParseResult from "@effect/schema/ParseResult";
    
    ParseResult.type(ast, actual);
    

    Now

    import * as ParseResult from "@effect/schema/ParseResult";
    
    new ParseResult.Type(ast, actual);
    
  • Transform has been refactored to Transformation, and its kind property now accepts "Encoded", "Transformation", or "Type" as values

Schema module

  • uniqueSymbol has been renamed to uniqueSymbolFromSelf

  • Schema.Schema.To has been renamed to Schema.Schema.Type, and Schema.to to Schema.typeSchema

  • Schema.Schema.From has been renamed to Schema.Schema.Encoded, and Schema.from to Schema.encodedSchema

  • The type parameters of TaggedRequest have been swapped

  • The signature of PropertySignature has been changed from PropertySignature<From, FromOptional, To, ToOptional> to PropertySignature<ToToken extends Token, To, Key extends PropertyKey, FromToken extends Token, From, R>

  • Class APIs

    • Class APIs now expose fields and require an identifier
      -class A extends S.Class<A>()({ a: S.string }) {}
      +class A extends S.Class<A>("A")({ a: S.string }) {}
      
  • element and rest have been removed in favor of tuple:

    Before

    import * as S from "@effect/schema/Schema";
    
    const schema1 = S.tuple().pipe(S.rest(S.number), S.element(S.boolean));
    
    const schema2 = S.tuple(S.string).pipe(
      S.rest(S.number),
      S.element(S.boolean),
    );
    

    Now

    import * as S from "@effect/schema/Schema";
    
    const schema1 = S.tuple([], S.number, S.boolean);
    
    const schema2 = S.tuple([S.string], S.number, S.boolean);
    
  • optionalElement has been refactored:

    Before

    import * as S from "@effect/schema/Schema";
    
    const schema = S.tuple(S.string).pipe(S.optionalElement(S.number));
    

    Now

    import * as S from "@effect/schema/Schema";
    
    const schema = S.tuple(S.string, S.optionalElement(S.number));
    
  • use TreeFormatter in BrandSchemas

  • Schema annotations interfaces have been refactored into a namespace Annotations

  • the annotations option of the optional constructor has been replaced by the annotations method Before

    S.optional(S.string, {
      exact: true,
      annotations: { description: "description" },
    });
    

    Now

    S.optional(S.string, { exact: true }).annotations({
      description: "description",
    });
    
  • Updated the pluck function to return Schema<A[K], { readonly [key]: I[K] }> instead of Schema<A[K], I>. Removed the { transformation: false } option in favor of selecting the specific field from the fields exposed by a struct.

  • Removed propertySignatureAnnotations, use propertySignature(schema).annotations().

  • Updated the function name headOr to headOrElse to align with the standard naming convention.

Serializable module

  • The type parameters of SerializableWithResult and WithResult have been swapped

Patch Changes

  • #2172 5d47ee0 Thanks @gcanti! - ## AST module

    • expose the getTemplateLiteralRegExp API

    Schema module

    • enhance the struct API to allow records:

      const schema1 = S.struct(
        { a: S.number },
        { key: S.string, value: S.number },
      );
      // or
      const schema2 = S.struct({ a: S.number }, S.record(S.string, S.number));
      
    • enhance the extend API to allow nested (non-overlapping) fields:

      const A = S.struct({ a: S.struct({ b: S.string }) });
      const B = S.struct({ a: S.struct({ c: S.number }) });
      const schema = S.extend(A, B);
      /*
      same as:
      const schema = S.struct({
        a: S.struct({
          b: S.string,
          c: S.number
        })
      })
      */
      
    • add Annotable interface

    • add asSchema

    • add add Schema.Any, Schema.All, Schema.AnyNoContext helpers

    • refactor annotations API to be a method within the Schema interface

    • add support for AST.keyof, AST.getPropertySignatures, Parser.getSearchTree to Classes

    • fix BrandAnnotation type and add getBrandAnnotation

    • add annotations? parameter to Class constructors:

      import * as AST from "@effect/schema/AST";
      import * as S from "@effect/schema/Schema";
      
      class A extends S.Class<A>("A")(
        {
          a: S.string,
        },
        { description: "some description..." }, // <= annotations
      ) {}
      
  • Updated dependencies [5d47ee0, 817a04c, d90a99d, dd05faa, dd05faa, 802674b]:

    • effect@2.4.4

0.63.4

Patch Changes

0.63.3

Patch Changes

0.63.2

Patch Changes

  • #2222 39f583e Thanks @gcanti! - TaggedClass: ensure constructor parameters don't overwrite the tag

  • #2227 f428198 Thanks @gcanti! - add ConcurrencyAnnotation, default value: undefined (sequential)

    Example:

    const schema = S.struct({
      a: S.string,
      b: S.number,
    }).pipe(S.concurrency(1 /* number | "unbounded" | "inherit" | undefined */));
    
  • #2221 c035972 Thanks @tim-smart! - ensure Schema.Class is compatible without strictNullCheck

  • Updated dependencies [a4a0006, 0a37676, 6f503b7]:

    • effect@2.4.1

0.63.1

Patch Changes

  • #2209 5d30853 Thanks @steffanek! - Add pickLiteral to Schema so that we can pick values from a Schema literal as follows:

    import * as S from "@effect/schema/Schema";
    
    const schema = S.literal("a", "b", "c").pipe(S.pickLiteral("a", "b")); // same as S.literal("a", "b")
    
    S.decodeUnknownSync(schema)("a"); // ok
    S.decodeUnknownSync(schema)("b"); // ok
    S.decodeUnknownSync(schema)("c");
    /*
    Error: "a" | "b"
    ├─ Union member
    │  └─ Expected "a", actual "c"
    └─ Union member
       └─ Expected "b", actual "c"
    */
    
  • #2217 6e350ed Thanks @gcanti! - JSONSchema: prune UndefinedKeyword if the property signature is marked as optional and contains a union that includes UndefinedKeyword, closes #2068

0.63.0

Minor Changes

  • #2101 54ddbb7 Thanks @github-actions! - Updated the MessageAnnotation type to accept a ParseIssue; it's now (issue: ParseResult.ParseIssue) => string to support custom error messages, which can be triggered under any circumstances.

    You can retrieve the actual value by accessing the actual property of the issue object:

    import * as S from "@effect/schema/Schema";
    
    const schema = S.string.pipe(
      S.filter((s): s is string => s.length === 1, {
    -    message: (actual) => `invalid value ${actual}`,
    +    message: (issue) => `invalid value ${issue.actual}`,
      })
    );
    
  • #2101 a025b12 Thanks @github-actions! - Swap type params of Either from Either<E, A> to Either<R, L = never>.

    Along the same line of the other changes this allows to shorten the most common types such as:

    import { Either } from "effect";
    
    const right: Either.Either<string> = Either.right("ok");
    

Patch Changes

0.62.9

Patch Changes

0.62.8

Patch Changes

0.62.7

Patch Changes

  • #2141 dbff62c Thanks @gcanti! - add { exact: true } optional argument to the partial API, mirroring the implementation in the optional API, closes #2140

    The partial operation allows you to make all properties within a schema optional.

    By default, the partial operation adds a union with undefined to the types. If you wish to avoid this, you can opt-out by passing a { exact: true } argument to the partial operation.

    Example

    import * as S from "@effect/schema/Schema";
    
    /*
    const schema: S.Schema<{
        readonly a?: string | undefined;
    }, {
        readonly a?: string | undefined;
    }, never>
    */
    const schema = S.partial(S.struct({ a: S.string }));
    
    S.decodeUnknownSync(schema)({ a: "a" }); // ok
    S.decodeUnknownSync(schema)({ a: undefined }); // ok
    
    /*
    const exact: S.Schema<{
        readonly a?: string;
    }, {
        readonly a?: string;
    }, never>
    */
    const exactSchema = S.partial(S.struct({ a: S.string }), { exact: true });
    
    S.decodeUnknownSync(exactSchema)({ a: "a" }); // ok
    S.decodeUnknownSync(exactSchema)({ a: undefined });
    /*
    throws:
    Error: { a?: string }
    └─ ["a"]
       └─ Expected a string, actual undefined
    */
    
  • #2128 e572b07 Thanks @tim-smart! - allow passing structs when encoding schema classes

    The following will no longer throw an error:

    import * as S from "@effect/schema/Schema";
    
    class C extends S.Class<C>()({
      n: S.NumberFromString,
    }) {
      get b() {
        return 1;
      }
    }
    class D extends S.Class<D>()({
      n: S.NumberFromString,
      b: S.number,
    }) {}
    
    console.log(S.encodeSync(D)(new C({ n: 1 })));
    // Output: { b: 1, n: '1' }
    
  • #2123 e787a57 Thanks @gcanti! - Refactor the declare signature to ensure that the decoding and encoding functions do not utilize context.

    As a result, we can relax the signature of the following functions to accept R !== never:

    • Parser.validateSync
    • Parser.validateOption
    • Parser.validateEither
    • Parser.is
    • Parser.asserts
    • Schema.validateSync
    • Schema.validateOption
    • Schema.validateEither
    • Schema.is
    • Schema.asserts

    Additionally, the Class API no longer requires the optional argument disableValidation to be true when R !== never.

  • Updated dependencies [b1163b2, b46b869, de1b226, a663390, ff88f80, 11be07b, c568645, 88835e5, b415577, ff8046f]:

    • effect@2.3.6

0.62.6

Patch Changes

  • #2121 aef2b8b Thanks @gcanti! - Use the identity function in the transformation defining a schema class

  • #2124 7eecb1c Thanks @gcanti! - ParseResult: add missing decode / encode exports

  • Updated dependencies [b881365]:

    • effect@2.3.5

0.62.5

Patch Changes

  • Updated dependencies [17bda66]:
    • effect@2.3.4

0.62.4

Patch Changes

  • #2108 1c6d18b Thanks @gcanti! - Schema: add transformation: false option to pluck.

    Given a schema Schema<A, I, R> and a key K, this function extracts a specific field from the A type, producing a new schema that represents a transformation from the I type to A[K].

    If the option { transformation: false } is provided, the returned schema Schema<A[K], I[K], R> only represents the value of the field without any transformation.

    Example

    import * as S from "@effect/schema/Schema";
    
    // ---------------------------------------------
    // use case: pull out a single field from a
    // struct through a transformation
    // ---------------------------------------------
    
    const mytable = S.struct({
      column1: S.NumberFromString,
      column2: S.number,
    });
    
    // const pullOutColumn1: S.Schema<number, {
    //     readonly column1: string;
    //     readonly column2: number;
    // }, never>
    const pullOutColumn1 = mytable.pipe(S.pluck("column1"));
    
    console.log(
      S.decode(S.array(pullOutColumn1))([
        { column1: "1", column2: 100 },
        { column1: "2", column2: 300 },
      ]),
    );
    // Output: { _id: 'Either', _tag: 'Right', right: [ 1, 2 ] }
    
    // ---------------------------------------------
    // use case: pull out a single field from a
    // struct (no transformation)
    // ---------------------------------------------
    
    // const pullOutColumn1Value: S.Schema<number, string, never>
    const pullOutColumn1Value = mytable.pipe(
      S.pluck("column1", { transformation: false }),
    );
    
    console.log(S.decode(S.array(pullOutColumn1Value))(["1", "2"]));
    // Output: { _id: 'Either', _tag: 'Right', right: [ 1, 2 ] }
    
  • #2110 13d3266 Thanks @gcanti! - make headOr dual

  • #2111 a344b42 Thanks @gcanti! - add support for unions to keyof

0.62.3

Patch Changes

0.62.2

Patch Changes

0.62.1

Patch Changes

  • Updated dependencies [b5a8215]:
    • effect@2.3.1

0.62.0

Minor Changes

  • #2006 9a2d1c1 Thanks @github-actions! - With this change we now require a string key to be provided for all tags and renames the dear old Tag to GenericTag, so when previously you could do:

    import { Effect, Context } from "effect";
    interface Service {
      readonly _: unique symbol;
    }
    const Service = Context.Tag<
      Service,
      {
        number: Effect.Effect<never, never, number>;
      }
    >();
    

    you are now mandated to do:

    import { Effect, Context } from "effect";
    interface Service {
      readonly _: unique symbol;
    }
    const Service = Context.GenericTag<
      Service,
      {
        number: Effect.Effect<never, never, number>;
      }
    >("Service");
    

    This makes by default all tags globals and ensures better debuggaility when unexpected errors arise.

    Furthermore we introduce a new way of constructing tags that should be considered the new default:

    import { Effect, Context } from "effect";
    class Service extends Context.Tag("Service")<
      Service,
      {
        number: Effect.Effect<never, never, number>;
      }
    >() {}
    
    const program = Effect.flatMap(Service, ({ number }) => number).pipe(
      Effect.flatMap((_) => Effect.log(`number: ${_}`)),
    );
    

    this will use "Service" as the key and will create automatically an opaque identifier (the class) to be used at the type level, it does something similar to the above in a single shot.

  • #2006 1a77f72 Thanks @github-actions! - change Effect type parameters order from Effect<R, E, A> to Effect<A, E = never, R = never>

  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch readonlyMapFromSelf, readonlyMap from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema";
    
    S.readonlyMapFromSelf(S.string, S.number);
    S.readonlyMap(S.string, S.number);
    

    Now:

    import * as S from "@effect/schema/Schema";
    
    S.readonlyMapFromSelf({ key: S.string, value: S.number });
    S.readonlyMap({ key: S.string, value: S.number });
    
  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch hashMapFromSelf, hashMap from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema";
    
    S.hashMapFromSelf(S.string, S.number);
    S.hashMap(S.string, S.number);
    

    Now:

    import * as S from "@effect/schema/Schema";
    
    S.hashMapFromSelf({ key: S.string, value: S.number });
    S.hashMap({ key: S.string, value: S.number });
    
  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch causeFromSelf, cause from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema";
    
    S.causeFromSelf(S.string);
    S.causeFromSelf(S.string, S.unknown);
    S.cause(S.string);
    S.cause(S.string, S.unknown);
    

    Now:

    import * as S from "@effect/schema/Schema";
    
    S.causeFromSelf({ error: S.string });
    S.causeFromSelf({ error: S.string, defect: S.unknown });
    S.cause({ error: S.string });
    S.cause({ error: S.string, defect: S.unknown });
    
  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch exitFromSelf, exit from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema";
    
    S.exitFromSelf(S.string, S.number);
    S.exit(S.string, S.number);
    

    Now:

    import * as S from "@effect/schema/Schema";
    
    S.exitFromSelf({ failure: S.string, success: S.number });
    S.exit({ failure: S.string, success: S.number });
    
  • #2006 a34dbdc Thanks @github-actions! - - Schema: change type parameters order from Schema<R, I, A> to Schema<A, I = A, R = never>

    • Serializable: change type parameters order from Serializable<R, I, A> to Serializable<A, I, R>
    • Class: change type parameters order from Class<R, I, A, C, Self, Inherited> to Class<A, I, R, C, Self, Inherited>
    • PropertySignature: change type parameters order from PropertySignature<R, From, FromIsOptional, To, ToIsOptional> to PropertySignature<From, FromIsOptional, To, ToIsOptional, R = never>
  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch eitherFromSelf, either, eitherFromUnion from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema";
    
    S.eitherFromSelf(S.string, S.number);
    S.either(S.string, S.number);
    S.eitherFromUnion(S.string, S.number);
    

    Now:

    import * as S from "@effect/schema/Schema";
    
    S.eitherFromSelf({ left: S.string, right: S.number });
    S.either({ left: S.string, right: S.number });
    S.eitherFromUnion({ left: S.string, right: S.number });
    
  • #2006 02c3461 Thanks @github-actions! - With this change we remove the Data.Data type and we make Equal.Equal & Hash.Hash implicit traits.

    The main reason is that Data.Data<A> was structurally equivalent to A & Equal.Equal but extending Equal.Equal doesn't mean that the equality is implemented by-value, so the type was simply adding noise without gaining any level of safety.

    The module Data remains unchanged at the value level, all the functions previously available are supposed to work in exactly the same manner.

    At the type level instead the functions return Readonly variants, so for example we have:

    import { Data } from "effect";
    
    const obj = Data.struct({
      a: 0,
      b: 1,
    });
    

    will have the obj typed as:

    declare const obj: {
      readonly a: number;
      readonly b: number;
    };
    
  • #2006 9a2d1c1 Thanks @github-actions! - This change enables Effect.serviceConstants and Effect.serviceMembers to access any constant in the service, not only the effects, namely it is now possible to do:

    import { Effect, Context } from "effect";
    
    class NumberRepo extends Context.TagClass("NumberRepo")<
      NumberRepo,
      {
        readonly numbers: Array<number>;
      }
    >() {
      static numbers = Effect.serviceConstants(NumberRepo).numbers;
    }
    
  • #2006 56b8691 Thanks @github-actions! - Fix usage of Schema.TaggedError in combination with Unify.

    When used with Unify we previously had:

    import { Schema } from "@effect/schema";
    import type { Unify } from "effect";
    
    class Err extends Schema.TaggedError<Err>()("Err", {}) {}
    
    // $ExpectType Effect<unknown, unknown, unknown>
    export type IdErr = Unify.Unify<Err>;
    

    With this fix we now have:

    import { Schema } from "@effect/schema";
    import type { Unify } from "effect";
    
    class Err extends Schema.TaggedError<Err>()("Err", {}) {}
    
    // $ExpectType Err
    export type IdErr = Unify.Unify<Err>;
    

Patch Changes

0.61.7

Patch Changes

0.61.6

Patch Changes

0.61.5

Patch Changes

0.61.4

Patch Changes

0.61.3

Patch Changes

0.61.2

Patch Changes

  • #1988 64f710a Thanks @gcanti! - Class constructor: avoid overwriting props with additionalProps, closes #1987

0.61.1

Patch Changes

0.61.0

Minor Changes

  • #1922 62b40e8 Thanks @gcanti! - Refactoring:

    • Schema:
      • refactor Schema.declare API to make it safe
      • add Schema.declare overloads
      • add encodeUnknown* APIs
      • rename parse* APIs to decodeUnknown*
      • symplify brand implementation
      • rename params to annotation in typeId annotation
      • add optional { strict: false } parameter to compose
      • Class
        • rename transform to transformOrFail
        • rename transformFrom to transformOrFailFrom
      • add hashSet and hashSetFromSelf
      • add hashMap and hashMapFromSelf
      • add list and listFromSelf
    • AST:
      • return ParseResult.ParseIssue instead of ParseResult.ParseError in all APIs
      • Declaration
        • split decode into decodeUnknown / encodeUnknown
        • remove type field
    • ParseResult
      • align mapBoth with Effect (i.e. onFailure, onSuccess handlers)
      • add missing Declaration node in ParseIssue
  • #1922 62b40e8 Thanks @gcanti! - add context tracking to Schema, closes #1873

Patch Changes

0.60.7

Patch Changes

0.60.6

Patch Changes

  • Updated dependencies [21b9edd]:
    • effect@2.1.2

0.60.5

Patch Changes

0.60.4

Patch Changes

0.60.3

Patch Changes

0.60.2

Patch Changes

0.60.1

Patch Changes

  • Updated dependencies [f7f19f6]:
    • effect@2.0.5

0.60.0

Minor Changes

  • #1913 b557a10 Thanks @gcanti! - ParseResult refactoring:

    • remove ParseResult type
    • rename mapLeft to mapError
    • rename bimap to mapBoth

Patch Changes

0.59.1

Patch Changes

0.59.0

Minor Changes

  • #1878 c4b84f7 Thanks @gcanti! - Schema: remove from/to API in favour of make in:

    • Equivalence
    • JSONSchema
    • Pretty

Patch Changes

0.58.0

Minor Changes

  • #1877 a904a73 Thanks @gcanti! - Schema: Arbitrary remove from/to API in favour of make

  • #1842 7b2f874 Thanks @fubhy! - Schema: simplify AST.createRefinement return type

  • #1842 7b2f874 Thanks @fubhy! - Schema: refactor ParseResult module:

    • add Union issue, and replace UnionMember with Union
    • add Tuple issue, and replace Index with Tuple
    • add TypeLiteral issue
    • add Transform issue
    • add Refinement issue
    • add ast field to Member
    • rename UnionMember to Member
    • Type: rename expected to ast
    • ParseError replace errors field with error field and refactor parseError constructor accordingly
    • Index replace errors field with error field
    • Key replace errors field with error field
    • Member replace errors field with error field
    • ParseError replace errors field with error field
    • make ParseError a Data.TaggedError
    • Forbidden: add actual field

Patch Changes

0.57.2

Patch Changes

  • Updated dependencies [d5a1949]:
    • effect@2.0.2

0.57.1

Patch Changes

  • Updated dependencies [16bd87d]:
    • effect@2.0.1

0.57.0

Minor Changes

Patch Changes

0.56.1

Patch Changes

  • #684 6b9585b Thanks @patroza! - improve: Actually use Arbitrary interface in to/from/unsafe signature

  • #679 0f8a8f1 Thanks @gcanti! - Schema: add annotations argument to attachPropertySignature

0.56.0

Minor Changes

0.55.0

Minor Changes

  • #649 d80b933 Thanks @gcanti! - Arbitrary: should throw on declarations without annotations

  • #669 294dfad Thanks @gcanti! - Schema: refactor parseJson to replace ParseJson and fromJson

  • #649 d80b933 Thanks @gcanti! - Schema: refactor S.optional API.

    Upgrade Guide:

    • S.optional(schema, { exact: true }) replaces the old S.optional(schema)
    • S.optional(schema, { exact: true, default: () => A }) replaces the old S.optional(schema).withDefault(() => A)
    • S.optional(schema, { exact: true, as: "Option" }) replaces the old S.optional(schema).toOption()
  • #649 d80b933 Thanks @gcanti! - Schema: replace propertySignature constructor with propertySignatureAnnotations combinator

  • #669 294dfad Thanks @gcanti! - Schema: simplify split parameters to only accept separator

  • #669 294dfad Thanks @gcanti! - Schema: remove useless combinators

    • lowercase
    • uppercase
    • trim
    • numberFromString
    • symbolFromString
    • bigintFromString
    • bigintFromNumber
    • secret
    • durationFromHrTime
    • durationFromMillis
    • durationFromNanos
    • uint8ArrayFromNumbers
    • base64
    • base64url
    • hex
    • dateFromString
    • bigDecimalFromNumber
    • bigDecimalFromString
    • not

Patch Changes

0.54.1

Patch Changes

0.54.0

Minor Changes

0.53.3

Patch Changes

0.53.2

Patch Changes

0.53.1

Patch Changes

0.53.0

Minor Changes

Patch Changes

  • #645 ece6128 Thanks @gcanti! - ensure that JSON Schema annotations can be exclusively applied to refinements

0.52.0

Minor Changes

Patch Changes

0.51.5

Patch Changes

  • #629 f690ebe Thanks @gcanti! - Schema: add filter overloading returning Option

    For more complex scenarios, you can return an Option<ParseError> type instead of a boolean. In this context, None indicates success, and Some(error) rejects the input with a specific error

0.51.4

Patch Changes

0.51.3

Patch Changes

0.51.2

Patch Changes

0.51.1

Patch Changes

0.51.0

Minor Changes

Patch Changes

0.50.0

Minor Changes

  • #593 cbc2e3f Thanks @gcanti! - ParseResult: merge failure APIs into fail

  • #607 e85aefb Thanks @gcanti! - Bug Fix: align index signature behaviour to TypeScript

  • #589 3b99569 Thanks @gcanti! - - remove ValidDate (which is just an alias of Date)

    • add DateFromString (decodes from string, output: possibly invalid Date)
  • #593 cbc2e3f Thanks @gcanti! - ParseResult: rename success to succeed (standard naming)

Patch Changes

  • #597 caeed29 Thanks @jessekelly881! - added BigDecimal

  • #585 5b27f03 Thanks @gcanti! - improve JSON Schema output:

    • rename dependencies to $defs
    • remove "type" from const schemas
    • use "oneOf" for enums and add "title"s
    • add support for record(pattern, number)
    • add "$id" and "$comment" properties
    • literals should be converted to enum instead of anyOf, closes #579
  • #603 8e21d7e Thanks @gcanti! - TreeFormatter: enhance formatActual for data types with a custom toString implementation, closes #600

0.49.4

Patch Changes

0.49.3

Patch Changes

0.49.2

Patch Changes

  • #587 64fe91f Thanks @gcanti! - DateFromSelf: its arbitrary should also generate "Invalid Date"s

0.49.1

Patch Changes

0.49.0

Minor Changes

Patch Changes

0.48.4

Patch Changes

0.48.3

Patch Changes

0.48.2

Patch Changes

0.48.1

Patch Changes

0.48.0

Minor Changes

0.47.7

Patch Changes

0.47.6

Patch Changes

0.47.5

Patch Changes

  • #553 522161a Thanks @gcanti! - Fix bug in property signature transformations when used for renaming (old key/value pair was not removed)

0.47.4

Patch Changes

  • #550 5167e2d Thanks @gcanti! - attachPropertySignature: add support for symbols as values

0.47.3

Patch Changes

0.47.2

Patch Changes

0.47.1

Patch Changes

0.47.0

Minor Changes

0.46.4

Patch Changes

0.46.3

Patch Changes

0.46.2

Patch Changes

0.46.1

Patch Changes

0.46.0

Minor Changes

0.45.8

Patch Changes

0.45.7

Patch Changes

0.45.6

Patch Changes

0.45.5

Patch Changes

0.45.4

Patch Changes

0.45.3

Patch Changes

  • #500 e9ff876 Thanks @gcanti! - Arbitrary: remove NaN while generating numeric template literals

0.45.2

Patch Changes

0.45.1

Patch Changes

  • #496 ff360c6 Thanks @gcanti! - Arbitrary: fix issue with generating optional tuple elements

0.45.0

Minor Changes

Patch Changes

0.44.0

Minor Changes

0.43.2

Patch Changes

  • #485 0a20788 Thanks @gcanti! - Arbitrary: use Math.fround when creating number constraints, closes #484

0.43.1

Patch Changes

0.43.0

Minor Changes

0.42.0

Minor Changes

0.41.1

Patch Changes

0.41.0

Minor Changes

0.40.2

Patch Changes

0.40.1

Patch Changes

0.40.0

Minor Changes

0.39.2

Patch Changes

0.39.1

Patch Changes

0.39.0

Minor Changes

0.38.0

Minor Changes

  • #439 2197496 Thanks @gcanti! - Schema: remove *Result APIs

    • decodeResult (use decode instead)
    • encodeResult (use encode instead)
    • parseResult (use parse instead)
    • validateResult (use validate instead)

Patch Changes

  • #447 0252143 Thanks @gcanti! - int filter: use Number.isSafeInteger instead of Number.isInteger

0.37.2

Patch Changes

0.37.1

Patch Changes

0.37.0

Minor Changes

0.36.5

Patch Changes

0.36.4

Patch Changes

  • #434 994a37e Thanks @gcanti! - Exclude property signatures from index signatures validations, fix #433

0.36.3

Patch Changes

0.36.2

Patch Changes

0.36.1

Patch Changes

0.36.0

Minor Changes

0.35.1

Patch Changes

0.35.0

Minor Changes

  • #401 8b1ae6b Thanks @gcanti! - backport AST changes from POC:

    • change decode in Declaration- change decode in Refinement (to filter)
    • remove isReversed from Refinement
    • add transformation to Transform (and remove decode, encode, propertySignatureTransformations)
    • refactor PropertySignature
  • #401 8b1ae6b Thanks @gcanti! - refactor annotations: keys must be symbols

  • #411 2f6c4d1 Thanks @gcanti! - rename symbol to symbolFromSelf and add symbol which decodes/encodes from/to string

  • #401 8b1ae6b Thanks @gcanti! - remove Spread in favour of /data/Types#Simplify

  • #413 20ef377 Thanks @tim-smart! - update /io

  • #401 8b1ae6b Thanks @gcanti! - fix fromBrand definition (self is a Schema<I, A> now instead of Schema)

  • #401 8b1ae6b Thanks @gcanti! - rename bigint to bigintFromSelf and BigintFromString to bigint

  • #401 8b1ae6b Thanks @gcanti! - change transformation display in error messages (from A -> B to A <-> B)

  • #401 8b1ae6b Thanks @gcanti! - move From, To to Schema namespace (conforming to the ecosystem standard)

  • #401 8b1ae6b Thanks @gcanti! - rename transformResult to transformOrFail and change signature (add additional ast parameter to transformations)

Patch Changes

0.34.0

Minor Changes

Patch Changes

0.33.2

Patch Changes

0.33.1

Patch Changes

0.33.0

Minor Changes

Patch Changes

0.32.0

Minor Changes

0.31.0

Minor Changes

0.30.4

Patch Changes

0.30.3

Patch Changes

0.30.2

Patch Changes

0.30.1

Patch Changes

0.30.0

Minor Changes

0.29.1

Patch Changes

0.29.0

Minor Changes

0.28.0

Minor Changes

0.27.0

Minor Changes

0.26.1

Patch Changes

0.26.0

Minor Changes

0.25.0

Minor Changes

0.24.0

Minor Changes

Patch Changes

0.23.0

Minor Changes

0.22.0

Minor Changes

0.21.1

Patch Changes

0.21.0

Minor Changes

0.20.3

Patch Changes

0.20.2

Patch Changes

0.20.1

Patch Changes

0.20.0

Minor Changes

0.19.3

Patch Changes

  • #285 39d3c55 Thanks @gcanti! - AST: memoize createLazy

  • #285 39d3c55 Thanks @gcanti! - Arbitrary: fix maximum call stack size exceeded when producing nested arrays and records that are too deep

0.19.2

Patch Changes

0.19.1

Patch Changes

0.19.0

Minor Changes

0.18.0

Minor Changes

0.17.5

Patch Changes

  • #272 d91a7a7 Thanks @gcanti! - pick / omit: add support for structs with property signature transformations

0.17.4

Patch Changes

0.17.3

Patch Changes

0.17.2

Patch Changes

0.17.1

Patch Changes

  • #256 162e099 Thanks @gcanti! - leverage annotations (e.g. maxLength, int, between) to improve fast-check performance

0.17.0

Minor Changes

0.16.0

Minor Changes

0.15.0

Minor Changes

0.14.1

Patch Changes

0.14.0

Minor Changes

Patch Changes

0.13.1

Patch Changes

  • #234 9ed0ee2 Thanks @gcanti! - attachPropertySignature as PropertySignatureTransformation

0.13.0

Minor Changes

0.12.1

Patch Changes

0.12.0

Minor Changes

0.11.1

Patch Changes

0.11.0

Minor Changes

Patch Changes

0.10.0

Minor Changes

0.9.1

Patch Changes

0.9.0

Minor Changes

0.8.3

Patch Changes

0.8.2

Patch Changes

0.8.1

Patch Changes

0.8.0

Minor Changes

Patch Changes

0.7.1

Patch Changes

0.7.0

Minor Changes

0.6.0

Minor Changes

Patch Changes

0.5.0

Minor Changes

  • #178 f60341f Thanks @gcanti! - merge transformEither and transformEffect into transformResult

0.4.0

Minor Changes

Patch Changes

0.3.1

Patch Changes

0.3.0

Minor Changes

Patch Changes

0.2.1

Patch Changes

0.2.0

Minor Changes

Patch Changes

0.1.0

Minor Changes

Patch Changes

0.0.5

Patch Changes

0.0.4

Patch Changes

  • #115 1555a81 Thanks @gcanti! - Optimize decoding of unions using a heuristic based on literals

0.0.3

Patch Changes

0.0.2

Patch Changes

0.0.1

Patch Changes