299 KiB
@effect/schema
0.75.5
Patch Changes
-
#3792
382556fThanks @gcanti! - resolve parse error when usingpickwith union of class schemas, closes #3751 -
#3790
97cb014Thanks @gcanti! - Equivalence: Fixed a bug related to discriminated tuples.Example:
The following equivalence check was incorrectly returning
false:import * as E from "@effect/schema/Equivalence" import * as S from "@effect/schema/Schema" // Union of discriminated tuples const schema = S.Union( S.Tuple(S.Literal("a"), S.String), S.Tuple(S.Literal("b"), S.Number) ) const equivalence = E.make(schema) console.log(equivalence(["a", "x"], ["a", "x"])) // false
0.75.4
Patch Changes
- Updated dependencies [
61a99b2]:- effect@3.9.2
0.75.3
Patch Changes
-
#3761
360ec14Thanks @gcanti! - Allow Schema.Either to support Schema.Never without type errors, closes #3755.- Updated the type parameters of
formatto extendSchema.Allinstead ofSchema<A, I, R>. - Updated the type parameters of
Schema.EitherFromSelfto extendSchema.Allinstead ofSchema.Any. - Updated the type parameters of
Schema.Eitherto extendSchema.Allinstead ofSchema.Any. - Updated the type parameters of
Schema.EitherFromUnionto extendSchema.Allinstead ofSchema.Any.
- Updated the type parameters of
0.75.2
Patch Changes
-
#3753
f02b354Thanks @gcanti! - Enhanced Error Reporting for Discriminated Union Tuple Schemas, closes #3752Previously, irrelevant error messages were generated for each member of the union. Now, when a discriminator is present in the input, only the relevant member will trigger an error.
Before
import * as Schema from "@effect/schema/Schema" const schema = Schema.Union( Schema.Tuple(Schema.Literal("a"), Schema.String), Schema.Tuple(Schema.Literal("b"), Schema.Number) ).annotations({ identifier: "MyUnion" }) console.log(Schema.decodeUnknownSync(schema)(["a", 0])) /* throws: ParseError: MyUnion ├─ readonly ["a", string] │ └─ [1] │ └─ Expected string, actual 0 └─ readonly ["b", number] └─ [0] └─ Expected "b", actual "a" */After
import * as Schema from "@effect/schema/Schema" const schema = Schema.Union( Schema.Tuple(Schema.Literal("a"), Schema.String), Schema.Tuple(Schema.Literal("b"), Schema.Number) ).annotations({ identifier: "MyUnion" }) console.log(Schema.decodeUnknownSync(schema)(["a", 0])) /* throws: ParseError: MyUnion └─ readonly ["a", string] └─ [1] └─ Expected string, actual 0 */
0.75.1
Patch Changes
-
#3740
3b2ad1dThanks @tim-smart! - revert deno Inspectable changes -
Updated dependencies [
3b2ad1d]:- effect@3.9.1
0.75.0
Minor Changes
Patch Changes
- Updated dependencies [
ff3d1aa,0ba66f2,bf77f51,016f9ad,0779681,534129f,d75140c,be0451c,9237ac6,be0451c,5b36494,c716adb,4986391,d75140c,d1387ae]:- effect@3.9.0
0.74.2
Patch Changes
0.74.1
Patch Changes
-
#3669
734eae6Thanks @gcanti! - Add description annotation to the encoded part of NumberFromString.Before
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.NumberFromString console.log(JSON.stringify(JSONSchema.make(schema), null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string" } */After
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.NumberFromString console.log(JSON.stringify(JSONSchema.make(schema), null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string", "description": "a string that will be parsed into a number" } */ -
#3667
fd83d0eThanks @gcanti! - Remove default json schema annotations from string, number and boolean.Before
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.String.annotations({ examples: ["a", "b"] }) console.log(JSON.stringify(JSONSchema.make(schema), null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string", "description": "a string", "title": "string", "examples": [ "a", "b" ] } */After
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.String.annotations({ examples: ["a", "b"] }) console.log(JSON.stringify(JSONSchema.make(schema), null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string", "examples": [ "a", "b" ] } */ -
#3673
ad7e1deThanks @gcanti! - Add more description annotations. -
#3672
090e41cThanks @gcanti! - JSON Schema: handle refinements where the 'from' part includes a transformation, closes #3662Before
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Date console.log(JSON.stringify(JSONSchema.make(schema), null, 2)) /* throws Error: Missing annotation details: Generating a JSON Schema for this schema requires a "jsonSchema" annotation schema (Refinement): Date */After
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Date console.log(JSON.stringify(JSONSchema.make(schema), null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string", "description": "a string that will be parsed into a Date" } */ -
#3672
090e41cThanks @gcanti! - Add description annotation to the encoded part of DateFromString.Before
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.DateFromString console.log(JSON.stringify(JSONSchema.make(schema), null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string" } */After
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.DateFromString console.log(JSON.stringify(JSONSchema.make(schema), null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string", "description": "a string that will be parsed into a Date" } */ -
Updated dependencies [
4509656]:- effect@3.8.4
0.74.0
Minor Changes
0.73.4
Patch Changes
- Updated dependencies [
bb5ec6b]:- effect@3.8.3
0.73.3
Patch Changes
-
#3635
e6440a7Thanks @gcanti! - Stable filters such asminItems,maxItems, anditemsCountnow generate multiple errors when the 'errors' option is set to 'all', closes #3633Example:
import { ArrayFormatter, Schema } from "@effect/schema" const schema = Schema.Struct({ tags: Schema.Array(Schema.String.pipe(Schema.minLength(2))).pipe( Schema.minItems(3) ) }) const invalidData = { tags: ["AB", "B"] } const either = Schema.decodeUnknownEither(schema, { errors: "all" })( invalidData ) if (either._tag === "Left") { console.log(ArrayFormatter.formatErrorSync(either.left)) /* Output: [ { _tag: 'Type', path: [ 'tags', 1 ], message: 'Expected a string at least 2 character(s) long, actual "B"' }, { _tag: 'Type', path: [ 'tags' ], message: 'Expected an array of at least 3 items, actual ["AB","B"]' } ] */ }Previously, only the issue related to the
[ 'tags', 1 ]path was reported.
0.73.2
Patch Changes
- Updated dependencies [
f0d8ef1]:- effect@3.8.2
0.73.1
Patch Changes
-
#3619
f56ab78Thanks @gcanti! - add Date filters (less than, greater than, between), closes #3606 -
Updated dependencies [
10bf621,ae36fa6]:- effect@3.8.1
0.73.0
Minor Changes
-
#3589
7fdf9d9Thanks @gcanti! - Updates the constraints for members within a union from the more restrictiveSchema.Anyto the more inclusiveSchema.All, closes #3587.Affected APIs include:
Schema.UnionSchema.UndefinedOrSchema.NullOrSchema.NullishOrSchema.optionalAST.Union.makenow retains duplicate members and no longer eliminates theneverKeyword.
Patch Changes
- Updated dependencies [
fcfa6ee,bb9931b,5798f76,5f0bfa1,812a4e8,273565e,569a801,aa1fa53,02f6b06,12b893e,bbad27e,adf7d7a,007289a,42a8f99,eebfd29,040703d]:- effect@3.8.0
0.72.4
Patch Changes
- Updated dependencies [
35a0f81]:- effect@3.7.3
0.72.3
Patch Changes
- #3560
f6acb71Thanks @gcanti! - Enhanced the generation of recursive Arbitraries to prevent infinite nesting, closes #3512
0.72.2
Patch Changes
0.72.1
Patch Changes
0.72.0
Patch Changes
- Updated dependencies [
db89601,2f456cc,8745e41,e557838,d6e7e40,8356321,192f2eb,718cb70,e9d0310,6bf28f7]:- effect@3.7.0
0.71.4
Patch Changes
- Updated dependencies [
e809286]:- effect@3.6.8
0.71.3
Patch Changes
- Updated dependencies [
50ec889]:- effect@3.6.7
0.71.2
Patch Changes
0.71.1
Patch Changes
0.71.0
Minor Changes
-
#3433
c1987e2Thanks @gcanti! - Make json schema output more compatible with Open AI structured output, closes #3432.JSONSchema
- remove
oneOfin favour ofanyOf(e.g. inJsonSchema7object,JsonSchema7empty,JsonSchema7Enums) - remove
constin favour ofenum(e.g. inJsonSchema7Enums) - remove
JsonSchema7Consttype - remove
JsonSchema7OneOftype
AST
- remove
identifierannotation fromSchema.Null - remove
identifierannotation fromSchema.Object
- remove
Patch Changes
-
#3448
1ceed14Thanks @tim-smart! - add Schema.ArrayEnsure & Schema.NonEmptyArrayEnsureThese schemas can be used to ensure that a value is an array, from a value that may be an array or a single value.
import { Schema } from "@effect/schema" const schema = Schema.ArrayEnsure(Schema.String) Schema.decodeUnknownSync(schema)("hello") // => ["hello"] Schema.decodeUnknownSync(schema)(["a", "b", "c"]) // => ["a", "b", "c"] -
Updated dependencies [
8295281,c940df6,00b6c6d,f8d95a6]:- effect@3.6.4
0.70.4
Patch Changes
- Updated dependencies [
04adcac]:- effect@3.6.3
0.70.3
Patch Changes
-
#3430
99ad841Thanks @gcanti! - Fix return types forattachPropertySignaturefunction.This commit addresses an inconsistency in the return types between the curried and non-curried versions of the
attachPropertySignaturefunction. Previously, the curried version returned aSchema, while the non-curried version returned aSchemaClass. -
Updated dependencies [
fd4b2f6]:- effect@3.6.2
0.70.2
Patch Changes
0.70.1
Patch Changes
-
#3347
3dce357Thanks @gcanti! - Enhanced Parsing withTemplateLiteralParser, closes #3307In this update we've introduced a sophisticated API for more refined string parsing:
TemplateLiteralParser. This enhancement stems from recognizing limitations in theSchema.TemplateLiteralandSchema.patternfunctionalities, which effectively validate string formats without extracting structured data.Overview of Existing Limitations
The
Schema.TemplateLiteralfunction, while useful as a simple validator, only verifies that an input conforms to a specific string pattern by converting template literal definitions into regular expressions. Similarly,Schema.patternemploys regular expressions directly for the same purpose. Post-validation, both methods require additional manual parsing to convert the validated string into a usable data format.Introducing TemplateLiteralParser
To address these limitations and eliminate the need for manual post-validation parsing, the new
TemplateLiteralParserAPI has been developed. It not only validates the input format but also automatically parses it into a more structured and type-safe output, specifically into a tuple format.This new approach enhances developer productivity by reducing boilerplate code and simplifying the process of working with complex string inputs.
Example (string based schemas)
import { Schema } from "@effect/schema" // const schema: Schema.Schema<readonly [number, "a", string], `${string}a${string}`, never> const schema = Schema.TemplateLiteralParser( Schema.NumberFromString, "a", Schema.NonEmptyString ) console.log(Schema.decodeEither(schema)("100ab")) // { _id: 'Either', _tag: 'Right', right: [ 100, 'a', 'b' ] } console.log(Schema.encode(schema)([100, "a", "b"])) // { _id: 'Either', _tag: 'Right', right: '100ab' }Example (number based schemas)
import { Schema } from "@effect/schema" // const schema: Schema.Schema<readonly [number, "a"], `${number}a`, never> const schema = Schema.TemplateLiteralParser(Schema.Int, "a") console.log(Schema.decodeEither(schema)("1a")) // { _id: 'Either', _tag: 'Right', right: [ 1, 'a' ] } console.log(Schema.encode(schema)([1, "a"])) // { _id: 'Either', _tag: 'Right', right: '1a' } -
#3346
657fc48Thanks @gcanti! - ImplementDecodingFallbackAnnotationto manage decoding errors.export type DecodingFallbackAnnotation<A> = ( issue: ParseIssue ) => Effect<A, ParseIssue>This update introduces a
decodingFallbackannotation, enabling custom handling of decoding failures in schemas. This feature allows developers to specify fallback behaviors when decoding operations encounter issues.Example
import { Schema } from "@effect/schema" import { Effect, Either } from "effect" // Basic Fallback const schema = Schema.String.annotations({ decodingFallback: () => Either.right("<fallback>") }) console.log(Schema.decodeUnknownSync(schema)("valid input")) // Output: valid input console.log(Schema.decodeUnknownSync(schema)(null)) // Output: <fallback value> // Advanced Fallback with Logging const schemaWithLog = Schema.String.annotations({ decodingFallback: (issue) => Effect.gen(function* () { yield* Effect.log(issue._tag) yield* Effect.sleep(10) return yield* Effect.succeed("<fallback2>") }) }) Effect.runPromise(Schema.decodeUnknown(schemaWithLog)(null)).then(console.log) /* Output: timestamp=2024-07-25T13:22:37.706Z level=INFO fiber=#0 message=Type <fallback2> */
0.70.0
Patch Changes
-
#3380
8135294Thanks @tim-smart! - add schemas for working with the DateTime module -
Updated dependencies [
1e0fe80,8135294,cd255a4,3845646,2d09078,4bce5a0,4ddbff0,e74cc38,bb069b4,cd255a4,7d02174]:- effect@3.6.0
0.69.3
Patch Changes
-
#3359
7c0da50Thanks @gcanti! - AddContextfield toSchemainterface, closes #3356 -
#3363
2fc0ff4Thanks @gcanti! - exportisPropertySignatureguard -
#3357
f262665Thanks @gcanti! - Improve annotation retrieval fromClassAPIs, closes #3348.Previously, accessing annotations such as
identifierandtitlerequired explicit casting of theastfield toAST.Transformation. This update refines the type definitions to reflect thatastis always anAST.Transformation, eliminating the need for casting and simplifying client code.import { AST, Schema } from "@effect/schema" class Person extends Schema.Class<Person>("Person")( { name: Schema.String, age: Schema.Number }, { description: "my description" } ) {} console.log(AST.getDescriptionAnnotation(Person.ast.to)) // { _id: 'Option', _tag: 'Some', value: 'my description' } -
#3343
9bbe7a6Thanks @gcanti! - - addNonEmptyTrimmedStringExample
import { Schema } from "@effect/schema" console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)("")) // Option.none() console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)(" a ")) // Option.none() console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)("a")) // Option.some("a")-
add
OptionFromNonEmptyTrimmedString, closes #3335Example
import { Schema } from "@effect/schema" console.log(Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)("")) // Option.none() console.log( Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)(" a ") ) // Option.some("a") console.log(Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)("a")) // Option.some("a")
-
-
Updated dependencies [
6359644,7f41e42,f566fd1]:- effect@3.5.9
0.69.2
Patch Changes
0.69.1
Patch Changes
- #3333
f241154Thanks @gcanti! - Expose success and failure schemas onTaggedRequestClassinterface, closes #3331
0.69.0
Minor Changes
-
#3227
20807a4Thanks @gcanti! - ## CodemodFor some of the breking changes, a code-mod has been released to make migration as easy as possible.
You can run it by executing:
npx @effect/codemod schema-0.69 src/**/*It might not be perfect - if you encounter issues, let us know! Also make sure you commit any changes before running it, in case you need to revert anything.
Breaking Changes
Schema
-
We've improved the
TaggedRequestAPI to make it more intuitive by grouping parameters into a single object (codmod), closes #3144Before Update
class Sample extends Schema.TaggedRequest<Sample>()( "Sample", Schema.String, // Failure Schema Schema.Number, // Success Schema { id: Schema.String, foo: Schema.Number } // Payload Schema ) {}After Update
class Sample extends Schema.TaggedRequest<Sample>()("Sample", { payload: { id: Schema.String, foo: Schema.Number }, success: Schema.Number, failure: Schema.String }) {} -
change
TaggedRequestClasstype parameters order (swapSuccesswithFailure) -
simplify
TaggedRequest.Any, useTaggedRequest.Allinstead -
To improve clarity, we have renamed
nonEmptyfilter tononEmptyStringandNonEmptyschema toNonEmptyString(codmod), closes #3115 -
The
Recordconstructor now consistently accepts an object argument, aligning it with similar constructors such asMapandHashMap(codmod), closes #2793Before Update
import { Schema } from "@effect/schema" const schema = Schema.Record(Schema.String, Schema.Number)After Update
import { Schema } from "@effect/schema" const schema = Schema.Record({ key: Schema.String, value: Schema.Number }) -
rename
Base64toUint8ArrayFromBase64(codmod) -
rename
Base64UrltoUint8ArrayFromBase64Url(codmod) -
rename
HextoUint8ArrayFromHex(codmod) -
make
defectschema required inExitFromSelf,Exit,CauseFromSelf,CauseFromSelf(codmod) This is for two reasons:- The optionality of
defectcaused inference issues when the schema was declared within a Struct. In such cases, theRtype of the schema was erroneously inferred asunknowninstead ofnever. - In general, schema definitions such as
Schema.ExitFromSelforSchema.Exitshouldn't have a default. The user should actively choose them to avoid hidden behaviors.
- The optionality of
-
rename
CauseDefectUnknowntoDefect(codmod) -
fix
Schema.Voidbehavior: now accepts any value instead of only validatingundefined, closes #3297 -
rename
optionalWithOptionsinterface tooptionalWith -
We've refined the
optionalandpartialAPIs by splitting them into two distinct methods: one without options (optionalandpartial) and another with options (optionalWithandpartialWith). This change resolves issues with previous implementations when used with thepipemethod:Schema.String.pipe(Schema.optional)
ParseResult
Missing: changeastfield fromAST.AnnotatedtoAST.TypeComposite: changeastfield fromAST.AnnotatedtoAST.ASTType: changeastfield fromAST.AnnotatedtoAST.ASTForbidden: changeastfield fromAST.AnnotatedtoAST.AST
AST
-
pass the input of the transformation to
transformandtransformOrFailAPIs -
fix
TemplateLiteralSpan.toStringimplementation by returning both its type and its literalBefore
import { AST } from "@effect/schema" console.log(String(new AST.TemplateLiteralSpan(AST.stringKeyword, "a"))) // ${string}Now
import { AST } from "@effect/schema" console.log(String(new AST.TemplateLiteralSpan(AST.stringKeyword, "a"))) // ${string}a
Serializable
- change
WithResultfields to standard lowercase (Success->success,Failure->failure) - rename
WithResult.ErrortoWithResult.Failure
New Features
Schema
-
add
StringFromBase64transformation -
add
StringFromBase64Urltransformation -
add
StringFromHextransformation -
add
TaggedRequest.All -
Support for extending
Schema.String,Schema.Number, andSchema.Booleanwith refinements has been added:import { Schema } from "@effect/schema" const Integer = Schema.Int.pipe(Schema.brand("Int")) const Positive = Schema.Positive.pipe(Schema.brand("Positive")) // Schema.Schema<number & Brand<"Positive"> & Brand<"Int">, number, never> const PositiveInteger = Schema.asSchema(Schema.extend(Positive, Integer)) Schema.decodeUnknownSync(PositiveInteger)(-1) /* throws ParseError: Int & Brand<"Int"> └─ From side refinement failure └─ Positive & Brand<"Positive"> └─ Predicate refinement failure └─ Expected Positive & Brand<"Positive">, actual -1 */ Schema.decodeUnknownSync(PositiveInteger)(1.1) /* throws ParseError: Int & Brand<"Int"> └─ Predicate refinement failure └─ Expected Int & Brand<"Int">, actual 1.1 */
Serializable
- add
WithResult.SuccessEncoded - add
WithResult.FailureEncoded - add
WithResult.Any - add
WithResult.All - add
asWithResult - add
Serializable.Any - add
Serializable.All - add
asSerializable - add
SerializableWithResult.Any - add
SerializableWithResult.All - add
asSerializableWithResult
-
0.68.27
Patch Changes
-
#3310
99bddcfThanks @fubhy! - Added additional pure annotations to improve tree-shakeability -
#3311
6921c4fThanks @gcanti! - Remove incorrect static override type annotations in class definitions.This will also improve tree-shakeability.
-
Updated dependencies [
3afcc93,99bddcf]:- effect@3.5.7
0.68.26
Patch Changes
-
#3287
f0285d3Thanks @gcanti! - JSON Schema: change default behavior for property signatures containingundefinedChanged the default behavior when encountering a required property signature whose type contains
undefined. Instead of raising an exception,undefinedis now pruned and the field is set as optional.Before
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Struct({ a: Schema.NullishOr(Schema.Number) }) const jsonSchema = JSONSchema.make(schema) console.log(JSON.stringify(jsonSchema, null, 2)) /* throws Error: Missing annotation at path: ["a"] details: Generating a JSON Schema for this schema requires a "jsonSchema" annotation schema (UndefinedKeyword): undefined */Now
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Struct({ a: Schema.NullishOr(Schema.Number) }) const jsonSchema = JSONSchema.make(schema) console.log(JSON.stringify(jsonSchema, null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "required": [], // <=== empty "properties": { "a": { "anyOf": [ { "type": "number" }, { "$ref": "#/$defs/null" } ] } }, "additionalProperties": false, "$defs": { "null": { "const": null } } } */ -
#3291
8ec4955Thanks @gcanti! - remove type-level error message fromoptionalsignature, closes #3290This fix eliminates the type-level error message from the
optionalfunction signature, which was causing issues in generic contexts. -
#3284
3ac2d76Thanks @gcanti! - Fix: Correct Handling of JSON Schema Annotations in RefinementsFixes an issue where the JSON schema annotation set by a refinement after a transformation was mistakenly interpreted as an override annotation. This caused the output to be incorrect, as the annotations were not applied as intended.
Before
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Trim.pipe(Schema.nonEmpty()) const jsonSchema = JSONSchema.make(schema) console.log(JSON.stringify(jsonSchema, null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "minLength": 1 } */Now
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Trim.pipe(Schema.nonEmpty()) const jsonSchema = JSONSchema.make(schema) console.log(JSON.stringify(jsonSchema, null, 2)) /* { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string" } */ -
Updated dependencies [
cc327a1,4bfe4fb,2b14d18]:- effect@3.5.6
0.68.25
Patch Changes
- Updated dependencies [
a9d7800]:- effect@3.5.5
0.68.24
Patch Changes
0.68.23
Patch Changes
-
#3234
edb0da3Thanks @tim-smart! - ensure Schema.TaggedError renders a .cause correctly -
Updated dependencies [
edb0da3,c8d3fb0,dabd028,786b2ab,fc57354]:- effect@3.5.3
0.68.22
Patch Changes
0.68.21
Patch Changes
- Updated dependencies [
55fdd76]:- effect@3.5.1
0.68.20
Patch Changes
- Updated dependencies [
a1f5b83,a1f5b83,a1f5b83,60bc3d0,5ab348f,60bc3d0,3e04bf8,e7fc45f,a1f5b83,4626de5,f01e7db,60bc3d0,79d2d91,ac71f37,8432360,e4bf1bf,13cb861,79d2d91,e7fc45f,9f66825]:- effect@3.5.0
0.68.19
Patch Changes
0.68.18
Patch Changes
-
#3192
5d5cc6cThanks @KhraksMamtsov! - SupportCapitalizeUncapitalizefilters and schemas -
#3148
359ff8aThanks @gcanti! - addSerializable.Serializable.TypeandSerializable.Serializable.Encoded -
#3198
f7534b9Thanks @gcanti! - AddtoStringtoAST.PropertySignatureandAST.IndexSignatureand fix type display for IndexSignature.Before the Change
Previously, when a type mismatch occurred in
Schema.decodeUnknownSync, the error message displayed forIndexSignaturewas not accurately representing the type used. For example:import { Schema } from "@effect/schema" const schema = Schema.Record(Schema.Char, Schema.String) Schema.decodeUnknownSync(schema)({ a: 1 }) /* throws ParseError: { readonly [x: string]: string } └─ ["a"] └─ Expected string, actual 1 */This output incorrectly indicated
[x: string]when the actual index type wasChar.After the Change
The
toStringimplementation now correctly reflects the type used inIndexSignature, providing more accurate and informative error messages:import { Schema } from "@effect/schema" const schema = Schema.Record(Schema.Char, Schema.String) Schema.decodeUnknownSync(schema)({ a: 1 }) /* throws ParseError: { readonly [x: Char]: string } └─ ["a"] └─ Expected string, actual 1 */The updated output now correctly displays
{ readonly [x: Char]: string }, aligning the error messages with the actual data types used in the schema. -
Updated dependencies [
a435e0f,b5554db,a9c4fb3]:- effect@3.4.8
0.68.17
Patch Changes
-
#3166
15967cfThanks @gcanti! - AddfilterEffectAPI, closes #3165The
filterEffectfunction enhances thefilterfunctionality by allowing the integration of effects, thus enabling asynchronous or dynamic validation scenarios. This is particularly useful when validations need to perform operations that require side effects, such as network requests or database queries.Example: Validating Usernames Asynchronously
import { Schema } from "@effect/schema" import { Effect } from "effect" async function validateUsername(username: string) { return Promise.resolve(username === "gcanti") } const ValidUsername = Schema.String.pipe( Schema.filterEffect((username) => Effect.promise(() => validateUsername(username).then((valid) => valid || "Invalid username") ) ) ).annotations({ identifier: "ValidUsername" }) Effect.runPromise(Schema.decodeUnknown(ValidUsername)("xxx")).then( console.log ) /* ParseError: ValidUsername └─ Transformation process failure └─ Invalid username */ -
#3163
2328e17Thanks @gcanti! - Addpickandomitstatic functions toStructinterface, closes #3152.pick
The
pickstatic function available in each struct schema can be used to create a newStructby selecting particular properties from an existingStruct.import { Schema } from "@effect/schema" const MyStruct = Schema.Struct({ a: Schema.String, b: Schema.Number, c: Schema.Boolean }) // Schema.Struct<{ a: typeof Schema.String; c: typeof Schema.Boolean; }> const PickedSchema = MyStruct.pick("a", "c")omit
The
omitstatic function available in each struct schema can be used to create a newStructby excluding particular properties from an existingStruct.import { Schema } from "@effect/schema" const MyStruct = Schema.Struct({ a: Schema.String, b: Schema.Number, c: Schema.Boolean }) // Schema.Struct<{ a: typeof Schema.String; c: typeof Schema.Boolean; }> const PickedSchema = MyStruct.omit("b") -
Updated dependencies [
a5737d6]:- effect@3.4.7
0.68.16
Patch Changes
-
#3143
d006cecThanks @gcanti! - Enhance JSON Schema Support for Refinements in Record Parameters.Enhanced
JSONSchema.maketo properly support refinements as record parameters. Previously, using refinements withSchema.Recordresulted in errors when generating JSON schemas.Before
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Record( Schema.String.pipe(Schema.minLength(1)), Schema.Number ) console.log(JSONSchema.make(schema)) /* throws Error: Unsupported index signature parameter schema (Refinement): a string at least 1 character(s) long */Now
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Record( Schema.String.pipe(Schema.minLength(1)), Schema.Number ) console.log(JSONSchema.make(schema)) /* Output: { '$schema': 'http://json-schema.org/draft-07/schema#', type: 'object', required: [], properties: {}, patternProperties: { '': { type: 'number' } }, propertyNames: { type: 'string', description: 'a string at least 1 character(s) long', minLength: 1 } } */ -
#3149
cb22726Thanks @tim-smart! - add Serializable.WithResult.Success/Error inference helpers -
#3139
e911cfdThanks @gcanti! - Optimize JSON Schema output for homogeneous tuples (such as non empty arrays).This change corrects the JSON Schema generation for
S.NonEmptyArrayto eliminate redundant schema definitions. Previously, the element schema was unnecessarily duplicated under bothitemsandadditionalItems.
0.68.15
Patch Changes
-
#3130
34faeb6Thanks @gcanti! - AddReadonlyMapFromRecordandMapFromRecord, closes #3119- decoding
{ readonly [x: string]: VI }->ReadonlyMap<KA, VA>
- encoding
ReadonlyMap<KA, VA>->{ readonly [x: string]: VI }
import { Schema } from "@effect/schema" const schema = Schema.ReadonlyMapFromRecord({ key: Schema.BigInt, value: Schema.NumberFromString }) const decode = Schema.decodeUnknownSync(schema) const encode = Schema.encodeSync(schema) console.log( decode({ "1": "4", "2": "5", "3": "6" }) ) // Map(3) { 1n => 4, 2n => 5, 3n => 6 } console.log( encode( new Map([ [1n, 4], [2n, 5], [3n, 6] ]) ) ) // { '1': '4', '2': '5', '3': '6' } - decoding
-
Updated dependencies [
5c0ceb0,5c0ceb0,33735b1,5c0ceb0,139d4b3]:- effect@3.4.6
0.68.14
Patch Changes
- #3125
61e5964Thanks @gcanti! - Add support for Union, Suspend, and Refinement as the second argument of extend, closes #3124
0.68.13
Patch Changes
-
#3117
cb76bcbThanks @gcanti! - ModifiedJSONSchema.maketo selectively ignore thetitleanddescriptionfields in schema types such asSchema.String,Schema.Number, andSchema.Boolean, closes #3116Before
import { JSONSchema, Schema as S } from "@effect/schema" const schema = S.Struct({ foo: S.String, bar: S.Number }) console.log(JSONSchema.make(schema)) /* { '$schema': 'http://json-schema.org/draft-07/schema#', type: 'object', required: [ 'foo', 'bar' ], properties: { foo: { type: 'string', description: 'a string', title: 'string' }, bar: { type: 'number', description: 'a number', title: 'number' } }, additionalProperties: false } */Now
import { JSONSchema, Schema as S } from "@effect/schema" const schema = S.Struct({ foo: S.String, bar: S.Number }) console.log(JSONSchema.make(schema)) /* { '$schema': 'http://json-schema.org/draft-07/schema#', type: 'object', required: [ 'foo', 'bar' ], properties: { foo: { type: 'string' }, bar: { type: 'number' } }, additionalProperties: false } */
0.68.12
Patch Changes
-
#3101
d990544Thanks @gcanti! - Generate JSON Schemas correctly for a schema created by extending two refinements using theextendAPI, ensuring their JSON Schema annotations are preserved.Example
import { JSONSchema, Schema } from "@effect/schema" const schema = Schema.Struct({ a: Schema.String }) .pipe(Schema.filter(() => true, { jsonSchema: { a: 1 } })) .pipe( Schema.extend( Schema.Struct({ b: Schema.Number }).pipe(Schema.filter(() => true, { jsonSchema: { b: 2 } })) ) ) console.log(JSONSchema.make(schema)) /* { '$schema': 'http://json-schema.org/draft-07/schema#', type: 'object', required: [ 'a', 'b' ], properties: { a: { type: 'string', description: 'a string', title: 'string' }, b: { type: 'number', description: 'a number', title: 'number' } }, additionalProperties: false, b: 2, a: 1 } */ -
Updated dependencies [
a047af9]:- effect@3.4.5
0.68.11
Patch Changes
-
#3087
d71c192Thanks @gcanti! - Special caseS.parseJsonto generate JSON Schemas by targeting the "to" side of transformations, closes #3086Resolved an issue where
JSONSchema.makeimproperly generated JSON Schemas for schemas defined withS.parseJson(<real schema>). Previously, invokingJSONSchema.makeon these transformed schemas produced a JSON Schema corresponding to a string type rather than the underlying real schema.Before
import { JSONSchema, Schema } from "@effect/schema" // Define a schema that parses a JSON string into a structured object const schema = Schema.parseJson( Schema.Struct({ a: Schema.parseJson(Schema.NumberFromString) // Nested parsing from JSON string to number }) ) console.log(JSONSchema.make(schema)) /* { '$schema': 'http://json-schema.org/draft-07/schema#', '$ref': '#/$defs/JsonString', '$defs': { JsonString: { type: 'string', description: 'a JSON string', title: 'JsonString' } } } */Now
import { JSONSchema, Schema } from "@effect/schema" // Define a schema that parses a JSON string into a structured object const schema = Schema.parseJson( Schema.Struct({ a: Schema.parseJson(Schema.NumberFromString) // Nested parsing from JSON string to number }) ) console.log(JSONSchema.make(schema)) /* { '$schema': 'http://json-schema.org/draft-07/schema#', type: 'object', required: [ 'a' ], properties: { a: { type: 'string', description: 'a string', title: 'string' } }, additionalProperties: false } */ -
Updated dependencies [
72638e3,d7dde2b,9b2fc3b]:- effect@3.4.4
0.68.10
Patch Changes
0.68.9
Patch Changes
- #3074
0b47fdfThanks @gcanti! - Revert the 0.67.22 patch as it is causing issues with other array filters, closes #3073
0.68.8
Patch Changes
-
#3070
192261bThanks @gcanti! - AddrefineTypeIdunique symbol to therefineinterface to ensure correct inference ofFieldsin the Class APIs, closes #3063 -
Updated dependencies [
3da1497]:- effect@3.4.2
0.68.7
Patch Changes
- Updated dependencies [
66a1910]:- effect@3.4.1
0.68.6
Patch Changes
-
#3046
530fa9eThanks @gcanti! - Fix error message display for composite errors whenoverwrite = falseThis commit resolves an issue where the custom message for a struct (or tuple or union) was displayed regardless of whether the validation error was related to the entire struct or just a specific part of it. Previously, users would see the custom error message even when the error only concerned a particular field within the struct and the flag
overwritewas not set totrue.import { Schema, TreeFormatter } from "@effect/schema" import { Either } from "effect" const schema = Schema.Struct({ a: Schema.String }).annotations({ message: () => "custom message" }) const res = Schema.decodeUnknownEither(schema)({ a: null }) if (Either.isLeft(res)) { console.log(TreeFormatter.formatErrorSync(res.left)) // before: custom message // now: { readonly a: string } // └─ ["a"] // └─ Expected string, actual null }
0.68.5
Patch Changes
-
#3043
1d62815Thanks @gcanti! - Addmakeconstructor toClass-based APIs, closes #3042Introduced a
makeconstructor to class-based APIs to facilitate easier instantiation of classes. This method allows developers to create instances of a class without directly using thenewkeyword.Example
import { Schema } from "@effect/schema" class MyClass extends Schema.Class<MyClass>("MyClass")({ someField: Schema.String }) { someMethod() { return this.someField + "bar" } } // Create an instance of MyClass using the make constructor const instance = MyClass.make({ someField: "foo" }) // same as new MyClass({ someField: "foo" }) // Outputs to console to demonstrate that the instance is correctly created console.log(instance instanceof MyClass) // true console.log(instance.someField) // "foo" console.log(instance.someMethod()) // "foobar"
0.68.4
Patch Changes
- Updated dependencies [
c0ce180,61707b6,9c1b5b3,a35faf8,ff73c0c,984d516,8c3b8a2,017e2f9,91bf8a2,c6a4a26]:- effect@3.4.0
0.68.3
Patch Changes
-
#3028
d473800Thanks @gcanti! - Introducing Customizable Parsing Behavior at the Schema Level, closes #3027With this latest update, developers can now set specific parse options for each schema using the
parseOptionsannotation. This flexibility allows for precise parsing behaviors across different levels of your schema hierarchy, giving you the ability to override settings in parent schemas and propagate settings to nested schemas as needed.Here's how you can leverage this new feature:
import { Schema } from "@effect/schema" import { Either } from "effect" const schema = Schema.Struct({ a: Schema.Struct({ b: Schema.String, c: Schema.String }).annotations({ title: "first error only", parseOptions: { errors: "first" } // Only the first error in this sub-schema is reported }), d: Schema.String }).annotations({ title: "all errors", parseOptions: { errors: "all" } // All errors in the main schema are reported }) const result = Schema.decodeUnknownEither(schema)( { a: {} }, { errors: "first" } ) if (Either.isLeft(result)) { console.log(result.left.message) } /* all errors ├─ ["d"] │ └─ is missing └─ ["a"] └─ first error only └─ ["b"] └─ is missing */Detailed Output Explanation:
In this example:
- The main schema is configured to display all errors. Hence, you will see errors related to both the
dfield (since it's missing) and any errors from theasubschema. - The subschema (
a) is set to display only the first error. Although bothbandcfields are missing, only the first missing field (b) is reported.
- The main schema is configured to display all errors. Hence, you will see errors related to both the
0.68.2
Patch Changes
- #3024
eb341b3Thanks @gcanti! - ReplaceTypes.Simplifywith a customSimplifyto restore nice types forpickandomit
0.68.1
Patch Changes
- #3015
b51e266Thanks @gcanti! - - Fix handling ofexactoption overrides inAST.ParseOptionsThis commit resolves a bug affecting theexactoption withinAST.ParseOptions. Previously, the implementation failed to correctly incorporate overrides for theexactsetting, resulting in the parser not respecting the specified behavior in extended configurations.- Improve error messaging in
Pretty.makefor unmatched union schemas
- Improve error messaging in
- Updated dependencies [
6c89408]:- effect@3.3.5
0.68.0
Minor Changes
-
#2906
f6c7977Thanks @gcanti! - ## Refactoring of theParseIssueModelThe
ParseIssuemodel in the@effect/schema/ParseResultmodule has undergone a comprehensive redesign and simplification that enhances its expressiveness without compromising functionality. This section explores the motivation and details of this refactoring.Enhanced
Schema.filterAPIThe
Schema.filterAPI has been improved to support more complex filtering that can involve multiple properties of a struct. This is especially useful for validations that compare two fields, such as ensuring that apasswordfield matches aconfirm_passwordfield, a common requirement in form validations.Previous Limitations:
Previously, while it was possible to implement a filter that compared two fields, there was no straightforward way to attach validation messages to a specific field. This posed challenges, especially in form validations where precise error reporting is crucial.
Example of Previous Implementation:
import { ArrayFormatter, Schema } from "@effect/schema" import { Either } from "effect" const Password = Schema.Trim.pipe(Schema.minLength(1)) const MyForm = Schema.Struct({ password: Password, confirm_password: Password }).pipe( Schema.filter((input) => { if (input.password !== input.confirm_password) { return "Passwords do not match" } }) ) console.log( "%o", Schema.decodeUnknownEither(MyForm)({ password: "abc", confirm_password: "d" }).pipe(Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error))) ) /* { _id: 'Either', _tag: 'Left', left: [ { _tag: 'Type', path: [], message: 'Passwords do not match' } ] } */In this scenario, while the filter functionally works, the lack of a specific error path (
path: []) means errors are not as descriptive or helpful as they could be.Specifying Error Paths
With the new improvements, it's now possible to specify an error path along with the message, which enhances error specificity and is particularly beneficial for integration with tools like
react-hook-form.Updated Implementation Example:
import { ArrayFormatter, Schema } from "@effect/schema" import { Either } from "effect" const Password = Schema.Trim.pipe(Schema.minLength(1)) const MyForm = Schema.Struct({ password: Password, confirm_password: Password }).pipe( Schema.filter((input) => { if (input.password !== input.confirm_password) { return { path: ["confirm_password"], message: "Passwords do not match" } } }) ) console.log( "%o", Schema.decodeUnknownEither(MyForm)({ password: "abc", confirm_password: "d" }).pipe(Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error))) ) /* { _id: 'Either', _tag: 'Left', left: [ { _tag: 'Type', path: [ 'confirm_password' ], message: 'Passwords do not match' } ] } */This modification allows the error to be directly associated with the
confirm_passwordfield, improving clarity for the end-user.Multiple Error Reporting
The refactored API also supports reporting multiple issues at once, which is useful in forms where several validation checks might fail simultaneously.
Example of Multiple Issues Reporting:
import { ArrayFormatter, Schema } from "@effect/schema" import { Either } from "effect" const Password = Schema.Trim.pipe(Schema.minLength(1)) const OptionalString = Schema.optional(Schema.String) const MyForm = Schema.Struct({ password: Password, confirm_password: Password, name: OptionalString, surname: OptionalString }).pipe( Schema.filter((input) => { const issues: Array<Schema.FilterIssue> = [] // passwords must match if (input.password !== input.confirm_password) { issues.push({ path: ["confirm_password"], message: "Passwords do not match" }) } // either name or surname must be present if (!input.name && !input.surname) { issues.push({ path: ["surname"], message: "Surname must be present if name is not present" }) } return issues }) ) console.log( "%o", Schema.decodeUnknownEither(MyForm)({ password: "abc", confirm_password: "d" }).pipe(Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error))) ) /* { _id: 'Either', _tag: 'Left', left: [ { _tag: 'Type', path: [ 'confirm_password' ], message: 'Passwords do not match' }, { _tag: 'Type', path: [ 'surname' ], message: 'Surname must be present if name is not present' } ] } */The new
ParseIssueModelThe
ParseIssuetype has undergone a significant restructuring to improve its expressiveness and simplicity. This new model categorizes issues into leaf and composite types, enhancing clarity and making error handling more systematic.Structure of
ParseIsssueType:export type ParseIssue = // leaf | Type | Missing | Unexpected | Forbidden // composite | Pointer | Refinement | Transformation | CompositeKey Changes in the Model:
-
New Members:
Composite: A new class that aggregates multipleParseIssueinstances.Missing: Identifies when a required element or value is absent.Unexpected: Flags unexpected elements or values in the input.Pointer: Points to the part of the data structure where an issue occurs.
-
Removed Members:
- Previous categories like
Declaration,TupleType,TypeLiteral,Union,Member,Key, andIndexhave been consolidated under theCompositetype for a more streamlined approach.
- Previous categories like
Definition of
Composite:interface Composite { readonly _tag: "Composite" readonly ast: AST.Annotated readonly actual: unknown readonly issues: ParseIssue | NonEmptyReadonlyArray<ParseIssue> readonly output?: unknown }Refined Error Messaging System
We've updated our internal function
getErrorMessageto enhance how error messages are formatted throughout our application. This function constructs an error message that includes the reason for the error, additional details, the path to where the error occurred, and the schema's AST representation if available.Example
import { JSONSchema, Schema } from "@effect/schema" JSONSchema.make(Schema.Struct({ a: Schema.Void })) /* throws: Error: Missing annotation at path: ["a"] details: Generating a JSON Schema for this schema requires a "jsonSchema" annotation schema (VoidKeyword): void */Enhancing Tuples with Element Annotations
Annotations are used to add metadata to tuple elements, which can describe the purpose or requirements of each element more clearly. This can be particularly useful when generating documentation or JSON schemas from your schemas.
import { JSONSchema, Schema } from "@effect/schema" // Defining a tuple with annotations for each coordinate in a point const Point = Schema.Tuple( Schema.element(Schema.Number).annotations({ title: "X", description: "X coordinate" }), Schema.optionalElement(Schema.Number).annotations({ title: "Y", description: "optional Y coordinate" }) ) // Generating a JSON Schema from the tuple console.log(JSONSchema.make(Point)) /* Output: { '$schema': 'http://json-schema.org/draft-07/schema#', type: 'array', minItems: 1, items: [ { type: 'number', description: 'X coordinate', title: 'X' }, { type: 'number', description: 'optional Y coordinate', title: 'Y' } ], additionalItems: false } */Missing messages
You can provide custom messages for missing fields or elements using the new
missingMessageannotation.Example (missing field)
import { Schema } from "@effect/schema" const Person = Schema.Struct({ name: Schema.propertySignature(Schema.String).annotations({ missingMessage: () => "Name is required" }) }) Schema.decodeUnknownSync(Person)({}) /* Output: Error: { readonly name: string } └─ ["name"] └─ Name is required */Example (missing element)
import { Schema } from "@effect/schema" const Point = Schema.Tuple( Schema.element(Schema.Number).annotations({ missingMessage: () => "X coordinate is required" }), Schema.element(Schema.Number).annotations({ missingMessage: () => "Y coordinate is required" }) ) Schema.decodeUnknownSync(Point)([], { errors: "all" }) /* Output: Error: readonly [number, number] ├─ [0] │ └─ X coordinate is required └─ [1] └─ Y coordinate is required */Streamlining Annotations
The individual APIs that were previously used to add annotations to schemas have been removed. This change was made because these individual annotation APIs did not provide significant value and were burdensome to maintain. Instead, you can now use the
annotationsmethod directly or theSchema.annotationsAPI for apipe-able approach.Before
import { Schema } from "@effect/schema" // Example of adding an identifier using a dedicated API const schema = Schema.String.pipe(Schema.identifier("myIdentitifer"))Now
import { Schema } from "@effect/schema" // Directly using the annotations method const schema = Schema.String.annotations({ identifier: "myIdentitifer" }) // or const schema2 = Schema.String.pipe( // Using the annotations function in a pipe-able format Schema.annotations({ identifier: "myIdentitifer" }) )Standardize Error Handling for
*Either,*SyncandassertsAPIsNow the
*SyncandassertsAPIs throw aParseErrorwhile before they was throwing a simpleErrorwith acausecontaining aParseIssueimport { ParseResult, Schema } from "@effect/schema" try { Schema.decodeUnknownSync(Schema.String)(null) } catch (e) { console.log(ParseResult.isParseError(e)) // true } const asserts: (u: unknown) => asserts u is string = Schema.asserts( Schema.String ) try { asserts(null) } catch (e) { console.log(ParseResult.isParseError(e)) // true }List of Changes
AST
- add
MissingMessageAnnotationannotations - add
Type - remove
verboseoption fromtoString()methods
Breaking
- rename
ElementtoOptionalTypeand add anannotationsfield - change
TupleTypedefinition: fromrest: ReadonlyArray<AST>torest: ReadonlyArray<Type> - remove
TemplateLiteral.make
Schema
- add
missingMessageannotation toPropertySignature - add
FilterIssuehelper interface
Breaking
- remove
TupleType.Elementtype - replace
OptionalElementAPI interface withElementAPI interface - remove
PropertySignature.GetToken - remove duplicated annotation APIs
messageidentifiertitledescriptionexamplesdefaultdocumentationjsonSchemaequivalenceconcurrencyconcurrencyparseIssueTitle
- remove
SecretandSecretFromSelf
ParseResult
- add
isParseErrortype guard
Breaking
ParseIssuerefactoring- make
MissingandUnexpectedparse issues - replace
DeclarationwithComposite - remove
Unionin favour ofComposite - remove
TypeLiteralin favour ofComposite - remove
TupleTypein favour ofComposite - remove
Memberclass - merge
KeyandIndexintoPointer Type- change
messagefield fromOption<string>tostring | undefined
- change
Refinement- rename
errorfield toissue
- rename
Transformation- rename
errorfield toissue
- rename
Missing- add
ast: AST.Typefield - add
messagefield - add
actualfield
- add
Unexpected- replace
astfield with amessagefield - add
actualfield
- replace
- make
ParseError- rename
errorproperty toissue
- rename
- remove
missingexport - Standardize Error Handling for
*Either,*SyncandassertsAPIs, closes #2968
-
Patch Changes
- Updated dependencies [
a67b8fe]:- effect@3.3.4
0.67.24
Patch Changes
-
#2997
3b15e1bThanks @gcanti! - Improve error handling (type-level) for improper usage ofoptional, closes #2995This commit addresses concerns raised by users about the confusing behavior when 'optional' is misused in a schema definition. Previously, users experienced unexpected results, such as a schema returning 'Schema.All' when 'optional' was used incorrectly, without clear guidance on the correct usage or error messages.
Changes:
- Enhanced the 'optional' method to return a descriptive type-level error when used incorrectly, helping users identify and correct their schema definitions.
- Updated the
Schema.optional()implementation to check its context within a pipeline and ensure it is being used correctly. - Added unit tests to verify that the new error handling works as expected and to ensure that correct usage does not affect existing functionality.
-
#2994
3a750b2Thanks @gcanti! - Exposeexactoption for strict decoding on missing properties, closes #2993This commit addresses an issue where users encountered unexpected decoding behaviors, specifically regarding how undefined values and missing properties are handled. The default behavior of the
@effect/schemalibrary treats missing properties asundefinedduring decoding, which can lead to confusion when stricter validation is expected.Changes:
- Exposed an internal configuration option
exțact(default:false), which when set totrue, enforces strict decoding that will error on missing properties instead of treating them asundefined. - Updated documentation to clearly outline the default and strict decoding behaviors, providing users with guidance on how to enable strict validation.
- Exposed an internal configuration option
-
Updated dependencies [
06ede85,7204ca5]:- effect@3.3.3
0.67.23
Patch Changes
-
#2991
2ee4f2bThanks @gcanti! - RemoveSimplifyfromextend,pick,omit,pluckAPIs, closes #2989, #2990 -
#2971
9b3b4acThanks @gcanti! - AddSchema.NonEmptyChunkFromSelfandSchema.NonEmptyChunk, closes #2961 -
Updated dependencies [
3572646,1aed347,df4bf4b,f085f92]:- effect@3.3.2
0.67.22
Patch Changes
-
#2955
d79ca17Thanks @gcanti! - TheminItemsfilter now checks for an invalid argument (n < 1) and, when valid, refines the type toNonEmptyReadonlyArray<A>. -
Updated dependencies [
eb98c5b,184fed8,6068e07,3a77e20]:- effect@3.3.1
0.67.21
Patch Changes
- #2837
67f160aThanks @KhraksMamtsov! - Added two related schemasRedactedandRedactedFromSelfSecretandSecretFromSelfmarked as deprecated - Updated dependencies [
1f4ac00,9305b76,0f40d98,b761ef0,b53f69b,0f40d98,5bd549e,67f160a]:- effect@3.3.0
0.67.20
Patch Changes
-
#2926
4c6bc7fThanks @gcanti! - AddpropertyOrderoption toParseOptionsto control the order of keys in the output, closes #2925.The
propertyOrderoption provides control over the order of object fields in the output. This feature is particularly useful when the sequence of keys is important for the consuming processes or when maintaining the input order enhances readability and usability.By default, the
propertyOrderoption is set to"none". This means that the internal system decides the order of keys to optimize parsing speed. The order of keys in this mode should not be considered stable, and it's recommended not to rely on key ordering as it may change in future updates without notice.Setting
propertyOrderto"input"ensures that the keys are ordered as they appear in the input during the decoding/encoding process.Example (Synchronous Decoding)
import { Schema } from "@effect/schema" const schema = Schema.Struct({ a: Schema.Number, b: Schema.Literal("b"), c: Schema.Number }) // Decoding an object synchronously without specifying the property order console.log(Schema.decodeUnknownSync(schema)({ b: "b", c: 2, a: 1 })) // Output decided internally: { b: 'b', a: 1, c: 2 } // Decoding an object synchronously while preserving the order of properties as in the input console.log( Schema.decodeUnknownSync(schema)( { b: "b", c: 2, a: 1 }, { propertyOrder: "original" } ) ) // Output preserving input order: { b: 'b', c: 2, a: 1 }Example (Asynchronous Decoding)
import { ParseResult, Schema } from "@effect/schema" import type { Duration } from "effect" import { Effect } from "effect" // Function to simulate an asynchronous process within the schema const effectify = (duration: Duration.DurationInput) => Schema.Number.pipe( Schema.transformOrFail(Schema.Number, { decode: (x) => Effect.sleep(duration).pipe(Effect.andThen(ParseResult.succeed(x))), encode: ParseResult.succeed }) ) // Define a structure with asynchronous behavior in each field const schema = Schema.Struct({ a: effectify("200 millis"), b: effectify("300 millis"), c: effectify("100 millis") }).annotations({ concurrency: 3 }) // Decoding data asynchronously without preserving order Schema.decode(schema)({ a: 1, b: 2, c: 3 }) .pipe(Effect.runPromise) .then(console.log) // Output decided internally: { c: 3, a: 1, b: 2 } // Decoding data asynchronously while preserving the original input order Schema.decode(schema)({ a: 1, b: 2, c: 3 }, { propertyOrder: "original" }) .pipe(Effect.runPromise) .then(console.log) // Output preserving input order: { a: 1, b: 2, c: 3 }
0.67.19
Patch Changes
-
#2916
cd7496bThanks @gcanti! - Add support forAST.LiteralinSchema.TemplateLiteral, closes #2913 -
#2915
349a036Thanks @gcanti! - Align constructors arguments:- Refactor
Classinterface to accept options for disabling validation - Refactor
TypeLiteralinterface to accept options for disabling validation - Refactor
refineinterface to accept options for disabling validation - Refactor
BrandSchemainterface to accept options for disabling validation
Example
import { Schema } from "@effect/schema" const BrandedNumberSchema = Schema.Number.pipe( Schema.between(1, 10), Schema.brand("MyNumber") ) BrandedNumberSchema.make(20, { disableValidation: true }) // Bypasses validation and creates the instance without errors - Refactor
-
Updated dependencies [
8c5d280,6ba6d26,3f28bf2,5817820]:- effect@3.2.9
0.67.18
Patch Changes
0.67.17
Patch Changes
-
#2892
d9d22e7Thanks @gcanti! - Schema- add
propertySignatureAPI interface (with afromproperty) - extend
optionalAPI interface with afromproperty - extend
optionalWithOptionsAPI interface with afromproperty
- add
-
#2901
3c080f7Thanks @gcanti! - make theAST.TemplateLiteralconstructor public -
#2901
3c080f7Thanks @gcanti! - add support for string literals toSchema.TemplateLiteralandTemplateLiteralAPI interface.Before
import { Schema } from "@effect/schema" // `https://${string}.com` | `https://${string}.net` const MyUrl = Schema.TemplateLiteral( Schema.Literal("https://"), Schema.String, Schema.Literal("."), Schema.Literal("com", "net") )Now
import { Schema } from "@effect/schema" // `https://${string}.com` | `https://${string}.net` const MyUrl = Schema.TemplateLiteral( "https://", Schema.String, ".", Schema.Literal("com", "net") ) -
#2905
7d6d875Thanks @gcanti! - add support for unions torename, closes #2904 -
#2897
70cda70Thanks @gcanti! - AddencodedBoundSchemaAPI.The
encodedBoundSchemafunction is similar toencodedSchemabut preserves the refinements up to the first transformation point in the original schema.Function Signature:
export const encodedBoundSchema = <A, I, R>(schema: Schema<A, I, R>): Schema<I>The term "bound" in this context refers to the boundary up to which refinements are preserved when extracting the encoded form of a schema. It essentially marks the limit to which initial validations and structure are maintained before any transformations are applied.
Example Usage:
import { Schema } from "@effect/schema" const schema = Schema.Struct({ foo: Schema.String.pipe(Schema.minLength(3), Schema.compose(Schema.Trim)) }) // The resultingEncodedBoundSchema preserves the minLength(3) refinement, // ensuring the string length condition is enforced but omits the Trim transformation. const resultingEncodedBoundSchema = Schema.encodedBoundSchema(schema) // resultingEncodedBoundSchema is the same as: Schema.Struct({ foo: Schema.String.pipe(Schema.minLength(3)) })In the provided example:
- Initial Schema: The schema for
fooincludes a refinement to ensure strings have a minimum length of three characters and a transformation to trim the string. - Resulting Schema:
resultingEncodedBoundSchemamaintains theminLength(3)condition, ensuring that this validation persists. However, it excludes the trimming transformation, focusing solely on the length requirement without altering the string's formatting.
- Initial Schema: The schema for
-
Updated dependencies [
fb91f17]:- effect@3.2.8
0.67.16
Patch Changes
-
#2890
5745886Thanks @gcanti! - Fix constructor type inference for classes with all optional fields, closes #2888This fix addresses an issue where TypeScript incorrectly inferred the constructor parameter type as an empty object {} when all class fields were optional. Now, the constructor properly recognizes arguments as objects with optional fields (e.g., { abc?: number, xyz?: number }).
-
Updated dependencies [
6801fca]:- effect@3.2.7
0.67.15
Patch Changes
-
#2882
e2740fcThanks @gcanti! - addrequiredToOptionalfunction toSchemamodule, closes #2881 -
#2880
60fe3d5Thanks @gcanti! - add missingmakePropertySignatureconstructor -
Updated dependencies [
cc8ac50]:- effect@3.2.6
0.67.14
Patch Changes
-
#2851
c5846e9Thanks @gcanti! - AddtagandTaggedStructconstructors.In TypeScript tags help to enhance type discrimination and pattern matching by providing a simple yet powerful way to define and recognize different data types.
What is a Tag?
A tag is a literal value added to data structures, commonly used in structs, to distinguish between various object types or variants within tagged unions. This literal acts as a discriminator, making it easier to handle and process different types of data correctly and efficiently.
Using the
tagConstructorThe
tagconstructor is specifically designed to create a property signature that holds a specific literal value, serving as the discriminator for object types. Here's how you can define a schema with a tag:import { Schema } from "@effect/schema" const User = Schema.Struct({ _tag: Schema.tag("User"), name: Schema.String, age: Schema.Number }) assert.deepStrictEqual(User.make({ name: "John", age: 44 }), { _tag: "User", name: "John", age: 44 })In the example above,
Schema.tag("User")attaches a_tagproperty to theUserstruct schema, effectively labeling objects of this struct type as "User". This label is automatically applied when using themakemethod to create new instances, simplifying object creation and ensuring consistent tagging.Simplifying Tagged Structs with
TaggedStructThe
TaggedStructconstructor streamlines the process of creating tagged structs by directly integrating the tag into the struct definition. This method provides a clearer and more declarative approach to building data structures with embedded discriminators.import { Schema } from "@effect/schema" const User = Schema.TaggedStruct("User", { name: Schema.String, age: Schema.Number }) // `_tag` is optional const userInstance = User.make({ name: "John", age: 44 }) assert.deepStrictEqual(userInstance, { _tag: "User", name: "John", age: 44 })Multiple Tags
While a primary tag is often sufficient, TypeScript allows you to define multiple tags for more complex data structuring needs. Here's an example demonstrating the use of multiple tags within a single struct:
import { Schema } from "@effect/schema" const Product = Schema.TaggedStruct("Product", { category: Schema.tag("Electronics"), name: Schema.String, price: Schema.Number }) // `_tag` and `category` are optional const productInstance = Product.make({ name: "Smartphone", price: 999 }) assert.deepStrictEqual(productInstance, { _tag: "Product", category: "Electronics", name: "Smartphone", price: 999 })This example showcases a product schema that not only categorizes each product under a general tag (
"Product") but also specifies a category tag ("Electronics"), enhancing the clarity and specificity of the data model.
0.67.13
Patch Changes
0.67.12
Patch Changes
-
#2814
f8038caThanks @gcanti! - Add support for Enums in Record, closes #2811 -
#2816
e376641Thanks @gcanti! - Add support forConfigmodule, closes #2346 -
Updated dependencies [
1af94df,e313a01]:- effect@3.2.4
0.67.11
Patch Changes
0.67.10
Patch Changes
-
#2794
78ffc27Thanks @gcanti! - addoptionalandoptionalWithOptionsAPI interfaces -
Updated dependencies [
5d9266e,9f8122e,6a6f670]:- effect@3.2.2
0.67.9
Patch Changes
- #2775
5432fffThanks @KhraksMamtsov! - fixpatternin JSONSchemaAnnotation ofTrimmedschema
0.67.8
Patch Changes
- Updated dependencies [
c1e991d]:- effect@3.2.1
0.67.7
Patch Changes
- Updated dependencies [
146cadd,7135748,7135748,963b4e7,64c9414,7135748,2cbb76b,870c5fa,7135748,64c9414]:- effect@3.2.0
0.67.6
Patch Changes
-
#2772
17da864Thanks @vinassefranche! - Add onNoneEncoding for Schema.optional used with {as: "Option"} -
#2769
ff0efa0Thanks @TylorS! - Point-free usage of Schema.make constructors -
Updated dependencies [
17fc22e,810f222,596aaea]:- effect@3.1.6
0.67.5
Patch Changes
0.67.4
Patch Changes
-
#2756
ee08593Thanks @gcanti! - Improving Predicate Usability ofSchema.isBefore this update, the
Schema.is(mySchema)function couldn't be easily used as a predicate or refinement in common array methods likefilterorfind. This was because the function's signature was:(value: unknown, overrideOptions?: AST.ParseOptions) => value is AMeanwhile, the function expected by methods like
filterhas the following signature:(value: unknown, index: number) => value is ATo make
Schema.iscompatible with these array methods, we've adjusted the function's signature to acceptnumberas 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 AHere'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
da6d7d8Thanks @gcanti! -pick: do not return aComposeTransformationif 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
89a3afbThanks @gcanti! - addcausein errors thrown byasserts, closes #2729 -
#2741
992c8e2Thanks @gcanti! -Schema.optional: thedefaultoption 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
d7e4997Thanks @gcanti! - ## Simplifying Type ExtractionWhen 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
Schemainterface. Now, you can easily accessTypeandEncodeddirectly from a schema without the need forSchema.Schema.TypeandSchema.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.EncodedDefault 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, andbrands.Note
Default constructors associated with a schema
Schema<A, I, R>are specifically related to theAtype, not theItype.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
MyBrandexample, the return type of the constructor isnumber & Brand<"MyNumber">, indicating that the resulting value is anumberwith 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.withConstructorDefaultcombinator 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
timestampfield varies.Defaults can also be applied using the
ClassAPI: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
ClassAPI: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.withDecodingDefaultcombinator 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
overridewith the valuetrue. 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
overrideflag totrue: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
stringornumber), 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
filterAPI. This allows you to access the refined schema using the exposedfromfield: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.aThe signature of the
filterfunction has been simplified and streamlined to be more ergonomic when setting a default message. In the new signature offilter, the type of the predicate passed as an argument is as follows:predicate: (a: A, options: ParseOptions, self: AST.Refinement) => undefined | boolean | string | ParseResult.ParseIssuewith the following semantics:
truemeans the filter is successful.falseorundefinedmeans the filter fails and no default message is set.stringmeans the filter fails and the returned string is used as the default message.ParseIssuemeans 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
makeAPI 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
foofield, correctly modeled with a constraint ("minLength": 2) - a required numeric
barfield
This happens because in the previous version, the
JSONSchema.makeAPI by default produces a JSON Schema for theTypepart 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": 2constraint, which is the useful part of precisely defining our schemas using refinements.After
Now, let's see what
JSONSchema.makeAPI 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
extendto support refinements andsuspended schemasNow
extendsupports 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.toStringto honorreadonlymodifiers - improve
AST.toStringfor refinements
Schema
- return
BrandSchemafromfromBrand - add
SchemaClassinterface - add
AnnotableClassinterface extend: add support for refinements, closes #2642- add
patternjson schema annotation toTrimmed - add
parseNumbernumber transformation - add
TaggedClassapi interface (exposing a_tagfield) - add
TaggedErrorClassapi interface (exposing a_tagfield) - add
TaggedRequestClassapi interface (exposing a_tagfield) - add
DateFromNumberschema - add
Schema.Schema.AsSchematype-level helper to facilitate working with generic schemas.
Other Breaking Changes
- move
fast-checkfrompeerDependenciestodependencies
AST
-
add
pathargument toCompilerAPI-export type Compiler<A> = (ast: AST) => A +export type Compiler<A> = (ast: AST, path: ReadonlyArray<PropertyKey>) => A -
remove
hashfunction, 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
JsonSchemaAnnotationsexport interface JsonSchemaAnnotations { title?: string description?: string default?: unknown examples?: Array<unknown> }
Schema
-
replace numerous API interfaces with class-based schema definitions
-
rename
$ArrayAPI interface to `Array# @effect/schema -
rename
$RecordAPI interface to `Record# @effect/schema -
rename
$ReadonlyMapAPI interface to `ReadonlyMap# @effect/schema -
rename
$MapAPI interface to `Map# @effect/schema -
rename
$ReadonlySetAPI interface to `ReadonlySet# @effect/schema -
rename
$SetAPI interface to `Set# @effect/schema -
remove
asBrandSchemautility -
change
BrandSchemainterface -
remove
hashfunctionfrom
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 itsmakeconstructor:Before
import { Schema } from "@effect/schema" const UserId = Schema.Number.pipe(Schema.brand("UserId")) console.log(UserId(1)) // 1Now
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
121d6d9Thanks @gcanti! - Class API: avoid access before initialization when creating a class with suspended props, closes #2709
0.66.14
Patch Changes
-
#2679
2e1cdf6Thanks @tim-smart! - ensure all type ids are annotated withunique symbol -
Updated dependencies [
2e1cdf6]:- effect@3.1.2
0.66.13
Patch Changes
- Updated dependencies [
e5e56d1]:- effect@3.1.1
0.66.12
Patch Changes
0.66.11
Patch Changes
-
#2656
557707bThanks @tim-smart! - update dependencies -
Updated dependencies [
557707b,f4ed306,661004f,e79cb83]:- effect@3.0.8
0.66.10
Patch Changes
- Updated dependencies [
18de56b]:- effect@3.0.7
0.66.9
Patch Changes
-
#2626
027418eThanks @fubhy! - Reintroduce customNoInfertype -
#2631
8206529Thanks @gcanti! - add support for data-last subtype overloads incomposeBefore
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 errorNow
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
dd41c6cThanks @gcanti! - Remove excessive constraint from the pipeable overload ofattachPropertySignature, closes #2593 -
Updated dependencies [
9a24667]:- effect@3.0.4
0.66.6
Patch Changes
-
#2586
9dfc156Thanks @gcanti! - remove non-tree-shakable compiler dependencies from the Schema module:- remove dependency from
Arbitrarycompiler - remove dependency from
Equivalencecompiler - remove dependency from
Prettycompiler
- remove dependency from
-
#2583
80271bdThanks @suddenlyGiovanni! - - Fixed a typo in the JSDoc comment of theBooleanFromUnknownboolean constructors inSchema.ts- Fixed a typo in the JSDoc comment of the
splitstring transformations combinator inSchema.ts
- Fixed a typo in the JSDoc comment of the
-
#2585
e4ba97dThanks @gcanti! - JSONSchema: rearrange handling of surrogate annotations to occur after JSON schema annotations
0.66.5
Patch Changes
-
#2582
b3fe829Thanks @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
a58b7deThanks @gcanti! - Fix formatting for Class and brands AST. -
#2579
d90e8c3Thanks @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 annotationNow
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
773b8e0Thanks @gcanti! - partial / required: add support for renaming property keys in property signature transformationsBefore
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 transformationsNow
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
-
Updated dependencies [
2cecdbd]:- effect@3.0.2
0.66.1
Patch Changes
-
#2550
b2b5d66Thanks @gcanti! - FixtransformOrFailandtransformOrFailFromsignatures in the exportedClassinterface by adding the missingannotationsoptional argument -
#2555
8edaccaThanks @tim-smart! - prevent use ofArrayas import name to solve bundler issues -
Updated dependencies [
3da0cfa,570e8d8,8edacca]:- effect@3.0.1
0.66.0
Minor Changes
-
#2207
5a2314bThanks @github-actions! - replace use ofunitterminology withvoidFor all the data types.
Effect.unit // => Effect.void Stream.unit // => Stream.void // etc -
#2207
2fb7d9cThanks @github-actions! - Release Effect 3.0 🎉
Patch Changes
-
#2207
9aeae46Thanks @github-actions! - Removed the customSimplifytype that was previously introduced to address a bug in TypeScript 5.0 -
#2531
e542371Thanks @gcanti! - addcomposeoverloads to enable a subtyping relationship in both directions betweenCandB. -
#2529
78b767cThanks @fubhy! - RenamedReadonlyArrayandReadonlyRecordmodules for better discoverability. -
Updated dependencies [
1b5f0c7,d50a652,9a3bd47,be9d025,78b767c,1499974,1b5f0c7,5c2b561,a18f594,1499974,2f96d93,5a2314b,271b79f,1b5f0c7,2fb7d9c,53d1c2a,e7e1bbe,10c169e,6424181]:- effect@3.0.0
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
0aee906Thanks @mikearnaldi! - Re-export FastCheck to simplify usage and to resolve long term issues with ESM/CJS -
#2440
b3acf47Thanks @gcanti! - ##ASTmodule- rename
isTransformtoisTransformation
ParseResultmodule- rename
TupletoTupleType
TreeFormattermodule- rename
formatIssuetoformatIssueSync(This change was made to maintain consistency in API naming across all decoding and encoding APIs.) - rename
formatIssueEffecttoformatIssue - rename
formatErrortoformatErrorSync - rename
formatErrorEffecttoformatError
ArrayFormattermodule- rename
formatIssuetoformatIssueSync - rename
formatIssueEffecttoformatIssue - rename
formatErrortoformatErrorSync - rename
formatErrorEffecttoformatError
Schemamodule- consolidate
transformandtransformOrFailparameters into anoptionsobject, #2434 - consolidate
Class.transformOrFailandClass.transformOrFailFromparameters into anoptionsobject - consolidate
declareparameters into anoptionsobject - consolidate
optionalToRequiredparameters into anoptionsobject - consolidate
optionalToOptionalparameters into anoptionsobject - Removed
negateBigDecimalfunction (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,negateBigDecimalwas removed)
Renaming
- rename
uniqueSymbolFromSelftoUniqueSymbolFromSelf - rename
undefinedtoUndefined - rename
voidtoVoid - rename
nulltoNull - rename
nevertoNever - rename
unknowntoUnknown - rename
anytoAny - rename
stringtoString - rename
numbertoNumber - rename
booleantoBoolean - rename
/bigint/igtoBigInt - rename
symbolFromSelftoSymbolFromSelf - rename
objecttoObject - rename
uniontoUnion - rename
nullabletoNullOr - rename
orUndefinedtoUndefinedOr - rename
nullishtoNullishOr - rename
tupletoTuple - rename
arraytoArray - rename
nonEmptyArraytoNonEmptyArray - rename
structtoStruct - rename
recordtoRecord - rename
symboltoSymbol - rename
optionFromSelftoOptionFromSelf - rename
optiontoOption - rename
optionFromNullabletoOptionFromNullOr - rename
optionFromNullishtoOptionFromNullishOr - rename
optionFromOrUndefinedtoOptionFromUndefinedOr - rename
eitherFromSelftoEitherFromSelf - rename
eithertoEither - rename
eitherFromUniontoEitherFromUnion - rename
readonlyMapFromSelftoReadonlyMapFromSelf - rename
mapFromSelftoMapFromSelf - rename
readonlyMaptoReadonlyMap - rename
maptoMap - rename
readonlySetFromSelftoReadonlySetFromSelf - rename
setFromSelftoSetFromSelf - rename
readonlySettoReadonlySet - rename
settoSet - rename
chunkFromSelftoChunkFromSelf - rename
chunktoChunk - rename
dataFromSelftoDataFromSelf - rename
datatoData - rename
causeFromSelftoCauseFromSelf - rename
causeDefectUnknowntoCauseDefectUnknown - rename
causetoCause - rename
exitFromSelftoExitFromSelf - rename
exittoExit - rename
hashSetFromSelftoHashSetFromSelf - rename
hashSettoHashSet - rename
hashMapFromSelftoHashMapFromSelf - rename
hashMaptoHashMap - rename
listFromSelftoListFromSelf - rename
listtoList - rename
sortedSetFromSelftoSortedSetFromSelf - rename
sortedSettoSortedSet - rename
literaltoLiteral - rename
enumstoEnums - rename
templateLiteraltoTemplateLiteral
- rename
-
#2511
0d3231aThanks @gcanti! - makeAST.pickcorrectly handle key renames -
#2508
c22b019Thanks @mikearnaldi! - Rename Arbitrary.Arbitrary to Arbitrary.LazyArbitrary, rename Arbitrary.make to Arbitrary.makeLazy and introduce Arbitrary.makeBefore
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
-
#2496
4c37001Thanks @gcanti! - fixexitFromSelfdescription -
#2495
8a69b4eThanks @gcanti! - fixeitherFromSelfdescription annotation -
Updated dependencies [
41c8102,776ef2b,217147e,90776ec,8709856,232c353,0ca835c,8709856,e983740,e3e0924]:- effect@2.4.19
0.64.20
Patch Changes
-
#2483
42b3651Thanks @gcanti! - AddParseIssueTitleannotation, closes #2482When a decoding or encoding operation fails, it's useful to have additional details in the default error message returned by
TreeFormatterto 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 anidfield. TheParseIssueTitleannotation facilitates this kind of analysis during error handling.The type of the annotation is:
export type ParseIssueTitleAnnotation = ( issue: ParseIssue ) => string | undefinedIf you set this annotation on a schema and the provided function returns a
string, then that string is used as the title byTreeFormatter, unless amessageannotation (which has the highest priority) has also been set. If the function returnsundefined, then the default title used byTreeFormatteris determined with the following priorities:identifiertitledescriptionast.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
parseIssueTitleannotation helps provide meaningful error messages when decoding fails.
0.64.19
Patch Changes
-
#2471
58f66feThanks @gcanti! - Class API: Added defaulttitleannotation 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
3cad21dThanks @gcanti! -lengthnow allows expressing a rangeExample
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
- Updated dependencies [
8fdfda6,607b2e7,8fdfda6,8206caf,7ddd654,7ddd654,8fdfda6,f456ba2]:- effect@2.4.17
0.64.17
Patch Changes
-
#2446
62a7f23Thanks @gcanti! - ParseResult: Addoutputfield toTupleTypeandTypeLiteral. 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
7cc2b41Thanks @jessekelly881! - added Schema.BooleanFromUnknown -
#2456
8b46fdeThanks @gcanti! - addset,setFromSelf,map,mapFromSelf -
Updated dependencies [
5170ce7]:- effect@2.4.16
0.64.16
Patch Changes
-
#2428
a31917aThanks @gcanti! - exportnullfrom the AST module -
#2436
4cd2bedThanks @patroza! - fix: Schema JSDOC and editor click-follow for fields on struct and class -
#2442
6cc6267Thanks @gcanti! - Enums are now exposed under anenumsproperty 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
-
#2424
5ded019Thanks @gcanti! - corrected theoptionalsignature to exclude invalid options -
Updated dependencies [
d7688c0,b3a4fac]:- effect@2.4.15
0.64.14
Patch Changes
-
Updated dependencies [
6180c0c]:- effect@2.4.14
0.64.13
Patch Changes
0.64.12
Patch Changes
-
#2359
9392de6Thanks @tim-smart! - preserve defect information in Cause.Die -
#2385
3307729Thanks @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
9392de6Thanks @tim-smart! - use provided message in Schema.TaggedError .toString -
#2385
3307729Thanks @tim-smart! - update typescript to 5.4 -
#2396
d17a427Thanks @sukovanej! - Fix extend with nested union. -
Updated dependencies [
3307729]:- effect@2.4.12
0.64.11
Patch Changes
-
#2384
2f488c4Thanks @tim-smart! - update dependencies -
Updated dependencies [
2f488c4,37ca592,317b5b8]:- effect@2.4.11
0.64.10
Patch Changes
0.64.9
Patch Changes
-
#2370
dc7e497Thanks @leonitousconforti! - Template literal regex escape special characters -
#2366
ffaf7c3Thanks @gcanti! - ImproveAlltypes to encompass additionalany/nevercombinations.
0.64.8
Patch Changes
0.64.7
Patch Changes
- Updated dependencies [
71fd528]:- effect@2.4.9
0.64.6
Patch Changes
-
#2347
595140aThanks @gcanti! - add backBrandSchemaand introduceasBrandSchemautility -
#2353
5f5fcd9Thanks @tim-smart! - makeoptionaldual: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
7a45ad0Thanks @gcanti! - makepartialdual: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
5c3b1ccThanks @gcanti! - useSimplifyfromeffect/TypesinTaggedClass,TaggedErrorandTaggedRequestto avoid errors inSchema.d.ts, closes #1841 -
#2343
6f7dfc9Thanks @gcanti! - improve pick/omit and add support for Class -
#2337
88b8583Thanks @gcanti! - JSONSchema: allow overrides through annotations, closes #1823 -
#2348
cb20824Thanks @gcanti! - feedback: expose Class APIidentifiers -
#2350
a45a525Thanks @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
d0f56c6Thanks @gcanti! - add missingDateapi interfaces:DateFromSelfValidDateFromSelfDateFromString$Date
0.64.4
Patch Changes
- Updated dependencies [
eb93283]:- effect@2.4.7
0.64.3
Patch Changes
0.64.2
Patch Changes
-
#2310
89748c9Thanks @gcanti! - mergeParsermodule intoParseResult:- remove
Parsermodule - remove
internal/parseResultinternal module
- remove
-
Updated dependencies [
4f35a7e,9971186]:- effect@2.4.6
0.64.1
Patch Changes
-
#2305
d10f876Thanks @gcanti! - chore: improves the display ofStruct.TypeandStruct.Encodedwhen the parameter is generic -
#2304
743ae6dThanks @gcanti! - chore: remove staticstructfrommakeClassinternal constructor -
#2308
a75bc48Thanks @sukovanej! - Expose missing types from theParseResultmodule. -
Updated dependencies [
bce21c5,c7d3036]:- effect@2.4.5
0.64.0
Minor Changes
Breaking Changes
- The
Formatmodule has been removed
AST module
-
Tuplehas been refactored toTupleType, and its_taghas consequently been renamed. The type of itsrestproperty has changed fromOption.Option<ReadonlyArray.NonEmptyReadonlyArray<AST>>toReadonlyArray<AST>. -
Transformhas been refactored toTransformation, and its_tagproperty has consequently been renamed. Its propertytransformationhas now the typeTransformationKind = FinalTransformation | ComposeTransformation | TypeLiteralTransformation. -
createRecordhas been removed -
AST.tohas been renamed toAST.typeAST -
AST.fromhas been renamed toAST.encodedAST -
ExamplesAnnotationandDefaultAnnotationnow accept a type parameter -
formathas been removed: BeforeAST.format(ast, verbose?)Now
ast.toString(verbose?) -
setAnnotationhas been removed (useannotationsinstead) -
mergeAnnotationshas been renamed toannotations -
move
defaultParseOptionfromParser.tstoAST.ts
ParseResult module
-
The
ParseResultmodule now uses classes and custom constructors have been removed: Beforeimport * as ParseResult from "@effect/schema/ParseResult" ParseResult.type(ast, actual)Now
import * as ParseResult from "@effect/schema/ParseResult" new ParseResult.Type(ast, actual) -
Transformhas been refactored toTransformation, and itskindproperty now accepts"Encoded","Transformation", or"Type"as values
Schema module
-
uniqueSymbolhas been renamed touniqueSymbolFromSelf -
Schema.Schema.Tohas been renamed toSchema.Schema.Type, andSchema.totoSchema.typeSchema -
Schema.Schema.Fromhas been renamed toSchema.Schema.Encoded, andSchema.fromtoSchema.encodedSchema -
The type parameters of
TaggedRequesthave been swapped -
The signature of
PropertySignaturehas been changed fromPropertySignature<From, FromOptional, To, ToOptional>toPropertySignature<ToToken extends Token, To, Key extends PropertyKey, FromToken extends Token, From, R> -
Class APIs
- Class APIs now expose
fieldsand require an identifier-class A extends S.Class<A>()({ a: S.string }) {} +class A extends S.Class<A>("A")({ a: S.string }) {}
- Class APIs now expose
-
elementandresthave been removed in favor oftuple: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) -
optionalElementhas 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
TreeFormatterinBrandSchemas -
Schema annotations interfaces have been refactored into a namespace
Annotations -
the
annotationsoption of theoptionalconstructor has been replaced by theannotationsmethod BeforeS.optional(S.string, { exact: true, annotations: { description: "description" } })Now
S.optional(S.string, { exact: true }).annotations({ description: "description" }) -
Updated the
pluckfunction to returnSchema<A[K], { readonly [key]: I[K] }>instead ofSchema<A[K], I>. Removed the{ transformation: false }option in favor of selecting the specific field from thefieldsexposed by a struct. -
Removed
propertySignatureAnnotations, usepropertySignature(schema).annotations(). -
Updated the function name
headOrtoheadOrElseto align with the standard naming convention.
Serializable module
- The type parameters of
SerializableWithResultandWithResulthave been swapped
Patch Changes
-
#2172
5d47ee0Thanks @gcanti! - ##ASTmodule- expose the
getTemplateLiteralRegExpAPI
Schemamodule-
enhance the
structAPI 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
extendAPI 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
Annotableinterface -
add
asSchema -
add add
Schema.Any,Schema.All,Schema.AnyNoContexthelpers -
refactor
annotationsAPI to be a method within theSchemainterface -
add support for
AST.keyof,AST.getPropertySignatures,Parser.getSearchTreeto Classes -
fix
BrandAnnotationtype and addgetBrandAnnotation -
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 ) {}
- expose the
-
Updated dependencies [
5d47ee0,817a04c,d90a99d,dd05faa,dd05faa,802674b]:- effect@2.4.4
0.63.4
Patch Changes
0.63.3
Patch Changes
-
#2234
465be79Thanks @gcanti! - addBatchingAnnotation, default value:falseExample:
const schema = S.struct({ a: S.string, b: S.number }).pipe(S.batching(true /* boolean | "inherit" | undefined */)) -
#2241
d8e6940Thanks @jessekelly881! - addsortedSetandsortedSetFromSeldcombinators -
Updated dependencies [
e03811e,ac41d84,6137533,f373529,1bf9f31,e3ff789,6137533,507ba40,e466afe,f373529,de74eb8]:- effect@2.4.2
0.63.2
Patch Changes
-
#2222
39f583eThanks @gcanti! - TaggedClass: ensure constructor parameters don't overwrite the tag -
#2227
f428198Thanks @gcanti! - addConcurrencyAnnotation, default value:undefined(sequential)Example:
const schema = S.struct({ a: S.string, b: S.number }).pipe(S.concurrency(1 /* number | "unbounded" | "inherit" | undefined */)) -
#2221
c035972Thanks @tim-smart! - ensure Schema.Class is compatible without strictNullCheck -
Updated dependencies [
a4a0006,0a37676,6f503b7]:- effect@2.4.1
0.63.1
Patch Changes
-
#2209
5d30853Thanks @steffanek! - AddpickLiteralto 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
6e350edThanks @gcanti! - JSONSchema: pruneUndefinedKeywordif the property signature is marked as optional and contains a union that includesUndefinedKeyword, closes #2068
0.63.0
Minor Changes
-
#2101
54ddbb7Thanks @github-actions! - Updated theMessageAnnotationtype to accept aParseIssue; it's now(issue: ParseResult.ParseIssue) => stringto support custom error messages, which can be triggered under any circumstances.You can retrieve the actual value by accessing the
actualproperty of theissueobject: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
a025b12Thanks @github-actions! - Swap type params of Either fromEither<E, A>toEither<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
-
#2193
b9cb3a9Thanks @jessekelly881! - added Number.parse, BigInt.toNumber, ParseResult.fromOption -
#2101
136ef40Thanks @github-actions! - Equivalence: returnEqual.equalsinstead ofEquivalence.strict()as default -
#2101
f24ac9fThanks @github-actions! - add support forEquivalenceto class APIs -
Updated dependencies [
5de7be5,489fcf3,7d9c3bf,d8d278b,14c5711,5de7be5,b9cb3a9,585fcce,93b412d,55b26a6,a025b12,2097739]:- effect@2.4.0
0.62.9
Patch Changes
-
#2187
e6d36c0Thanks @tim-smart! - update development dependencies -
Updated dependencies [
5ad2eec,e6d36c0]:- effect@2.3.8
0.62.8
Patch Changes
0.62.7
Patch Changes
-
#2141
dbff62cThanks @gcanti! - add{ exact: true }optional argument to thepartialAPI, mirroring the implementation in theoptionalAPI, closes #2140The
partialoperation allows you to make all properties within a schema optional.By default, the
partialoperation adds a union withundefinedto the types. If you wish to avoid this, you can opt-out by passing a{ exact: true }argument to thepartialoperation.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
e572b07Thanks @tim-smart! - allow passing structs when encoding schema classesThe 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
e787a57Thanks @gcanti! - Refactor thedeclaresignature 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.validateSyncParser.validateOptionParser.validateEitherParser.isParser.assertsSchema.validateSyncSchema.validateOptionSchema.validateEitherSchema.isSchema.asserts
Additionally, the
ClassAPI no longer requires the optional argumentdisableValidationto betruewhenR !== never. -
Updated dependencies [
b1163b2,b46b869,de1b226,a663390,ff88f80,11be07b,c568645,88835e5,b415577,ff8046f]:- effect@2.3.6
0.62.6
Patch Changes
-
#2121
aef2b8bThanks @gcanti! - Use theidentityfunction in the transformation defining a schema class -
#2124
7eecb1cThanks @gcanti! - ParseResult: add missingdecode/encodeexports -
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
1c6d18bThanks @gcanti! - Schema: addtransformation: falseoption topluck.Given a schema
Schema<A, I, R>and a keyK, this function extracts a specific field from theAtype, producing a new schema that represents a transformation from theItype toA[K].If the option
{ transformation: false }is provided, the returned schemaSchema<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 ] } -
#2111
a344b42Thanks @gcanti! - add support for unions tokeyof
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
9a2d1c1Thanks @github-actions! - With this change we now require a string key to be provided for all tags and renames the dear oldTagtoGenericTag, 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
1a77f72Thanks @github-actions! - changeEffecttype parameters order fromEffect<R, E, A>toEffect<A, E = never, R = never> -
#2006
d3f9f4dThanks @github-actions! - Schema: switchreadonlyMapFromSelf,readonlyMapfrom positional arguments to a singleoptionsargument: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
d3f9f4dThanks @github-actions! - Schema: switchhashMapFromSelf,hashMapfrom positional arguments to a singleoptionsargument: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
d3f9f4dThanks @github-actions! - Schema: switchcauseFromSelf,causefrom positional arguments to a singleoptionsargument: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
d3f9f4dThanks @github-actions! - Schema: switchexitFromSelf,exitfrom positional arguments to a singleoptionsargument: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
a34dbdcThanks @github-actions! - - Schema: change type parameters order fromSchema<R, I, A>toSchema<A, I = A, R = never>- Serializable: change type parameters order from
Serializable<R, I, A>toSerializable<A, I, R> - Class: change type parameters order from
Class<R, I, A, C, Self, Inherited>toClass<A, I, R, C, Self, Inherited> - PropertySignature: change type parameters order from
PropertySignature<R, From, FromIsOptional, To, ToIsOptional>toPropertySignature<From, FromIsOptional, To, ToIsOptional, R = never>
- Serializable: change type parameters order from
-
#2006
d3f9f4dThanks @github-actions! - Schema: switcheitherFromSelf,either,eitherFromUnionfrom positional arguments to a singleoptionsargument: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
02c3461Thanks @github-actions! - With this change we remove theData.Datatype and we makeEqual.Equal&Hash.Hashimplicit traits.The main reason is that
Data.Data<A>was structurally equivalent toA & Equal.Equalbut extendingEqual.Equaldoesn't mean that the equality is implemented by-value, so the type was simply adding noise without gaining any level of safety.The module
Dataremains 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
Readonlyvariants, so for example we have:import { Data } from "effect" const obj = Data.struct({ a: 0, b: 1 })will have the
objtyped as:declare const obj: { readonly a: number readonly b: number } -
#2006
9a2d1c1Thanks @github-actions! - This change enablesEffect.serviceConstantsandEffect.serviceMembersto 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
56b8691Thanks @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
-
#2006
4cd6e14Thanks @github-actions! - Rename transform type parameters and de/en-coder param names to be more helpful in IDE hints. -
#2006
9dc04c8Thanks @github-actions! - Introducing Optional Annotations inoptionalAPI.Previously, when adding annotations to an optional field using
optionalAPI, you needed to usepropertySignatureAnnotations. However, a new optional argumentannotationsis now available to simplify this process.Before:
import * as S from "@effect/schema/Schema" const myschema = S.struct({ a: S.optional(S.string).pipe( S.propertySignatureAnnotations({ description: "my description..." }) ) })Now:
import * as S from "@effect/schema/Schema" const myschema = S.struct({ a: S.optional(S.string, { annotations: { description: "my description..." } }) })With this update, you can easily include annotations directly within the
optionalAPI without the need for additional calls. -
Updated dependencies [
96bcee2,96bcee2,c77f635,e343a74,acf1894,9a2d1c1,1a77f72,c986f0e,96bcee2,70dde23,81b7425,02c3461,0e56e99,8b0ded9,8dd83e8,5127afe,d75f6fe,7356e5c,3077cde,be19ce0,4a5d01a,78f47ab,52e5d20,c6137ec,f5ae081,4a5d01a,60686f5,9a2d1c1,5127afe,8ee2931,6727474,5127afe]:- effect@2.3.0
0.61.7
Patch Changes
0.61.6
Patch Changes
-
#2057
6928a2bThanks @joepjoosten! - Fix for possible stack overflow errors when using Array.push with spread operator arguments -
Updated dependencies [
d0b911c,330e1a4,6928a2b,296bc1c]:- effect@2.2.4
0.61.5
Patch Changes
-
#2011
f1ff44bThanks @gcanti! - add option to preserve excess properties, closes #2008 -
#2017
13785cfThanks @gcanti! - Equivalence: handle transformations
0.61.4
Patch Changes
-
#2005
6bf02c7Thanks @gcanti! - optional: rearrange overloads to enhance DX, closes #2002 -
Updated dependencies [
22794e0,f73e6c0]:- effect@2.2.3
0.61.3
Patch Changes
0.61.2
Patch Changes
- #1988
64f710aThanks @gcanti! - Class constructor: avoid overwritingpropswithadditionalProps, closes #1987
0.61.1
Patch Changes
-
#1975
c7550f9Thanks @gcanti! - fix templateLiteral signature (R should be never) -
#1974
8d1f6e4Thanks @gcanti! - causeFromSelf: add missing type parameter -
#1978
ac30bf4Thanks @gcanti! - Allow non-async Effects to be used with *Sync combinators, closes #1976ParseResult- add
astandmessagefields toForbidden
- add
-
Updated dependencies [
d404561,7b84a3c]:- effect@2.2.2
0.61.0
Minor Changes
-
#1922
62b40e8Thanks @gcanti! - Refactoring:- Schema:
- refactor
Schema.declareAPI to make it safe - add
Schema.declareoverloads - add
encodeUnknown*APIs - rename
parse*APIs todecodeUnknown* - symplify brand implementation
- rename
paramstoannotationintypeIdannotation - add optional
{ strict: false }parameter tocompose Class- rename
transformtotransformOrFail - rename
transformFromtotransformOrFailFrom
- rename
- add
hashSetandhashSetFromSelf - add
hashMapandhashMapFromSelf - add
listandlistFromSelf
- refactor
- AST:
- return
ParseResult.ParseIssueinstead ofParseResult.ParseErrorin all APIs - Declaration
- split
decodeintodecodeUnknown/encodeUnknown - remove
typefield
- split
- return
- ParseResult
- align
mapBothwithEffect(i.e. onFailure, onSuccess handlers) - add missing
Declarationnode inParseIssue
- align
- Schema:
-
#1922
62b40e8Thanks @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
-
#1939
0d1af1eThanks @gcanti! - fixhead/headOrsignatures and addgetNumberIndexedAccess -
Updated dependencies [
a222524]:- effect@2.1.1
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
b557a10Thanks @gcanti! - ParseResult refactoring:- remove
ParseResulttype - rename
mapLefttomapError - rename
bimaptomapBoth
- remove
Patch Changes
-
#1910
ec2bdfaThanks @gcanti! - refactoreitherFromUnionas union of transformations -
#1892
687e02eThanks @matheuspuel! - Schema: fix ParseIssue.actual on transformation -
#1891
8eec87eThanks @gcanti! - fixpickbehavior when the input is a record -
#1906
0c397e7Thanks @matheuspuel! - Schema: show error message when throw ParseError -
#1909
74b9094Thanks @tim-smart! - fix formatting of suspend before initialization -
#1904
337e80fThanks @gcanti! - add more title and identifier annotations -
Updated dependencies [
536c1df,8eec87e,540b294,536c1df,a3f96d6,8eec87e,536c1df,8eec87e,8eec87e,25adce7,536c1df]:- effect@2.0.4
0.59.1
Patch Changes
-
#1888
5b46e99Thanks @gcanti! - Schema: treat missing properties asundefined(excludingisandasserts), closes #1882 -
#1794
210d27eThanks @matheuspuel! - add eitherFromUnion -
Updated dependencies [
87f7ef2,1d3a06b]:- effect@2.0.3
0.59.0
Minor Changes
-
#1878
c4b84f7Thanks @gcanti! - Schema: removefrom/toAPI in favour ofmakein:- Equivalence
- JSONSchema
- Pretty
Patch Changes
-
#1878
c4b84f7Thanks @gcanti! - Schema: Pretty addprettyannotation API -
#1878
c4b84f7Thanks @gcanti! - Schema: Arbitrary addarbitraryannotation -
#1878
c4b84f7Thanks @gcanti! - Schema: Equivalence addequivalenceannotation
0.58.0
Minor Changes
-
#1877
a904a73Thanks @gcanti! - Schema: Arbitrary removefrom/toAPI in favour ofmake -
#1842
7b2f874Thanks @fubhy! - Schema: simplifyAST.createRefinementreturn type -
#1842
7b2f874Thanks @fubhy! - Schema: refactorParseResultmodule:- add
Unionissue, and replaceUnionMemberwithUnion - add
Tupleissue, and replaceIndexwithTuple - add
TypeLiteralissue - add
Transformissue - add
Refinementissue - add
astfield toMember - rename
UnionMembertoMember Type: renameexpectedtoastParseErrorreplaceerrorsfield witherrorfield and refactorparseErrorconstructor accordinglyIndexreplaceerrorsfield witherrorfieldKeyreplaceerrorsfield witherrorfieldMemberreplaceerrorsfield witherrorfieldParseErrorreplaceerrorsfield witherrorfield- make
ParseErroraData.TaggedError Forbidden: addactualfield
- add
Patch Changes
-
#1842
7b2f874Thanks @fubhy! - Schema: add more description annotations to built-in schemas -
#1842
7b2f874Thanks @fubhy! - Schema: add outeroptionarg to parse/decode/encode/validation/asserts/is APIs
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
d0471caThanks @mikearnaldi! - Switch to monorepo structure
Patch Changes
-
d987daaThanks @mikearnaldi! - Switch effect dependency to caret -
#1848
04fb8b4Thanks @fubhy! - Avoid default parameter initilization -
Updated dependencies [
d987daa,7b5eaa3,0724211,9f2bc5a,04fb8b4,d0471ca,bcf0900,6299b84]:- effect@2.0.0
0.56.1
Patch Changes
-
#684
6b9585bThanks @patroza! - improve: Actually use Arbitrary interface in to/from/unsafe signature -
#679
0f8a8f1Thanks @gcanti! - Schema: add annotations argument toattachPropertySignature
0.56.0
Minor Changes
- #673
0508ac5Thanks @tim-smart! - update effect
0.55.0
Minor Changes
-
#649
d80b933Thanks @gcanti! - Arbitrary: should throw on declarations without annotations -
#669
294dfadThanks @gcanti! - Schema: refactorparseJsonto replaceParseJsonandfromJson -
#649
d80b933Thanks @gcanti! - Schema: refactorS.optionalAPI.Upgrade Guide:
S.optional(schema, { exact: true })replaces the oldS.optional(schema)S.optional(schema, { exact: true, default: () => A })replaces the oldS.optional(schema).withDefault(() => A)S.optional(schema, { exact: true, as: "Option" })replaces the oldS.optional(schema).toOption()
-
#649
d80b933Thanks @gcanti! - Schema: replacepropertySignatureconstructor withpropertySignatureAnnotationscombinator -
#669
294dfadThanks @gcanti! - Schema: simplifysplitparameters to only acceptseparator -
#669
294dfadThanks @gcanti! - Schema: remove useless combinatorslowercaseuppercasetrimnumberFromStringsymbolFromStringbigintFromStringbigintFromNumbersecretdurationFromHrTimedurationFromMillisdurationFromNanosuint8ArrayFromNumbersbase64base64urlhexdateFromStringbigDecimalFromNumberbigDecimalFromStringnot
Patch Changes
0.54.1
Patch Changes
-
#665
a238f20Thanks @gcanti! - AST: make Annotations readonly -
#665
a238f20Thanks @gcanti! - Schema: remove Mutable helper in favour of Types.Mutable -
#665
a238f20Thanks @gcanti! - AST: preserve identifier annotations when callingfrom
0.54.0
Minor Changes
- #662
7f448ddThanks @tim-smart! - update effect
0.53.3
Patch Changes
- #654
a5950d1Thanks @jessekelly881! - added S.Secret
0.53.2
Patch Changes
0.53.1
Patch Changes
-
#655
54f61d6Thanks @tim-smart! - fix for never error types in TaggedRequest.Any -
#604
88f61ccThanks @jessekelly881! - added filters for Duration -
#605
c728880Thanks @jessekelly881! - added toString for schema classes
0.53.0
Minor Changes
-
#635
30802d5Thanks @gcanti! - JSONSchema: renameJsonSchema7ToptoJsonSchema7Root -
#650
05c2275Thanks @tim-smart! - update effect -
#640
8dcf12cThanks @gcanti! - ParseResult: renameParseErrorstoParseIssue -
#636
deddf6eThanks @gcanti! - Schema: rename lazy to suspend (to align with Effect.suspend)
Patch Changes
- #645
ece6128Thanks @gcanti! - ensure that JSON Schema annotations can be exclusively applied to refinements
0.52.0
Minor Changes
- #632
ad220ddThanks @tim-smart! - update effect
Patch Changes
-
#609
8ca0220Thanks @tim-smart! - add Serializable module -
#609
8ca0220Thanks @tim-smart! - add FiberId schema -
#609
8ca0220Thanks @tim-smart! - add Exit schema -
#609
8ca0220Thanks @tim-smart! - add Cause schema
0.51.5
Patch Changes
-
#629
f690ebeThanks @gcanti! - Schema: add filter overloading returning OptionFor more complex scenarios, you can return an
Option<ParseError>type instead of a boolean. In this context,Noneindicates success, andSome(error)rejects the input with a specific error
0.51.4
Patch Changes
-
#623
3a56b06Thanks @sukovanej! - ExportJsonSchema7types. -
#626
67c154eThanks @gcanti! - S.rename: handle field transformations, closes #625
0.51.3
Patch Changes
0.51.2
Patch Changes
-
#618
95a0354Thanks @gcanti! - Arbitrary: remove runtime dependency from Schema module -
#617
0cd3262Thanks @matheuspuel! - add Schema.transformLiteral and Schema.transformLiterals -
#618
95a0354Thanks @gcanti! - Pretty: remove runtime dependency from Schema module
0.51.1
Patch Changes
- #615
f851621Thanks @tim-smart! - update effect
0.51.0
Minor Changes
- #613
2af3914Thanks @tim-smart! - update effect
Patch Changes
0.50.0
Minor Changes
-
#593
cbc2e3fThanks @gcanti! - ParseResult: merge failure APIs intofail -
#607
e85aefbThanks @gcanti! - Bug Fix: align index signature behaviour to TypeScript -
#589
3b99569Thanks @gcanti! - - removeValidDate(which is just an alias ofDate)- add
DateFromString(decodes from string, output: possibly invalid Date)
- add
-
#593
cbc2e3fThanks @gcanti! - ParseResult: renamesuccesstosucceed(standard naming)
Patch Changes
-
#597
caeed29Thanks @jessekelly881! - added BigDecimal -
#585
5b27f03Thanks @gcanti! - improve JSON Schema output:- rename
dependenciesto$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
enuminstead ofanyOf, closes #579
- rename
-
#603
8e21d7eThanks @gcanti! - TreeFormatter: enhanceformatActualfor data types with a customtoStringimplementation, closes #600
0.49.4
Patch Changes
- #595
931b557Thanks @tim-smart! - add _tag to TaggedRequest.Base
0.49.3
Patch Changes
-
#592
c2b0e6bThanks @jessekelly881! - added ParseResult.try -
#590
0d0f0beThanks @gcanti! - Parser: should use the original ast to generate a more informative error message when an incorrect data type is provided
0.49.2
Patch Changes
0.49.1
Patch Changes
- #580
4491e75Thanks @tim-smart! - fix missing class .struct schema
0.49.0
Minor Changes
- #577
9653cf4Thanks @tim-smart! - update effect
Patch Changes
- #574
2ed5f8eThanks @tim-smart! - add TaggedRequest class
0.48.4
Patch Changes
0.48.3
Patch Changes
0.48.2
Patch Changes
-
#568
573419eThanks @tim-smart! - add Schema.TaggedError -
#568
573419eThanks @tim-smart! - add Schema.TaggedClass
0.48.1
Patch Changes
-
#566
1c1d5a5Thanks @matheuspuel! - add dual api to Schema.rename -
#566
1c1d5a5Thanks @matheuspuel! - forbid excess properties on Schema.rename -
#564
8440e1eThanks @fubhy! - UsesideEffects: []to circumvent bundler issues
0.48.0
Minor Changes
- #561
ec63224Thanks @tim-smart! - update effect
0.47.7
Patch Changes
0.47.6
Patch Changes
0.47.5
Patch Changes
- #553
522161aThanks @gcanti! - Fix bug in property signature transformations when used for renaming (old key/value pair was not removed)
0.47.4
Patch Changes
0.47.3
Patch Changes
- #546
b6e8e12Thanks @rjdellecese! - added S.uppercased, S.uppercase, and S.Uppercase
0.47.2
Patch Changes
0.47.1
Patch Changes
- #540
85526bfThanks @tim-smart! - update effect
0.47.0
Minor Changes
- #538
c8a8b79Thanks @tim-smart! - update effect
0.46.4
Patch Changes
-
#532
1e115afThanks @gcanti! - Arbitrary: add BigIntConstraints support -
#530
23b1e1cThanks @gcanti! - Arbitrary: merge ArrayConstraints
0.46.3
Patch Changes
0.46.2
Patch Changes
- #523
dca107aThanks @jessekelly881! - Replaced TreeFormatter with ArrayFormatter for BrandErrors when using Schema.brand
0.46.1
Patch Changes
- #519
9fe7693Thanks @tim-smart! - update effect
0.46.0
Minor Changes
- #515
c9bf451Thanks @sukovanej! - Update effect and fast-check.
0.45.8
Patch Changes
-
#514
3acbc38Thanks @gcanti! - Arbitrary: handle array constraints -
#514
3acbc38Thanks @gcanti! - Arbitrary: fix recursive generation (memory issues)
0.45.7
Patch Changes
0.45.6
Patch Changes
- #508
618b1b5Thanks @matheuspuel! - fix encode discriminated union with transformation
0.45.5
Patch Changes
0.45.4
Patch Changes
0.45.3
Patch Changes
0.45.2
Patch Changes
0.45.1
Patch Changes
0.45.0
Minor Changes
-
#491
135072eThanks @gcanti! - Make transformations strict by default (and allow relaxing constraints withstrict: falseoption) -
#495
c02334cThanks @tim-smart! - update effect
Patch Changes
- #475
46dcfebThanks @tim-smart! - memoize the Parser per AST
0.44.0
Minor Changes
- #488
e00491cThanks @tim-smart! - update effect
0.43.2
Patch Changes
- #485
0a20788Thanks @gcanti! - Arbitrary: use Math.fround when creating number constraints, closes #484
0.43.1
Patch Changes
-
#483
c80c94fThanks @gcanti! - Schema: add jsonSchema annotation helper -
#481
56f5ac0Thanks @gcanti! - AST/Schema: add mutable combinator
0.43.0
Minor Changes
- #476
1fb1002Thanks @tim-smart! - update effect
0.42.0
Minor Changes
0.41.1
Patch Changes
0.41.0
Minor Changes
- #468
da7a851Thanks @tim-smart! - update effect
0.40.2
Patch Changes
0.40.1
Patch Changes
0.40.0
Minor Changes
-
#457
693b81fThanks @tim-smart! - update effect -
#457
693b81fThanks @tim-smart! - use preconstruct for builds
0.39.2
Patch Changes
0.39.1
Patch Changes
- #452
ca65e43Thanks @tim-smart! - update effect
0.39.0
Minor Changes
- #449
5950b14Thanks @tim-smart! - update to use unified "effect" package
0.38.0
Minor Changes
-
#439
2197496Thanks @gcanti! - Schema: remove *Result APIs- decodeResult (use decode instead)
- encodeResult (use encode instead)
- parseResult (use parse instead)
- validateResult (use validate instead)
Patch Changes
0.37.2
Patch Changes
0.37.1
Patch Changes
0.37.0
Minor Changes
- #441
63f1149Thanks @tim-smart! - update /data & /io
0.36.5
Patch Changes
0.36.4
Patch Changes
- #434
994a37eThanks @gcanti! - Exclude property signatures from index signatures validations, fix #433
0.36.3
Patch Changes
0.36.2
Patch Changes
- #428
73a8424Thanks @tim-smart! - fix Class transform helper types
0.36.1
Patch Changes
0.36.0
Minor Changes
-
#420
3a46cbcThanks @tim-smart! - have Schema.Class constructors implement Schema directly -
#422
295561bThanks @gcanti! - move ToAsserts utility type to Schema namespace
0.35.1
Patch Changes
0.35.0
Minor Changes
-
#401
8b1ae6bThanks @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
8b1ae6bThanks @gcanti! - refactor annotations: keys must be symbols -
#411
2f6c4d1Thanks @gcanti! - renamesymboltosymbolFromSelfand addsymbolwhich decodes/encodes from/tostring -
#401
8b1ae6bThanks @gcanti! - remove Spread in favour of /data/Types#Simplify -
#413
20ef377Thanks @tim-smart! - update /io -
#401
8b1ae6bThanks @gcanti! - fix fromBrand definition (self is a Schema<I, A> now instead of Schema) -
#401
8b1ae6bThanks @gcanti! - renamebiginttobigintFromSelfandBigintFromStringtobigint -
#401
8b1ae6bThanks @gcanti! - change transformation display in error messages (from A -> B to A <-> B) -
#401
8b1ae6bThanks @gcanti! - move From, To to Schema namespace (conforming to the ecosystem standard) -
#401
8b1ae6bThanks @gcanti! - renametransformResulttotransformOrFailand change signature (add additional ast parameter to transformations)
Patch Changes
-
#401
8b1ae6bThanks @gcanti! - record: add support for branded keys -
#407
9a1b8deThanks @fubhy! - Add support forbase64,base64urlandhexencoding -
#412
3768461Thanks @gcanti! - relax transform / transformOrFail / compose constraints -
#401
8b1ae6bThanks @gcanti! - TreeFormatter: should not collapse union members -
#401
8b1ae6bThanks @gcanti! - add description annotations to: string, number, boolean, symbol, bigint, object
0.34.0
Minor Changes
- #403
da52c2bThanks @tim-smart! - update /data & /io
Patch Changes
-
#397
376fc3dThanks @jessekelly881! - added S.Lowercase -
#382
d79309bThanks @fubhy! - AddedbigintFromNumbertransform
0.33.2
Patch Changes
-
#392
4c1ed27Thanks @gcanti! - pattern filter: set default Arbitrary -
#388
27a78bbThanks @gcanti! - compose: allow forcing decoding / encoding
0.33.1
Patch Changes
0.33.0
Minor Changes
- #376
64c2567Thanks @tim-smart! - update /io
Patch Changes
-
#375
bd61bcfThanks @tim-smart! - update build tools -
#373
e74455eThanks @tim-smart! - use peer deps for /data and /io
0.32.0
Minor Changes
- #370
70e4fffThanks @tim-smart! - update /data and /io
0.31.0
Minor Changes
- #366
77fffedThanks @tim-smart! - update /data and /io
0.30.4
Patch Changes
-
#350
00f6898Thanks @vecerek! - Add schema for BigintFromString -
#359
cb00668Thanks @vecerek! - Adds combinator that splits a string into an array of strings -
#361
60affebThanks @vecerek! - Addscompose: a combinator that composes Schema<A, B> with Schema<B, C> into Schema<A, C>.
0.30.3
Patch Changes
-
#357
00c2a47Thanks @sukovanej! - Update /data. -
#357
00c2a47Thanks @sukovanej! - Add_idtoSchema. AddisSchemaguard.
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
- #338
b2560dfThanks @tim-smart! - update /io and /data
0.28.0
Minor Changes
- #334
5a6d733Thanks @tim-smart! - update /io
0.27.0
Minor Changes
- #332
9f0fa5dThanks @tim-smart! - update dependencies
0.26.1
Patch Changes
0.26.0
Minor Changes
0.25.0
Minor Changes
- #322
5f5bcb5Thanks @tim-smart! - rename *Effect parser methods
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
- #310
10f8457Thanks @sukovanej! - Update /data and /io.
0.20.3
Patch Changes
0.20.2
Patch Changes
- #303
0f70b22Thanks @sukovanej! - Update @effect/data and fast-check.
0.20.1
Patch Changes
0.20.0
Minor Changes
0.19.3
Patch Changes
-
#285
39d3c55Thanks @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
-
#274
eae1614Thanks @gcanti! - remove getPropertySignatures API -
#274
eae1614Thanks @gcanti! - rename AST.getTo -> to, AST.getFrom -> from
0.17.5
Patch Changes
- #272
d91a7a7Thanks @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
- #258
1b65e53Thanks @mikearnaldi! - Try publishing again
0.17.1
Patch Changes
- #256
162e099Thanks @gcanti! - leverage annotations (e.g. maxLength, int, between) to improve fast-check performance
0.17.0
Minor Changes
- #254
32e987aThanks @mikearnaldi! - Update effect/io, make parsing fields of records and tuples parallel
0.16.0
Minor Changes
0.15.0
Minor Changes
-
#247
28c7484Thanks @gcanti! - refactor optional APIs (Default values and Optional fields asOptions)
0.14.1
Patch Changes
0.14.0
Minor Changes
-
#238
f4ce344Thanks @sukovanej! - update @effect/io dependency -
#243
87382aeThanks @gcanti! - narrow down IndexSignature type -
#239
58be561Thanks @gcanti! - rename DateFromString to date
Patch Changes
-
#243
87382aeThanks @gcanti! - Arbitrary: should throw on effectful refinements -
#231
2c2d749Thanks @tim-smart! - add isValidDate filter -
#217
7911525Thanks @jessekelly881! - data/Boolean: added S.not transform -
#243
87382aeThanks @gcanti! - createRecord: should throw on unsupported literals -
#237
2a911efThanks @gcanti! - export ValidDateFromSelf and rename validDate filter
0.13.1
Patch Changes
0.13.0
Minor Changes
-
#232
49ebabaThanks @gcanti! - rename OptionalSchema to PropertySignature -
#232
49ebabaThanks @gcanti! - simplify keyof and getPropertySignatures implementations -
#232
49ebabaThanks @gcanti! - remove optionsFromOptionals API
0.12.1
Patch Changes
0.12.0
Minor Changes
0.11.1
Patch Changes
0.11.0
Minor Changes
-
#215
b47e8abThanks @tsteckenborn! - aligns usage of dateFromString with numberFromString -
#219
10c505aThanks @gcanti! - remove hasTransformation optimisations -
#223
6cc1a56Thanks @gcanti! - upgrade to latest /data and /io -
#219
10c505aThanks @gcanti! - keyof cannot handle refinements nor transformations -
#219
10c505aThanks @gcanti! - fix transformation signatures
Patch Changes
-
#219
10c505aThanks @gcanti! - cannot build an Arbitrary for transformations -
#219
10c505aThanks @gcanti! - fix AST.getTo implementation for Transform -
#219
10c505aThanks @gcanti! - export NumberFromString schema -
#218
c6c96a4Thanks @OlaoluwaM! - Added missing assertion functions for some AST nodes
0.10.0
Minor Changes
- #211
45c322bThanks @mikearnaldi! - Update effect/data and effect/io
0.9.1
Patch Changes
0.9.0
Minor Changes
- #206
39da1cbThanks @mikearnaldi! - Update effect/data and effect/io
0.8.3
Patch Changes
0.8.2
Patch Changes
-
#201
5aa2d78Thanks @gcanti! - cannot compute property signatures for refinements -
#202
6f51084Thanks @gcanti! - Schema: add support for never to From / To utility types
0.8.1
Patch Changes
0.8.0
Minor Changes
-
#196
96e5bf5Thanks @gcanti! - tuples should always fail on excess indexes -
#196
96e5bf5Thanks @gcanti! - refactor ParseOptions, closes #163
Patch Changes
- #173
4090099Thanks @jessekelly881! - Schema: added S.required
0.7.1
Patch Changes
0.7.0
Minor Changes
-
#188
bb31acbThanks @gcanti! - getPropertySignatures: cannot compute property signatures for transformations -
#188
bb31acbThanks @gcanti! - upgrade to latest @effect/data @effect/io -
#188
bb31acbThanks @gcanti! -partialcannot handle refinement or transformations
0.6.0
Minor Changes
Patch Changes
-
#184
b0b6423Thanks @gcanti! - make optionsFromOptionals composable -
#182
f7899b7Thanks @gcanti! - optionsFromOptionals: ensure non overlapping property signatures -
#181
0062b25Thanks @gcanti! - fix optionsFromOptionals implementation
0.5.0
Minor Changes
0.4.0
Minor Changes
- #174
c3a1230Thanks @mikearnaldi! - Only run effects when allowed
Patch Changes
-
#172
6277f5aThanks @mikearnaldi! - Optimize ParseResult conditional functions -
#176
dbb0a59Thanks @gcanti! - Optimize internal validations
0.3.1
Patch Changes
- #169
6b0a45fThanks @mikearnaldi! - Add back missing commits from wrong rebase.
0.3.0
Minor Changes
-
#165
3704121Thanks @mikearnaldi! - AST: remove isReversed from Transform -
#165
3704121Thanks @mikearnaldi! - make ParseError tagged -
#165
3704121Thanks @mikearnaldi! - ParseResult: add optional message to Type error -
#165
3704121Thanks @mikearnaldi! - remove useless options argument from is -
#165
3704121Thanks @mikearnaldi! - Integrate Effect into Parser -
#165
3704121Thanks @mikearnaldi! - simplify dateFromString -
#165
3704121Thanks @mikearnaldi! - Schema: add reverse API -
#165
3704121Thanks @mikearnaldi! - rename decodeFromInput to decode and decode to parse
Patch Changes
-
#165
3704121Thanks @mikearnaldi! - add parse, parseOption, parseEither -
#165
3704121Thanks @mikearnaldi! - fix trim, clamp, clampBigint definition
0.2.1
Patch Changes
0.2.0
Minor Changes
-
#144
df9ea09Thanks @gcanti! - rename encodeOrThrow -> encode -
#144
df9ea09Thanks @gcanti! - AST: rename typeAlis to Declaration -
#144
df9ea09Thanks @gcanti! - renametransformOrFailtotransformEither -
#144
df9ea09Thanks @gcanti! - rename encode -> encodeEither -
#144
df9ea09Thanks @gcanti! - AST: change Refinement definition form predicate to decode -
#144
df9ea09Thanks @gcanti! - move /formatter/Tree up and rename to TreeFormatter -
#144
df9ea09Thanks @gcanti! - remove /annotation/Hook module -
#144
df9ea09Thanks @gcanti! - refactor instanceOf as Declaration -
#144
df9ea09Thanks @gcanti! - rename decodeOrThrow -> decode -
#144
df9ea09Thanks @gcanti! - AST: refactor typeAlias adding decode -
#144
df9ea09Thanks @gcanti! - rename getOption -> decodeOption -
#144
df9ea09Thanks @gcanti! - remove /annotation/AST module -
#144
df9ea09Thanks @gcanti! - rename decode -> decodeEither -
#144
df9ea09Thanks @gcanti! - formatErrors/ should collapse trees that have a branching factor of 1 -
#144
df9ea09Thanks @gcanti! - simplify Arbitrary implementation
Patch Changes
0.1.0
Minor Changes
- #145
cc05ffeThanks @tim-smart! - update /data to 0.4.1
Patch Changes
0.0.5
Patch Changes
0.0.4
Patch Changes
0.0.3
Patch Changes
- #127
fd87ac6Thanks @mikearnaldi! - Fix release for github
0.0.2
Patch Changes
- #125
41841a3Thanks @mikearnaldi! - update release
0.0.1
Patch Changes
-
#119
62ed1b0Thanks @mikearnaldi! - Move to the @effect org -
#120
6ddb736Thanks @gcanti! - move parseNumber to /data/Number -
#120
6ddb736Thanks @gcanti! - upgrade to latest effect/data -
#120
6ddb736Thanks @gcanti! - /data/Option rename fromNullable to parseNullable -
#120
6ddb736Thanks @gcanti! - refactor instanceOf (to a constructor) -
#120
6ddb736Thanks @gcanti! - Added clamp transform to Number and Bigint