add decode / encode APIs + renaming (#130)

* add decode / encode APIs + renaming

* fix bundle

* all transformation as functions

* rename SchemaParser to SchemaToParser

* fix

* remove useless transformations

* fix bundles

* enhance decodeTo / encodeTo to act as composition operators
This commit is contained in:
Giulio Canti
2025-05-22 17:02:16 +02:00
committed by GitHub
parent 84045cb8a2
commit ebb3f8d47e
19 changed files with 595 additions and 329 deletions
+6 -8
View File
@@ -1,21 +1,19 @@
import * as Duration from "#dist/effect/Duration"
import * as Effect from "#dist/effect/Effect"
import * as Option from "#dist/effect/Option"
import * as Result from "#dist/effect/Result"
import * as Schema from "#dist/effect/Schema"
import * as SchemaParser from "#dist/effect/SchemaParser"
import * as SchemaTransformation from "#dist/effect/SchemaTransformation"
const schema = Schema.String.pipe(Schema.decodeTo(
Schema.String,
SchemaTransformation.transformOrFail(
(s) =>
SchemaTransformation.transformOrFail({
decode: (s) =>
Effect.gen(function*() {
yield* Effect.clockWith((clock) => clock.sleep(Duration.millis(300)))
return Option.some(s)
return s
}),
(s) => Result.succeedSome(s)
)
encode: Result.ok
})
))
SchemaParser.decodeUnknown(schema)("a").pipe(Effect.runPromise).then(console.log)
Schema.decodeUnknownEffect(schema)("a").pipe(Effect.runPromise).then(console.log)
+1 -2
View File
@@ -1,7 +1,6 @@
import * as Schema from "#dist/effect/Schema"
import * as SchemaCheck from "#dist/effect/SchemaCheck"
import * as SchemaParser from "#dist/effect/SchemaParser"
const schema = Schema.String.pipe(Schema.check(SchemaCheck.nonEmpty))
console.log(SchemaParser.decodeUnknownSync(schema)("a"))
console.log(Schema.decodeUnknownSync(schema)("a"))
+1 -2
View File
@@ -1,6 +1,5 @@
import * as Schema from "#dist/effect/Schema"
import * as SchemaParser from "#dist/effect/SchemaParser"
const schema = Schema.String
console.log(SchemaParser.decodeUnknownSync(schema)("a"))
console.log(Schema.decodeUnknownSync(schema)("a"))
+1 -2
View File
@@ -1,5 +1,4 @@
import * as Schema from "#dist/effect/Schema"
import * as SchemaParser from "#dist/effect/SchemaParser"
const schema = Schema.Struct({
a: Schema.String,
@@ -7,4 +6,4 @@ const schema = Schema.Struct({
c: Schema.ReadonlyArray(Schema.String)
})
console.log(SchemaParser.decodeUnknownSync(schema)({ a: "a", b: 1, c: ["c"] }))
console.log(Schema.decodeUnknownSync(schema)({ a: "a", b: 1, c: ["c"] }))
+128 -114
View File
@@ -23,22 +23,13 @@ flowchart TD
end
```
## Current Pain Points
These are known limitations and difficulties:
- `partial` only allows toggling all fields at once, which limits flexibility.
- Suspended schemas are awkward to use.
- Performance and bundle size need improvement.
- (optional) Custom error handling is limited ([example](https://discord.com/channels/795981131316985866/1347665724361019433/1347831833282347079)).
## Type Hierarchy
```mermaid
flowchart TD
T[Top] --> S["Schema[T]"]
S --> C["Codec[T, E, RD, RE]"]
C --> B["Bottom[T,E, RD, RE, Ast, CloneOut, AnnotateIn, MakeIn, TypeReadonly, TypeIsOptional, TypeDefault, EncodedIsReadonly, EncodedIsOptional]"]
C --> B["Bottom[T, E, RD, RE, Ast, RebuildOut, AnnotateIn, TypeMakeIn, TypeReadonly, TypeIsOptional, TypeDefault, EncodedIsReadonly, EncodedIsOptional]"]
```
## More Requirement Type Parameters
@@ -73,11 +64,11 @@ const schema = Schema.Struct({
// ┌─── Effect.Effect<{ readonly a: string; }, Schema.CodecError, never>
// ▼
const dec = Schema.decodeUnknown(schema)({ a: "a" })
const dec = Schema.decodeUnknownEffect(schema)({ a: "a" })
// ┌─── Effect.Effect<{ readonly a: string; }, Schema.CodecError, EncodingService>
// ▼
const enc = Schema.encodeUnknown(schema)({ a: "a" })
const enc = Schema.encodeUnknownEffect(schema)({ a: "a" })
```
## Default JSON Serialization
@@ -217,13 +208,13 @@ const User = Schema.Struct({
const data = { id: 1, name: Option.some("John") }
const program = Effect.gen(function* () {
const json = yield* Schema.encode(
const json = yield* Schema.encodeEffect(
SchemaSerializer.json(Schema.typeCodec(User))
)(data)
console.log(json)
const t = yield* Schema.decode(SchemaSerializer.json(Schema.typeCodec(User)))(
json
)
const t = yield* Schema.decodeEffect(
SchemaSerializer.json(Schema.typeCodec(User))
)(json)
console.log(t)
})
@@ -242,7 +233,7 @@ import { Schema } from "effect"
// Flips a schema that decodes a string into a number,
// turning it into one that decodes a number into a string
//
// const StringFromFinite: Schema.flip<Schema.decodeTo<Schema.Number, Schema.String, never, never>>
// const StringFromFinite: flip<decodeTo<Number, String, never, never>>
const StringFromFinite = Schema.flip(Schema.FiniteFromString)
// Schema.Codec<string, number, never, never>
@@ -256,7 +247,7 @@ import { Schema } from "effect"
const StringFromFinite = Schema.flip(Schema.FiniteFromString)
// Schema.decodeTo<Schema.Number, Schema.String, never, never>
// decodeTo<Number, String, never, never>
StringFromFinite.schema
```
@@ -265,7 +256,7 @@ Applying `flip` twice will return a schema with the same shape as the original o
```ts
import { Schema } from "effect"
// const schema: Schema.decodeTo<Schema.Number, Schema.String, never, never>
// const schema: decodeTo<Number, String, never, never>
const schema = Schema.flip(Schema.flip(Schema.FiniteFromString))
```
@@ -496,7 +487,7 @@ const schema = Schema.Option(Schema.String).pipe(
Schema.refine(Option.isSome, { title: "Some" })
)
Schema.decodeUnknown(schema)(Option.none())
Schema.decodeUnknownEffect(schema)(Option.none())
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -531,7 +522,7 @@ const schema = Schema.String.pipe(
)
)
Schema.decodeUnknown(schema)(" a")
Schema.decodeUnknownEffect(schema)(" a")
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -556,7 +547,7 @@ const schema = Schema.Struct({ length: Schema.Number }).pipe(
Schema.check(SchemaCheck.minLength(3))
)
Schema.decodeUnknown(schema)({ length: 2 })
Schema.decodeUnknownEffect(schema)({ length: 2 })
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -581,7 +572,7 @@ const schema = Schema.String.pipe(
Schema.check(SchemaCheck.minLength(3), SchemaCheck.trimmed)
)
Schema.decodeUnknown(schema)(" a", { errors: "all" })
Schema.decodeUnknownEffect(schema)(" a", { errors: "all" })
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -611,7 +602,7 @@ const schema = Schema.String.pipe(
)
)
Schema.decodeUnknown(schema)(" a", { errors: "all" })
Schema.decodeUnknownEffect(schema)(" a", { errors: "all" })
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -1089,7 +1080,7 @@ console.log(Schema.decodeUnknownSync(Product)({ quantity: "2" }))
import { Schema, SchemaTransformation } from "effect"
const SnakeToCamel = Schema.String.pipe(
Schema.decodeTo(Schema.String, SchemaTransformation.snakeToCamel)
Schema.decode(SchemaTransformation.snakeToCamel())
)
const schema = Schema.ReadonlyRecord(SnakeToCamel, Schema.Number)
@@ -1106,7 +1097,7 @@ By default duplicate keys are merged with the last value.
import { Schema, SchemaTransformation } from "effect"
const SnakeToCamel = Schema.String.pipe(
Schema.decodeTo(Schema.String, SchemaTransformation.snakeToCamel)
Schema.decode(SchemaTransformation.snakeToCamel())
)
const schema = Schema.ReadonlyRecord(SnakeToCamel, Schema.Number)
@@ -1123,7 +1114,7 @@ You can also customize how duplicate keys are merged.
import { Schema, SchemaTransformation } from "effect"
const SnakeToCamel = Schema.String.pipe(
Schema.decodeTo(Schema.String, SchemaTransformation.snakeToCamel)
Schema.decode(SchemaTransformation.snakeToCamel())
)
const schema = Schema.ReadonlyRecord(SnakeToCamel, Schema.Number, {
@@ -1279,7 +1270,7 @@ class Person extends Schema.Opaque<Person>()(
.annotate({ title: "Person" })
) {}
Schema.decodeUnknown(Person)({ name: "" })
Schema.decodeUnknownEffect(Person)({ name: "" })
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -1776,7 +1767,7 @@ const schema = Schema.Union(
{ mode: "oneOf" }
)
Schema.decodeUnknown(schema)({ a: "a", b: 1 })
Schema.decodeUnknownEffect(schema)({ a: "a", b: 1 })
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -1796,119 +1787,141 @@ Transformations are now treated as first-class values, rather than being tied to
For example, `trim` is no longer just a codec combinator. It is now a standalone transformation that can be used with any codec that supports it—in this case, any codec working with strings.
**Example** (Using a transformation with debug logging)
**Example**
```ts
import { Option, Schema, SchemaTransformation } from "effect"
import { Schema, SchemaTransformation } from "effect"
// Wrap the trim transformation with debug logging
const trim = SchemaTransformation.tap(SchemaTransformation.trim, {
onDecode: (o) => {
if (Option.isSome(o)) {
console.log(`about to trim "${o.value}"`)
}
}
})
// Decode a string, trim it, then parse it into a number
const schema = Schema.String.pipe(Schema.decodeTo(Schema.String, trim))
const schema = Schema.String.pipe(Schema.decode(SchemaTransformation.trim()))
console.log(Schema.decodeUnknownSync(schema)(" 123"))
/*
about to trim " 123"
123
*/
// 123
```
### Composition
### Transformation Composition
#### compose
Transformation composition is the process of combining multiple transformations into a single transformation.
The `compose` transformation lets you convert from one schema to another when the encoded output of the target schema matches the type of the source schema.
```ts
import { SchemaTransformation } from "effect"
/*
decoding: trim + toLowerCase
encoding: passthrough
*/
const trimToLowerCase = SchemaTransformation.trim().compose(
SchemaTransformation.toLowerCase()
)
```
### Schema Composition
#### decodeTo / encodeTo
The `Schema.decodeTo` API allows you to compose two schemas without requiring the types to match. It skips type checking during the transformation and focuses on structure alone.
```ts
import { Schema } from "effect"
const From = Schema.Struct({
a: Schema.String,
b: Schema.FiniteFromString
})
const To = Schema.Struct({
a: Schema.FiniteFromString,
b: Schema.UndefinedOr(Schema.Number)
})
const schema = From.pipe(Schema.decodeTo(To))
```
This approach is useful when you want to connect schemas without enforcing type compatibility between them.
If you want more control over how the types align, such as ensuring one is a subtype or supertype of the other, you can use the `SchemaTransformation.passthrough*` helpers.
The `Schema.encodeTo` API is the same as `Schema.decodeTo` but it applies the composition in the other direction.
```ts
import { Schema } from "effect"
const From = Schema.Struct({
a: Schema.String,
b: Schema.FiniteFromString
})
const To = Schema.Struct({
a: Schema.FiniteFromString,
b: Schema.UndefinedOr(Schema.Number)
})
const schema = To.pipe(Schema.encodeTo(From)) // same as From.pipe(Schema.decodeTo(To))
```
#### passthrough
The `passthrough` transformation lets you convert from one schema to another when the encoded output of the target schema matches the type of the source schema.
**Example** (Composing schemas where `To.Encoded = From.Type`)
```ts
import { Schema, SchemaGetter, SchemaTransformation } from "effect"
const FiniteFromString = Schema.String.pipe(
Schema.decodeTo(Schema.Finite, {
decode: SchemaGetter.Number,
encode: SchemaGetter.String
})
)
import { Schema, SchemaTransformation } from "effect"
const From = Schema.Struct({
a: Schema.String,
b: Schema.String
a: Schema.String
})
const To = Schema.Struct({
a: FiniteFromString,
b: FiniteFromString
a: Schema.FiniteFromString
})
// To.Encoded (string) = From.Type (string)
const schema = From.pipe(
Schema.decodeTo(To, SchemaTransformation.compose({ strict: false }))
Schema.decodeTo(To, SchemaTransformation.passthrough())
)
```
#### composeSupertype
#### passthroughSubtype
Use `composeSupertype` when your source type extends the encoded output of your target schema.
Use `passthroughSubtype` when your source type extends the encoded output of your target schema.
**Example** (Composing schemas where `From.Type extends To.Encoded`)
```ts
import { Schema, SchemaGetter, SchemaTransformation } from "effect"
import { Schema, SchemaTransformation } from "effect"
const FiniteFromString = Schema.String.pipe(
Schema.decodeTo(Schema.Finite, {
decode: SchemaGetter.Number,
encode: SchemaGetter.String
})
)
const From = FiniteFromString
const From = Schema.FiniteFromString
const To = Schema.UndefinedOr(Schema.Number)
// From.Type (number) extends To.Encoded (number | undefined)
const schema = From.pipe(
Schema.decodeTo(To, SchemaTransformation.composeSupertype())
Schema.decodeTo(To, SchemaTransformation.passthroughSubtype())
)
```
#### composeSubtype
#### passthroughSupertype
Use `composeSubtype` when the encoded output of your target schema extends the type of your source schema.
Use `passthroughSupertype` when the encoded output of your target schema extends the type of your source schema.
**Example** (Composing schemas where `From.Encoded extends To.Type`)
```ts
import { Schema, SchemaGetter, SchemaTransformation } from "effect"
const FiniteFromString = Schema.String.pipe(
Schema.decodeTo(Schema.Finite, {
decode: SchemaGetter.Number,
encode: SchemaGetter.String
})
)
import { Schema, SchemaTransformation } from "effect"
const From = Schema.UndefinedOr(Schema.String)
const To = FiniteFromString
const To = Schema.FiniteFromString
// To.Encoded (string) extends From.Type (string | undefined)
const schema = From.pipe(
Schema.decodeTo(To, SchemaTransformation.composeSubtype())
Schema.decodeTo(To, SchemaTransformation.passthroughSupertype())
)
```
#### Turning off strict mode
To turn off strict mode, pass `{ strict: false }` to `compose`
To turn off strict mode, pass `{ strict: false }` to `passthrough`
```ts
import { Schema, SchemaTransformation } from "effect"
@@ -1918,7 +1931,7 @@ const From = Schema.String
const To = Schema.Number
const schema = From.pipe(
Schema.decodeTo(To, SchemaTransformation.compose({ strict: false }))
Schema.decodeTo(To, SchemaTransformation.passthrough({ strict: false }))
)
```
@@ -1966,7 +1979,7 @@ import { Effect, Option, Result, Schema, SchemaFormatter } from "effect"
const fallback = Result.ok(Option.some("b"))
const schema = Schema.String.pipe(Schema.catchDecoding(() => fallback))
Schema.decodeUnknown(schema)(null)
Schema.decodeUnknownEffect(schema)(null)
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -2009,7 +2022,7 @@ const provided = schema.pipe(
)
)
Schema.decodeUnknown(provided)(null)
Schema.decodeUnknownEffect(provided)(null)
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -2033,7 +2046,7 @@ const schema = Schema.Struct({
b: Schema.Number
})
Schema.decodeUnknown(schema)({ a: "", b: null }, { errors: "all" })
Schema.decodeUnknownEffect(schema)({ a: "", b: null }, { errors: "all" })
.pipe(
Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)),
Effect.runPromise
@@ -2061,7 +2074,7 @@ const schema = Schema.Struct({
b: Schema.Number
})
Schema.decodeUnknown(schema)({ a: "", b: null }, { errors: "all" })
Schema.decodeUnknownEffect(schema)({ a: "", b: null }, { errors: "all" })
.pipe(
Effect.mapError((err) =>
SchemaFormatter.StructuredFormatter.format(err.issue)
@@ -2103,7 +2116,9 @@ Output:
*/
```
## Primitives
## Usage
### Primitives
```ts
import { Schema } from "effect"
@@ -2121,23 +2136,26 @@ Schema.Null
To coerce input data to the appropriate type:
```ts
import { Schema, SchemaParser, SchemaTransformation } from "effect"
import { Schema, SchemaGetter, SchemaToParser } from "effect"
// ┌─── Codec<string, unknown>
// ▼
const schema = Schema.Unknown.pipe(
Schema.decodeTo(Schema.String, SchemaTransformation.String)
Schema.decodeTo(Schema.String, {
decode: SchemaGetter.String(),
encode: SchemaGetter.passthrough()
})
)
const parse = SchemaParser.decodeUnknownSync(schema)
const parser = SchemaToParser.decodeUnknownSync(schema)
console.log(parse("tuna")) // => "tuna"
console.log(parse(42)) // => "42"
console.log(parse(true)) // => "true"
console.log(parse(null)) // => "null"
console.log(parser("tuna")) // => "tuna"
console.log(parser(42)) // => "42"
console.log(parser(true)) // => "true"
console.log(parser(null)) // => "null"
```
## Literals
### Literals
Literal types:
@@ -2186,7 +2204,7 @@ const schema = Schema.Literals(["red", "green", "blue"])
schema.literals
```
## Strings
### Strings
```ts
import { Schema, SchemaCheck } from "effect"
@@ -2207,16 +2225,12 @@ To perform some simple string transforms:
```ts
import { Schema, SchemaTransformation } from "effect"
Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.trim))
Schema.String.pipe(
Schema.decodeTo(Schema.String, SchemaTransformation.toLowerCase)
)
Schema.String.pipe(
Schema.decodeTo(Schema.String, SchemaTransformation.toUpperCase)
)
Schema.String.pipe(Schema.decode(SchemaTransformation.trim()))
Schema.String.pipe(Schema.decode(SchemaTransformation.toLowerCase()))
Schema.String.pipe(Schema.decode(SchemaTransformation.toUpperCase()))
```
## String formats
### String formats
```ts
import { Schema, SchemaCheck } from "effect"
@@ -2226,7 +2240,7 @@ Schema.String.pipe(Schema.check(SchemaCheck.base64))
Schema.String.pipe(Schema.check(SchemaCheck.base64url))
```
## Numbers
### Numbers
```ts
import { Schema } from "effect"
@@ -2252,7 +2266,7 @@ Schema.Number.pipe(Schema.check(SchemaCheck.nonPositive))
Schema.Number.pipe(Schema.check(SchemaCheck.multipleOf(5)))
```
## Integers
### Integers
```ts
import { Schema, SchemaCheck } from "effect"
@@ -2261,7 +2275,7 @@ Schema.Number.pipe(Schema.check(SchemaCheck.int))
Schema.Number.pipe(Schema.check(SchemaCheck.int32))
```
## BigInts
### BigInts
```ts
import { BigInt, Order, Schema, SchemaCheck } from "effect"
@@ -2295,7 +2309,7 @@ Schema.BigInt.pipe(Schema.check(negative))
Schema.BigInt.pipe(Schema.check(nonPositive))
```
## Dates
### Dates
```ts
import { Schema, SchemaGetter } from "effect"
+88 -10
View File
@@ -9,8 +9,8 @@ const revealClass = <Self, S extends Schema.Struct<Schema.Struct.Fields>, Inheri
const FiniteFromString = Schema.String.pipe(Schema.decodeTo(
Schema.Finite,
new SchemaTransformation.SchemaTransformation(
SchemaGetter.Number,
SchemaGetter.String
SchemaGetter.Number(),
SchemaGetter.String()
)
))
@@ -18,8 +18,8 @@ const NumberFromString = Schema.String.pipe(
Schema.decodeTo(
Schema.Number,
new SchemaTransformation.SchemaTransformation(
SchemaGetter.Number,
SchemaGetter.String
SchemaGetter.Number(),
SchemaGetter.String()
)
)
)
@@ -634,12 +634,12 @@ describe("Schema", () => {
})
})
describe("compose", () => {
describe("passthrough", () => {
it("E = T", () => {
Schema.String.pipe(
Schema.decodeTo(
Schema.String.pipe(Schema.check(SchemaCheck.nonEmpty)),
SchemaTransformation.compose()
SchemaTransformation.passthrough()
)
)
})
@@ -648,14 +648,14 @@ describe("Schema", () => {
when(Schema.String.pipe).isCalledWith(
expect(Schema.decodeTo).type.not.toBeCallableWith(
Schema.Number,
SchemaTransformation.compose()
SchemaTransformation.passthrough()
)
)
Schema.String.pipe(
Schema.decodeTo(
Schema.Number,
SchemaTransformation.compose({ strict: false })
SchemaTransformation.passthrough({ strict: false })
)
)
})
@@ -664,7 +664,7 @@ describe("Schema", () => {
Schema.String.pipe(
Schema.decodeTo(
Schema.UndefinedOr(Schema.String),
SchemaTransformation.composeSupertype()
SchemaTransformation.passthroughSubtype()
)
)
})
@@ -673,7 +673,7 @@ describe("Schema", () => {
Schema.UndefinedOr(Schema.String).pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.composeSubtype()
SchemaTransformation.passthroughSupertype()
)
)
})
@@ -966,4 +966,82 @@ describe("Schema", () => {
>()
})
})
it("decodeTo as composition", () => {
const From = Schema.Struct({
a: Schema.String,
b: Schema.FiniteFromString
})
const To = Schema.Struct({
a: Schema.FiniteFromString,
b: Schema.UndefinedOr(Schema.Number)
})
const schema = From.pipe(Schema.decodeTo(To))
expect(Schema.revealCodec(schema)).type.toBe<
Schema.Codec<
{ readonly a: number; readonly b: number | undefined },
{ readonly a: string; readonly b: string },
never,
never
>
>()
expect(schema).type.toBe<
Schema.compose<
Schema.Struct<
{ readonly a: Schema.FiniteFromString; readonly b: Schema.Union<readonly [Schema.Number, Schema.Undefined]> }
>,
Schema.Struct<{ readonly a: Schema.String; readonly b: Schema.FiniteFromString }>
>
>()
expect(schema.annotate({})).type.toBe<
Schema.compose<
Schema.Struct<
{ readonly a: Schema.FiniteFromString; readonly b: Schema.Union<readonly [Schema.Number, Schema.Undefined]> }
>,
Schema.Struct<{ readonly a: Schema.String; readonly b: Schema.FiniteFromString }>
>
>()
})
it("encodeTo as composition", () => {
const From = Schema.Struct({
a: Schema.String,
b: Schema.FiniteFromString
})
const To = Schema.Struct({
a: Schema.FiniteFromString,
b: Schema.UndefinedOr(Schema.Number)
})
const schema = To.pipe(Schema.encodeTo(From))
expect(Schema.revealCodec(schema)).type.toBe<
Schema.Codec<
{ readonly a: number; readonly b: number | undefined },
{ readonly a: string; readonly b: string },
never,
never
>
>()
expect(schema).type.toBe<
Schema.compose<
Schema.Struct<
{ readonly a: Schema.FiniteFromString; readonly b: Schema.Union<readonly [Schema.Number, Schema.Undefined]> }
>,
Schema.Struct<{ readonly a: Schema.String; readonly b: Schema.FiniteFromString }>
>
>()
expect(schema.annotate({})).type.toBe<
Schema.compose<
Schema.Struct<
{ readonly a: Schema.FiniteFromString; readonly b: Schema.Union<readonly [Schema.Number, Schema.Undefined]> }
>,
Schema.Struct<{ readonly a: Schema.String; readonly b: Schema.FiniteFromString }>
>
>()
})
})
+103 -29
View File
@@ -21,8 +21,8 @@ import * as SchemaAST from "./SchemaAST.js"
import * as SchemaCheck from "./SchemaCheck.js"
import * as SchemaGetter from "./SchemaGetter.js"
import * as SchemaIssue from "./SchemaIssue.js"
import * as SchemaParser from "./SchemaParser.js"
import * as SchemaResult from "./SchemaResult.js"
import * as SchemaToParser from "./SchemaToParser.js"
import * as SchemaTransformation from "./SchemaTransformation.js"
import * as Struct_ from "./Struct.js"
@@ -177,7 +177,7 @@ export abstract class Bottom$<
}
makeSync(input: this["~type.make.in"], options?: MakeOptions): this["Type"] {
return Result.getOrThrowWith(
SchemaParser.runSyncSchemaResult(SchemaParser.make(this)(input, options)),
SchemaToParser.runSyncSchemaResult(SchemaToParser.makeSchemaResult(this)(input, options)),
(issue) =>
new globalThis.Error("makeSync failure", {
cause: issue
@@ -268,10 +268,10 @@ export class SchemaError extends Data.TaggedError("SchemaError")<{
* @category Decoding
* @since 4.0.0
*/
export function decodeUnknown<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
const parser = SchemaParser.decodeUnknown(codec)
return (u: unknown, options?: SchemaAST.ParseOptions): Effect.Effect<T, SchemaError, RD> => {
return Effect.mapError(parser(u, options), (issue) => new SchemaError({ issue }))
export function decodeUnknownEffect<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
const parser = SchemaToParser.decodeUnknownEffect(codec)
return (input: unknown, options?: SchemaAST.ParseOptions): Effect.Effect<T, SchemaError, RD> => {
return Effect.mapError(parser(input, options), (issue) => new SchemaError({ issue }))
}
}
@@ -279,10 +279,10 @@ export function decodeUnknown<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
* @category Decoding
* @since 4.0.0
*/
export function decode<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
const parser = SchemaParser.decode(codec)
return (e: E, options?: SchemaAST.ParseOptions): Effect.Effect<T, SchemaError, RD> => {
return Effect.mapError(parser(e, options), (issue) => new SchemaError({ issue }))
export function decodeEffect<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
const parser = SchemaToParser.decodeEffect(codec)
return (input: E, options?: SchemaAST.ParseOptions): Effect.Effect<T, SchemaError, RD> => {
return Effect.mapError(parser(input, options), (issue) => new SchemaError({ issue }))
}
}
@@ -290,16 +290,16 @@ export function decode<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
* @category Decoding
* @since 4.0.0
*/
export const decodeUnknownSync = SchemaParser.decodeUnknownSync
export const decodeUnknownSync = SchemaToParser.decodeUnknownSync
/**
* @category Encoding
* @since 4.0.0
*/
export function encodeUnknown<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
const parser = SchemaParser.encodeUnknown(codec)
return (u: unknown, options?: SchemaAST.ParseOptions): Effect.Effect<E, SchemaError, RE> => {
return Effect.mapError(parser(u, options), (issue) => new SchemaError({ issue }))
export function encodeUnknownEffect<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
const parser = SchemaToParser.encodeUnknownEffect(codec)
return (input: unknown, options?: SchemaAST.ParseOptions): Effect.Effect<E, SchemaError, RE> => {
return Effect.mapError(parser(input, options), (issue) => new SchemaError({ issue }))
}
}
@@ -307,10 +307,10 @@ export function encodeUnknown<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
* @category Encoding
* @since 4.0.0
*/
export function encode<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
const parser = SchemaParser.encode(codec)
return (t: T, options?: SchemaAST.ParseOptions): Effect.Effect<E, SchemaError, RE> => {
return Effect.mapError(parser(t, options), (issue) => new SchemaError({ issue }))
export function encodeEffect<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
const parser = SchemaToParser.encodeEffect(codec)
return (input: T, options?: SchemaAST.ParseOptions): Effect.Effect<E, SchemaError, RE> => {
return Effect.mapError(parser(input, options), (issue) => new SchemaError({ issue }))
}
}
@@ -318,13 +318,13 @@ export function encode<T, E, RD, RE>(codec: Codec<T, E, RD, RE>) {
* @category Encoding
* @since 4.0.0
*/
export const encodeUnknownSync = SchemaParser.encodeUnknownSync
export const encodeUnknownSync = SchemaToParser.encodeUnknownSync
/**
* @category Encoding
* @since 4.0.0
*/
export const encodeSync = SchemaParser.encodeSync
export const encodeSync = SchemaToParser.encodeSync
/**
* @category Api interface
@@ -1872,6 +1872,12 @@ export interface decodeTo<To extends Top, From extends Top, RD, RE> extends
readonly to: To
}
/**
* @category Api interface
* @since 4.0.0
*/
export interface compose<To extends Top, From extends Top> extends decodeTo<To, From, never, never> {}
class decodeTo$<To extends Top, From extends Top, RD, RE> extends make$<decodeTo<To, From, RD, RE>>
implements decodeTo<To, From, RD, RE>
{
@@ -1887,16 +1893,40 @@ class decodeTo$<To extends Top, From extends Top, RD, RE> extends make$<decodeTo
/**
* @since 4.0.0
*/
export function decodeTo<To extends Top>(to: To): <From extends Top>(from: From) => compose<To, From>
export function decodeTo<To extends Top, From extends Top, RD = never, RE = never>(
to: To,
transformation: {
readonly decode: SchemaGetter.SchemaGetter<To["Encoded"], From["Type"], RD>
readonly encode: SchemaGetter.SchemaGetter<From["Type"], To["Encoded"], RE>
}
): (from: From) => decodeTo<To, From, RD, RE>
/**
* Used by {@link encodeTo}
*
* @internal
*/
export function decodeTo<To extends Top, From extends Top, RD = never, RE = never>(
to: To,
transformation?: {
readonly decode: SchemaGetter.SchemaGetter<To["Encoded"], From["Type"], RD>
readonly encode: SchemaGetter.SchemaGetter<From["Type"], To["Encoded"], RE>
} | undefined
): (from: From) => decodeTo<To, From, RD, RE>
export function decodeTo<To extends Top, From extends Top, RD = never, RE = never>(
to: To,
transformation?: {
readonly decode: SchemaGetter.SchemaGetter<To["Encoded"], From["Type"], RD>
readonly encode: SchemaGetter.SchemaGetter<From["Type"], To["Encoded"], RE>
} | undefined
) {
return (from: From): decodeTo<To, From, RD, RE> => {
return (from: From) => {
return new decodeTo$(
SchemaAST.decodeTo(from.ast, to.ast, SchemaTransformation.make(transformation)),
SchemaAST.decodeTo(
from.ast,
to.ast,
transformation ? SchemaTransformation.make(transformation) : SchemaTransformation.passthrough()
),
from,
to
)
@@ -1904,17 +1934,61 @@ export function decodeTo<To extends Top, From extends Top, RD = never, RE = neve
}
/**
* Like {@link decodeTo}, but the transformation is applied to the type codec
* (`typeCodec(self)`).
*
* @since 4.0.0
*/
export function decode<S extends Top, RD = never, RE = never>(transformation: {
readonly decode: SchemaGetter.SchemaGetter<S["Type"], S["Type"], RD>
readonly encode: SchemaGetter.SchemaGetter<S["Type"], S["Type"], RE>
}) {
return (self: S): decodeTo<typeCodec<S>, S, RD, RE> => {
return self.pipe(
decodeTo<typeCodec<S>, S, RD, RE>(typeCodec(self), SchemaTransformation.make(transformation))
)
}
}
/**
* @since 4.0.0
*/
export function encodeTo<To extends Top>(
to: To
): <From extends Top>(from: From) => decodeTo<From, To, never, never>
export function encodeTo<To extends Top, From extends Top, RD = never, RE = never>(
to: To,
transformation: {
readonly decode: SchemaGetter.SchemaGetter<From["Encoded"], To["Type"], RD>
readonly encode: SchemaGetter.SchemaGetter<To["Type"], From["Encoded"], RE>
}
) {
): (from: From) => decodeTo<From, To, RD, RE>
export function encodeTo<To extends Top, From extends Top, RD = never, RE = never>(
to: To,
transformation?: {
readonly decode: SchemaGetter.SchemaGetter<From["Encoded"], To["Type"], RD>
readonly encode: SchemaGetter.SchemaGetter<To["Type"], From["Encoded"], RE>
}
): (from: From) => decodeTo<From, To, RD, RE> {
return (from: From): decodeTo<From, To, RD, RE> => {
return to.pipe(decodeTo(from, SchemaTransformation.make(transformation)))
return to.pipe(decodeTo(from, transformation))
}
}
/**
* Like {@link encodeTo}, but the transformation is applied to the encoded codec
* (`encodedCodec(self)`).
*
* @since 4.0.0
*/
export function encode<S extends Top, RD = never, RE = never>(transformation: {
readonly decode: SchemaGetter.SchemaGetter<S["Encoded"], S["Encoded"], RD>
readonly encode: SchemaGetter.SchemaGetter<S["Encoded"], S["Encoded"], RE>
}) {
return (self: S): decodeTo<S, encodedCodec<S>, RD, RE> => {
return encodedCodec(self).pipe(
decodeTo<S, encodedCodec<S>, RD, RE>(self, SchemaTransformation.make(transformation))
)
}
}
@@ -1991,7 +2065,7 @@ export function Option<S extends Top>(value: S) {
return Result.okNone
}
const input = oinput.value
return SchemaParser.decodeUnknownSchemaResult(value)(input, options).pipe(SchemaResult.mapBoth(
return SchemaToParser.decodeUnknownSchemaResult(value)(input, options).pipe(SchemaResult.mapBoth(
{
onSuccess: O.some,
onFailure: (issue) => {
@@ -2044,7 +2118,7 @@ export function Map<Key extends Top, Value extends Top>(key: Key, value: Value)
([key, value]) => (input, ast, options) => {
if (input instanceof globalThis.Map) {
const array = ReadonlyArray(ReadonlyTuple([key, value]))
return SchemaParser.decodeUnknownSchemaResult(array)([...input], options).pipe(SchemaResult.mapBoth(
return SchemaToParser.decodeUnknownSchemaResult(array)([...input], options).pipe(SchemaResult.mapBoth(
{
onSuccess: (array: ReadonlyArray<readonly [Key["Type"], Value["Type"]]>) => new globalThis.Map(array),
onFailure: (issue) => new SchemaIssue.Composite(ast, O.some(input), [issue])
@@ -2226,8 +2300,8 @@ export interface FiniteFromString extends decodeTo<Number, String, never, never>
export const FiniteFromString: FiniteFromString = String.pipe(decodeTo(
Finite,
{
decode: SchemaGetter.Number,
encode: SchemaGetter.String
decode: SchemaGetter.Number(),
encode: SchemaGetter.String()
}
))
+6 -6
View File
@@ -12,8 +12,8 @@ import * as Result from "./Result.js"
import type { Annotated, Annotations } from "./SchemaAnnotations.js"
import type * as SchemaCheck from "./SchemaCheck.js"
import * as SchemaIssue from "./SchemaIssue.js"
import type * as SchemaParser from "./SchemaParser.js"
import type * as SchemaResult from "./SchemaResult.js"
import type * as SchemaToParser from "./SchemaToParser.js"
import type * as SchemaTransformation from "./SchemaTransformation.js"
/**
@@ -610,7 +610,7 @@ export class TupleType extends Extensions {
new TupleType(this.isReadonly, elements, rest, this.annotations, this.checks, undefined, this.context)
}
/** @internal */
parser(go: (ast: AST) => SchemaParser.Parser<any, any>) {
parser(go: (ast: AST) => SchemaToParser.Parser<any, any>) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const ast = this
return Effect.fnUntraced(function*(oinput, options) {
@@ -762,7 +762,7 @@ export class TypeLiteral extends Extensions {
)
}
/** @internal */
parser(go: (ast: AST) => SchemaParser.Parser<any, any>) {
parser(go: (ast: AST) => SchemaToParser.Parser<any, any>) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const ast = this
// Handle empty Struct({}) case
@@ -983,7 +983,7 @@ export class UnionType<A extends AST = AST> extends Extensions {
new UnionType(types, this.mode, this.annotations, this.checks, undefined, this.context)
}
/** @internal */
parser(go: (ast: AST) => SchemaParser.Parser<any, any>) {
parser(go: (ast: AST) => SchemaToParser.Parser<any, any>) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const ast = this
return Effect.fnUntraced(function*(oinput, options) {
@@ -1056,7 +1056,7 @@ export class Suspend extends Extensions {
return new Suspend(() => flip(this.thunk()), this.annotations, this.checks, undefined, this.context)
}
/** @internal */
parser(go: (ast: AST) => SchemaParser.Parser<any, any>) {
parser(go: (ast: AST) => SchemaToParser.Parser<any, any>) {
return go(this.thunk())
}
}
@@ -1678,7 +1678,7 @@ const handleTemplateLiteralSpanTypeParens = (
/** @internal */
export const fromPredicate =
(ast: AST, predicate: (input: unknown) => boolean): SchemaParser.Parser<any, any> => (oinput) => {
(ast: AST, predicate: (input: unknown) => boolean): SchemaToParser.Parser<any, any> => (oinput) => {
if (Option.isNone(oinput)) {
return Effect.succeedNone
}
+53 -8
View File
@@ -25,6 +25,17 @@ export class SchemaGetter<out T, in E, R = never> extends PipeableClass {
) {
super()
}
compose<T2, R2>(other: SchemaGetter<T2, T, R2>): SchemaGetter<T2, E, R | R2> {
if (isPassthrough(this)) {
return other as any
}
if (isPassthrough(other)) {
return this as any
}
return new SchemaGetter((oe, ast, options) =>
this.run(oe, ast, options).pipe(SchemaResult.flatMap((ot) => other.run(ot, ast, options)))
)
}
}
/**
@@ -33,8 +44,14 @@ export class SchemaGetter<out T, in E, R = never> extends PipeableClass {
* @category constructors
* @since 4.0.0
*/
export function fail<T>(f: (ot: Option.Option<T>) => SchemaIssue.Issue): SchemaGetter<T, T> {
return new SchemaGetter((ot) => SchemaResult.fail(f(ot)))
export function fail<T, E>(f: (oe: Option.Option<E>) => SchemaIssue.Issue): SchemaGetter<T, E> {
return new SchemaGetter((oe) => SchemaResult.fail(f(oe)))
}
const passthrough_ = new SchemaGetter<any, any>(SchemaResult.succeed)
function isPassthrough<T, E, R>(getter: SchemaGetter<T, E, R>): getter is typeof passthrough_ {
return getter.run === passthrough_.run
}
/**
@@ -43,8 +60,26 @@ export function fail<T>(f: (ot: Option.Option<T>) => SchemaIssue.Issue): SchemaG
* @category constructors
* @since 4.0.0
*/
export function passthrough<T, E>(options: { readonly strict: false }): SchemaGetter<T, E>
export function passthrough<T>(): SchemaGetter<T, T>
export function passthrough<T>(): SchemaGetter<T, T> {
return new SchemaGetter(SchemaResult.succeed)
return passthrough_
}
/**
* @since 4.0.0
*/
export function passthroughSupertype<T extends E, E>(): SchemaGetter<T, E>
export function passthroughSupertype<T>(): SchemaGetter<T, T> {
return passthrough_
}
/**
* @since 4.0.0
*/
export function passthroughSubtype<T, E extends T>(): SchemaGetter<T, E>
export function passthroughSubtype<T>(): SchemaGetter<T, T> {
return passthrough_
}
/**
@@ -156,31 +191,41 @@ export function withDefault<T>(defaultValue: () => T): SchemaGetter<T, T | undef
* @category Coercions
* @since 4.0.0
*/
export const String: SchemaGetter<string, unknown> = transform(globalThis.String)
export function String<E>(): SchemaGetter<string, E> {
return transform(globalThis.String)
}
/**
* @category Coercions
* @since 4.0.0
*/
export const Number: SchemaGetter<number, unknown> = transform(globalThis.Number)
export function Number<E>(): SchemaGetter<number, E> {
return transform(globalThis.Number)
}
/**
* @category Coercions
* @since 4.0.0
*/
export const Boolean: SchemaGetter<boolean, unknown> = transform(globalThis.Boolean)
export function Boolean<E>(): SchemaGetter<boolean, E> {
return transform(globalThis.Boolean)
}
/**
* @category Coercions
* @since 4.0.0
*/
export const BigInt: SchemaGetter<bigint, string | number | bigint | boolean> = transform(globalThis.BigInt)
export function BigInt<E extends string | number | bigint | boolean>(): SchemaGetter<bigint, E> {
return transform(globalThis.BigInt)
}
/**
* @category Coercions
* @since 4.0.0
*/
export const Date: SchemaGetter<Date, string | number | Date> = transform((u) => new globalThis.Date(u))
export function Date<E extends string | number | Date>(): SchemaGetter<Date, E> {
return transform((u) => new globalThis.Date(u))
}
/**
* @category String transformations
+1 -1
View File
@@ -141,6 +141,6 @@ const bigIntLink = new SchemaAST.Link(
SchemaAST.stringKeyword,
new SchemaTransformation.SchemaTransformation(
SchemaGetter.transform(BigInt),
SchemaGetter.String
SchemaGetter.String()
)
)
@@ -18,13 +18,13 @@ import * as SchemaResult from "./SchemaResult.js"
* @category Make
* @since 4.0.0
*/
export const make = <S extends Schema.Top>(schema: S) =>
export const makeSchemaResult = <S extends Schema.Top>(schema: S) =>
(
input: S["~type.make.in"],
options?: Schema.MakeOptions
): SchemaResult.SchemaResult<S["Type"]> => {
const parseOptions: SchemaAST.ParseOptions = { "~variant": "make", ...options?.parseOptions }
return validateUnknownParserResult(schema)(input, parseOptions)
return fromASTSchemaResult<S["Type"], never>(SchemaAST.typeAST(schema.ast))(input, parseOptions)
}
/**
@@ -38,7 +38,7 @@ export const decodeUnknownSchemaResult = <T, E, RD, RE>(codec: Schema.Codec<T, E
* @category Decoding
* @since 4.0.0
*/
export const decodeUnknown = <T, E, RD, RE>(codec: Schema.Codec<T, E, RD, RE>) => {
export const decodeUnknownEffect = <T, E, RD, RE>(codec: Schema.Codec<T, E, RD, RE>) => {
const parser = decodeUnknownSchemaResult(codec)
return (u: unknown, options?: SchemaAST.ParseOptions) => {
return SchemaResult.asEffect(parser(u, options))
@@ -49,9 +49,9 @@ export const decodeUnknown = <T, E, RD, RE>(codec: Schema.Codec<T, E, RD, RE>) =
* @category Decoding
* @since 4.0.0
*/
export const decode: <T, E, RD, RE>(
export const decodeEffect: <T, E, RD, RE>(
codec: Schema.Codec<T, E, RD, RE>
) => (e: E, options?: SchemaAST.ParseOptions) => Effect.Effect<T, SchemaIssue.Issue, RD> = decodeUnknown
) => (e: E, options?: SchemaAST.ParseOptions) => Effect.Effect<T, SchemaIssue.Issue, RD> = decodeUnknownEffect
/**
* @category Decoding
@@ -70,7 +70,7 @@ export const encodeUnknownSchemaResult = <T, E, RD, RE>(codec: Schema.Codec<T, E
* @category Encoding
* @since 4.0.0
*/
export const encodeUnknown = <T, E, RD, RE>(codec: Schema.Codec<T, E, RD, RE>) => {
export const encodeUnknownEffect = <T, E, RD, RE>(codec: Schema.Codec<T, E, RD, RE>) => {
const parser = encodeUnknownSchemaResult(codec)
return (u: unknown, options?: SchemaAST.ParseOptions) => {
return SchemaResult.asEffect(parser(u, options))
@@ -81,9 +81,9 @@ export const encodeUnknown = <T, E, RD, RE>(codec: Schema.Codec<T, E, RD, RE>) =
* @category Encoding
* @since 4.0.0
*/
export const encode: <T, E, RD, RE>(
export const encodeEffect: <T, E, RD, RE>(
codec: Schema.Codec<T, E, RD, RE>
) => (t: T, options?: SchemaAST.ParseOptions) => Effect.Effect<E, SchemaIssue.Issue, RE> = encodeUnknown
) => (t: T, options?: SchemaAST.ParseOptions) => Effect.Effect<E, SchemaIssue.Issue, RE> = encodeUnknownEffect
/**
* @category Encoding
@@ -100,20 +100,6 @@ export const encodeSync = <T, E, RD>(
codec: Schema.Codec<T, E, RD, never>
): (t: T, options?: SchemaAST.ParseOptions) => E => fromASTSync<E>(SchemaAST.flip(codec.ast))
/**
* @category validating
* @since 4.0.0
*/
export const validateUnknownParserResult = <T, E, RD, RE>(codec: Schema.Codec<T, E, RD, RE>) =>
fromASTSchemaResult<T, never>(SchemaAST.typeAST(codec.ast))
/**
* @category validating
* @since 4.0.0
*/
export const validateUnknownSync = <T, E, RD, RE>(codec: Schema.Codec<T, E, RD, RE>) =>
fromASTSync<T>(SchemaAST.typeAST(codec.ast))
/** @internal */
export const runSyncSchemaResult = <A, R>(
sr: SchemaResult.SchemaResult<A, R>
@@ -160,8 +146,8 @@ const defaultParseOptions: SchemaAST.ParseOptions = {}
/** @internal */
export const fromASTSchemaResult = <A, R>(ast: SchemaAST.AST) => {
const parser = go<A, R>(ast)
return (u: unknown, options?: SchemaAST.ParseOptions): SchemaResult.SchemaResult<A, R> => {
const oinput = Option.some(u)
return (input: unknown, options?: SchemaAST.ParseOptions): SchemaResult.SchemaResult<A, R> => {
const oinput = Option.some(input)
const oa = parser(oinput, options ?? defaultParseOptions)
return Effect.flatMap(oa, (oa) => {
if (Option.isNone(oa)) {
@@ -174,8 +160,8 @@ export const fromASTSchemaResult = <A, R>(ast: SchemaAST.AST) => {
const fromASTSync = <A>(ast: SchemaAST.AST) => {
const parser = fromASTSchemaResult<A, never>(ast)
return (u: unknown, options?: SchemaAST.ParseOptions): A => {
return Result.getOrThrow(runSyncSchemaResult(parser(u, options)))
return (input: unknown, options?: SchemaAST.ParseOptions): A => {
return Result.getOrThrow(runSyncSchemaResult(parser(input, options)))
}
}
+45 -74
View File
@@ -43,6 +43,12 @@ export class SchemaTransformation<in out T, in out E, RD = never, RE = never> {
flip(): SchemaTransformation<E, T, RE, RD> {
return new SchemaTransformation(this.encode, this.decode)
}
compose<T2, RD2, RE2>(other: SchemaTransformation<T2, T, RD2, RE2>): SchemaTransformation<T2, E, RD | RD2, RE | RE2> {
return new SchemaTransformation(
this.decode.compose(other.decode),
other.encode.compose(this.encode)
)
}
}
/**
@@ -98,85 +104,48 @@ export function transformOptional<T, E>(options: {
}
/**
* @category Coercions
* @category String transformations
* @since 4.0.0
*/
export const String: SchemaTransformation<string, unknown> = new SchemaTransformation(
SchemaGetter.String,
SchemaGetter.passthrough<unknown>()
)
/**
* @category Coercions
* @since 4.0.0
*/
export const Number: SchemaTransformation<number, unknown> = new SchemaTransformation(
SchemaGetter.Number,
SchemaGetter.passthrough<unknown>()
)
/**
* @category Coercions
* @since 4.0.0
*/
export const Boolean: SchemaTransformation<boolean, unknown> = new SchemaTransformation(
SchemaGetter.Boolean,
SchemaGetter.passthrough<unknown>()
)
/**
* @category Coercions
* @since 4.0.0
*/
export const BigInt: SchemaTransformation<bigint, string | number | bigint | boolean> = new SchemaTransformation(
SchemaGetter.BigInt,
SchemaGetter.passthrough<string | number | bigint | boolean>()
)
/**
* @category Coercions
* @since 4.0.0
*/
export const Date: SchemaTransformation<Date, string | number | Date> = new SchemaTransformation(
SchemaGetter.Date,
SchemaGetter.passthrough<string | number | Date>()
)
export function trim(): SchemaTransformation<string, string> {
return new SchemaTransformation(
SchemaGetter.trim(),
SchemaGetter.passthroughSupertype()
)
}
/**
* @category String transformations
* @since 4.0.0
*/
export const trim: SchemaTransformation<string, string> = new SchemaTransformation(
SchemaGetter.trim(),
SchemaGetter.passthrough<string>()
)
export function snakeToCamel(): SchemaTransformation<string, string> {
return new SchemaTransformation(
SchemaGetter.snakeToCamel(),
SchemaGetter.camelToSnake()
)
}
/**
* @category String transformations
* @since 4.0.0
*/
export const snakeToCamel: SchemaTransformation<string, string> = new SchemaTransformation(
SchemaGetter.snakeToCamel(),
SchemaGetter.camelToSnake()
)
export function toLowerCase(): SchemaTransformation<string, string> {
return new SchemaTransformation(
SchemaGetter.toLowerCase(),
SchemaGetter.passthroughSupertype()
)
}
/**
* @category String transformations
* @since 4.0.0
*/
export const toLowerCase: SchemaTransformation<string, string> = new SchemaTransformation(
SchemaGetter.toLowerCase(),
SchemaGetter.passthrough()
)
/**
* @category String transformations
* @since 4.0.0
*/
export const toUpperCase: SchemaTransformation<string, string> = new SchemaTransformation(
SchemaGetter.toUpperCase(),
SchemaGetter.passthrough()
)
export function toUpperCase(): SchemaTransformation<string, string> {
return new SchemaTransformation(
SchemaGetter.toUpperCase(),
SchemaGetter.passthroughSupertype()
)
}
/**
* @since 4.0.0
@@ -194,30 +163,32 @@ export function json(options?: JsonOptions): SchemaTransformation<unknown, strin
)
}
const passthrough = SchemaGetter.passthrough<any>()
const _compose = new SchemaTransformation(passthrough, passthrough)
const passthrough_ = new SchemaTransformation(
SchemaGetter.passthrough<any>(),
SchemaGetter.passthrough<any>()
)
/**
* @since 4.0.0
*/
export function compose<T, E>(options: { readonly strict: false }): SchemaTransformation<T, E>
export function compose<T>(): SchemaTransformation<T, T>
export function compose<T>(): SchemaTransformation<T, T> {
return _compose
export function passthrough<T, E>(options: { readonly strict: false }): SchemaTransformation<T, E>
export function passthrough<T>(): SchemaTransformation<T, T>
export function passthrough<T>(): SchemaTransformation<T, T> {
return passthrough_
}
/**
* @since 4.0.0
*/
export function composeSubtype<T extends E, E>(): SchemaTransformation<T, E>
export function composeSubtype<T>(): SchemaTransformation<T, T> {
return _compose
export function passthroughSupertype<T extends E, E>(): SchemaTransformation<T, E>
export function passthroughSupertype<T>(): SchemaTransformation<T, T> {
return passthrough_
}
/**
* @since 4.0.0
*/
export function composeSupertype<T, E extends T>(): SchemaTransformation<T, E>
export function composeSupertype<T>(): SchemaTransformation<T, T> {
return _compose
export function passthroughSubtype<T, E extends T>(): SchemaTransformation<T, E>
export function passthroughSubtype<T>(): SchemaTransformation<T, T> {
return passthrough_
}
+5 -5
View File
@@ -514,11 +514,6 @@ export * as SchemaGetter from "./SchemaGetter.js"
*/
export * as SchemaIssue from "./SchemaIssue.js"
/**
* @since 4.0.0
*/
export * as SchemaParser from "./SchemaParser.js"
/**
* @since 4.0.0
*/
@@ -529,6 +524,11 @@ export * as SchemaResult from "./SchemaResult.js"
*/
export * as SchemaSerializer from "./SchemaSerializer.js"
/**
* @since 4.0.0
*/
export * as SchemaToParser from "./SchemaToParser.js"
/**
* @since 4.0.0
*/
+2 -2
View File
@@ -10,7 +10,7 @@ import * as Predicate from "../Predicate.js"
import type * as Schema from "../Schema.js"
import type { ParseOptions } from "../SchemaAST.js"
import type { Issue } from "../SchemaIssue.js"
import * as SchemaParser from "../SchemaParser.js"
import * as SchemaParser from "../SchemaToParser.js"
import type * as Stream_ from "../Stream.js"
import * as UrlParams from "./UrlParams.js"
@@ -239,7 +239,7 @@ export const jsonSchema = <S extends Schema.Schema<any>>(
schema: S,
options?: ParseOptions | undefined
) => {
const encode = SchemaParser.encodeUnknown(schema)
const encode = SchemaParser.encodeUnknownEffect(schema)
return (body: S["Type"]): Effect.Effect<Uint8Array, HttpBodyError, S["EncodingContext"]> =>
encode(body, options).pipe(
Effect.mapError((issue) => new HttpBodyError({ reason: { _tag: "SchemaError", issue }, cause: issue })),
@@ -82,7 +82,7 @@ export const schemaJson = <
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
) => {
const decode = Schema.decodeUnknown(schema)
const decode = Schema.decodeUnknownEffect(schema)
return (
self: HttpClientResponse
): Effect.Effect<A, Schema.SchemaError | Error.ResponseError, RD> =>
@@ -110,7 +110,7 @@ export const schemaNoBody = <
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
) => {
const decode = Schema.decodeUnknown(schema)
const decode = Schema.decodeUnknownEffect(schema)
return (self: HttpClientResponse): Effect.Effect<A, Schema.SchemaError, RD> =>
decode({
status: self.status,
@@ -45,7 +45,7 @@ export interface HttpIncomingMessage<E> extends Inspectable.Inspectable {
* @category schema
*/
export const schemaBodyJson = <S extends Schema.Schema<any>>(schema: S, options?: ParseOptions | undefined) => {
const decode = Schema.decodeUnknown(schema)
const decode = Schema.decodeUnknownEffect(schema)
return <E>(
self: HttpIncomingMessage<E>
): Effect.Effect<S["Type"], E | Schema.SchemaError, S["DecodingContext"]> =>
@@ -77,7 +77,7 @@ export const schemaHeaders = <A, I extends Readonly<Record<string, string | unde
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
) => {
const decode = Schema.decodeUnknown(schema)
const decode = Schema.decodeUnknownEffect(schema)
return <E>(self: HttpIncomingMessage<E>): Effect.Effect<A, Schema.SchemaError, RD> => decode(self.headers, options)
}
+125 -22
View File
@@ -12,8 +12,8 @@ import {
SchemaCheck,
SchemaGetter,
SchemaIssue,
SchemaParser,
SchemaResult,
SchemaToParser,
SchemaTransformation
} from "effect"
import { describe, it } from "vitest"
@@ -27,12 +27,11 @@ const assertions = Util.assertions({
fail
})
const Trim = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.trim))
const Trim = Schema.String.pipe(Schema.decode(SchemaTransformation.trim()))
const SnakeToCamel = Schema.String.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.snakeToCamel
Schema.decode(
SchemaTransformation.snakeToCamel()
)
)
@@ -40,8 +39,8 @@ const NumberFromString = Schema.String.pipe(
Schema.decodeTo(
Schema.Number,
{
decode: SchemaGetter.Number,
encode: SchemaGetter.String
decode: SchemaGetter.Number(),
encode: SchemaGetter.String()
}
)
)
@@ -1371,7 +1370,7 @@ describe("Schema", () => {
describe("String transformations", () => {
it("trim", async () => {
const schema = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.trim))
const schema = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.trim()))
strictEqual(SchemaAST.format(schema.ast), `string <-> string`)
@@ -1446,7 +1445,7 @@ describe("Schema", () => {
const schema = Schema.String.pipe(
Schema.decodeTo(
Schema.FiniteFromString,
SchemaTransformation.trim
SchemaTransformation.trim()
)
)
@@ -1458,7 +1457,7 @@ describe("Schema", () => {
a: Schema.String.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.compose()
SchemaTransformation.passthrough()
)
)
})
@@ -1537,7 +1536,7 @@ describe("Schema", () => {
it("double transformation", async () => {
const schema = Trim.pipe(Schema.decodeTo(
Schema.FiniteFromString,
SchemaTransformation.compose()
SchemaTransformation.passthrough()
))
await assertions.decoding.succeed(schema, " 2 ", { expected: 2 })
await assertions.decoding.fail(
@@ -1556,11 +1555,11 @@ describe("Schema", () => {
a: Schema.String.pipe(Schema.check(SchemaCheck.minLength(2))).pipe(
Schema.decodeTo(
Schema.String.pipe(Schema.check(SchemaCheck.minLength(3))),
SchemaTransformation.compose()
SchemaTransformation.passthrough()
),
Schema.decodeTo(
Schema.String,
SchemaTransformation.compose()
SchemaTransformation.passthrough()
)
)
})
@@ -1619,13 +1618,29 @@ describe("Schema", () => {
})
})
describe("decode", () => {
it("double transformation", async () => {
const schema = Schema.String.pipe(
Schema.decode(
SchemaTransformation.trim().compose(
SchemaTransformation.toLowerCase()
)
)
)
await assertions.decoding.succeed(schema, " A ", { expected: "a" })
await assertions.encoding.succeed(schema, " A ", { expected: " A " })
})
})
describe("encodeTo", () => {
it("required to required", async () => {
const schema = Schema.Struct({
a: Schema.String.pipe(
Schema.encodeTo(
Schema.String,
SchemaTransformation.compose()
SchemaTransformation.passthrough()
)
)
})
@@ -1700,7 +1715,7 @@ describe("Schema", () => {
it("double transformation", async () => {
const schema = Schema.FiniteFromString.pipe(Schema.encodeTo(
Trim,
SchemaTransformation.compose()
SchemaTransformation.passthrough()
))
await assertions.decoding.succeed(schema, " 2 ", { expected: 2 })
await assertions.decoding.fail(
@@ -1719,11 +1734,11 @@ describe("Schema", () => {
a: Schema.String.pipe(
Schema.encodeTo(
Schema.String.pipe(Schema.check(SchemaCheck.minLength(3))),
SchemaTransformation.compose()
SchemaTransformation.passthrough()
),
Schema.encodeTo(
Schema.String.pipe(Schema.check(SchemaCheck.minLength(2))),
SchemaTransformation.compose()
SchemaTransformation.passthrough()
)
)
})
@@ -1753,6 +1768,22 @@ describe("Schema", () => {
})
})
describe("encode", () => {
it("double transformation", async () => {
const schema = Schema.String.pipe(
Schema.encode(
SchemaTransformation.trim().compose(
SchemaTransformation.toLowerCase()
).flip()
)
)
await assertions.decoding.succeed(schema, " A ", { expected: " A " })
await assertions.encoding.succeed(schema, " A ", { expected: "a" })
})
})
describe("flip", () => {
it("string & minLength(3) <-> number & greaterThan(2)", async () => {
const schema = Schema.FiniteFromString.pipe(
@@ -2007,7 +2038,7 @@ describe("Schema", () => {
})
await assertions.make.succeed(schema, { a: 1 })
const spr = SchemaParser.make(schema)({})
const spr = SchemaToParser.makeSchemaResult(schema)({})
const eff = SchemaResult.asEffect(spr)
const provided = Effect.provideService(
eff,
@@ -2279,7 +2310,7 @@ describe("Schema", () => {
const schema = Schema.String.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.toLowerCase
SchemaTransformation.toLowerCase()
)
)
@@ -2289,7 +2320,7 @@ describe("Schema", () => {
it("toUpperCase", async () => {
const schema = Schema.String.pipe(
Schema.decodeTo(Schema.String, SchemaTransformation.toUpperCase)
Schema.decodeTo(Schema.String, SchemaTransformation.toUpperCase())
)
await assertions.decoding.succeed(schema, "a", { expected: "A" })
@@ -2414,7 +2445,7 @@ describe("Schema", () => {
const jsonSerializer = schema.pipe(
Schema.encodeTo(
Schema.UnknownFromJsonString,
SchemaTransformation.composeSubtype()
SchemaTransformation.passthroughSupertype()
)
)
@@ -2433,7 +2464,7 @@ describe("Schema", () => {
a: Schema.UnknownFromJsonString.pipe(
Schema.decodeTo(
Schema.Struct({ b: Schema.Number }),
SchemaTransformation.composeSubtype()
SchemaTransformation.passthroughSupertype()
)
)
})
@@ -3483,4 +3514,76 @@ describe("Schema", () => {
strictEqual(SchemaAST.format(schema.ast), `[string, number & finite <-> string]`)
})
})
it("decodeTo as composition", async () => {
const From = Schema.Struct({
a: Schema.String,
b: Schema.FiniteFromString
})
const To = Schema.Struct({
a: Schema.FiniteFromString,
b: Schema.UndefinedOr(Schema.Number)
})
const schema = From.pipe(Schema.decodeTo(To))
await assertions.decoding.succeed(schema, { a: "1", b: "2" }, { expected: { a: 1, b: 2 } })
await assertions.encoding.succeed(schema, { a: 1, b: 2 }, { expected: { a: "1", b: "2" } })
await assertions.encoding.fail(
schema,
{ a: 1, b: NaN },
`{ readonly "a": string; readonly "b": string <-> number & finite } <-> { readonly "a": number & finite; readonly "b": number | undefined }
└─ ["b"]
└─ string <-> number & finite
└─ number & finite
└─ finite
└─ Invalid data NaN`
)
await assertions.encoding.fail(
schema,
{ a: 1, b: undefined },
`{ readonly "a": string; readonly "b": string <-> number & finite } <-> { readonly "a": number & finite; readonly "b": number | undefined }
└─ ["b"]
└─ string <-> number & finite
└─ Expected number & finite, actual undefined`
)
})
it("encodeTo as composition", async () => {
const From = Schema.Struct({
a: Schema.String,
b: Schema.FiniteFromString
})
const To = Schema.Struct({
a: Schema.FiniteFromString,
b: Schema.UndefinedOr(Schema.Number)
})
const schema = To.pipe(Schema.encodeTo(From))
await assertions.decoding.succeed(schema, { a: "1", b: "2" }, { expected: { a: 1, b: 2 } })
await assertions.encoding.succeed(schema, { a: 1, b: 2 }, { expected: { a: "1", b: "2" } })
await assertions.encoding.fail(
schema,
{ a: 1, b: NaN },
`{ readonly "a": string; readonly "b": string <-> number & finite } <-> { readonly "a": number & finite; readonly "b": number | undefined }
└─ ["b"]
└─ string <-> number & finite
└─ number & finite
└─ finite
└─ Invalid data NaN`
)
await assertions.encoding.fail(
schema,
{ a: 1, b: undefined },
`{ readonly "a": string; readonly "b": string <-> number & finite } <-> { readonly "a": number & finite; readonly "b": number | undefined }
└─ ["b"]
└─ string <-> number & finite
└─ Expected number & finite, actual undefined`
)
})
})
+3 -3
View File
@@ -1,4 +1,4 @@
import { Effect, Option, Schema, SchemaCheck, SchemaFormatter, SchemaGetter, SchemaIssue, SchemaParser } from "effect"
import { Effect, Option, Schema, SchemaCheck, SchemaFormatter, SchemaGetter, SchemaIssue, SchemaToParser } from "effect"
import { describe, it } from "vitest"
import * as Util from "./SchemaTest.js"
import { deepStrictEqual, fail, strictEqual, throws } from "./utils/assert.js"
@@ -15,7 +15,7 @@ const assertStructuredIssue = async <T, E>(
input: unknown,
expected: ReadonlyArray<SchemaFormatter.StructuredIssue>
) => {
const r = await SchemaParser.decodeUnknown(schema)(input, { errors: "all" }).pipe(
const r = await SchemaToParser.decodeUnknownEffect(schema)(input, { errors: "all" }).pipe(
Effect.mapError((issue) => SchemaFormatter.StructuredFormatter.format(issue)),
Effect.result,
Effect.runPromise
@@ -118,7 +118,7 @@ describe("StructuredFormatter", () => {
it("Forbidden", async () => {
const schema = Schema.Struct({
a: Schema.String.pipe(Schema.decodeTo(Schema.String, {
decode: SchemaGetter.fail((o) => new SchemaIssue.Forbidden(o, { description: "my message" })),
decode: SchemaGetter.fail((os) => new SchemaIssue.Forbidden(os, { description: "my message" })),
encode: SchemaGetter.passthrough()
}))
})
+11 -11
View File
@@ -1,5 +1,5 @@
import type { Context, SchemaAST, SchemaIssue } from "effect"
import { Effect, Result, Schema, SchemaFormatter, SchemaParser, SchemaResult, SchemaSerializer } from "effect"
import { Effect, Result, Schema, SchemaFormatter, SchemaResult, SchemaSerializer, SchemaToParser } from "effect"
export const assertions = (asserts: {
readonly deepStrictEqual: (actual: unknown, expected: unknown) => void
@@ -34,7 +34,7 @@ export const assertions = (asserts: {
expected?: S["Type"]
) {
return out.effect.succeed(
SchemaResult.asEffect(SchemaParser.make(schema)(input)),
SchemaResult.asEffect(SchemaToParser.makeSchemaResult(schema)(input)),
expected === undefined ? input : expected
)
},
@@ -45,7 +45,7 @@ export const assertions = (asserts: {
message: string,
options?: Schema.MakeOptions
) {
return out.effect.fail(SchemaResult.asEffect(SchemaParser.make(schema)(input, options)), message)
return out.effect.fail(SchemaResult.asEffect(SchemaToParser.makeSchemaResult(schema)(input, options)), message)
}
},
@@ -83,7 +83,7 @@ export const assertions = (asserts: {
expected?: unknown
) {
return out.effect.succeed(
Schema.encode(SchemaSerializer.json(Schema.typeCodec(schema)))(input),
Schema.encodeEffect(SchemaSerializer.json(Schema.typeCodec(schema)))(input),
arguments.length > 2 ? expected : input
)
},
@@ -94,7 +94,7 @@ export const assertions = (asserts: {
message: string
) {
return out.effect.fail(
Schema.encode(SchemaSerializer.json(Schema.typeCodec(schema)))(input).pipe(
Schema.encodeEffect(SchemaSerializer.json(Schema.typeCodec(schema)))(input).pipe(
Effect.mapError((err) => err.issue)
),
message
@@ -133,7 +133,7 @@ export const assertions = (asserts: {
expected?: A
) {
return out.effect.succeed(
Schema.decode(SchemaSerializer.json(Schema.typeCodec(schema)))(input),
Schema.decodeEffect(SchemaSerializer.json(Schema.typeCodec(schema)))(input),
arguments.length > 2 ? expected : input
)
},
@@ -144,7 +144,7 @@ export const assertions = (asserts: {
message: string
) {
return out.effect.fail(
Schema.decode(SchemaSerializer.json(Schema.typeCodec(schema)))(input).pipe(
Schema.decodeEffect(SchemaSerializer.json(Schema.typeCodec(schema)))(input).pipe(
Effect.mapError((err) => err.issue)
),
message
@@ -185,7 +185,7 @@ export const assertions = (asserts: {
readonly provide?: ReadonlyArray<readonly [Context.Tag<any, any>, any]> | undefined
} | undefined
) {
const decoded = SchemaParser.decodeUnknownSchemaResult(schema)(input, options?.parseOptions)
const decoded = SchemaToParser.decodeUnknownSchemaResult(schema)(input, options?.parseOptions)
const eff = Result.isResult(decoded) ? Effect.fromResult(decoded) : decoded
const effWithMessage = Effect.catch(eff, (issue) => Effect.fail(SchemaFormatter.TreeFormatter.format(issue)))
let provided = effWithMessage
@@ -214,7 +214,7 @@ export const assertions = (asserts: {
readonly provide?: ReadonlyArray<readonly [Context.Tag<any, any>, any]> | undefined
} | undefined
) {
const decoded = SchemaParser.decodeUnknownSchemaResult(schema)(input, options?.parseOptions)
const decoded = SchemaToParser.decodeUnknownSchemaResult(schema)(input, options?.parseOptions)
const eff = Result.isResult(decoded) ? Effect.fromResult(decoded) : decoded
let provided = eff
if (options?.provide) {
@@ -241,7 +241,7 @@ export const assertions = (asserts: {
} | undefined
) {
// Account for `expected` being `undefined`
const encoded = SchemaParser.encodeUnknownSchemaResult(schema)(input, options?.parseOptions)
const encoded = SchemaToParser.encodeUnknownSchemaResult(schema)(input, options?.parseOptions)
const eff = Result.isResult(encoded) ? Effect.fromResult(encoded) : encoded
return out.effect.succeed(
Effect.catch(eff, (issue) => Effect.fail(SchemaFormatter.TreeFormatter.format(issue))),
@@ -262,7 +262,7 @@ export const assertions = (asserts: {
readonly parseOptions?: SchemaAST.ParseOptions | undefined
} | undefined
) {
const encoded = SchemaParser.encodeUnknownSchemaResult(schema)(input, options?.parseOptions)
const encoded = SchemaToParser.encodeUnknownSchemaResult(schema)(input, options?.parseOptions)
return out.effect.fail(SchemaResult.asEffect(encoded), message)
}
},