fix contextual make (#143)

* fix contextual make

* fix other APIs + more tests

* update tstyche

* docs

* add Opaque test
This commit is contained in:
Giulio Canti
2025-06-03 08:41:58 +02:00
committed by GitHub
parent 22c05c7d3e
commit fdb8d96bc3
6 changed files with 665 additions and 264 deletions
+1 -1
View File
@@ -77,7 +77,7 @@
"rollup-plugin-bundle-stats": "^4.19.1",
"rollup-plugin-esbuild": "^6.2.1",
"terser": "^5.39.0",
"tstyche": "4.0.0-rc.0",
"tstyche": "4.0.0",
"tsx": "^4.17.0",
"typescript": "^5.7.2",
"typescript-eslint": "^8.31.1",
+111 -29
View File
@@ -269,13 +269,95 @@ encode(schema) = decode(flip(schema))
## Constructors Redesign
### Keeping Constructors in Composed Schemas
### Constructors in Composed Schemas
To support constructors in composed schemas, `makeSync` will be added to the base `Bottom` type.
To support constructing values from composed schemas, `makeSync` is now available on all schemas, including unions.
### Constructor Default Values
```ts
import { Schema } from "effect"
A constructor default allows a schema to generate a value when one is not provided.
const schema = Schema.Union([
Schema.Struct({ a: Schema.String }),
Schema.Struct({ b: Schema.Number })
])
schema.makeSync({ a: "hello" })
schema.makeSync({ b: 1 })
```
### Branded Constructors
For branded schemas, the default constructor accepts an unbranded input and returns a branded output.
```ts
import { Schema } from "effect"
const schema = Schema.String.pipe(Schema.brand("a"))
// makeSync(input: string, options?: Schema.MakeOptions): string & Brand<"a">
schema.makeSync
```
However, when a branded schema is part of a composite (such as a struct), you must pass a branded value.
```ts
import { Schema } from "effect"
const schema = Schema.Struct({
a: Schema.String.pipe(Schema.brand("a")),
b: Schema.Number
})
/*
makeSync(input: {
readonly a: string & Brand<"a">;
readonly b: number;
}, options?: Schema.MakeOptions): {
readonly a: string & Brand<"a">;
readonly b: number;
}
*/
schema.makeSync
```
### Refined Constructors
For refined schemas, the constructor accepts the unrefined type and returns the refined one.
```ts
import { Option, Schema } from "effect"
const schema = Schema.Option(Schema.String).pipe(Schema.guard(Option.isSome))
// makeSync(input: Option.Option<string>, options?: Schema.MakeOptions): Option.Some<string>
schema.makeSync
```
As with branding, when used in a composite schema, the refined value must be provided.
```ts
import { Option, Schema } from "effect"
const schema = Schema.Struct({
a: Schema.Option(Schema.String).pipe(Schema.guard(Option.isSome)),
b: Schema.Number
})
/*
makeSync(input: {
readonly a: Option.Some<string>;
readonly b: number;
}, options?: Schema.MakeOptions): {
readonly a: Option.Some<string>;
readonly b: number;
}
*/
schema.makeSync
```
### Default Values in Constructors
You can define a default value for a field using `Schema.withConstructorDefault`. If no value is provided at runtime, the constructor uses this default.
**Example** (Providing a default number)
@@ -313,7 +395,7 @@ console.log(schema.makeSync({}))
// { a: 2025-05-19T16:46:10.913Z }
```
If the function returns `Option.none()`, it means no default value was provided, and the field is considered missing.
If the default function returns `Option.none()`, it means no default value was provided, and the field is considered missing.
**Example** (Returning `None` to skip a default)
@@ -350,7 +432,30 @@ try {
// { a: 2025-05-19T16:48:41.948Z }
```
#### Effectful Defaults
#### Nested Constructor Default Values
Default values can be nested inside composed schemas. In this case, inner defaults are resolved first.
**Example** (Nested default values)
```ts
import { Result, Schema } from "effect"
const schema = Schema.Struct({
a: Schema.Struct({
b: Schema.Number.pipe(
Schema.withConstructorDefault(() => Result.succeedSome(-1))
)
}).pipe(Schema.withConstructorDefault(() => Result.succeedSome({})))
})
console.log(schema.makeSync({}))
// { a: { b: -1 } }
console.log(schema.makeSync({ a: {} }))
// { a: { b: -1 } }
```
### Effectful Defaults
Default values can also be computed using effects, as long as the environment is `never`.
@@ -412,29 +517,6 @@ SchemaResult.asEffect(schema.make({}))
// { a: -1 }
```
### Nested Constructor Default Values
Default values can be nested inside composed schemas. In this case, inner defaults are resolved first.
**Example** (Nested default values)
```ts
import { Result, Schema } from "effect"
const schema = Schema.Struct({
a: Schema.Struct({
b: Schema.Number.pipe(
Schema.withConstructorDefault(() => Result.succeedSome(-1))
)
}).pipe(Schema.withConstructorDefault(() => Result.succeedSome({})))
})
console.log(schema.makeSync({}))
// { a: { b: -1 } }
console.log(schema.makeSync({ a: {} }))
// { a: { b: -1 } }
```
## Filters Redesign
Filters are applied using the either the `.check` method or the `Schema.check` function.
+317 -69
View File
@@ -12,6 +12,8 @@ import {
} from "effect"
import { describe, expect, it, when } from "tstyche"
type MakeSync<In, Out> = (input: In, options?: Schema.MakeOptions | undefined) => Out
const revealClass = <Self, S extends Schema.Struct<Schema.Struct.Fields>, Inherited>(
klass: Schema.Class<Self, S, Inherited>
): Schema.Class<Self, S, Inherited> => klass
@@ -68,70 +70,332 @@ describe("Schema", () => {
describe("makeSync", () => {
it("Never", () => {
const schema = Schema.Never
expect(schema.makeSync).type.toBe<(input: never, options?: Schema.MakeOptions | undefined) => never>()
expect(schema.makeSync).type.toBe<MakeSync<never, never>>()
})
it("Unknown", () => {
const schema = Schema.Unknown
expect(schema.makeSync).type.toBe<(input: unknown, options?: Schema.MakeOptions | undefined) => unknown>()
expect(schema.makeSync).type.toBe<MakeSync<unknown, unknown>>()
})
it("Any", () => {
const schema = Schema.Any
expect(schema.makeSync).type.toBe<MakeSync<any, any>>()
})
it("Null", () => {
const schema = Schema.Null
expect(schema.makeSync).type.toBe<(input: null, options?: Schema.MakeOptions | undefined) => null>()
expect(schema.makeSync).type.toBe<MakeSync<null, null>>()
})
it("Undefined", () => {
const schema = Schema.Undefined
expect(schema.makeSync).type.toBe<(input: undefined, options?: Schema.MakeOptions | undefined) => undefined>()
expect(schema.makeSync).type.toBe<MakeSync<undefined, undefined>>()
})
it("String", () => {
const schema = Schema.String
expect(schema.makeSync).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>()
expect(schema.makeSync).type.toBe<MakeSync<string, string>>()
})
it("Number", () => {
const schema = Schema.Number
expect(schema.makeSync).type.toBe<(input: number, options?: Schema.MakeOptions | undefined) => number>()
expect(schema.makeSync).type.toBe<MakeSync<number, number>>()
})
it("check", () => {
const schema = Schema.String.check(SchemaCheck.minLength(1))
expect(schema.makeSync).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>()
expect(schema.makeSync).type.toBe<MakeSync<string, string>>()
})
it("brand", () => {
const schema = Schema.String.pipe(Schema.brand("a"))
expect(schema.makeSync).type.toBe<MakeSync<string, string & Brand.Brand<"a">>>()
})
it("guard", () => {
const schema = Schema.Option(Schema.String).pipe(Schema.guard(Option.isSome))
expect(schema.makeSync).type.toBe<MakeSync<Option.Option<string>, Option.Some<string>>>()
})
describe("Struct", () => {
it("simple field", () => {
const schema = Schema.Struct({
a: Schema.String
})
expect(schema.makeSync).type.toBe<MakeSync<{ readonly a: string }, { readonly a: string }>>()
})
it("branded field", () => {
const schema = Schema.Struct({
a: Schema.String.pipe(Schema.brand("a"))
})
expect(schema.makeSync).type.toBe<
MakeSync<{ readonly a: string & Brand.Brand<"a"> }, { readonly a: string & Brand.Brand<"a"> }>
>()
})
it("guarded field", () => {
const schema = Schema.Struct({
a: Schema.Option(Schema.String).pipe(Schema.guard(Option.isSome))
})
expect(schema.makeSync).type.toBe<
MakeSync<{ readonly a: Option.Some<string> }, { readonly a: Option.Some<string> }>
>()
})
it("defaulted field", () => {
const schema = Schema.Struct({
a: Schema.String.pipe(Schema.withConstructorDefault(() => Option.some("default")))
})
expect(schema.makeSync).type.toBe<MakeSync<{ readonly a?: string }, { readonly a: string }>>()
})
it("branded defaulted field", () => {
const schema = Schema.Struct({
a: Schema.String.pipe(Schema.brand("a"), Schema.withConstructorDefault(() => Option.some("default")))
})
expect(schema.makeSync).type.toBe<
MakeSync<{ readonly a?: string & Brand.Brand<"a"> }, { readonly a: string & Brand.Brand<"a"> }>
>()
})
it("defaulted branded field", () => {
const schema = Schema.Struct({
a: Schema.String.pipe(Schema.withConstructorDefault(() => Option.some("default")), Schema.brand("a"))
})
expect(schema.makeSync).type.toBe<
MakeSync<{ readonly a?: string & Brand.Brand<"a"> }, { readonly a: string & Brand.Brand<"a"> }>
>()
})
it("nested defaulted fields", () => {
const schema = Schema.Struct({
a: Schema.Struct({
b: Schema.Finite.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.withConstructorDefault(() => Option.some({})))
})
expect(schema.makeSync).type.toBe<
MakeSync<{ readonly a?: { readonly b?: number } }, { readonly a: { readonly b: number } }>
>()
})
it("nested defaulted & branded field", () => {
const A = Schema.Struct({
b: Schema.Finite.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.brand("a"))
const schema = Schema.Struct({
a: A.pipe(Schema.withConstructorDefault(() => Option.some(A.makeSync({}))))
})
expect(schema.makeSync).type.toBe<
MakeSync<
{ readonly a?: { readonly b: number } & Brand.Brand<"a"> },
{ readonly a: { readonly b: number } & Brand.Brand<"a"> }
>
>()
})
it("Class field", () => {
class A extends Schema.Class<A, { readonly brand: unique symbol }>("A")(Schema.Struct({
a: Schema.String
})) {}
const schema = Schema.Struct({
a: A
})
expect(schema.makeSync).type.toBe<MakeSync<{ readonly a: A }, { readonly a: A }>>()
})
it("optional Class field", () => {
class A extends Schema.Class<A, { readonly brand: unique symbol }>("A")(Schema.Struct({
a: Schema.String
})) {}
const schema = Schema.Struct({
a: A.pipe(Schema.withConstructorDefault(() => Option.some(new A({ a: "default" }))))
})
expect(schema.makeSync).type.toBe<MakeSync<{ readonly a?: A }, { readonly a: A }>>()
})
})
describe("Tuple", () => {
it("simple element", () => {
const schema = Schema.Tuple([Schema.String])
expect(schema.makeSync).type.toBe<MakeSync<readonly [string], readonly [string]>>()
})
it("branded field", () => {
const schema = Schema.Tuple([Schema.String.pipe(Schema.brand("a"))])
expect(schema.makeSync).type.toBe<
MakeSync<readonly [string & Brand.Brand<"a">], readonly [string & Brand.Brand<"a">]>
>()
})
it("defaulted field", () => {
const schema = Schema.Tuple([Schema.String.pipe(Schema.withConstructorDefault(() => Option.some("default")))])
expect(schema.makeSync).type.toBe<MakeSync<readonly [string?], readonly [string]>>()
})
it("nested defaults (Struct)", () => {
const schema = Schema.Tuple(
[
Schema.Struct({
b: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.withConstructorDefault(() => Option.some({})))
]
)
expect(schema.makeSync).type.toBe<
MakeSync<readonly [{ readonly b?: number }?], readonly [{ readonly b: number }]>
>()
})
it("nested defaults (Tuple)", () => {
const schema = Schema.Tuple(
[
Schema.Tuple([
Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
]).pipe(Schema.withConstructorDefault(() => Option.some([] as const)))
]
)
expect(schema.makeSync).type.toBe<MakeSync<readonly [(readonly [number?])?], readonly [readonly [number]]>>()
})
})
describe("Class", () => {
it("nested defaulted fields", () => {
class A extends Schema.Class<A, { readonly brand: unique symbol }>("A")(Schema.Struct({
a: Schema.Struct({
b: Schema.Finite.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.withConstructorDefault(() => Option.some({})))
})) {}
expect(A.makeSync).type.toBe<MakeSync<{ readonly a?: { readonly b?: number } }, A>>()
const schema = Schema.Struct({
a: A
})
expect(schema.makeSync).type.toBe<MakeSync<{ readonly a: A }, { readonly a: A }>>()
})
})
it("typeCodec", () => {
const schema = Schema.typeCodec(Schema.FiniteFromString)
expect(schema.makeSync).type.toBe<MakeSync<number, number>>()
})
it("encodedCodec", () => {
const schema = Schema.encodedCodec(Schema.FiniteFromString)
expect(schema.makeSync).type.toBe<MakeSync<string, string>>()
})
it("flip", () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString
})
const flipped = Schema.flip(schema)
expect(flipped.makeSync).type.toBe<MakeSync<{ readonly a: string }, { readonly a: string }>>()
})
it("Array", () => {
const schema = Schema.Array(Schema.FiniteFromString.pipe(Schema.brand("a")))
expect(schema.makeSync).type.toBe<
(input: string, options?: Schema.MakeOptions | undefined) => string & Brand.Brand<"a">
MakeSync<ReadonlyArray<number & Brand.Brand<"a">>, ReadonlyArray<number & Brand.Brand<"a">>>
>()
})
it("Struct", () => {
const schema = Schema.Struct({
a: Schema.String.pipe(Schema.brand("a"))
})
it("Record", () => {
const schema = Schema.Record(
Schema.String.pipe(Schema.brand("k")),
Schema.FiniteFromString.pipe(Schema.brand("a"))
)
expect(schema.makeSync).type.toBe<
(
input: { readonly a: string },
options?: Schema.MakeOptions | undefined
) => { readonly a: string & Brand.Brand<"a"> }
MakeSync<
{ readonly [x: string & Brand.Brand<"k">]: number & Brand.Brand<"a"> },
{ readonly [x: string & Brand.Brand<"k">]: number & Brand.Brand<"a"> }
>
>()
})
it("StructWithRest", () => {
const schema = Schema.StructWithRest(
Schema.Struct({ a: Schema.FiniteFromString.pipe(Schema.brand("a")) }),
[Schema.Record(Schema.String.pipe(Schema.brand("k")), Schema.FiniteFromString.pipe(Schema.brand("a")))]
)
expect(schema.makeSync).type.toBe<
MakeSync<{
readonly [x: string & Brand.Brand<"k">]: number & Brand.Brand<"a">
readonly a: number & Brand.Brand<"a">
}, {
readonly [x: string & Brand.Brand<"k">]: number & Brand.Brand<"a">
readonly a: number & Brand.Brand<"a">
}>
>()
})
it("TupleWithRest", () => {
const schema = Schema.TupleWithRest(
Schema.Tuple([Schema.FiniteFromString.pipe(Schema.brand("a"))]),
[Schema.FiniteFromString.pipe(Schema.brand("b")), Schema.FiniteFromString.pipe(Schema.brand("c"))]
)
expect(schema.makeSync).type.toBe<
MakeSync<
readonly [number & Brand.Brand<"a">, ...Array<number & Brand.Brand<"b">>, number & Brand.Brand<"c">],
readonly [number & Brand.Brand<"a">, ...Array<number & Brand.Brand<"b">>, number & Brand.Brand<"c">]
>
>()
})
it("Union", () => {
const schema = Schema.Union([
Schema.Array(Schema.FiniteFromString.pipe(Schema.brand("a"))),
Schema.FiniteFromString.pipe(Schema.brand("b"))
])
expect(schema.makeSync).type.toBe<
MakeSync<
ReadonlyArray<number & Brand.Brand<"a">> | number & Brand.Brand<"b">,
ReadonlyArray<number & Brand.Brand<"a">> | number & Brand.Brand<"b">
>
>()
})
it("Opaque", () => {
class A extends Schema.Opaque<A>()(
Schema.Struct({
b: Schema.FiniteFromString.pipe(Schema.brand("a"), Schema.withConstructorDefault(() => Option.some(-1)))
})
) {}
const schema = Schema.Struct({
a: A
})
expect(schema.makeSync).type.toBe<
MakeSync<{ readonly a: { readonly b?: number & Brand.Brand<"a"> } }, { readonly a: A }>
>()
})
})
describe("typeSchema", () => {
describe("typeCodec", () => {
it("ast type", () => {
const schema = Schema.String.pipe(Schema.brand("a"), Schema.typeCodec)
expect(schema.ast).type.toBe<SchemaAST.StringKeyword>()
const schema = Schema.typeCodec(Schema.FiniteFromString)
expect(schema.ast).type.toBe<SchemaAST.NumberKeyword>()
})
it("typeSchema", () => {
const schema = Schema.String.pipe(Schema.brand("a"), Schema.typeCodec)
expect(schema.makeSync).type.toBe<
(input: string, options?: Schema.MakeOptions | undefined) => string & Brand.Brand<"a">
>()
it("revealCodec + annotate", () => {
const schema = Schema.typeCodec(Schema.FiniteFromString)
expect(Schema.revealCodec(schema)).type.toBe<Schema.Codec<number, number, never, never>>()
expect(schema).type.toBe<Schema.typeCodec<Schema.FiniteFromString>>()
expect(schema.annotate({})).type.toBe<Schema.typeCodec<Schema.FiniteFromString>>()
})
})
describe("encodedCodec", () => {
it("ast type", () => {
const schema = Schema.FiniteFromString
expect(schema.ast).type.toBe<SchemaAST.NumberKeyword>()
})
it("revealCodec + annotate", () => {
const schema = Schema.encodedCodec(Schema.FiniteFromString)
expect(Schema.revealCodec(schema)).type.toBe<Schema.Codec<string, string, never, never>>()
expect(schema).type.toBe<Schema.encodedCodec<Schema.FiniteFromString>>()
expect(schema.annotate({})).type.toBe<Schema.encodedCodec<Schema.FiniteFromString>>()
})
})
@@ -368,16 +632,6 @@ describe("Schema", () => {
expect(Schema.revealCodec(flipped.annotate({}))).type.toBe<Schema.Codec<string, number>>()
})
it(`flipped "~type.make.in" should be "Encoded"`, () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString
})
const flipped = Schema.flip(schema)
expect(flipped.makeSync).type.toBe<
(input: { readonly a: string }, options?: Schema.MakeOptions | undefined) => { readonly a: string }
>()
})
it("optionalKey", () => {
const schema = Schema.Struct({
a: Schema.optionalKey(Schema.FiniteFromString)
@@ -419,10 +673,6 @@ describe("Schema", () => {
expect(schema.annotate({})).type.toBe<Schema.Array$<typeof FiniteFromString>>()
expect(schema.schema).type.toBe<typeof FiniteFromString>()
expect(schema.makeSync).type.toBe<
(input: ReadonlyArray<number>, options?: Schema.MakeOptions | undefined) => ReadonlyArray<number>
>()
})
})
@@ -491,20 +741,6 @@ describe("Schema", () => {
})
})
it("withConstructorDefault", () => {
const service = hole<Context.Tag<"Tag", "-">>()
const schema = Schema.String.pipe(Schema.withConstructorDefault(() =>
Effect.gen(function*() {
yield* Effect.serviceOption(service)
return Option.some("some-result")
})
))
expect(schema.makeSync).type.toBe<
(input: string, options?: Schema.MakeOptions | undefined) => string
>()
})
describe("Record", () => {
it("Record(String, Number)", () => {
const schema = Schema.Record(Schema.String, Schema.Number)
@@ -512,9 +748,7 @@ describe("Schema", () => {
Schema.Codec<{ readonly [x: string]: number }, { readonly [x: string]: number }, never>
>()
expect(schema).type.toBe<Schema.Record$<Schema.String, Schema.Number>>()
expect(schema.annotate({})).type.toBe<
Schema.Record$<Schema.String, Schema.Number>
>()
expect(schema.annotate({})).type.toBe<Schema.Record$<Schema.String, Schema.Number>>()
})
it("Record(Symbol, Number)", () => {
@@ -523,9 +757,7 @@ describe("Schema", () => {
Schema.Codec<{ readonly [x: symbol]: number }, { readonly [x: symbol]: number }, never>
>()
expect(schema).type.toBe<Schema.Record$<Schema.Symbol, Schema.Number>>()
expect(schema.annotate({})).type.toBe<
Schema.Record$<Schema.Symbol, Schema.Number>
>()
expect(schema.annotate({})).type.toBe<Schema.Record$<Schema.Symbol, Schema.Number>>()
})
it("Record(String, NumberFromString)", () => {
@@ -534,9 +766,7 @@ describe("Schema", () => {
Schema.Codec<{ readonly [x: string]: number }, { readonly [x: string]: string }, never>
>()
expect(schema).type.toBe<Schema.Record$<Schema.String, typeof NumberFromString>>()
expect(schema.annotate({})).type.toBe<
Schema.Record$<Schema.String, typeof NumberFromString>
>()
expect(schema.annotate({})).type.toBe<Schema.Record$<Schema.String, typeof NumberFromString>>()
})
})
@@ -550,6 +780,15 @@ describe("Schema", () => {
expect(schema.elements).type.toBe<readonly []>()
})
it("defaulted element", () => {
const schema = Schema.Tuple([Schema.String.pipe(Schema.withConstructorDefault(() => Option.some("default")))])
expect(Schema.revealCodec(schema)).type.toBe<Schema.Codec<readonly [string], readonly [string]>>()
expect(schema).type.toBe<Schema.Tuple<readonly [Schema.withConstructorDefault<Schema.String>]>>()
expect(schema.annotate({})).type.toBe<Schema.Tuple<readonly [Schema.withConstructorDefault<Schema.String>]>>()
expect(schema.elements).type.toBe<readonly [Schema.withConstructorDefault<Schema.String>]>()
})
it("readonly [String, Number?]", () => {
const schema = Schema.Tuple([Schema.String, Schema.optionalKey(Schema.Number)])
expect(Schema.revealCodec(schema)).type.toBe<
@@ -976,14 +1215,6 @@ describe("Schema", () => {
})
})
it("encodedCodec", () => {
const schema = Schema.encodedCodec(Schema.FiniteFromString)
expect(Schema.revealCodec(schema)).type.toBe<
Schema.Codec<string, string, never, never>
>()
expect(schema.makeSync).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>()
})
it("decodeTo as composition", () => {
const From = Schema.Struct({
a: Schema.String,
@@ -1386,4 +1617,21 @@ describe("Schema", () => {
>()
})
})
describe("withConstructorDefault", () => {
it("effectful", () => {
const service = hole<Context.Tag<"Tag", "-">>()
const schema = Schema.String.pipe(Schema.withConstructorDefault(() =>
Effect.gen(function*() {
yield* Effect.serviceOption(service)
return Option.some("some-result")
})
))
expect(schema.makeSync).type.toBe<(input: string, options?: Schema.MakeOptions | undefined) => string>()
expect(Schema.revealCodec(schema)).type.toBe<Schema.Codec<string, string, never, never>>()
})
})
})
+85 -53
View File
@@ -75,6 +75,7 @@ export interface Bottom<
RebuildOut extends Top,
AnnotateIn extends SchemaAnnotations.Annotations,
TypeMakeIn = T,
TypeMake = TypeMakeIn,
TypeReadonly extends ReadonlyToken = "readonly",
TypeIsOptional extends OptionalToken = "required",
TypeDefault extends DefaultConstructorToken = "no-constructor-default",
@@ -93,6 +94,7 @@ export interface Bottom<
readonly "EncodingContext": RE
readonly "~type.make.in": TypeMakeIn
readonly "~type.make": TypeMake
readonly "~type.isReadonly": TypeReadonly
readonly "~type.isOptional": TypeIsOptional
readonly "~type.default": TypeDefault
@@ -128,6 +130,7 @@ export function revealBottom<S extends Top>(
S["~rebuild.out"],
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -167,6 +170,7 @@ export abstract class Bottom$<
RebuildOut extends Top,
AnnotateIn extends SchemaAnnotations.Annotations,
TypeMakeIn = T,
TypeMake = TypeMakeIn,
TypeReadonly extends ReadonlyToken = "readonly",
TypeIsOptional extends OptionalToken = "required",
TypeDefault extends DefaultConstructorToken = "no-constructor-default",
@@ -182,6 +186,7 @@ export abstract class Bottom$<
RebuildOut,
AnnotateIn,
TypeMakeIn,
TypeMake,
TypeReadonly,
TypeIsOptional,
TypeDefault,
@@ -200,6 +205,7 @@ export abstract class Bottom$<
declare readonly "~annotate.in": AnnotateIn
declare readonly "~type.make.in": TypeMakeIn
declare readonly "~type.make": TypeMake
declare readonly "~type.isReadonly": TypeReadonly
declare readonly "~type.isOptional": TypeIsOptional
declare readonly "~type.default": TypeDefault
@@ -243,6 +249,7 @@ export interface Top extends
Top,
SchemaAnnotations.Annotations,
unknown,
unknown,
ReadonlyToken,
OptionalToken,
DefaultConstructorToken,
@@ -560,6 +567,7 @@ class make$<S extends Top> extends Bottom$<
S["~rebuild.out"],
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -593,6 +601,7 @@ export function make<S extends Top>(ast: S["ast"]): Bottom<
S["~rebuild.out"],
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -627,6 +636,7 @@ export interface optionalKey<S extends Top> extends
optionalKey<S>,
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
"optional",
S["~type.default"],
@@ -666,6 +676,7 @@ export interface mutableKey<S extends Top> extends
mutableKey<S>,
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
"mutable",
S["~type.isOptional"],
S["~type.default"],
@@ -697,6 +708,7 @@ export interface typeCodec<S extends Top> extends
typeCodec<S>,
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -726,6 +738,7 @@ export interface encodedCodec<S extends Top> extends
encodedCodec<S>,
SchemaAnnotations.Annotations,
S["Encoded"],
S["Encoded"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -755,6 +768,7 @@ export interface flip<S extends Top> extends
flip<S>,
SchemaAnnotations.Annotations,
S["Encoded"],
S["Encoded"],
S["~encoded.isReadonly"],
S["~encoded.isOptional"],
DefaultConstructorToken,
@@ -998,7 +1012,7 @@ export function Enums<A extends { [x: string]: string | number }>(enums: A): Enu
* @since 4.0.0
*/
export interface Never
extends Bottom<never, never, never, never, SchemaAST.NeverKeyword, Never, SchemaAnnotations.Annotations>
extends Bottom<never, never, never, never, SchemaAST.NeverKeyword, Never, SchemaAnnotations.Bottom<never>>
{}
/**
@@ -1010,9 +1024,7 @@ export const Never: Never = make<Never>(SchemaAST.neverKeyword)
* @category Api interface
* @since 4.0.0
*/
export interface Any
extends Bottom<unknown, unknown, never, never, SchemaAST.AnyKeyword, Any, SchemaAnnotations.Annotations>
{}
export interface Any extends Bottom<any, any, never, never, SchemaAST.AnyKeyword, Any, SchemaAnnotations.Bottom<any>> {}
/**
* @since 4.0.0
@@ -1024,7 +1036,7 @@ export const Any: Any = make<Any>(SchemaAST.anyKeyword)
* @since 4.0.0
*/
export interface Unknown
extends Bottom<unknown, unknown, never, never, SchemaAST.UnknownKeyword, Unknown, SchemaAnnotations.Annotations>
extends Bottom<unknown, unknown, never, never, SchemaAST.UnknownKeyword, Unknown, SchemaAnnotations.Bottom<unknown>>
{}
/**
@@ -1037,7 +1049,7 @@ export const Unknown: Unknown = make<Unknown>(SchemaAST.unknownKeyword)
* @since 4.0.0
*/
export interface Null
extends Bottom<null, null, never, never, SchemaAST.NullKeyword, Null, SchemaAnnotations.Annotations>
extends Bottom<null, null, never, never, SchemaAST.NullKeyword, Null, SchemaAnnotations.Bottom<null>>
{}
/**
@@ -1049,9 +1061,16 @@ export const Null: Null = make<Null>(SchemaAST.nullKeyword)
* @category Api interface
* @since 4.0.0
*/
export interface Undefined
extends
Bottom<undefined, undefined, never, never, SchemaAST.UndefinedKeyword, Undefined, SchemaAnnotations.Annotations>
export interface Undefined extends
Bottom<
undefined,
undefined,
never,
never,
SchemaAST.UndefinedKeyword,
Undefined,
SchemaAnnotations.Bottom<undefined>
>
{}
/**
@@ -1064,7 +1083,7 @@ export const Undefined: Undefined = make<Undefined>(SchemaAST.undefinedKeyword)
* @since 4.0.0
*/
export interface String
extends Bottom<string, string, never, never, SchemaAST.StringKeyword, String, SchemaAnnotations.Annotations>
extends Bottom<string, string, never, never, SchemaAST.StringKeyword, String, SchemaAnnotations.Bottom<string>>
{}
/**
@@ -1079,7 +1098,7 @@ export const String: String = make<String>(SchemaAST.stringKeyword)
* @since 4.0.0
*/
export interface Number
extends Bottom<number, number, never, never, SchemaAST.NumberKeyword, Number, SchemaAnnotations.Annotations>
extends Bottom<number, number, never, never, SchemaAST.NumberKeyword, Number, SchemaAnnotations.Bottom<number>>
{}
/**
@@ -1092,7 +1111,7 @@ export const Number: Number = make<Number>(SchemaAST.numberKeyword)
* @since 4.0.0
*/
export interface Boolean
extends Bottom<boolean, boolean, never, never, SchemaAST.BooleanKeyword, Boolean, SchemaAnnotations.Annotations>
extends Bottom<boolean, boolean, never, never, SchemaAST.BooleanKeyword, Boolean, SchemaAnnotations.Bottom<boolean>>
{}
/**
@@ -1105,7 +1124,7 @@ export const Boolean: Boolean = make<Boolean>(SchemaAST.booleanKeyword)
* @since 4.0.0
*/
export interface Symbol
extends Bottom<symbol, symbol, never, never, SchemaAST.SymbolKeyword, Symbol, SchemaAnnotations.Annotations>
extends Bottom<symbol, symbol, never, never, SchemaAST.SymbolKeyword, Symbol, SchemaAnnotations.Bottom<symbol>>
{}
/**
@@ -1117,7 +1136,7 @@ export const Symbol: Symbol = make<Symbol>(SchemaAST.symbolKeyword)
* @since 4.0.0
*/
export interface BigInt
extends Bottom<bigint, bigint, never, never, SchemaAST.BigIntKeyword, BigInt, SchemaAnnotations.Annotations>
extends Bottom<bigint, bigint, never, never, SchemaAST.BigIntKeyword, BigInt, SchemaAnnotations.Bottom<bigint>>
{}
/**
@@ -1129,7 +1148,7 @@ export const BigInt: BigInt = make<BigInt>(SchemaAST.bigIntKeyword)
* @since 4.0.0
*/
export interface Void
extends Bottom<void, void, never, never, SchemaAST.VoidKeyword, Void, SchemaAnnotations.Annotations>
extends Bottom<void, void, never, never, SchemaAST.VoidKeyword, Void, SchemaAnnotations.Bottom<void>>
{}
/**
@@ -1141,7 +1160,7 @@ export const Void: Void = make<Void>(SchemaAST.voidKeyword)
* @since 4.0.0
*/
export interface Object$
extends Bottom<object, object, never, never, SchemaAST.ObjectKeyword, Object$, SchemaAnnotations.Annotations>
extends Bottom<object, object, never, never, SchemaAST.ObjectKeyword, Object$, SchemaAnnotations.Bottom<object>>
{}
const Object_: Object$ = make<Object$>(SchemaAST.objectKeyword)
@@ -1158,7 +1177,7 @@ export {
* @since 4.0.0
*/
export interface UniqueSymbol<sym extends symbol>
extends Bottom<sym, sym, never, never, SchemaAST.UniqueSymbol, UniqueSymbol<sym>, SchemaAnnotations.Annotations>
extends Bottom<sym, sym, never, never, SchemaAST.UniqueSymbol, UniqueSymbol<sym>, SchemaAnnotations.Bottom<sym>>
{}
/**
@@ -1251,8 +1270,8 @@ export declare namespace Struct {
F extends Fields,
O = TypeOptionalKeys<F> | TypeDefaultedKeys<F>
> =
& { readonly [K in keyof F as K extends O ? never : K]: F[K]["~type.make.in"] }
& { readonly [K in keyof F as K extends O ? K : never]?: F[K]["~type.make.in"] }
& { readonly [K in keyof F as K extends O ? never : K]: F[K]["~type.make"] }
& { readonly [K in keyof F as K extends O ? K : never]?: F[K]["~type.make"] }
/**
* @since 4.0.0
@@ -1353,7 +1372,7 @@ export declare namespace Record {
* @since 4.0.0
*/
export interface Key extends Codec<PropertyKey, PropertyKey, unknown, unknown> {
readonly "~type.make.in": PropertyKey
readonly "~type.make": PropertyKey
}
/**
@@ -1393,7 +1412,7 @@ export declare namespace Record {
* @since 4.0.0
*/
export type MakeIn<Key extends Record.Key, Value extends Top> = {
readonly [P in Key["~type.make.in"]]: Value["~type.make.in"]
readonly [P in Key["~type.make"]]: Value["~type.make"]
}
}
@@ -1403,14 +1422,14 @@ export declare namespace Record {
*/
export interface Record$<Key extends Record.Key, Value extends Top> extends
Bottom<
Record.Type<Key, Value>,
Record.Encoded<Key, Value>,
Simplify<Record.Type<Key, Value>>,
Simplify<Record.Encoded<Key, Value>>,
Record.DecodingContext<Key, Value>,
Record.EncodingContext<Key, Value>,
SchemaAST.TypeLiteral,
Record$<Key, Value>,
SchemaAnnotations.Bottom<Record.Type<Key, Value>>,
Record.MakeIn<Key, Value>
Simplify<Record.MakeIn<Key, Value>>
>
{
readonly key: Key
@@ -1508,8 +1527,8 @@ export declare namespace StructWithRest {
* @since 4.0.0
*/
export type MakeIn<S extends TypeLiteral, Records extends StructWithRest.Records> =
& S["~type.make.in"]
& MergeTuple<{ readonly [K in keyof Records]: Records[K]["~type.make.in"] }>
& S["~type.make"]
& MergeTuple<{ readonly [K in keyof Records]: Records[K]["~type.make"] }>
}
/**
@@ -1574,11 +1593,12 @@ export declare namespace Tuple {
export type Elements = ReadonlyArray<Element>
type Type_<
E,
Elements,
Out extends ReadonlyArray<any> = readonly []
> = E extends readonly [infer Head, ...infer Tail] ?
Head extends { readonly "~type.isOptional": "optional"; "Type": infer T } ? Type_<Tail, readonly [...Out, T?]>
: Head extends { readonly "~type.isOptional": OptionalToken; "Type": infer T } ? Type_<Tail, readonly [...Out, T]>
> = Elements extends readonly [infer Head, ...infer Tail] ?
Head extends { readonly "Type": infer T } ?
Head extends { readonly "~type.isOptional": "optional" } ? Type_<Tail, readonly [...Out, T?]>
: Type_<Tail, readonly [...Out, T]>
: Out
: Out
@@ -1588,13 +1608,12 @@ export declare namespace Tuple {
export type Type<E extends Elements> = Type_<E>
type Encoded_<
E,
Elements,
Out extends ReadonlyArray<any> = readonly []
> = E extends readonly [infer Head, ...infer Tail] ?
Head extends { readonly "~encoded.isOptional": "optional"; "Encoded": infer T } ?
Encoded_<Tail, readonly [...Out, T?]>
: Head extends { readonly "~encoded.isOptional": OptionalToken; "Encoded": infer T } ?
Encoded_<Tail, readonly [...Out, T]>
> = Elements extends readonly [infer Head, ...infer Tail] ?
Head extends { readonly "Encoded": infer T } ?
Head extends { readonly "~encoded.isOptional": "optional" } ? Encoded_<Tail, readonly [...Out, T?]>
: Encoded_<Tail, readonly [...Out, T]>
: Out
: Out
@@ -1617,12 +1636,13 @@ export declare namespace Tuple {
E,
Out extends ReadonlyArray<any> = readonly []
> = E extends readonly [infer Head, ...infer Tail] ?
Head extends { readonly "~type.isOptional": "optional"; "~type.make.in": infer T } ?
MakeIn_<Tail, readonly [...Out, T?]>
: Head extends { readonly "~type.isOptional": "required"; "~type.make.in": infer T } ?
Head extends { "~type.make": infer T } ?
Head extends
{ readonly "~type.isOptional": "optional" } | { readonly "~type.default": "has-constructor-default" } ?
MakeIn_<Tail, readonly [...Out, T?]> :
MakeIn_<Tail, readonly [...Out, T]>
: Out
: Out
: Out :
Out
/**
* @since 4.0.0
@@ -1686,7 +1706,7 @@ export declare namespace TupleWithRest {
readonly Type: ReadonlyArray<unknown>
readonly Encoded: ReadonlyArray<unknown>
readonly ast: SchemaAST.TupleType
readonly "~type.make.in": ReadonlyArray<unknown>
readonly "~type.make": ReadonlyArray<unknown>
}
/**
@@ -1709,21 +1729,21 @@ export declare namespace TupleWithRest {
* @since 4.0.0
*/
export type Encoded<E extends ReadonlyArray<unknown>, Rest extends TupleWithRest.Rest> = Rest extends
readonly [infer Head extends Top, ...infer Tail extends ReadonlyArray<Top>] ? Readonly<[
readonly [infer Head extends Top, ...infer Tail extends ReadonlyArray<Top>] ? readonly [
...E,
...ReadonlyArray<Head["Encoded"]>,
...Array<Head["Encoded"]>,
...{ readonly [K in keyof Tail]: Tail[K]["Encoded"] }
]> :
] :
E
/**
* @since 4.0.0
*/
export type MakeIn<M extends ReadonlyArray<unknown>, Rest extends TupleWithRest.Rest> = Rest extends
readonly [infer Head extends Top, ...infer Tail extends ReadonlyArray<Top>] ? [
readonly [infer Head extends Top, ...infer Tail extends ReadonlyArray<Top>] ? readonly [
...M,
...ReadonlyArray<Head["~type.make.in"]>,
...{ readonly [K in keyof Tail]: Tail[K]["~type.make.in"] }
...Array<Head["~type.make"]>,
...{ readonly [K in keyof Tail]: Tail[K]["~type.make"] }
] :
M
}
@@ -1744,7 +1764,7 @@ export interface TupleWithRest<
SchemaAST.TupleType,
TupleWithRest<S, Rest>,
SchemaAnnotations.Bottom<TupleWithRest.Type<S["Type"], Rest>>,
TupleWithRest.MakeIn<S["~type.make.in"], Rest>
TupleWithRest.MakeIn<S["~type.make"], Rest>
>
{
readonly schema: S
@@ -1785,7 +1805,7 @@ export interface Array$<S extends Top> extends
SchemaAST.TupleType,
Array$<S>,
SchemaAnnotations.Bottom<ReadonlyArray<S["Type"]>>,
ReadonlyArray<S["~type.make.in"]>
ReadonlyArray<S["~type.make"]>
>
{
readonly schema: S
@@ -1812,9 +1832,10 @@ export interface mutable<S extends Top> extends
S["EncodingContext"],
S["ast"],
mutable<S>,
// we keep "~annotate.in" and "~type.make.in" as they are because they are contravariant
// we keep "~annotate.in", "~type.make" and "~type.make.in" as they are because they are contravariant
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -1843,9 +1864,10 @@ export interface readonly$<S extends Top> extends
S["EncodingContext"],
S["ast"],
readonly$<S>,
// we keep "~annotate.in" and "~type.make.in" as they are because they are contravariant
// we keep "~annotate.in", "~type.make" and "~type.make.in" as they are because they are contravariant
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -1875,7 +1897,7 @@ export interface Union<Members extends ReadonlyArray<Top>> extends
SchemaAST.UnionType<Members[number]["ast"]>,
Union<Members>,
SchemaAnnotations.Bottom<Members[number]["Type"]>,
Members[number]["~type.make.in"]
Members[number]["~type.make"]
>
{
readonly members: Members
@@ -1988,6 +2010,7 @@ export interface suspend<S extends Top> extends
suspend<S>,
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -2042,6 +2065,7 @@ export interface refine<T extends S["Type"], S extends Top> extends
refine<T, S["~rebuild.out"]>,
S["~annotate.in"],
S["~type.make.in"],
T,
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -2100,6 +2124,7 @@ export interface decodingMiddleware<S extends Top, RD> extends
decodingMiddleware<S, RD>,
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -2142,6 +2167,7 @@ export interface encodingMiddleware<S extends Top, RE> extends
encodingMiddleware<S, RE>,
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -2228,6 +2254,7 @@ export interface decodeTo<To extends Top, From extends Top, RD, RE> extends
decodeTo<To, From, RD, RE>,
To["~annotate.in"],
To["~type.make.in"],
To["~type.make"],
To["~type.isReadonly"],
To["~type.isOptional"],
To["~type.default"],
@@ -2357,6 +2384,7 @@ export interface withConstructorDefault<S extends Top> extends
withConstructorDefault<S>,
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
"has-constructor-default",
@@ -2373,6 +2401,7 @@ export interface withConstructorDefault<S extends Top> extends
export function withConstructorDefault<S extends Top & { readonly "~type.default": "no-constructor-default" }>(
defaultValue: (
input: O.Option<undefined>
// `"~type.make.in"` is intentional here because it makes easier to define the default value
) => O.Option<S["~type.make.in"]> | Effect.Effect<O.Option<S["~type.make.in"]>>
) {
return (self: S): withConstructorDefault<S> => {
@@ -2503,6 +2532,7 @@ export interface Opaque<Self, S extends Top> extends
S["~rebuild.out"],
S["~annotate.in"],
S["~type.make.in"],
S["~type.make"],
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -2696,6 +2726,7 @@ export interface Class<Self, S extends Top & { readonly fields: Struct.Fields },
Class<Self, S, Self>,
SchemaAnnotations.Declaration<Self, readonly [S]>,
S["~type.make.in"],
Self,
S["~type.isReadonly"],
S["~type.isOptional"],
S["~type.default"],
@@ -2761,6 +2792,7 @@ function makeClass<
declare static readonly "~rebuild.out": Class<Self, S, Self>
declare static readonly "~annotate.in": SchemaAnnotations.Declaration<Self, readonly [S]>
declare static readonly "~type.make.in": S["~type.make.in"]
declare static readonly "~type.make": Self
declare static readonly "~type.isReadonly": S["~type.isReadonly"]
declare static readonly "~type.isOptional": S["~type.isOptional"]
+146 -107
View File
@@ -1935,125 +1935,166 @@ describe("Schema", () => {
})
describe("withConstructorDefault", () => {
it("should not apply defaults when decoding / encoding", async () => {
const schema = Schema.Struct({
a: Schema.String.pipe(Schema.optionalKey, Schema.withConstructorDefault(() => Option.some("a")))
})
await assertions.decoding.succeed(schema, {})
await assertions.encoding.succeed(schema, {}, {})
})
it("should pass the input to the default value", () => {
const schema = Schema.Struct({
a: Schema.String.pipe(
Schema.UndefinedOr,
Schema.withConstructorDefault((o) => {
if (Option.isSome(o)) {
return Option.some("undefined-default")
}
return Option.some("otherwise-default")
})
)
})
assertions.makeSync.succeed(schema, { a: "a" })
assertions.makeSync.succeed(schema, {}, { a: "otherwise-default" })
assertions.makeSync.succeed(schema, { a: undefined }, { a: "undefined-default" })
})
it("Struct & Some", () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
})
assertions.makeSync.succeed(schema, { a: 1 })
assertions.makeSync.succeed(schema, {}, { a: -1 })
})
it("Struct & None", () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.none()))
})
assertions.makeSync.succeed(schema, { a: 1 })
assertions.makeSync.fail(schema, {})
})
describe("nested defaults", () => {
it("Struct", () => {
describe("Struct", () => {
it("should not apply defaults when decoding / encoding", async () => {
const schema = Schema.Struct({
a: Schema.Struct({
b: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.withConstructorDefault(() => Option.some({})))
a: Schema.String.pipe(Schema.optionalKey, Schema.withConstructorDefault(() => Option.some("a")))
})
assertions.makeSync.succeed(schema, { a: { b: 1 } })
assertions.makeSync.succeed(schema, { a: {} }, { a: { b: -1 } })
assertions.makeSync.succeed(schema, {}, { a: { b: -1 } })
await assertions.decoding.succeed(schema, {})
await assertions.encoding.succeed(schema, {}, {})
})
it("Class", () => {
class A extends Schema.Class<A>("A")(Schema.Struct({
a: Schema.Struct({
b: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.withConstructorDefault(() => Option.some({})))
})) {}
it("should pass the input to the default value", () => {
const schema = Schema.Struct({
a: Schema.String.pipe(
Schema.UndefinedOr,
Schema.withConstructorDefault((o) => {
if (Option.isSome(o)) {
return Option.some("undefined-default")
}
return Option.some("otherwise-default")
})
)
})
assertions.makeSync.succeed(A, { a: { b: 1 } }, new A({ a: { b: 1 } }))
assertions.makeSync.succeed(A, { a: {} }, new A({ a: { b: -1 } }))
assertions.makeSync.succeed(A, {}, new A({ a: { b: -1 } }))
})
})
it("Struct & Effect sync", () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Effect.succeed(Option.some(-1))))
assertions.makeSync.succeed(schema, { a: "a" })
assertions.makeSync.succeed(schema, {}, { a: "otherwise-default" })
assertions.makeSync.succeed(schema, { a: undefined }, { a: "undefined-default" })
})
assertions.makeSync.succeed(schema, { a: 1 })
assertions.makeSync.succeed(schema, {}, { a: -1 })
})
it("Struct & Some", () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
})
it("Struct & Effect async", async () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() =>
Effect.gen(function*() {
yield* Effect.sleep(100)
return Option.some(-1)
assertions.makeSync.succeed(schema, { a: 1 })
assertions.makeSync.succeed(schema, {}, { a: -1 })
})
it("Struct & None", () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.none()))
})
assertions.makeSync.succeed(schema, { a: 1 })
assertions.makeSync.fail(schema, {})
})
describe("nested defaults", () => {
it("Struct", () => {
const schema = Schema.Struct({
a: Schema.Struct({
b: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.withConstructorDefault(() => Option.some({})))
})
))
assertions.makeSync.succeed(schema, { a: { b: 1 } })
assertions.makeSync.succeed(schema, { a: {} }, { a: { b: -1 } })
assertions.makeSync.succeed(schema, {}, { a: { b: -1 } })
})
it("Class", () => {
class A extends Schema.Class<A>("A")(Schema.Struct({
a: Schema.Struct({
b: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.withConstructorDefault(() => Option.some({})))
})) {}
assertions.makeSync.succeed(A, { a: { b: 1 } }, new A({ a: { b: 1 } }))
assertions.makeSync.succeed(A, { a: {} }, new A({ a: { b: -1 } }))
assertions.makeSync.succeed(A, {}, new A({ a: { b: -1 } }))
})
})
await assertions.make.succeed(schema, { a: 1 })
await assertions.make.succeed(schema, {}, { a: -1 })
it("Struct & Effect sync", () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Effect.succeed(Option.some(-1))))
})
assertions.makeSync.succeed(schema, { a: 1 })
assertions.makeSync.succeed(schema, {}, { a: -1 })
})
it("Struct & Effect async", async () => {
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() =>
Effect.gen(function*() {
yield* Effect.sleep(100)
return Option.some(-1)
})
))
})
await assertions.make.succeed(schema, { a: 1 })
await assertions.make.succeed(schema, {}, { a: -1 })
})
it("Struct & Effect async & service", async () => {
class Service extends Context.Tag<Service, { value: Effect.Effect<number> }>()("Service") {}
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() =>
Effect.gen(function*() {
yield* Effect.sleep(100)
const oservice = yield* Effect.serviceOption(Service)
if (Option.isNone(oservice)) {
return Option.none()
}
return Option.some(yield* oservice.value.value)
})
))
})
await assertions.make.succeed(schema, { a: 1 })
const spr = SchemaToParser.makeSchemaResult(schema)({})
const eff = SchemaResult.asEffect(spr)
const provided = Effect.provideService(
eff,
Service,
Service.of({ value: Effect.succeed(-1) })
)
await assertions.effect.succeed(provided, { a: -1 })
})
})
it("Struct & Effect async & service", async () => {
class Service extends Context.Tag<Service, { value: Effect.Effect<number> }>()("Service") {}
describe("Tuple", () => {
it("Tuple & Some", () => {
const schema = Schema.Tuple(
[Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))]
)
const schema = Schema.Struct({
a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() =>
Effect.gen(function*() {
yield* Effect.sleep(100)
const oservice = yield* Effect.serviceOption(Service)
if (Option.isNone(oservice)) {
return Option.none()
}
return Option.some(yield* oservice.value.value)
})
))
assertions.makeSync.succeed(schema, [1])
assertions.makeSync.succeed(schema, [], [-1])
})
await assertions.make.succeed(schema, { a: 1 })
const spr = SchemaToParser.makeSchemaResult(schema)({})
const eff = SchemaResult.asEffect(spr)
const provided = Effect.provideService(
eff,
Service,
Service.of({ value: Effect.succeed(-1) })
)
await assertions.effect.succeed(provided, { a: -1 })
it("nested defaults (Struct)", () => {
const schema = Schema.Tuple(
[
Schema.Struct({
b: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
}).pipe(Schema.withConstructorDefault(() => Option.some({})))
]
)
assertions.makeSync.succeed(schema, [{ b: 1 }])
assertions.makeSync.succeed(schema, [{}], [{ b: -1 }])
assertions.makeSync.succeed(schema, [], [{ b: -1 }])
})
it("nested defaults (Tuple)", () => {
const schema = Schema.Tuple(
[
Schema.Tuple([
Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => Option.some(-1)))
]).pipe(Schema.withConstructorDefault(() => Option.some([] as const)))
]
)
assertions.makeSync.succeed(schema, [[1]])
assertions.makeSync.succeed(schema, [[]], [[-1]])
assertions.makeSync.succeed(schema, [], [[-1]])
})
})
})
@@ -3201,7 +3242,7 @@ describe("Schema", () => {
})
it("Struct with nested Class", () => {
class A extends Schema.Class<A>("A")(Schema.Struct({
class A extends Schema.Class<A, { readonly brand: unique symbol }>("A")(Schema.Struct({
a: Schema.String
})) {}
const schema = Schema.Struct({
@@ -3209,21 +3250,19 @@ describe("Schema", () => {
})
assertions.makeSync.succeed(schema, { a: new A({ a: "a" }) })
assertions.makeSync.succeed(schema, { a: { a: "a" } }, { a: new A({ a: "a" }) })
assertions.makeSync.succeed(schema, {}, { a: new A({ a: "default" }) })
})
it("Class with nested Class", () => {
class A extends Schema.Class<A>("A")(Schema.Struct({
class A extends Schema.Class<A, { readonly brand: unique symbol }>("A")(Schema.Struct({
a: Schema.String
})) {}
class B extends Schema.Class<B>("B")(Schema.Struct({
class B extends Schema.Class<B, { readonly brand: unique symbol }>("B")(Schema.Struct({
a: A.pipe(Schema.withConstructorDefault(() => Option.some(new A({ a: "default" }))))
})) {}
const schema = B
assertions.makeSync.succeed(schema, { a: new A({ a: "a" }) }, new B({ a: new A({ a: "a" }) }))
assertions.makeSync.succeed(schema, { a: { a: "a" } }, new B({ a: new A({ a: "a" }) }))
assertions.makeSync.succeed(schema, {}, new B({ a: new A({ a: "default" }) }))
})
+5 -5
View File
@@ -146,8 +146,8 @@ importers:
specifier: ^5.39.0
version: 5.39.0
tstyche:
specifier: 4.0.0-rc.0
version: 4.0.0-rc.0(typescript@5.8.3)
specifier: 4.0.0
version: 4.0.0(typescript@5.8.3)
tsx:
specifier: ^4.17.0
version: 4.19.4
@@ -3360,8 +3360,8 @@ packages:
tslib@2.8.1:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
tstyche@4.0.0-rc.0:
resolution: {integrity: sha512-hoQTsjqHP0saFwXDaMgB6aM/9eRhd8T11qeyVfMJkodpUR0J24hs5Kwn+1CVTD+0pmu9n0xfif3zGxZcvtwBZQ==}
tstyche@4.0.0:
resolution: {integrity: sha512-ek8LfTl/raR7VB1bjmSxUjNByGHtJlaCNWeudTASRF4ykLQqTPKcK0HhsOv5LiM1+OEBJ7bmeD+DlrjQPTozVw==}
engines: {node: '>=20.9'}
hasBin: true
peerDependencies:
@@ -7118,7 +7118,7 @@ snapshots:
tslib@2.8.1: {}
tstyche@4.0.0-rc.0(typescript@5.8.3):
tstyche@4.0.0(typescript@5.8.3):
optionalDependencies:
typescript: 5.8.3