Improved handling of annotations throughout the codebase (#569)

This commit is contained in:
Giulio Canti
2025-09-24 19:09:31 +02:00
committed by GitHub
parent 8769a455a9
commit cf9876401e
26 changed files with 413 additions and 721 deletions
+9 -7
View File
@@ -15,7 +15,6 @@ import { memoize } from "../Function.ts"
import { effectIsExit } from "../internal/effect.ts"
import * as internalRecord from "../internal/record.ts"
import * as RegEx from "../primitives/RegExp.ts"
import type { Annotated } from "./Annotations.ts"
import * as Annotations from "./Annotations.ts"
import * as Check from "./Check.ts"
import * as Getter from "./Getter.ts"
@@ -308,7 +307,7 @@ export type Checks = readonly [Check.Check<any>, ...Array<Check.Check<any>>]
* @category model
* @since 4.0.0
*/
export abstract class Base implements Annotated {
export abstract class Base {
readonly annotations: Annotations.Annotations | undefined
readonly checks: Checks | undefined
readonly encoding: Encoding | undefined
@@ -382,6 +381,7 @@ export class Declaration extends Base {
}
/** @internal */
getExpected(): string {
// Annotations on checks are ignored internally
const expected = this.annotations?.identifier ?? this.annotations?.title
if (Predicate.isString(expected)) return expected
return "<Declaration>"
@@ -2070,15 +2070,17 @@ export function record(key: AST, value: AST, keyValueCombiner: KeyValueCombiner
return new TypeLiteral([], [new IndexSignature(false, key, value, keyValueCombiner)])
}
/** @internal */
export function isOptional(ast: AST): boolean {
return ast.context?.isOptional ?? false
}
// -------------------------------------------------------------------------------------
// Public APIs
// -------------------------------------------------------------------------------------
/**
* @since 4.0.0
*/
export function isOptional(ast: AST): boolean {
return ast.context?.isOptional ?? false
}
/**
* @since 4.0.0
*/
+32 -26
View File
@@ -20,14 +20,6 @@ export interface Annotations {
readonly [x: string]: unknown
}
/**
* @category Model
* @since 4.0.0
*/
export interface Annotated {
readonly annotations: Annotations | undefined
}
/**
* @category Model
* @since 4.0.0
@@ -98,6 +90,9 @@ export interface Declaration<T, TypeParameters extends ReadonlyArray<Schema.Top>
readonly "~sentinels"?: ReadonlyArray<AST.Sentinel> | undefined
}
/** @internal */
export const STRUCTURAL_ANNOTATION_KEY = "~structural"
/**
* @category Model
* @since 4.0.0
@@ -162,39 +157,50 @@ export function combine<A extends Annotations>(existing: A | undefined, incoming
return out
}
/** @internal */
export function getAnnotations(ast: AST.AST): Annotations | undefined {
/**
* Get all annotations from the AST.
* If the AST has checks, it will return the annotations from the last check.
*
* @since 4.0.0
*/
export function get(ast: AST.AST): Annotations | undefined {
return ast.checks ? ast.checks[ast.checks.length - 1].annotations : ast.annotations
}
/** @internal */
export function getAnnotation<A>(f: (annotations: Annotations | undefined) => A | undefined) {
return (ast: AST.AST): A | undefined => f(getAnnotations(ast))
/**
* Get an annotation from the AST.
* If the AST has checks, it will return the annotations from the last check.
*
* @since 4.0.0
*/
export function getAt<A>(key: string, parser: (u: unknown) => u is A) {
return (ast: AST.AST): A | undefined => {
const value = get(ast)?.[key]
if (parser(value)) return value
}
}
/** @internal */
export const getIdentifierAnnotation = getAnnotation((annotations) => {
const identifier = annotations?.identifier
if (Predicate.isString(identifier)) return identifier
})
/**
* @since 4.0.0
*/
export const getIdentifier = getAt("identifier", Predicate.isString)
/** @internal */
export const getDescriptionAnnotation = getAnnotation((annotations) => {
const description = annotations?.description
if (Predicate.isString(description)) return description
})
/**
* @since 4.0.0
*/
export const getDescription = getAt("description", Predicate.isString)
/** @internal */
export const getExpected = memoize((ast: AST.AST): string => {
return getIdentifierAnnotation(ast) ?? ast.getExpected(getExpected)
return getIdentifier(ast) ?? ast.getExpected(getExpected)
})
/** @internal */
export const BRAND_KEY = "~effect/schema/Check/brand"
export const BRAND_ANNOTATION_KEY = "~effect/schema/Check/brand"
/** @internal */
export function getBrand<T>(check: Check.Check<T>): string | symbol | undefined {
const brand = check.annotations?.[BRAND_KEY]
const brand = check.annotations?.[BRAND_ANNOTATION_KEY]
if (Predicate.isString(brand) || Predicate.isSymbol(brand)) {
return brand
}
+12 -12
View File
@@ -19,7 +19,7 @@ import * as Issue from "./Issue.ts"
* @category model
* @since 4.0.0
*/
export class Filter<in E> extends Class implements Annotations.Annotated {
export class Filter<in E> extends Class {
readonly _tag = "Filter"
readonly run: (input: E, self: AST.AST, options: AST.ParseOptions) => Issue.Issue | undefined
readonly annotations: Annotations.Filter | undefined
@@ -55,7 +55,7 @@ export class Filter<in E> extends Class implements Annotations.Annotated {
* @category model
* @since 4.0.0
*/
export class FilterGroup<in E> extends Class implements Annotations.Annotated {
export class FilterGroup<in E> extends Class {
readonly _tag = "FilterGroup"
readonly checks: readonly [Check<E>, Check<E>, ...Array<Check<E>>]
readonly annotations: Annotations.Filter | undefined
@@ -151,7 +151,7 @@ export function makeBrand<B extends string | symbol, T>(
brand: B,
annotations?: Annotations.Filter
): Refinement<T & Brand<B>, T> {
return brand_.annotate(Annotations.combine({ [Annotations.BRAND_KEY]: brand }, annotations))
return brand_.annotate(Annotations.combine({ [Annotations.BRAND_ANNOTATION_KEY]: brand }, annotations))
}
/**
@@ -1168,7 +1168,7 @@ export function minLength(minLength: number, annotations?: Annotations.Filter) {
_tag: "minLength",
minLength
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
@@ -1220,7 +1220,7 @@ export function maxLength(maxLength: number, annotations?: Annotations.Filter) {
_tag: "maxLength",
maxLength
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
@@ -1264,7 +1264,7 @@ export function length(length: number, annotations?: Annotations.Filter) {
_tag: "length",
length
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
@@ -1299,7 +1299,7 @@ export function minSize(minSize: number, annotations?: Annotations.Filter) {
_tag: "minSize",
minSize
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
@@ -1328,7 +1328,7 @@ export function maxSize(maxSize: number, annotations?: Annotations.Filter) {
_tag: "maxSize",
maxSize
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
@@ -1357,7 +1357,7 @@ export function size(size: number, annotations?: Annotations.Filter) {
_tag: "size",
size
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
@@ -1391,7 +1391,7 @@ export function minEntries(minEntries: number, annotations?: Annotations.Filter)
_tag: "minEntries",
minEntries
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
@@ -1424,7 +1424,7 @@ export function maxEntries(maxEntries: number, annotations?: Annotations.Filter)
_tag: "maxEntries",
maxEntries
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
@@ -1457,7 +1457,7 @@ export function entries(entries: number, annotations?: Annotations.Filter) {
_tag: "entries",
entries
},
"~structural": true,
[Annotations.STRUCTURAL_ANNOTATION_KEY]: true,
arbitrary: {
_tag: "Constraints",
constraints: {
+5 -5
View File
@@ -626,18 +626,18 @@ function toDefaultIssues(
}
}
function formatCheck<T>(filter: Check.Check<T>): string {
const out = filter.annotations?.description ?? filter.annotations?.title
function formatCheck<T>(check: Check.Check<T>): string {
const out = check.annotations?.description ?? check.annotations?.title
if (Predicate.isString(out)) return out
const brand = Annotations.getBrand(filter)
const brand = Annotations.getBrand(check)
if (brand !== undefined) return `Brand<"${String(brand)}">`
switch (filter._tag) {
switch (check._tag) {
case "Filter":
return "<filter>"
case "FilterGroup":
return filter.checks.map((check) => formatCheck(check)).join(" & ")
return check.checks.map((check) => formatCheck(check)).join(" & ")
}
}
+171 -450
View File
@@ -119,7 +119,7 @@ export interface Bottom<
readonly "EncodingServices": RE
readonly "~type.make.in": TypeMakeIn
readonly "~type.make": TypeMake
readonly "~type.make": TypeMake // useful to type the `refine` interface
readonly "~type.constructor.default": TypeConstructorDefault
readonly "Iso": Iso
@@ -145,86 +145,35 @@ export interface Bottom<
const TypeId = "~effect/schema/Schema"
abstract class BottomImpl<
T,
E,
RD,
RE,
Ast extends AST.AST,
RebuildOut extends Top,
AnnotateIn extends Annotations.Annotations,
TypeMakeIn = T,
Iso = T,
TypeMake = TypeMakeIn,
TypeMutability extends Mutability = "readonly",
TypeOptionality extends Optionality = "required",
TypeConstructorDefault extends ConstructorDefault = "no-default",
EncodedMutability extends Mutability = "readonly",
EncodedOptionality extends Optionality = "required"
> extends Pipeable.Class implements
Bottom<
T,
E,
RD,
RE,
Ast,
RebuildOut,
AnnotateIn,
TypeMakeIn,
Iso,
TypeMake,
TypeMutability,
TypeOptionality,
TypeConstructorDefault,
EncodedMutability,
EncodedOptionality
>
{
readonly [TypeId] = TypeId
declare readonly "Type": T
declare readonly "Encoded": E
declare readonly "DecodingServices": RD
declare readonly "EncodingServices": RE
declare readonly "~rebuild.out": RebuildOut
declare readonly "~annotate.in": AnnotateIn
declare readonly "~type.make.in": TypeMakeIn
declare readonly "~type.make": TypeMake
declare readonly "~type.constructor.default": TypeConstructorDefault
declare readonly "Iso": Iso
declare readonly "~type.mutability": TypeMutability
declare readonly "~type.optionality": TypeOptionality
declare readonly "~encoded.mutability": EncodedMutability
declare readonly "~encoded.optionality": EncodedOptionality
readonly ast: Ast
readonly makeSync: (input: this["~type.make.in"], options?: MakeOptions) => this["Type"]
constructor(ast: Ast) {
super()
this.ast = ast
this.makeSync = ToParser.makeSync(this)
}
abstract rebuild(ast: this["ast"]): this["~rebuild.out"]
annotate(annotations: this["~annotate.in"]): this["~rebuild.out"] {
const Proto = {
[TypeId]: TypeId,
pipe() {
return Pipeable.pipeArguments(this, arguments)
},
annotate(this: Top, annotations: Annotations.Annotations) {
return this.rebuild(AST.annotate(this.ast, annotations))
}
annotateKey(annotations: Annotations.Key<this["Type"]>): this["~rebuild.out"] {
},
annotateKey(this: Top, annotations: Annotations.Key<unknown>) {
return this.rebuild(AST.annotateKey(this.ast, annotations))
}
},
check(
...checks: readonly [
Check.Check<this["Type"]>,
...Array<Check.Check<this["Type"]>>
]
): this["~rebuild.out"] {
this: Top,
...checks: readonly [Check.Check<unknown>, ...Array<Check.Check<unknown>>]
) {
return this.rebuild(AST.appendChecks(this.ast, checks))
}
}
/** @internal */
export function makeProto<S extends Top>(ast: AST.AST, options: object): S {
const self = Object.create(Proto)
Object.assign(self, options)
self.ast = ast
self.rebuild = (ast: AST.AST) => makeProto(ast, options)
self.makeSync = ToParser.makeSync(self)
return self
}
/**
* Reveals the complete Bottom interface type of a schema, exposing all 14 type
* parameters.
@@ -737,34 +686,6 @@ export const encodeUnknownSync = ToParser.encodeUnknownSync
*/
export const encodeSync = ToParser.encodeSync
class make$<S extends Top> extends BottomImpl<
S["Type"],
S["Encoded"],
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
S["~rebuild.out"],
S["~annotate.in"],
S["~type.make.in"],
S["Iso"],
S["~type.make"],
S["~type.mutability"],
S["~type.optionality"],
S["~type.constructor.default"],
S["~encoded.mutability"],
S["~encoded.optionality"]
> {
readonly rebuild: (ast: S["ast"]) => S["~rebuild.out"]
constructor(
ast: S["ast"],
rebuild: (ast: S["ast"]) => S["~rebuild.out"]
) {
super(ast)
this.rebuild = rebuild
}
}
/**
* Creates a schema from an AST (Abstract Syntax Tree) node.
*
@@ -780,25 +701,8 @@ class make$<S extends Top> extends BottomImpl<
* @category Constructors
* @since 4.0.0
*/
export function make<S extends Top>(ast: S["ast"]): Bottom<
S["Type"],
S["Encoded"],
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
S["~rebuild.out"],
S["~annotate.in"],
S["~type.make.in"],
S["Iso"],
S["~type.make"],
S["~type.mutability"],
S["~type.optionality"],
S["~type.constructor.default"],
S["~encoded.mutability"],
S["~encoded.optionality"]
> {
const rebuild = (ast: AST.AST) => new make$<S>(ast, rebuild)
return rebuild(ast)
export function make<S extends Top>(ast: S["ast"]): S {
return makeProto(ast, {})
}
/**
@@ -842,15 +746,6 @@ interface optionalKeyLambda extends Lambda {
readonly "~lambda.out": this["~lambda.in"] extends Top ? optionalKey<this["~lambda.in"]> : never
}
class makeWithSchema$<S extends Top, Result extends Top> extends make$<Result> {
readonly schema: S
constructor(ast: AST.AST, schema: S) {
super(ast, (ast) => new makeWithSchema$(ast, schema))
this.schema = schema
}
}
/**
* Creates an exact optional key schema for struct fields. Unlike `optional`,
* this creates exact optional properties (not `| undefined`) that can be
@@ -872,8 +767,8 @@ class makeWithSchema$<S extends Top, Result extends Top> extends make$<Result> {
*
* @since 4.0.0
*/
export const optionalKey = lambda<optionalKeyLambda>(function optionalKey<S extends Top>(self: S): optionalKey<S> {
return new makeWithSchema$<S, optionalKey<S>>(AST.optionalKey(self.ast), self)
export const optionalKey = lambda<optionalKeyLambda>(function optionalKey<S extends Top>(schema: S): optionalKey<S> {
return makeProto(AST.optionalKey(schema.ast), { schema })
})
/**
@@ -950,8 +845,8 @@ interface mutableKeyLambda extends Lambda {
/**
* @since 4.0.0
*/
export const mutableKey = lambda<mutableKeyLambda>(function mutableKey<S extends Top>(self: S): mutableKey<S> {
return new makeWithSchema$<S, mutableKey<S>>(AST.mutableKey(self.ast), self)
export const mutableKey = lambda<mutableKeyLambda>(function mutableKey<S extends Top>(schema: S): mutableKey<S> {
return makeProto(AST.mutableKey(schema.ast), { schema })
})
/**
@@ -987,8 +882,8 @@ interface typeCodecLambda extends Lambda {
/**
* @since 4.0.0
*/
export const typeCodec = lambda<typeCodecLambda>(function typeCodec<S extends Top>(self: S): typeCodec<S> {
return new makeWithSchema$<S, typeCodec<S>>(AST.typeAST(self.ast), self)
export const typeCodec = lambda<typeCodecLambda>(function typeCodec<S extends Top>(schema: S): typeCodec<S> {
return makeProto(AST.typeAST(schema.ast), { schema })
})
/**
@@ -1024,9 +919,13 @@ interface encodedCodecLambda extends Lambda {
/**
* @since 4.0.0
*/
export const encodedCodec = lambda<encodedCodecLambda>(function encodedCodec<S extends Top>(self: S): encodedCodec<S> {
return new makeWithSchema$<S, encodedCodec<S>>(AST.encodedAST(self.ast), self)
})
export const encodedCodec = lambda<encodedCodecLambda>(
function encodedCodec<S extends Top>(schema: S): encodedCodec<S> {
return makeProto(AST.encodedAST(schema.ast), { schema })
}
)
const FlipTypeId = "~effect/schema/Schema/flip"
/**
* @since 4.0.0
@@ -1050,15 +949,11 @@ export interface flip<S extends Top> extends
S["~type.optionality"]
>
{
readonly "~rebuild.out": this
readonly [FlipTypeId]: typeof FlipTypeId
readonly schema: S
}
const FlipTypeId = "~effect/schema/Schema/flip$"
class flip$<S extends Top> extends makeWithSchema$<S, flip<S>> implements flip<S> {
readonly [FlipTypeId] = FlipTypeId
}
function isFlip$(schema: Top): schema is flip<any> {
return Predicate.hasProperty(schema, FlipTypeId) && schema[FlipTypeId] === FlipTypeId
}
@@ -1071,7 +966,7 @@ export function flip<S extends Top>(schema: S): flip<S> {
if (isFlip$(schema)) {
return schema.schema.rebuild(AST.flip(schema.ast))
}
return new flip$(AST.flip(schema.ast), schema)
return makeProto(AST.flip(schema.ast), { [FlipTypeId]: FlipTypeId, schema })
}
/**
@@ -1084,16 +979,6 @@ export interface Literal<L extends AST.Literal>
readonly literal: L
}
class Literal$<L extends AST.Literal> extends make$<Literal<L>> implements Literal<L> {
declare readonly "~rebuild.out": this
readonly literal: L
constructor(ast: AST.LiteralType, literal: L) {
super(ast, (ast) => new Literal$(ast, literal))
this.literal = literal
}
}
/**
* @see {@link Literals} for a schema that represents a union of literals.
* @see {@link tag} for a schema that represents a literal value that can be
@@ -1101,7 +986,7 @@ class Literal$<L extends AST.Literal> extends make$<Literal<L>> implements Liter
* @since 4.0.0
*/
export function Literal<L extends AST.Literal>(literal: L): Literal<L> {
return new Literal$(new AST.LiteralType(literal), literal)
return makeProto(new AST.LiteralType(literal), { literal })
}
/**
@@ -1162,18 +1047,6 @@ export interface TemplateLiteral<Parts extends TemplateLiteral.Parts> extends
readonly parts: Parts
}
class TemplateLiteral$<Parts extends TemplateLiteral.Parts> extends make$<TemplateLiteral<Parts>>
implements TemplateLiteral<Parts>
{
declare readonly "~rebuild.out": this
readonly parts: Parts
constructor(ast: AST.TemplateLiteral, parts: Parts) {
super(ast, (ast) => new TemplateLiteral$(ast, parts))
this.parts = parts
}
}
function templateLiteralFromParts<Parts extends TemplateLiteral.Parts>(parts: Parts) {
return new AST.TemplateLiteral(parts.map((part) => isSchema(part) ? part.ast : new AST.LiteralType(part)))
}
@@ -1182,7 +1055,7 @@ function templateLiteralFromParts<Parts extends TemplateLiteral.Parts>(parts: Pa
* @since 4.0.0
*/
export function TemplateLiteral<const Parts extends TemplateLiteral.Parts>(parts: Parts): TemplateLiteral<Parts> {
return new TemplateLiteral$(templateLiteralFromParts(parts), [...parts] as Parts)
return makeProto(templateLiteralFromParts(parts), { parts })
}
/**
@@ -1215,27 +1088,17 @@ export interface TemplateLiteralParser<Parts extends TemplateLiteral.Parts> exte
Annotations.Annotations
>
{
readonly "~rebuild.out": this
readonly parts: Parts
}
class TemplateLiteralParser$<Parts extends TemplateLiteral.Parts> extends make$<TemplateLiteralParser<Parts>>
implements TemplateLiteralParser<Parts>
{
readonly parts: Parts
constructor(ast: AST.TupleType, parts: Parts) {
super(ast, (ast) => new TemplateLiteralParser$(ast, parts))
this.parts = parts
}
}
/**
* @since 4.0.0
*/
export function TemplateLiteralParser<const Parts extends TemplateLiteral.Parts>(
parts: Parts
): TemplateLiteralParser<Parts> {
return new TemplateLiteralParser$(templateLiteralFromParts(parts).asTemplateLiteralParser(), [...parts] as Parts)
return makeProto(templateLiteralFromParts(parts).asTemplateLiteralParser(), { parts: [...parts] })
}
/**
@@ -1248,27 +1111,17 @@ export interface Enums<A extends { [x: string]: string | number }>
readonly enums: A
}
class Enums$<A extends { [x: string]: string | number }> extends make$<Enums<A>> implements Enums<A> {
declare readonly "~rebuild.out": this
readonly enums: A
constructor(ast: AST.Enums, enums: A) {
super(ast, (ast) => new Enums$(ast, enums))
this.enums = enums
}
}
/**
* @since 4.0.0
*/
export function Enums<A extends { [x: string]: string | number }>(enums: A): Enums<A> {
return new Enums$(
return makeProto(
new AST.Enums(
Object.keys(enums).filter(
(key) => typeof enums[enums[key]] !== "number"
).map((key) => [key, enums[key]])
),
enums
{ enums }
)
}
@@ -1612,30 +1465,27 @@ export interface Struct<Fields extends Struct.Fields> extends
): Struct<Simplify<Readonly<To>>>
}
class Struct$<Fields extends Struct.Fields> extends make$<Struct<Fields>> implements Struct<Fields> {
declare readonly "~rebuild.out": this
readonly fields: Fields
constructor(ast: AST.TypeLiteral, fields: Fields) {
super(ast, (ast) => new Struct$(ast, fields))
// clone to avoid accidental external mutation
this.fields = { ...fields }
}
mapFields<To extends Struct.Fields>(
f: (fields: Fields) => To,
options?: {
readonly preserveChecks?: boolean | undefined
} | undefined
): Struct<To> {
const fields = f(this.fields)
return new Struct$(AST.struct(fields, options?.preserveChecks ? this.ast.checks : undefined), fields)
}
function makeStruct<const Fields extends Struct.Fields>(ast: AST.TypeLiteral, fields: Fields): Struct<Fields> {
return makeProto(ast, {
fields,
mapFields<To extends Struct.Fields>(
this: Struct<Fields>,
f: (fields: Fields) => To,
options?: {
readonly preserveChecks?: boolean | undefined
} | undefined
): Struct<To> {
const fields = f(this.fields)
return makeStruct(AST.struct(fields, options?.preserveChecks ? this.ast.checks : undefined), fields)
}
})
}
/**
* @since 4.0.0
*/
export function Struct<const Fields extends Struct.Fields>(fields: Fields): Struct<Fields> {
return new Struct$(AST.struct(fields, undefined), fields)
return makeStruct(AST.struct(fields, undefined), fields)
}
/**
@@ -1816,20 +1666,6 @@ export interface Record$<Key extends Record.Key, Value extends Top> extends
readonly value: Value
}
class Record$$<Key extends Record.Key, Value extends Top> extends make$<Record$<Key, Value>>
implements Record$<Key, Value>
{
declare readonly "~rebuild.out": this
readonly key: Key
readonly value: Value
constructor(ast: AST.TypeLiteral, key: Key, value: Value) {
super(ast, (ast) => new Record$$(ast, key, value))
this.key = key
this.value = value
}
}
/**
* @since 4.0.0
*/
@@ -1846,7 +1682,7 @@ export function Record<Key extends Record.Key, Value extends Top>(
const keyValueCombiner = options?.keyValueCombiner?.decode || options?.keyValueCombiner?.encode
? new AST.KeyValueCombiner(options.keyValueCombiner.decode, options.keyValueCombiner.encode)
: undefined
return new Record$$(AST.record(key.ast, value.ast, keyValueCombiner), key, value)
return makeProto(AST.record(key.ast, value.ast, keyValueCombiner), { key, value })
}
/**
@@ -1934,22 +1770,6 @@ export interface StructWithRest<
readonly records: Records
}
class StructWithRest$$<S extends StructWithRest.TypeLiteral, Records extends StructWithRest.Records>
extends make$<StructWithRest<S, Records>>
implements StructWithRest<S, Records>
{
declare readonly "~rebuild.out": this
readonly schema: S
readonly records: Records
constructor(ast: AST.TypeLiteral, schema: S, records: Records) {
super(ast, (ast) => new StructWithRest$$(ast, this.schema, this.records))
this.schema = schema
// clone to avoid accidental external mutation
this.records = [...records] as any
}
}
/**
* @since 4.0.0
*/
@@ -1958,9 +1778,9 @@ export function StructWithRest<
const Records extends StructWithRest.Records
>(
schema: S,
rest: Records
records: Records
): StructWithRest<S, Records> {
return new StructWithRest$$(AST.structWithRest(schema.ast, rest.map(AST.getAST)), schema, rest)
return makeProto(AST.structWithRest(schema.ast, records.map(AST.getAST)), { schema, records })
}
/**
@@ -2079,24 +1899,20 @@ export interface Tuple<Elements extends Tuple.Elements> extends
): Tuple<Simplify<Readonly<To>>>
}
class Tuple$<Elements extends Tuple.Elements> extends make$<Tuple<Elements>> implements Tuple<Elements> {
declare readonly "~rebuild.out": this
readonly elements: Elements
constructor(ast: AST.TupleType, elements: Elements) {
super(ast, (ast) => new Tuple$(ast, elements))
// clone to avoid accidental external mutation
this.elements = [...elements] as any
}
mapElements<To extends Tuple.Elements>(
f: (elements: Elements) => To,
options?: {
readonly preserveChecks?: boolean | undefined
} | undefined
): Tuple<Simplify<Readonly<To>>> {
const elements = f(this.elements)
return new Tuple$(AST.tuple(elements, options?.preserveChecks ? this.ast.checks : undefined), elements)
}
function makeTuple<Elements extends Tuple.Elements>(ast: AST.TupleType, elements: Elements): Tuple<Elements> {
return makeProto(ast, {
elements,
mapElements<To extends Tuple.Elements>(
this: Tuple<Elements>,
f: (elements: Elements) => To,
options?: {
readonly preserveChecks?: boolean | undefined
} | undefined
): Tuple<Simplify<Readonly<To>>> {
const elements = f(this.elements)
return makeTuple(AST.tuple(elements, options?.preserveChecks ? this.ast.checks : undefined), elements)
}
})
}
/**
@@ -2104,7 +1920,7 @@ class Tuple$<Elements extends Tuple.Elements> extends make$<Tuple<Elements>> imp
* @since 4.0.0
*/
export function Tuple<const Elements extends ReadonlyArray<Top>>(elements: Elements): Tuple<Elements> {
return new Tuple$(AST.tuple(elements), elements)
return makeTuple(AST.tuple(elements), elements)
}
/**
@@ -2196,20 +2012,6 @@ export interface TupleWithRest<
readonly rest: Rest
}
class TupleWithRest$<S extends Tuple<Tuple.Elements> | mutable<Tuple<Tuple.Elements>>, Rest extends TupleWithRest.Rest>
extends make$<TupleWithRest<S, Rest>>
{
readonly schema: S
readonly rest: Rest
constructor(ast: AST.TupleType, schema: S, rest: Rest) {
super(ast, (ast) => new TupleWithRest$(ast, this.schema, this.rest))
this.schema = schema
// clone to avoid accidental external mutation
this.rest = [...rest]
}
}
/**
* @category Constructors
* @since 4.0.0
@@ -2217,11 +2019,8 @@ class TupleWithRest$<S extends Tuple<Tuple.Elements> | mutable<Tuple<Tuple.Eleme
export function TupleWithRest<
S extends Tuple<Tuple.Elements> | mutable<Tuple<Tuple.Elements>>,
const Rest extends TupleWithRest.Rest
>(
schema: S,
rest: Rest
): TupleWithRest<S, Rest> {
return new TupleWithRest$(AST.tupleWithRest(schema.ast, rest.map(AST.getAST)), schema, rest)
>(schema: S, rest: Rest): TupleWithRest<S, Rest> {
return makeProto(AST.tupleWithRest(schema.ast, rest.map(AST.getAST)), { schema, rest })
}
/**
@@ -2253,11 +2052,8 @@ interface ArrayLambda extends Lambda {
* @category Constructors
* @since 4.0.0
*/
export const Array = lambda<ArrayLambda>(function Array<S extends Top>(item: S): Array$<S> {
return new makeWithSchema$<S, Array$<S>>(
new AST.TupleType(false, [], [item.ast]),
item
)
export const Array = lambda<ArrayLambda>(function Array<S extends Top>(schema: S): Array$<S> {
return makeProto(new AST.TupleType(false, [], [schema.ast]), { schema })
})
/**
@@ -2290,11 +2086,8 @@ interface NonEmptyArrayLambda extends Lambda {
* @since 4.0.0
*/
export const NonEmptyArray = lambda<NonEmptyArrayLambda>(
function NonEmptyArray<S extends Top>(item: S): NonEmptyArray<S> {
return new makeWithSchema$<S, NonEmptyArray<S>>(
new AST.TupleType(false, [item.ast], [item.ast]),
item
)
function NonEmptyArray<S extends Top>(schema: S): NonEmptyArray<S> {
return makeProto(new AST.TupleType(false, [schema.ast], [schema.ast]), { schema })
}
)
@@ -2351,8 +2144,8 @@ interface mutableLambda extends Lambda {
/**
* @since 4.0.0
*/
export const mutable = lambda<mutableLambda>(function mutable<S extends Top>(self: S): mutable<S> {
return new makeWithSchema$<S, mutable<S>>(AST.mutable(self.ast), self)
export const mutable = lambda<mutableLambda>(function mutable<S extends Top>(schema: S): mutable<S> {
return makeProto(AST.mutable(schema.ast), { schema })
})
/**
@@ -2366,7 +2159,6 @@ export interface readonly$<S extends Top> extends
S["EncodingServices"],
S["ast"],
readonly$<S>,
// 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["Iso"],
@@ -2390,8 +2182,8 @@ interface readonlyLambda extends Lambda {
/**
* @since 4.0.0
*/
export const readonly = lambda<readonlyLambda>(function readonly<S extends Top>(self: S): readonly$<S> {
return new makeWithSchema$<S, readonly$<S>>(AST.mutable(self.ast), self)
export const readonly = lambda<readonlyLambda>(function readonly<S extends Top>(schema: S): readonly$<S> {
return makeProto(AST.readonly(schema.ast), { schema })
})
/**
@@ -2428,29 +2220,26 @@ export interface Union<Members extends ReadonlyArray<Top>> extends
): Union<Simplify<Readonly<To>>>
}
class Union$<Members extends ReadonlyArray<Top>> extends make$<Union<Members>> implements Union<Members> {
declare readonly "~rebuild.out": this
override readonly ast: AST.UnionType<Members[number]["ast"]>
readonly members: Members
constructor(ast: AST.UnionType<Members[number]["ast"]>, members: Members) {
super(ast, (ast) => new Union$(ast, members))
this.ast = ast
this.members = members
}
mapMembers<To extends ReadonlyArray<Top>>(
f: (members: Members) => To,
options?: {
readonly preserveChecks?: boolean | undefined
} | undefined
): Union<Simplify<Readonly<To>>> {
const members = f(this.members)
return new Union$(
AST.union(members, this.ast.mode, options?.preserveChecks ? this.ast.checks : undefined),
members
)
}
function makeUnion<Members extends ReadonlyArray<Top>>(
ast: AST.UnionType<Members[number]["ast"]>,
members: Members
): Union<Members> {
return makeProto(ast, {
members,
mapMembers<To extends ReadonlyArray<Top>>(
this: Union<Members>,
f: (members: Members) => To,
options?: {
readonly preserveChecks?: boolean | undefined
} | undefined
): Union<Simplify<Readonly<To>>> {
const members = f(this.members)
return makeUnion(
AST.union(members, this.ast.mode, options?.preserveChecks ? this.ast.checks : undefined),
members
)
}
})
}
/**
@@ -2468,7 +2257,7 @@ export function Union<const Members extends ReadonlyArray<Top>>(
members: Members,
options?: { mode?: "anyOf" | "oneOf" }
): Union<Members> {
return new Union$(AST.union(members, options?.mode ?? "anyOf", undefined), members)
return makeUnion(AST.union(members, options?.mode ?? "anyOf", undefined), members)
}
/**
@@ -2496,30 +2285,6 @@ export interface Literals<L extends ReadonlyArray<AST.Literal>> extends
pick<const L2 extends ReadonlyArray<L[number]>>(literals: L2): Literals<L2>
}
class Literals$<L extends ReadonlyArray<AST.Literal>> extends make$<Literals<L>> implements Literals<L> {
declare readonly "~rebuild.out": this
readonly literals: L
readonly members: { readonly [K in keyof L]: Literal<L[K]> }
constructor(
ast: AST.UnionType<AST.LiteralType>,
literals: L,
members: { readonly [K in keyof L]: Literal<L[K]> }
) {
super(ast, (ast) => new Literals$(ast, literals, members))
this.literals = literals
this.members = members
}
mapMembers<To extends ReadonlyArray<Top>>(f: (members: this["members"]) => To): Union<Simplify<Readonly<To>>> {
return Union(f(this.members))
}
pick<const L2 extends ReadonlyArray<L[number]>>(literals: L2): Literals<L2> {
return Literals(literals)
}
}
/**
* @see {@link Literal} for a schema that represents a single literal.
* @category Constructors
@@ -2527,7 +2292,19 @@ class Literals$<L extends ReadonlyArray<AST.Literal>> extends make$<Literals<L>>
*/
export function Literals<const L extends ReadonlyArray<AST.Literal>>(literals: L): Literals<L> {
const members = literals.map(Literal) as { readonly [K in keyof L]: Literal<L[K]> }
return new Literals$(AST.union(members, "anyOf", undefined), [...literals] as L, members)
return makeProto(AST.union(members, "anyOf", undefined), {
literals,
members,
mapMembers<To extends ReadonlyArray<Top>>(
this: Literals<L>,
f: (members: Literals<L>["members"]) => To
): Union<Simplify<Readonly<To>>> {
return Union(f(this.members))
},
pick<const L2 extends ReadonlyArray<L[number]>>(literals: L2): Literals<L2> {
return Literals(literals)
}
})
}
/**
@@ -2645,7 +2422,7 @@ export interface refine<T extends S["Type"], S extends Top> extends
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
refine<T, S["~rebuild.out"]>,
refine<T, S>,
Annotations.Bottom<T>,
S["~type.make.in"],
T,
@@ -2656,7 +2433,9 @@ export interface refine<T extends S["Type"], S extends Top> extends
S["~encoded.mutability"],
S["~encoded.optionality"]
>
{}
{
readonly "~rebuild.out": this
}
/**
* @category Filtering
@@ -2727,11 +2506,10 @@ export function decodingMiddleware<S extends Top, RD>(
options: AST.ParseOptions
) => Effect.Effect<O.Option<S["Type"]>, Issue.Issue, RD>
) {
return (self: S): decodingMiddleware<S, RD> => {
return new makeWithSchema$<S, decodingMiddleware<S, RD>>(
AST.decodingMiddleware(self.ast, new Transformation.Middleware(decode, identity)),
self
)
return (schema: S): decodingMiddleware<S, RD> => {
return makeProto(AST.decodingMiddleware(schema.ast, new Transformation.Middleware(decode, identity)), {
schema
})
}
}
@@ -2770,11 +2548,8 @@ export function encodingMiddleware<S extends Top, RE>(
options: AST.ParseOptions
) => Effect.Effect<O.Option<S["Type"]>, Issue.Issue, RE>
) {
return (self: S): encodingMiddleware<S, RE> => {
return new makeWithSchema$<S, encodingMiddleware<S, RE>>(
AST.encodingMiddleware(self.ast, new Transformation.Middleware(identity, encode)),
self
)
return (schema: S): encodingMiddleware<S, RE> => {
return makeProto(AST.encodingMiddleware(schema.ast, new Transformation.Middleware(identity, encode)), { schema })
}
}
@@ -2850,26 +2625,6 @@ export interface decodeTo<To extends Top, From extends Top, RD = never, RE = nev
*/
export interface compose<To extends Top, From extends Top> extends decodeTo<To, From> {}
class decodeTo$<To extends Top, From extends Top, RD, RE> extends make$<decodeTo<To, From, RD, RE>>
implements decodeTo<To, From, RD, RE>
{
declare readonly "~rebuild.out": this
override readonly ast: From["ast"]
readonly from: From
readonly to: To
constructor(
ast: From["ast"],
from: From,
to: To
) {
super(ast, (ast) => new decodeTo$<To, From, RD, RE>(ast, from, to))
this.ast = ast
this.from = from
this.to = to
}
}
/**
* @since 4.0.0
*/
@@ -2889,14 +2644,16 @@ export function decodeTo<To extends Top, From extends Top, RD = never, RE = neve
} | undefined
) {
return (from: From) => {
return new decodeTo$(
return makeProto(
AST.decodeTo(
from.ast,
to.ast,
transformation ? Transformation.make(transformation) : Transformation.passthrough()
),
from,
to
{
from,
to
}
)
}
}
@@ -2953,25 +2710,31 @@ export function encode<S extends Top, RD = never, RE = never>(transformation: {
/**
* @since 4.0.0
*/
export interface withConstructorDefault<S extends Top & { readonly "~type.constructor.default": "no-default" }>
extends
Bottom<
S["Type"],
S["Encoded"],
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
withConstructorDefault<S>,
S["~annotate.in"],
S["~type.make.in"],
S["Iso"],
S["~type.make"],
S["~type.mutability"],
S["~type.optionality"],
"with-default",
S["~encoded.mutability"],
S["~encoded.optionality"]
>
export interface WithoutConstructorDefault {
readonly "~type.constructor.default": "no-default"
}
/**
* @since 4.0.0
*/
export interface withConstructorDefault<S extends Top & WithoutConstructorDefault> extends
Bottom<
S["Type"],
S["Encoded"],
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
withConstructorDefault<S>,
S["~annotate.in"],
S["~type.make.in"],
S["Iso"],
S["~type.make"],
S["~type.mutability"],
S["~type.optionality"],
"with-default",
S["~encoded.mutability"],
S["~encoded.optionality"]
>
{
readonly "~rebuild.out": this
readonly schema: S
@@ -2980,15 +2743,15 @@ export interface withConstructorDefault<S extends Top & { readonly "~type.constr
/**
* @since 4.0.0
*/
export function withConstructorDefault<S extends Top & { readonly "~type.constructor.default": "no-default" }>(
export function withConstructorDefault<S extends Top & WithoutConstructorDefault>(
defaultValue: (
input: O.Option<undefined>
// `S["~type.make.in"]` instead of `S["Type"]` is intentional here because
// it makes easier to define the default value if there are nested defaults
) => O.Option<S["~type.make.in"]> | Effect.Effect<O.Option<S["~type.make.in"]>>
) {
return (self: S): withConstructorDefault<S> => {
return new makeWithSchema$<S, withConstructorDefault<S>>(AST.withConstructorDefault(self.ast, defaultValue), self)
return (schema: S): withConstructorDefault<S> => {
return makeProto(AST.withConstructorDefault(schema.ast, defaultValue), { schema })
}
}
@@ -3260,50 +3023,6 @@ export interface TaggedUnion<Cases extends Record<string, Top>> extends
}
}
class TaggedUnion$<Cases extends Record<string, Top>> extends make$<TaggedUnion<Cases>> implements TaggedUnion<Cases> {
declare readonly "~rebuild.out": this
override readonly ast: AST.UnionType<AST.TypeLiteral>
readonly cases: Cases
readonly isAnyOf: <const Keys>(
keys: ReadonlyArray<Keys>
) => (value: Cases[keyof Cases]["Type"]) => value is Extract<Cases[keyof Cases]["Type"], { _tag: Keys }>
readonly guards: { [K in keyof Cases]: (u: unknown) => u is Cases[K]["Type"] }
readonly match: {
<Output>(
value: Cases[keyof Cases]["Type"],
cases: { [K in keyof Cases]: (value: Cases[K]["Type"]) => Output }
): Output
<Output>(
cases: { [K in keyof Cases]: (value: Cases[K]["Type"]) => Output }
): (value: Cases[keyof Cases]["Type"]) => Output
}
constructor(
ast: AST.UnionType<AST.TypeLiteral>,
cases: Cases,
isAnyOf: <const Keys>(
keys: ReadonlyArray<Keys>
) => (value: Cases[keyof Cases]["Type"]) => value is Extract<Cases[keyof Cases]["Type"], { _tag: Keys }>,
guards: { [K in keyof Cases]: (u: unknown) => u is Cases[K]["Type"] },
match: {
<Output>(
value: Cases[keyof Cases]["Type"],
cases: { [K in keyof Cases]: (value: Cases[K]["Type"]) => Output }
): Output
<Output>(
cases: { [K in keyof Cases]: (value: Cases[K]["Type"]) => Output }
): (value: Cases[keyof Cases]["Type"]) => Output
}
) {
super(ast, (ast) => new TaggedUnion$(ast, cases, isAnyOf, guards, match))
this.ast = ast
this.cases = cases
this.isAnyOf = isAnyOf
this.guards = guards
this.match = match
}
}
/**
* @since 4.0.0
* @experimental
@@ -3318,7 +3037,7 @@ export function TaggedUnion<const CasesByTag extends Record<string, Struct.Field
}
const union = Union(members)
const { guards, isAnyOf, match } = asTaggedUnion("_tag")(union)
return new TaggedUnion$(union.ast, cases, isAnyOf, guards, match) as any
return makeProto(union.ast, { cases, isAnyOf, guards, match })
}
/**
@@ -4073,6 +3792,7 @@ export interface Opaque<Self, S extends Top, Brand> extends
S["~encoded.optionality"]
>
{
// intentionally left without `readonly "~rebuild.out": this`
new(_: never): S["Type"] & Brand
}
@@ -4485,6 +4205,7 @@ export interface Class<Self, S extends Top & { readonly fields: Struct.Fields },
S["~encoded.optionality"]
>
{
// intentionally left without `readonly "~rebuild.out": this`
new(props: S["~type.make.in"], options?: MakeOptions): S["Type"] & Inherited
readonly identifier: string
readonly fields: S["fields"]
@@ -4586,7 +4307,7 @@ function makeClass<
) => Class<Extended, Struct<Simplify<Merge<S["fields"], NewFields>>>, Self> {
return (newFields, annotations) => {
const fields = { ...schema.fields, ...newFields }
const struct: any = new Struct$(AST.struct(fields, schema.ast.checks), fields)
const struct: any = makeStruct(AST.struct(fields, schema.ast.checks), fields)
return makeClass(this, identifier, struct, annotations)
}
}
+3 -3
View File
@@ -227,7 +227,7 @@ export function ensureArray<T, RD, RE>(
return Schema.make<Schema.Codec<T, StringPojo, RD, RE>>(goEnsureArray(codec.ast))
}
const ENSURE_ARRAY_FLAG = "~effect/schema/Serializer/ensureArray"
const ENSURE_ARRAY_ANNOTATION_KEY = "~effect/schema/Serializer/ensureArray"
/** @internal */
export const goEnsureArray = memoize((ast: AST.AST): AST.AST => {
@@ -240,7 +240,7 @@ export const goEnsureArray = memoize((ast: AST.AST): AST.AST => {
}
return AST.replaceEncoding(ast, AST.replaceLastLink(links, new AST.Link(to, last.transformation)))
}
if (AST.isUnionType(ast) && ast.annotations?.[ENSURE_ARRAY_FLAG]) {
if (AST.isUnionType(ast) && ast.annotations?.[ENSURE_ARRAY_ANNOTATION_KEY]) {
return ast
}
const out: AST.AST = (ast as any).go?.(goEnsureArray) ?? ast
@@ -258,7 +258,7 @@ export const goEnsureArray = memoize((ast: AST.AST): AST.AST => {
)
],
"anyOf",
{ [ENSURE_ARRAY_FLAG]: true }
{ [ENSURE_ARRAY_ANNOTATION_KEY]: true }
)
return out.context?.isOptional ? AST.optionalKey(ensure) : ensure
}
+5 -5
View File
@@ -143,7 +143,7 @@ export function make<T>(schema: Schema.Schema<T>): FastCheck.Arbitrary<T> {
const arbitraryMemoMap = new WeakMap<AST.AST, LazyArbitrary<any>>()
function getArbitraryAnnotation(
function getAnnotation(
annotations: Annotations.Annotations | undefined
):
| Annotation.Declaration<any, ReadonlyArray<any>>
@@ -265,16 +265,16 @@ function resetContext(ctx: Context | undefined): Context | undefined {
}
const go = memoize((ast: AST.AST): LazyArbitrary<any> => {
// ---------------------------------------------
// handle annotations
// ---------------------------------------------
if (ast.checks) {
const filters = AST.getFilters(ast.checks)
const f = mergeFiltersConstraints(filters)
const out = go(AST.replaceChecks(ast, undefined))
return (fc, ctx) => applyChecks(ast, filters, out(fc, f(ctx)))
}
const annotation = getArbitraryAnnotation(ast.annotations)
// ---------------------------------------------
// handle annotations
// ---------------------------------------------
const annotation = getAnnotation(ast.annotations)
if (annotation) {
switch (annotation._tag) {
case "Declaration": {
+4 -7
View File
@@ -49,13 +49,10 @@ export function override<S extends Schema.Top>(override: () => Equivalence.Equiv
}
}
function getEquivalenceAnnotation(
annotations: Annotations.Annotations | undefined
): Annotation.Declaration<any, ReadonlyArray<any>> | Annotation.Override<any> | undefined {
return annotations?.equivalence as any
}
const getAnnotation = Annotations.getAnnotation(getEquivalenceAnnotation)
const getAnnotation = Annotations.getAt(
"equivalence",
(u: unknown): u is Annotation.Declaration<any, ReadonlyArray<any>> | Annotation.Override<any> => Predicate.isObject(u)
)
const go = memoize((ast: AST.AST): Equivalence.Equivalence<any> => {
// ---------------------------------------------
+5 -7
View File
@@ -3,6 +3,7 @@
*/
import type { Format } from "../data/Format.ts"
import * as Option from "../data/Option.ts"
import * as Predicate from "../data/Predicate.ts"
import { memoize } from "../Function.ts"
import { format, formatPropertyKey } from "../interfaces/Inspectable.ts"
import * as Annotations from "./Annotations.ts"
@@ -42,13 +43,10 @@ export function override<S extends Schema.Top>(override: () => Format<S["Type"]>
}
}
function getFormatAnnotation(
annotations: Annotations.Annotations | undefined
): Annotation.Declaration<any, ReadonlyArray<any>> | Annotation.Override<any> | undefined {
return annotations?.format as any
}
const getAnnotation = Annotations.getAnnotation(getFormatAnnotation)
const getAnnotation = Annotations.getAt(
"format",
(u: unknown): u is Annotation.Declaration<any, ReadonlyArray<any>> | Annotation.Override<any> => Predicate.isObject(u)
)
const defaultFormat = () => format
+1 -1
View File
@@ -316,7 +316,7 @@ type GoOptions = {
}
function getId(ast: AST.AST): string | undefined {
const id = Annotations.getIdentifierAnnotation(ast)
const id = Annotations.getIdentifier(ast)
if (id !== undefined) return id
if (AST.isSuspend(ast)) {
return getId(ast.thunk())
+2 -1
View File
@@ -9,6 +9,7 @@ import * as Option from "../data/Option.ts"
import * as Effect from "../Effect.ts"
import * as Exit from "../Exit.ts"
import { memoize } from "../Function.ts"
import * as Annotations from "./Annotations.ts"
import * as AST from "./AST.ts"
import * as Issue from "./Issue.ts"
import type * as Schema from "./Schema.ts"
@@ -356,7 +357,7 @@ const go = memoize(
sroa = Effect.catchEager(sroa, (issue) => {
const issues: Array<Issue.Issue> = []
AST.collectIssues(
checks.filter((check) => check.annotations?.["~structural"]),
checks.filter((check) => check.annotations?.[Annotations.STRUCTURAL_ANNOTATION_KEY]),
ou.value,
issues,
ast,
+19 -10
View File
@@ -2,6 +2,7 @@
* @since 4.0.0
*/
import * as Option from "../../data/Option.ts"
import * as Predicate from "../../data/Predicate.ts"
import type * as Effect from "../../Effect.ts"
import { constFalse, constTrue } from "../../Function.ts"
import * as Check from "../../schema/Check.ts"
@@ -18,14 +19,14 @@ import * as RpcMiddleware from "../rpc/RpcMiddleware.ts"
/**
* @since 4.0.0
*/
export interface optionalWithDefault<S extends Schema.Top & { readonly "~type.constructor.default": "no-default" }>
export interface optionalWithDefault<S extends Schema.Top & Schema.WithoutConstructorDefault>
extends Schema.withConstructorDefault<Schema.decodeTo<Schema.typeCodec<Schema.optionalKey<S>>, Schema.optionalKey<S>>>
{}
/**
* @since 4.0.0
*/
export const optionalWithDefault = <S extends Schema.Top & { readonly "~type.constructor.default": "no-default" }>(
export const optionalWithDefault = <S extends Schema.Top & Schema.WithoutConstructorDefault>(
schema: S,
defaultValue: () => Schema.optionalKey<S>["Type"]
): optionalWithDefault<S> =>
@@ -2027,11 +2028,15 @@ export type FromClientEncoded = ClientRequestEncoded | ClientNotificationEncoded
*/
export type FromServerEncoded = ServerResultEncoded | ServerNotificationEncoded
const ParamSchemaTypeId = "~effect/ai/McpSchema/ParamSchema"
/**
* @since 4.0.0
* @category Parameters
*/
export const ParamAnnotation: unique symbol = Symbol.for("effect/ai/McpSchema/ParamNameId")
export function isParam(schema: Schema.Top): schema is Param<string, Schema.Top> {
return Predicate.hasProperty(schema, ParamSchemaTypeId)
}
/**
* @since 4.0.0
@@ -2044,7 +2049,7 @@ export interface Param<Name extends string, S extends Schema.Top> extends
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
S["~rebuild.out"],
Param<Name, S>,
S["~annotate.in"],
S["~type.make.in"],
S["Iso"],
@@ -2056,10 +2061,10 @@ export interface Param<Name extends string, S extends Schema.Top> extends
S["~encoded.optionality"]
>
{
readonly "~effect/ai/McpSchema/Param": {
readonly name: Name
readonly schema: S
}
readonly "~rebuild.out": this
readonly [ParamSchemaTypeId]: typeof ParamSchemaTypeId
readonly name: Name
readonly schema: S
}
/**
@@ -2068,5 +2073,9 @@ export interface Param<Name extends string, S extends Schema.Top> extends
* @since 4.0.0
* @category Parameters
*/
export const param = <const Id extends string, S extends Schema.Top>(id: Id, schema: S): Param<Id, S> =>
schema.annotate({ mcpServerParam: id }) as any
export function param<const Name extends string, S extends Schema.Top>(
name: Name,
schema: S
): Param<Name, S> {
return Schema.makeProto(schema.ast, { [ParamSchemaTypeId]: ParamSchemaTypeId, name, schema })
}
+6 -4
View File
@@ -9,6 +9,7 @@ import * as Exit from "../../Exit.ts"
import * as Layer from "../../Layer.ts"
import * as Queue from "../../Queue.ts"
import * as RcMap from "../../RcMap.ts"
import * as SchemaAnnotations from "../../schema/Annotations.ts"
import * as AST from "../../schema/AST.ts"
import * as Schema from "../../schema/Schema.ts"
import * as Serializer from "../../schema/Serializer.ts"
@@ -38,6 +39,7 @@ import {
GetPromptResult,
InternalError,
InvalidParams,
isParam,
ListPromptsResult,
ListResourcesResult,
ListResourceTemplatesResult,
@@ -868,8 +870,8 @@ export const registerPrompt = <
for (const [name, prop] of Object.entries(props)) {
args.push({
name,
description: prop.ast.annotations?.description as string,
required: prop.ast.context?.isOptional !== true
description: SchemaAnnotations.getDescription(prop.ast),
required: !AST.isOptional(prop.ast)
})
}
const prompt = new Prompt({
@@ -1030,8 +1032,8 @@ const compileUriTemplate = (segments: TemplateStringsArray, ...schemas: Readonly
const key = String(i)
arr.push(schema)
routerPath += `:${key}${segment.replace(":", "::")}`
const paramName = schema.ast.annotations?.mcpServerParam ?? `param${key}`
params[paramName as string] = schema
const paramName = isParam(schema) ? schema.name : `param${key}`
params[paramName] = schema
uriPath += `{${paramName}}${segment}`
}
pathSchema = Schema.Tuple(arr)
@@ -58,9 +58,7 @@ export declare namespace Snowflake {
*/
export interface SnowflakeFromBigInt
extends Schema.refine<bigint & Brand.Brand<"~effect/cluster/Snowflake">, Schema.BigInt>
{
readonly "~rebuild.out": SnowflakeFromBigInt
}
{}
/**
* @since 4.0.0
@@ -270,7 +270,7 @@ export const reflect = <Id extends string, Groups extends HttpApiGroup.Any>(
const emptyMap = new Map<never, never>()
function getDescriptionOrIdentifier(ast: AST.AST): string | undefined {
return Annotations.getDescriptionAnnotation(ast) ?? Annotations.getIdentifierAnnotation(ast)
return Annotations.getDescription(ast) ?? Annotations.getIdentifier(ast)
}
const extractMembers = (
@@ -286,14 +286,14 @@ const extractMembers = (
}>()
function process(type: Schema.Top) {
const status = getStatus(type.ast)
const isEmpty = type.ast.annotations?.httpApiIsEmpty
const isEmpty = HttpApiSchema.getHttpApiIsEmpty(type.ast)
const current = members.get(status)
members.set(
status,
{
description: current?.description ?? getDescriptionOrIdentifier(type.ast),
ast: UndefinedOr.map(current?.ast, (ast) => HttpApiSchema.UnionUnifyAST(ast, type.ast)) ??
(!isEmpty && HttpApiSchema.isVoid(type.ast) ? undefined : type.ast)
(!isEmpty && HttpApiSchema.isVoidEncoded(type.ast) ? undefined : type.ast)
}
)
}
@@ -319,7 +319,7 @@ const extractPayloads = (topAst: AST.AST): ReadonlyMap<string, {
...ast.annotations
})
const encoding = HttpApiSchema.getEncoding(ast)
const contentType = ast.annotations?.httpApiMultipart || ast.annotations?.httpApiMultipartStream
const contentType = HttpApiSchema.getHttpApiMultipart(ast) ?? HttpApiSchema.getHttpApiMultipartStream(ast)
? "multipart/form-data"
: encoding.contentType
const current = members.get(contentType)
@@ -11,7 +11,7 @@ import * as UndefinedOr from "../../data/UndefinedOr.ts"
import * as Effect from "../../Effect.ts"
import * as Encoding from "../../encoding/Encoding.ts"
import * as Fiber from "../../Fiber.ts"
import { constFalse, identity } from "../../Function.ts"
import { identity } from "../../Function.ts"
import { type Pipeable, pipeArguments } from "../../interfaces/Pipeable.ts"
import * as Layer from "../../Layer.ts"
import type { FileSystem } from "../../platform/FileSystem.ts"
@@ -441,10 +441,10 @@ const handlerToRoute = (
): HttpRouter.Route<any, any> => {
const endpoint = handler.endpoint
const isMultipartStream = endpoint.payloadSchema?.pipe(
({ ast }) => ast.annotations?.httpApiMultipartStream !== undefined
) ?? constFalse
({ ast }) => HttpApiSchema.getHttpApiMultipartStream(ast) !== undefined
) ?? false
const multipartLimits = endpoint.payloadSchema?.pipe(
({ ast }) => ast.annotations?.httpApiMultipartStream ?? ast.annotations?.httpApiMultipart
({ ast }) => HttpApiSchema.getHttpApiMultipartStream(ast) ?? HttpApiSchema.getHttpApiMultipart(ast)
)
const decodePath = UndefinedOr.map(endpoint.pathSchema, Schema.decodeUnknownEffect)
const decodePayload = handler.withFullRequest || isMultipartStream
@@ -638,7 +638,7 @@ const responseTransformation = <A, I, RD, RE>(
decode: decodeForbidden<HttpServerResponse>,
encode(data: I) {
const ast = schema.ast
const isEmpty = HttpApiSchema.isVoid(ast)
const isEmpty = HttpApiSchema.isVoidEncoded(ast)
const status = getStatus(ast)
if (isEmpty) {
return Effect.succeed(Response.empty({ status }))
@@ -20,50 +20,51 @@ declare module "../../schema/Annotations.ts" {
readonly httpApiIsEmpty?: true | undefined
readonly httpApiMultipart?: Multipart_.withLimits.Options | undefined
readonly httpApiMultipartStream?: Multipart_.withLimits.Options | undefined
readonly httpApiParam?: {
readonly name: string
readonly schema: Schema.Top
} | undefined
readonly httpApiStatus?: number | undefined
}
}
/**
* @since 4.0.0
* @category reflection
*/
export const isVoid = (ast: AST.AST): boolean => {
function isEncoding(u: unknown): u is Encoding {
return Predicate.isObject(u) // TODO: Add more checks?
}
function isMultipartWithLimitsOptions(u: unknown): u is Multipart_.withLimits.Options {
return Predicate.isObject(u) // TODO: Add more checks?
}
/** @internal */
export const getHttpApiIsEmpty = Annotations.getAt("httpApiIsEmpty", Predicate.isBoolean)
const getHttpApiEncoding = Annotations.getAt("httpApiEncoding", isEncoding)
/** @internal */
export const getHttpApiMultipart = Annotations.getAt("httpApiMultipart", isMultipartWithLimitsOptions)
/** @internal */
export const getHttpApiMultipartStream = Annotations.getAt("httpApiMultipartStream", isMultipartWithLimitsOptions)
const getHttpApiStatus = Annotations.getAt("httpApiStatus", Predicate.isNumber)
/** @internal */
export function isVoidEncoded(ast: AST.AST): boolean {
ast = AST.encodedAST(ast)
switch (ast._tag) {
case "VoidKeyword": {
case "VoidKeyword":
return true
}
case "Suspend": {
return isVoid(ast.thunk())
}
default: {
case "Suspend":
return isVoidEncoded(ast.thunk())
default:
return false
}
}
}
const getHttpApiStatusAnnotation = Annotations.getAnnotation((annotations) => {
const status = annotations?.httpApiStatus
if (Predicate.isNumber(status)) return status
})
/**
* @since 4.0.0
* @category reflection
*/
export const getStatusSuccess = (self: AST.AST): number => getHttpApiStatus(self) ?? (isVoidEncoded(self) ? 204 : 200)
/**
* @since 4.0.0
* @category reflection
*/
export const getStatusSuccess = (self: AST.AST): number =>
getHttpApiStatusAnnotation(self) ?? (isVoid(self) ? 204 : 200)
/**
* @since 4.0.0
* @category reflection
*/
export const getStatusError = (self: AST.AST): number => getHttpApiStatusAnnotation(self) ?? 500
export const getStatusError = (self: AST.AST): number => getHttpApiStatus(self) ?? 500
function isHttpApiAnnotationKey(key: string): boolean {
return key.startsWith("httpApi")
@@ -78,7 +79,7 @@ export const getHttpApiAnnotations = (self: Annotations.Annotations | undefined)
if (!self) return out
for (const [key, value] of Object.entries(self)) {
if (isHttpApiAnnotationKey(key)) {
if (isHttpApiAnnotationKey(key) && value !== undefined) {
out[key] = value
}
}
@@ -123,13 +124,13 @@ function shouldExtractUnion(ast: AST.UnionType): boolean {
if (ast.encoding) return false
if (
ast.types.some((ast) => {
const annotations = Annotations.getAnnotations(ast)
const annotations = Annotations.get(ast)
return annotations && Object.keys(annotations).some(isHttpApiAnnotationKey)
})
) {
return true
}
return Annotations.getAnnotations(ast) === undefined
return Annotations.get(ast) === undefined
}
/**
@@ -151,7 +152,7 @@ export interface Param<Name extends string, S extends Schema.Top> extends
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
S["~rebuild.out"],
Param<Name, S>,
S["~annotate.in"],
S["~type.make.in"],
S["Iso"],
@@ -163,36 +164,27 @@ export interface Param<Name extends string, S extends Schema.Top> extends
S["~encoded.optionality"]
>
{
readonly "~effect/httpapi/HttpApiSchema/Param": {
readonly name: Name
readonly schema: S
}
readonly "~rebuild.out": this
readonly name: Name
readonly schema: S
}
/**
* @since 4.0.0
* @category path params
*/
export const param: {
<Name extends string>(
name: Name
): <S extends Schema.Codec<any, string, any, any>>(
schema: S
) => Param<Name, S>
<Name extends string, S extends Schema.Codec<any, string, any, any>>(
name: Name,
schema: S
): Param<Name, S>
} = function(name: string) {
export function param<Name extends string>(
name: Name
): <S extends Schema.Top & { readonly "Encoded": string }>(schema: S) => Param<Name, S>
export function param<Name extends string, S extends Schema.Top & { readonly "Encoded": string }>(
name: Name,
schema: S
): Param<Name, S>
export function param(name: string): any {
if (arguments.length === 1) {
return (schema: Schema.Top) =>
schema.annotate({
httpApiParam: { name, schema }
})
return (schema: Schema.Top) => Schema.makeProto(schema.ast, { name, schema })
}
return arguments[1].annotate({
httpApiParam: { name, schema: arguments[1] }
})
return Schema.makeProto(arguments[1].ast, { name, schema: arguments[1] })
}
/**
@@ -290,31 +282,24 @@ export interface NoContent extends Schema.Void {
*/
export const NoContent: NoContent = Empty(204) as any
/** @internal */
export type MultipartTypeId = "~effect/httpapi/HttpApiSchema/Multipart"
/**
* @since 4.0.0
* @category multipart
*/
export const MultipartTypeId = "~effect/httpapi/HttpApiSchema/Multipart"
/**
* @since 4.0.0
* @category multipart
*/
export interface Multipart<S extends Schema.Top> extends
Schema.Bottom<
S["Type"] & Brand<MultipartTypeId>,
S["Encoded"],
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
S["~rebuild.out"],
S["~annotate.in"],
S["~type.make.in"],
S["Iso"],
S["~type.make"],
S["~type.mutability"],
S["~type.optionality"],
S["~type.constructor.default"],
S["~encoded.mutability"],
S["~encoded.optionality"]
>
export type MultipartTypeId = typeof MultipartTypeId
/**
* @since 4.0.0
* @category multipart
*/
export interface Multipart<S extends Schema.Top>
extends Schema.refine<S["Type"] & Brand<"~effect/httpapi/HttpApiSchema/Multipart">, S["~rebuild.out"]>
{}
/**
@@ -328,35 +313,28 @@ export const Multipart = <S extends Schema.Top>(self: S, options?: {
readonly maxTotalSize?: FileSystem.SizeInput | undefined
readonly fieldMimeTypes?: ReadonlyArray<string> | undefined
}): Multipart<S> =>
self.annotate({
self.pipe(Schema.brand(MultipartTypeId, {
httpApiMultipart: options ?? {}
}) as Multipart<S>
/** @internal */
export type MultipartStreamTypeId = "~effect/httpapi/HttpApiSchema/MultipartStream"
}))
/**
* @since 4.0.0
* @category multipart
*/
export interface MultipartStream<S extends Schema.Top> extends
Schema.Bottom<
S["Type"] & Brand<MultipartStreamTypeId>,
S["Encoded"],
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
S["~rebuild.out"],
S["~annotate.in"],
S["~type.make.in"],
S["Iso"],
S["~type.make"],
S["~type.mutability"],
S["~type.optionality"],
S["~type.constructor.default"],
S["~encoded.mutability"],
S["~encoded.optionality"]
>
export const MultipartStreamTypeId = "~effect/httpapi/HttpApiSchema/MultipartStream"
/**
* @since 4.0.0
* @category multipart
*/
export type MultipartStreamTypeId = typeof MultipartStreamTypeId
/**
* @since 4.0.0
* @category multipart
*/
export interface MultipartStream<S extends Schema.Top>
extends Schema.refine<S["Type"] & Brand<"~effect/httpapi/HttpApiSchema/MultipartStream">, S["~rebuild.out"]>
{}
/**
@@ -370,9 +348,9 @@ export const MultipartStream = <S extends Schema.Top>(self: S, options?: {
readonly maxTotalSize?: FileSystem.SizeInput | undefined
readonly fieldMimeTypes?: ReadonlyArray<string> | undefined
}): MultipartStream<S> =>
self.annotate({
self.pipe(Schema.brand(MultipartStreamTypeId, {
httpApiMultipartStream: options ?? {}
}) as MultipartStream<S>
}))
/**
* @since 4.0.0
@@ -467,8 +445,9 @@ const encodingJson: Encoding = {
* @since 4.0.0
* @category annotations
*/
export const getEncoding = (ast: AST.AST, fallback = encodingJson): Encoding =>
ast.annotations?.httpApiEncoding ?? fallback
export function getEncoding(ast: AST.AST, fallback = encodingJson): Encoding {
return getHttpApiEncoding(ast) ?? fallback
}
/**
* @since 4.0.0
@@ -538,7 +517,7 @@ export interface EmptyErrorClass<Self, Tag> extends
never,
never,
AST.Declaration,
EmptyErrorClass<Self, Tag>,
EmptyErrorClass<Self, Tag>, // TODO: Fix this
Annotations.Annotations
>
{
@@ -323,7 +323,7 @@ export const fromApi = <Id extends string, Groups extends HttpApiGroup.Any>(
op.responses[status] = {
description: description ?? defaultDescription()
}
if (ast && !ast.annotations?.httpApiIsEmpty) {
if (ast && !HttpApiSchema.getHttpApiIsEmpty(ast)) {
const encoding = HttpApiSchema.getEncoding(ast)
op.responses[status].content = {
[encoding.contentType]: {
+2 -5
View File
@@ -728,10 +728,7 @@ export const make = <
_tag: tag,
payloadSchema,
successSchema: options?.stream ?
RpcSchema.Stream({
success: successSchema,
error: errorSchema
}) :
RpcSchema.Stream(successSchema, errorSchema) :
successSchema,
errorSchema: options?.stream ? Schema.Never : errorSchema,
annotations: ServiceMap.empty(),
@@ -757,7 +754,7 @@ export const exitSchema = <R extends Any>(
}
const rpc = self as any as AnyWithProps
const failures = new Set<Schema.Top>([rpc.errorSchema])
const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema.ast)
const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema)
if (streamSchemas) {
failures.add(streamSchemas.error)
}
@@ -772,7 +772,7 @@ const rpcSchemas = (rpc: Rpc.AnyWithProps) => {
if (rpcSchemasCache.has(rpc)) {
return rpcSchemasCache.get(rpc)!
}
const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema.ast)
const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema)
const entry: RpcSchemas = {
decodeChunk: streamSchemas ?
Schema.decodeUnknownEffect(Serializer.json(Schema.NonEmptyArray(streamSchemas.success))) :
+22 -29
View File
@@ -1,35 +1,33 @@
/**
* @since 4.0.0
*/
import type { Annotations } from "../../schema/Annotations.ts"
import * as Predicate from "../../data/Predicate.ts"
import type * as Annotations from "../../schema/Annotations.ts"
import type * as AST from "../../schema/AST.ts"
import * as Schema from "../../schema/Schema.ts"
import * as Stream_ from "../../stream/Stream.ts"
/**
* @since 4.0.0
* @category Stream
*/
export const StreamSchemaTypeId = "~effect/rpc/RpcSchema/StreamSchema"
const StreamSchemaTypeId = "~effect/rpc/RpcSchema/StreamSchema"
/**
* @since 4.0.0
* @category Stream
*/
export const isStreamSchema = (schema: Schema.Top): schema is Stream<any, any> =>
schema.ast.annotations !== undefined && StreamSchemaTypeId in schema.ast.annotations
export function isStreamSchema(schema: Schema.Top): schema is Stream<Schema.Top, Schema.Top> {
return Predicate.hasProperty(schema, StreamSchemaTypeId)
}
/**
* @since 4.0.0
* @category Stream
*/
export function getStreamSchemas(
ast: AST.AST
): {
/** @internal */
export function getStreamSchemas(schema: Schema.Top): {
readonly success: Schema.Top
readonly error: Schema.Top
} | undefined {
return ast.annotations?.[StreamSchemaTypeId] as any
return isStreamSchema(schema) ?
{
success: schema.success,
error: schema.error
} :
undefined
}
/**
@@ -42,28 +40,23 @@ export interface Stream<A extends Schema.Top, E extends Schema.Top> extends
Stream_.Stream<A["Encoded"], E["Encoded"]>,
A["DecodingServices"] | E["DecodingServices"],
A["EncodingServices"] | E["EncodingServices"],
AST.AST,
AST.Declaration,
Stream<A, E>,
Annotations
Annotations.Declaration<Stream<A, E>, readonly []>
>
{
readonly "~rebuild.out": this
readonly [StreamSchemaTypeId]: typeof StreamSchemaTypeId
readonly success: A
readonly error: E
}
const schema = Schema.declare(Stream_.isStream)
/**
* @since 4.0.0
* @category Stream
*/
export const Stream = <A extends Schema.Top, E extends Schema.Top>(
options: {
readonly error: E
readonly success: A
}
): Stream<A, E> => {
const schema = Schema.declare(Stream_.isStream, { [StreamSchemaTypeId]: options })
return Object.assign(
schema,
options
) as any as Stream<A, E>
export function Stream<A extends Schema.Top, E extends Schema.Top>(success: A, error: E): Stream<A, E> {
return Schema.makeProto(schema.ast, { [StreamSchemaTypeId]: StreamSchemaTypeId, success, error })
}
@@ -492,7 +492,7 @@ export const make: <Rpcs extends Rpc.Any>(
let schemas = schemasCache.get(rpc)
if (!schemas) {
const entry = services.mapUnsafe.get(rpc.key) as Rpc.Handler<Rpcs["_tag"]>
const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema.ast)
const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema)
schemas = {
decode: Schema.decodeUnknownEffect(Serializer.json(rpc.payloadSchema as any)),
encodeChunk: Schema.encodeUnknownEffect(
@@ -217,7 +217,7 @@ export interface Class<
S["DecodingServices"],
S["EncodingServices"],
AST.Declaration,
Class<Self, Fields, S>,
Schema.decodeTo<Schema.declareConstructor<Self, S["Encoded"], readonly [S], S["Iso"]>, S>,
Annotations.Declaration<Self, readonly [S]>,
S["~type.make.in"],
S["Iso"],
@@ -460,35 +460,23 @@ export const Override = <A>(value: A): A & Brand<"Override"> => value as any
* @since 4.0.0
* @category overrideable
*/
export interface Overrideable<S extends Schema.Top> extends
Schema.Bottom<
S["Type"] & Brand<"Override">,
S["Encoded"],
S["DecodingServices"],
S["EncodingServices"],
S["ast"],
Overrideable<S>,
Annotations.Bottom<S["Type"] & Brand<"Override">>,
S["~type.make.in"] & Brand<"Override"> | undefined,
S["Iso"] & Brand<"Override">,
S["Type"] & Brand<"Override"> | undefined,
S["~type.mutability"],
S["~type.optionality"],
"with-default",
S["~encoded.mutability"],
S["~encoded.optionality"]
>
export interface Overrideable<S extends Schema.Top & Schema.WithoutConstructorDefault>
extends Schema.refine<S["Type"] & Brand<"Override">, Schema.withConstructorDefault<S>>
{}
/**
* @since 4.0.0
* @category overrideable
*/
export const Overrideable = <S extends Schema.Top>(schema: S, options: {
readonly defaultValue: Effect.Effect<S["~type.make.in"]>
}): Overrideable<S> =>
(schema as any).pipe(
Schema.withConstructorDefault(constant(Effect.asSome(options.defaultValue)))
export const Overrideable = <S extends Schema.Top & Schema.WithoutConstructorDefault>(
schema: S,
options: {
readonly defaultValue: Effect.Effect<S["~type.make.in"]>
}
) =>
schema.pipe(
Schema.withConstructorDefault(constant(Effect.asSome(options.defaultValue))),
Schema.brand("Override")
)
const StructProto = {
@@ -135,10 +135,7 @@ export class PrimaryKeyTest extends Rpc.make("PrimaryKeyTest", {
}) {}
export class StreamRpc extends Rpc.make("StreamTest", {
success: RpcSchema.Stream({
success: Schema.Void,
error: Schema.Never
}),
success: RpcSchema.Stream(Schema.Void, Schema.Never),
payload: {
id: Schema.Number
},
+1 -4
View File
@@ -12,10 +12,7 @@ export class User extends Schema.Class<User>("User")({
}) {}
export class StreamWithKey extends Rpc.make("StreamWithKey", {
success: RpcSchema.Stream({
success: Schema.Number,
error: Schema.Never
}),
success: RpcSchema.Stream(Schema.Number, Schema.Never),
payload: { key: Schema.String },
primaryKey: ({ key }) => key
}) {}
@@ -70,6 +70,12 @@ describe("Schema", () => {
)
})
it("should expose the literal", () => {
const schema = Schema.Literal("a")
strictEqual(schema.literal, "a")
strictEqual(schema.annotate({}).literal, "a")
})
it(`"a"`, async () => {
const schema = Schema.Literal("a")
@@ -780,6 +786,7 @@ Unexpected key
it("should expose the item schema", () => {
const schema = Schema.Array(Schema.String)
strictEqual(schema.schema, Schema.String)
strictEqual(schema.annotate({}).schema, Schema.String)
})
it("readonly string[]", async () => {