/** * Define data shapes, validate unknown input, and transform values between formats. * * ## Mental model * * - **Schema** — a description of a data shape. Every schema carries a decoded * *Type* (the value you work with) and an *Encoded* representation (the * serialized form, e.g. JSON). * - **Decoding** — turning unknown external data (API responses, form * submissions, config files) into typed, validated values. * - **Encoding** — turning typed values back into a serializable format. * - **Codec** — a schema that tracks both Type and Encoded, so it can decode * *and* encode. Most concrete schemas are Codecs. * - **Check / Filter** — a constraint attached to a schema (e.g. `isMinLength`, * `isGreaterThan`). Attach them with `.check(...)`. * - **Transformation** — a pair of functions (decode + encode) that convert * values between two schemas. Created with {@link decodeTo} / {@link encodeTo}. * - **Annotation** — metadata attached to a schema (title, description, custom * keys). Attach with `.annotate(...)`. * * ## Common tasks * * - Define a struct: {@link Struct} * - Define a union: {@link Union}, {@link TaggedUnion}, {@link Literals} * - Define an array: {@link ArraySchema}, {@link NonEmptyArray} * - Define a record: {@link Record} * - Define a tuple: {@link Tuple}, {@link TupleWithRest} * - Validate unknown data synchronously: {@link decodeUnknownSync} * - Validate unknown data (Effect): {@link decodeUnknownEffect} * - Encode a value: {@link encodeUnknownSync}, {@link encodeUnknownEffect} * - Type guard: {@link is} * - Assertion: {@link asserts} * - Add constraints: `.check(...)` with filters like {@link isMinLength}, * {@link isGreaterThan}, {@link isPattern}, {@link isUUID} * - Transform between schemas: {@link decodeTo}, {@link encodeTo} * - Add a default for missing keys: {@link withDecodingDefault}, {@link withDecodingDefaultKey} * - Create branded types: {@link brand} * - Define classes with validation: {@link Class}, {@link TaggedClass} * - Define error classes: {@link ErrorClass}, {@link TaggedErrorClass} * - Generate JSON Schema: {@link toJsonSchemaDocument} * - Generate test data: {@link toArbitrary} * - Derive equivalence: {@link toEquivalence} * * ## Gotchas * * - `Schema.optional` creates `T | undefined` (key can be missing *or* * `undefined`). Use `Schema.optionalKey` for exact optional properties. * - `decodeTo` is curried: use `from.pipe(Schema.decodeTo(to, ...))`. * - `decodeUnknownSync` throws on failure. Use `decodeUnknownExit` or * `decodeUnknownOption` for non-throwing alternatives. * - Filters do not change the TypeScript type. Use {@link refine} or * {@link brand} to narrow the type. * - Recursive schemas require {@link suspend} to avoid infinite loops. * * ## Quickstart * * **Example** (Validate a user object) * * ```ts * import { Schema } from "effect" * * const User = Schema.Struct({ * name: Schema.String.check(Schema.isMinLength(1)), * age: Schema.Number.check(Schema.isGreaterThanOrEqualTo(0)), * email: Schema.optionalKey(Schema.String) * }) * * // Decode unknown input — throws on failure * const user = Schema.decodeUnknownSync(User)({ * name: "Alice", * age: 30 * }) * * console.log(user) * // { name: "Alice", age: 30 } * ``` * * @see {@link Schema} — type-level view tracking only the decoded Type * @see {@link Codec} — type-level view tracking both Type and Encoded * @see {@link Struct} — define object shapes * @see {@link decodeUnknownSync} — synchronous validation * @see {@link decodeTo} — schema transformations * * @since 4.0.0 */ /** @effect-diagnostics schemaStructWithTag:skip-file */ import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec"; import * as BigDecimal_ from "./BigDecimal.ts"; import type * as Brand from "./Brand.ts"; import * as Cause_ from "./Cause.ts"; import * as Chunk_ from "./Chunk.ts"; import type * as Combiner from "./Combiner.ts"; import * as DateTime from "./DateTime.ts"; import type { Differ } from "./Differ.ts"; import * as Duration_ from "./Duration.ts"; import * as Effect from "./Effect.ts"; import * as Equivalence from "./Equivalence.ts"; import * as Exit_ from "./Exit.ts"; import type { Formatter } from "./Formatter.ts"; import * as HashMap_ from "./HashMap.ts"; import * as HashSet_ from "./HashSet.ts"; import { SchemaError } from "./internal/schema/schema.ts"; import * as JsonPatch from "./JsonPatch.ts"; import * as JsonSchema from "./JsonSchema.ts"; import * as Optic_ from "./Optic.ts"; import * as Option_ from "./Option.ts"; import * as Order from "./Order.ts"; import * as Pipeable from "./Pipeable.ts"; import * as Redacted_ from "./Redacted.ts"; import * as Result_ from "./Result.ts"; import * as AST from "./SchemaAST.ts"; import * as Getter from "./SchemaGetter.ts"; import * as Issue from "./SchemaIssue.ts"; import * as Parser from "./SchemaParser.ts"; import type * as SchemaRepresentation from "./SchemaRepresentation.ts"; import type { Assign, Lambda, Mutable, Simplify } from "./Struct.ts"; import * as Struct_ from "./Struct.ts"; import * as FastCheck from "./testing/FastCheck.ts"; import type { RequiredKeys, UnionToIntersection } from "./Types.ts"; import type { Unify } from "./Unify.ts"; declare const TypeId = "~effect/Schema/Schema"; /** * Whether a schema field is required or optional within a struct. * * @see {@link optionalKey} — mark a struct field as optional * @see {@link optional} — mark a struct field as optional with `| undefined` * * @since 4.0.0 */ export type Optionality = "required" | "optional"; /** * Whether a schema field is readonly or mutable within a struct. * * @see {@link mutableKey} — mark a struct field as mutable * * @since 4.0.0 */ export type Mutability = "readonly" | "mutable"; /** * Whether a schema field has a constructor default value. * * @see {@link withConstructorDefault} — add a default to a schema field * @see {@link tag} — creates a literal field with a constructor default * * @since 4.0.0 */ export type ConstructorDefault = "no-default" | "with-default"; /** * Options for `makeEffect`, `make`, and Class constructors. * * When to use: * - Pass `disableChecks: true` to skip validation when you trust the data. * - Pass `parseOptions` to control error reporting behavior. * * @see {@link Bottom.makeEffect} * @see {@link Bottom.make} * * @since 4.0.0 */ export interface MakeOptions { /** * The parse options to use for the schema. */ readonly parseOptions?: AST.ParseOptions | undefined; /** * Whether to disable validation for the schema. */ readonly disableChecks?: boolean | undefined; } /** * The fully-parameterized base interface for all schemas. Exposes all 14 type * parameters controlling type inference, mutability, optionality, services, * and transformation behavior. * * When to use: * - You are writing advanced generic schema utilities or performing schema * introspection. * - In user code, prefer {@link Schema}, {@link Codec}, {@link Decoder}, or * {@link Encoder} instead. * * @see {@link Top} — the existential "any schema" type (erased type params) * @see {@link Schema} — tracks only the decoded Type * @see {@link Codec} — tracks Type + Encoded * * @since 4.0.0 */ export interface Bottom = readonly [], out TypeMake = TypeMakeIn, out TypeMutability extends Mutability = "readonly", out TypeOptionality extends Optionality = "required", out TypeConstructorDefault extends ConstructorDefault = "no-default", out EncodedMutability extends Mutability = "readonly", out EncodedOptionality extends Optionality = "required"> extends Pipeable.Pipeable { readonly [TypeId]: typeof TypeId; readonly "ast": Ast; readonly "Rebuild": Rebuild; readonly "~type.parameters": TypeParameters; readonly "Type": T; readonly "Encoded": E; readonly "DecodingServices": RD; readonly "EncodingServices": RE; readonly "~type.make.in": TypeMakeIn; readonly "~type.make": TypeMake; readonly "~type.constructor.default": TypeConstructorDefault; readonly "Iso": Iso; readonly "~type.mutability": TypeMutability; readonly "~type.optionality": TypeOptionality; readonly "~encoded.mutability": EncodedMutability; readonly "~encoded.optionality": EncodedOptionality; annotate(annotations: Annotations.Bottom): this["Rebuild"]; annotateKey(annotations: Annotations.Key): this["Rebuild"]; check(...checks: readonly [AST.Check, ...Array>]): this["Rebuild"]; rebuild(ast: this["ast"]): this["Rebuild"]; /** * @throws {Error} The issue is contained in the error cause. */ make(input: this["~type.make.in"], options?: MakeOptions): this["Type"]; makeOption(input: this["~type.make.in"], options?: MakeOptions): Option_.Option; makeEffect(input: this["~type.make.in"], options?: MakeOptions): Effect.Effect; } /** * The schema type returned by {@link declareConstructor}, tracking the decoded * type `T`, the encoded type `E`, and the list of type-parameter schemas * `TypeParameters`. * * @category Constructors * @since 4.0.0 */ export interface declareConstructor, Iso = T> extends Bottom, T, Iso, TypeParameters> { } /** * Creates a schema for a **parametric** type (a generic container such as * `Array`, `Option`, etc.) by accepting a list of type-parameter schemas * and a decoder factory. * * The outer call `declareConstructor()` fixes the decoded type `T`, * the encoded type `E`, and the optional iso type. The inner call receives: * - `typeParameters` — the concrete schemas for each type variable * - `run` — a factory that, given resolved codecs for each type parameter, * returns a parsing function `(u, ast, options) => Effect` * - `annotations` — optional metadata * * @see {@link declare} for creating schemas for non-parametric types. * * **Example** (Schema for a parametric `Box` type) * * ```ts * import { Effect, Schema } from "effect" * import * as SchemaParser from "effect/SchemaParser" * import * as Issue from "effect/SchemaIssue" * import * as Option from "effect/Option" * * interface Box { * readonly value: A * } * * const isBox = (u: unknown): u is Box => * typeof u === "object" && u !== null && "value" in u * * const Box = (item: A) => * Schema.declareConstructor, Box>()( * [item], * ([itemCodec]) => * (u, ast, options) => { * if (!isBox(u)) { * return Effect.fail(new Issue.InvalidType(ast, Option.some(u))) * } * return Effect.map( * SchemaParser.decodeUnknownEffect(itemCodec)(u.value, options), * (value) => ({ value }) * ) * } * ) * * const schema = Box(Schema.Number) * ``` * * @category Constructors * @since 4.0.0 */ export declare function declareConstructor(): >(typeParameters: TypeParameters, run: (typeParameters: { readonly [K in keyof TypeParameters]: Codec; }) => (u: unknown, self: AST.Declaration, options: AST.ParseOptions) => Effect.Effect, annotations?: Annotations.Declaration) => declareConstructor; /** * The schema type returned by {@link declare}, representing a non-parametric * opaque type `T` with no type parameters. * * @category Constructors * @since 4.0.0 */ export interface declare extends declareConstructor { readonly "Rebuild": declare; } /** * Creates a schema for a **non-parametric** opaque type using a type-guard * function. The schema accepts any unknown value and succeeds when `is` returns * `true`, failing with an `InvalidType` issue otherwise. * * Use this when the type has no type parameters. For parametric types such as * `Option` or `Array`, use {@link declareConstructor} instead. * * **Example** (Schema for a custom `UserId` branded type) * * ```ts * import { Schema } from "effect" * * type UserId = string & { readonly _tag: "UserId" } * * const isUserId = (u: unknown): u is UserId => * typeof u === "string" && u.startsWith("user_") * * const UserId = Schema.declare(isUserId, { * title: "UserId", * description: "A user identifier starting with 'user_'" * }) * ``` * * @see {@link declareConstructor} for creating schemas for parametric types. * * @category Constructors * @since 4.0.0 */ export declare function declare(is: (u: unknown) => u is T, annotations?: Annotations.Declaration | undefined): declare; /** * Widens a schema's type to the fully-parameterized {@link Bottom} interface, * making all 14 type parameters visible to TypeScript. * * Normally, concrete schema interfaces (e.g. `Schema`) hide most type * parameters. `revealBottom` is useful when writing generic utilities that need * to inspect or propagate the complete set of type parameters. * * **Example** (Inspecting all type parameters of a schema) * * ```ts * import { Schema } from "effect" * * const schema = Schema.String * * // Widen to Bottom to access all 14 type parameters * const bottom = Schema.revealBottom(schema) * * // `bottom` now exposes Type, Encoded, DecodingServices, EncodingServices, * // ast, Rebuild, ~type.make.in, Iso, ~type.parameters, etc. * type T = typeof bottom["Type"] // string * type E = typeof bottom["Encoded"] // string * ``` * * @since 4.0.0 */ export declare function revealBottom(bottom: S): Bottom; /** * Adds metadata annotations to a schema without changing its runtime behavior. * This is the pipeable (curried) counterpart of the `.annotate` method. * * Annotations provide extra context used by documentation generators, JSON * Schema converters, error formatters, and other tooling. Common keys include * `title`, `description`, `examples`, `message`, and `identifier`. * * **Example** (Adding a title and description) * * ```ts * import { Schema } from "effect" * * const Age = Schema.Number.pipe( * Schema.annotate({ * title: "Age", * description: "A non-negative integer representing age in years" * }) * ) * ``` * * @see {@link annotateEncoded} to annotate the encoded side instead. * * @category Annotations * @since 4.0.0 */ export declare function annotate(annotations: Annotations.Bottom): (self: S) => S["Rebuild"]; /** * Adds metadata annotations to the **encoded** side of a schema without * changing its runtime behavior. This is the encoded-side counterpart of * `annotate`, which targets the decoded (Type) side. * * Internally the schema is flipped so that `Encoded` becomes `Type`, * annotated, and then flipped back. * * **Example** (Adding a title to the encoded representation) * * ```ts * import { Schema } from "effect" * * const schema = Schema.NumberFromString.pipe( * Schema.annotateEncoded({ * title: "my title" * }) * ) * * console.log(Schema.toEncoded(schema).ast.annotations?.title) * // "my title" * ``` * * @see {@link annotate} to annotate the type side instead. * * @category Annotations * @since 4.0.0 */ export declare function annotateEncoded(annotations: Annotations.Bottom): (self: S) => S["Rebuild"]; /** * Adds key-level annotations to a schema field. This is the pipeable * (curried) counterpart of the `.annotateKey` method. * * Key annotations apply to a field's position inside a `Struct` or `Tuple` * rather than to the field's value type. They can carry a * `messageMissingKey` to customise the error shown when the field is absent, * as well as standard documentation fields such as `title`, `description`, * and `examples`. * * **Example** (Custom missing-key message for a required field) * * ```ts * import { Schema } from "effect" * * const schema = Schema.Struct({ * username: Schema.String.pipe( * Schema.annotateKey({ * description: "The username used to log in", * messageMissingKey: "Username is required" * }) * ) * }) * ``` * * @category Annotations * @since 4.0.0 */ export declare function annotateKey(annotations: Annotations.Key): (self: S) => S["Rebuild"]; /** * The existential "any schema" type — all type parameters are erased to `unknown`. * * Use `Top` as a constraint when writing generic utilities that must accept *any* * schema regardless of its `Type`, `Encoded`, or service requirements. It is the * widest possible schema type and therefore gives you the least static information. * * In user code prefer the narrower interfaces: * - {@link Schema}`` — when you only care about the decoded type * - {@link Codec}`` — when you need the encoded type and service requirements * - {@link Decoder}`` — for decode-only APIs * - {@link Encoder}`` — for encode-only APIs * * @since 4.0.0 */ export interface Top extends Bottom { } /** * Namespace of type-level helpers for {@link Schema}. * * @since 4.0.0 */ export declare namespace Schema { /** * Extracts the decoded `Type` from a schema. * * **Example** (Extracting the decoded type) * * ```ts * import { Schema } from "effect" * * const Person = Schema.Struct({ name: Schema.String, age: Schema.Number }) * type Person = Schema.Schema.Type * // { readonly name: string; readonly age: number } * ``` * * @since 4.0.0 */ type Type = S extends Top ? S["Type"] : never; } /** * A typed view of a schema that tracks only the decoded (output) type `T`. * * Use `Schema` as a constraint when you want to accept "any schema that * decodes to `T`" and do not need to know or constrain the encoded * representation, required services, or any other type parameters. * * This is a structural interface — concrete schema values are produced by the * constructors in this module (e.g. {@link Struct}, {@link String}, {@link Number}). * When you also need the encoded type or service requirements, use {@link Codec}. * * **Example** (Function that accepts any schema decoding to `string`) * * ```ts * import { Schema } from "effect" * * declare function print(schema: Schema.Schema): void * * print(Schema.String) // ok * print(Schema.NonEmptyString) // ok * ``` * * @see {@link Codec} — also tracks Encoded, DecodingServices, EncodingServices * @see {@link Schema.Type} — extract the decoded type at the type level * * @since 4.0.0 */ export interface Schema extends Top { readonly "Type": T; readonly "Rebuild": Schema; } /** * Namespace of type-level helpers for {@link Codec}. * * @since 4.0.0 */ export declare namespace Codec { /** * Extracts the encoded (`Encoded`) type from a schema. * * **Example** (Extracting the encoded type) * * ```ts * import { Schema } from "effect" * * const schema = Schema.NumberFromString * type Enc = Schema.Codec.Encoded * // string * ``` * * @since 4.0.0 */ type Encoded = S extends Top ? S["Encoded"] : never; /** * Extracts the Effect services required during *decoding* from a schema. * * **Example** (Checking decoding service requirements) * * ```ts * import { Schema } from "effect" * * const schema = Schema.String * type RD = Schema.Codec.DecodingServices * // never * ``` * * @since 4.0.0 */ type DecodingServices = S extends Top ? S["DecodingServices"] : never; /** * Extracts the Effect services required during *encoding* from a schema. * * **Example** (Checking encoding service requirements) * * ```ts * import { Schema } from "effect" * * const schema = Schema.String * type RE = Schema.Codec.EncodingServices * // never * ``` * * @since 4.0.0 */ type EncodingServices = S extends Top ? S["EncodingServices"] : never; /** * Converts a schema type into an assertion function signature. The resulting * function narrows its argument to `I & S["Type"]`. Only schemas with * `DecodingServices: never` (i.e. no required services) can be used here. * * Produced by {@link asserts}. * * @since 4.0.0 */ type ToAsserts = (input: I) => asserts input is I & S["Type"]; } /** * A schema that additionally supports optic (lens/prism) operations. * * `Optic` extends {@link Schema}`` with an `Iso` type that * describes the isomorphic counterpart used by the optic layer. Crucially, * decoding and encoding require *no* Effect services (`DecodingServices` and * `EncodingServices` are both `never`), which means the optic can operate * purely without an Effect runtime. * * Most primitive schemas (e.g. `Schema.String`, `Schema.Number`) implement * `Optic` automatically. You normally interact with this interface through * {@link Optic_} utilities rather than constructing it directly. * * @since 4.0.0 */ export interface Optic extends Schema { readonly "Iso": Iso; readonly "DecodingServices": never; readonly "EncodingServices": never; readonly "Rebuild": Optic; } /** * A schema that tracks the decoded type `T`, the encoded type `E`, and the * Effect services required during decoding (`RD`) and encoding (`RE`). * * Use `Codec` when you need to preserve full type information * about a schema — both what it decodes to and what it serializes from/to. * Most concrete schemas produced by this module implement `Codec`. * * For APIs that only need one direction, prefer the narrower views: * - {@link Decoder}`` — decode-only * - {@link Encoder}`` — encode-only * - {@link Schema}`` — type-only (no encoded representation) * * **Example** (Accepting a codec that decodes to `number` from `string`) * * ```ts * import { Schema } from "effect" * * declare function serialize(codec: Schema.Codec): string * * serialize(Schema.NumberFromString) // ok — decodes number, encoded as string * ``` * * @see {@link Codec.Encoded} — extract the encoded type * @see {@link Codec.DecodingServices} — extract required decoding services * @see {@link Codec.EncodingServices} — extract required encoding services * @see {@link revealCodec} — helper to make TypeScript infer the full Codec type * * @since 4.0.0 */ export interface Codec extends Schema { readonly "Encoded": E; readonly "DecodingServices": RD; readonly "EncodingServices": RE; readonly "Rebuild": Codec; } /** * A {@link Codec} view for APIs that only *decode* (parse/validate) values. * * Use `Decoder` to accept "any schema that can decode to `T`" without * constraining or depending on the encoded representation (`Encoded` is * `unknown`) or encoding services. * * **Example** (Function that only needs to decode) * * ```ts * import { Schema } from "effect" * * declare function validate(decoder: Schema.Decoder): (input: unknown) => T * * validate(Schema.String) // ok * validate(Schema.NumberFromString) // ok * ``` * * @since 4.0.0 */ export interface Decoder extends Codec { readonly "Rebuild": Decoder; } /** * A {@link Codec} view for APIs that only *encode* values. * * Use `Encoder` to accept "any schema that can encode to `E`" without * constraining or depending on the decoded `Type` (`Type` is `unknown`) or * decoding services. * * **Example** (Function that only needs to encode) * * ```ts * import { Schema } from "effect" * * declare function serialize(encoder: Schema.Encoder): (value: unknown) => E * * serialize(Schema.String) // ok — encodes to string * serialize(Schema.NumberFromString) // ok — encodes number to string * ``` * * @since 4.0.0 */ export interface Encoder extends Codec { readonly "Rebuild": Encoder; } /** * Identity function that widens a value to the full {@link Codec} interface, * prompting TypeScript to infer all four type parameters (`T`, `E`, `RD`, `RE`). * * When a schema is stored in a variable typed as `Schema` or `Top`, the * encoded type and service requirements are erased. Passing the value through * `revealCodec` recovers those parameters without any runtime cost. * * **Example** (Recovering encoded type from a schema variable) * * ```ts * import { Schema } from "effect" * * const schema: Schema.Schema = Schema.NumberFromString * * // Without revealCodec, Encoded is unknown * const codec = Schema.revealCodec(schema) * type Enc = typeof codec["Encoded"] // string * ``` * * @since 4.0.0 */ export declare function revealCodec(codec: Codec): Codec; export { /** * Error thrown (or returned as the error channel value) when schema decoding * or encoding fails. * * The `issue` field contains a structured {@link Issue.Issue} tree describing * every validation failure, including the path to the problematic value, * expected types, and actual values received. `message` renders the issue tree * as a human-readable string. * * Use {@link isSchemaError} to narrow an unknown value to `SchemaError`. * * **Example** (Catching a SchemaError) * * ```ts * import { Schema } from "effect" * * try { * Schema.decodeUnknownSync(Schema.Number)("not a number") * } catch (err) { * if (Schema.isSchemaError(err)) { * console.log(err.message) * // Expected number, actual "not a number" * } * } * ``` * * @since 4.0.0 */ SchemaError }; /** * Returns `true` if `u` is a {@link SchemaError}. * * **Example** (Type guard in a catch block) * * ```ts * import { Schema } from "effect" * * try { * Schema.decodeUnknownSync(Schema.Number)("oops") * } catch (err) { * if (Schema.isSchemaError(err)) { * console.log(err._tag) // "SchemaError" * } * } * ``` * * @since 4.0.0 */ export declare function isSchemaError(u: unknown): u is SchemaError; /** * Returns a "Standard Schema" object conforming to the [Standard Schema * v1](https://standardschema.dev/) specification. * * This function creates a schema whose `validate` method attempts to decode and * validate the provided input synchronously. If the underlying `Schema` * includes any asynchronous components (e.g., asynchronous message resolutions * or checks), then validation will necessarily return a `Promise` instead. * * **Example** (Creating a standard schema from a regular schema) * * ```ts * import { Schema } from "effect" * * // Define custom hook functions for error formatting * const leafHook = (issue: any) => { * switch (issue._tag) { * case "InvalidType": * return "Expected different type" * case "InvalidValue": * return "Invalid value provided" * case "MissingKey": * return "Required property missing" * case "UnexpectedKey": * return "Unexpected property found" * case "Forbidden": * return "Operation not allowed" * case "OneOf": * return "Multiple valid options available" * default: * return "Validation error" * } * } * * // Create a standard schema from a regular schema * const PersonSchema = Schema.Struct({ * name: Schema.NonEmptyString, * age: Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 150 })) * }) * * const standardSchema = Schema.toStandardSchemaV1(PersonSchema, { * leafHook * }) * * // The standard schema can be used with any Standard Schema v1 compatible library * const validResult = standardSchema["~standard"].validate({ * name: "Alice", * age: 30 * }) * console.log(validResult) // { value: { name: "Alice", age: 30 } } * * const invalidResult = standardSchema["~standard"].validate({ * name: "", * age: 200 * }) * console.log(invalidResult) // { issues: [{ path: ["name"], message: "..." }, { path: ["age"], message: "..." }] } * ``` * * @category Standard Schema * @since 4.0.0 */ export declare function toStandardSchemaV1>(self: S, options?: { readonly leafHook?: Issue.LeafHook | undefined; readonly checkHook?: Issue.CheckHook | undefined; readonly parseOptions?: AST.ParseOptions | undefined; }): StandardSchemaV1 & S; /** * Experimental support for converting a schema to a Standard JSON Schema V1. * * https://github.com/standard-schema/standard-schema/pull/134 * * @category Standard Schema * @since 4.0.0 * @experimental */ export declare function toStandardJSONSchemaV1(self: S): StandardJSONSchemaV1 & S; /** * Creates a type guard function that checks if a value conforms to a given * schema. * * This function returns a predicate that performs a type-safe check, narrowing * the type of the input value if the check passes. It's particularly useful for * runtime type validation and TypeScript type narrowing. * * **Example** (Basic Type Guard) * * ```ts * import { Schema } from "effect" * * const isString = Schema.is(Schema.String) * * console.log(isString("hello")) // true * console.log(isString(42)) // false * * // Type narrowing in action * const value: unknown = "hello" * if (isString(value)) { * // value is now typed as string * console.log(value.toUpperCase()) // "HELLO" * } * ``` * * @category Asserting * @since 4.0.0 */ export declare const is: typeof Parser.is; /** * Creates an assertion function that throws an error if the input doesn't match * the schema. * * This function is useful for runtime type checking with TypeScript's `asserts` * type guard. It narrows the type of the input if the assertion succeeds, or * throws an error if it fails. * * **Example** (Basic Usage) * * ```ts * import { Schema } from "effect" * * const assertString: (u: unknown) => asserts u is string = Schema.asserts( * Schema.String * ) * * // This will pass silently (no return value) * try { * assertString("hello") * console.log("String assertion passed") * } catch (error) { * console.log("String assertion failed") * } * * // This will throw an error * try { * assertString(123) * } catch (error) { * console.log("Non-string assertion failed as expected") * } * ``` * * @category Asserting * @since 4.0.0 */ export declare const asserts: typeof Parser.asserts; /** * Decodes an `unknown` input against a schema, returning an `Effect` that * succeeds with the decoded value or fails with a {@link SchemaError}. Use this * when the input type is not statically known. Prefer {@link decodeEffect} when * the input is already typed as the schema's `Encoded` type. * * @category Decoding * @since 4.0.0 */ export declare function decodeUnknownEffect(schema: S): (input: unknown, options?: AST.ParseOptions) => Effect.Effect; /** * Decodes a typed input (the schema's `Encoded` type) against a schema, * returning an `Effect` that succeeds with the decoded value or fails with a * {@link SchemaError}. Use this when the input is already typed; for `unknown` * input use {@link decodeUnknownEffect}. * * @category Decoding * @since 4.0.0 */ export declare const decodeEffect: (schema: S) => (input: S["Encoded"], options?: AST.ParseOptions) => Effect.Effect; /** * Decodes an `unknown` input against a schema synchronously, returning an * `Exit` that is either a `Success` with the decoded value or a `Failure` with * a {@link SchemaError}. Only usable with schemas that have no * `DecodingServices` requirement. Prefer {@link decodeExit} when the input is * already typed as the schema's `Encoded` type. * * @category Decoding * @since 4.0.0 */ export declare function decodeUnknownExit>(schema: S): (input: unknown, options?: AST.ParseOptions) => Exit_.Exit; /** * Decodes a typed input (the schema's `Encoded` type) against a schema * synchronously, returning an `Exit` that is either a `Success` with the * decoded value or a `Failure` with a {@link SchemaError}. Only usable with * schemas that have no `DecodingServices` requirement. For `unknown` input use * {@link decodeUnknownExit}. * * @category Decoding * @since 4.0.0 */ export declare const decodeExit: >(schema: S) => (input: S["Encoded"], options?: AST.ParseOptions) => Exit_.Exit; /** * Decodes an `unknown` input against a schema, returning an `Option` that is * `Some` with the decoded value on success or `None` on failure. Prefer this * over {@link decodeUnknownExit} or {@link decodeUnknownEffect} when you only * need to know whether decoding succeeded and don't need error details. For * typed input use {@link decodeOption}. * * @category Decoding * @since 4.0.0 */ export declare const decodeUnknownOption: typeof Parser.decodeUnknownOption; /** * Decodes a typed input (the schema's `Encoded` type) against a schema, * returning an `Option` that is `Some` with the decoded value on success or * `None` on failure. For `unknown` input use {@link decodeUnknownOption}. * * @category Decoding * @since 4.0.0 */ export declare const decodeOption: >(schema: S) => (input: S["Encoded"], options?: AST.ParseOptions) => Option_.Option; /** * Decodes an `unknown` input against a schema, returning a `Promise` that * resolves with the decoded value or rejects with a {@link SchemaError}. Useful * for integrating with Promise-based APIs. For typed input use * {@link decodePromise}. * * @category Decoding * @since 4.0.0 */ export declare const decodeUnknownResult: typeof Parser.decodeUnknownResult; /** * @category Decoding * @since 4.0.0 */ export declare const decodeResult: >(schema: S) => (input: S["Encoded"], options?: AST.ParseOptions) => Result_.Result; /** * @category Decoding * @since 4.0.0 */ export declare const decodeUnknownPromise: typeof Parser.decodeUnknownPromise; /** * Decodes a typed input (the schema's `Encoded` type) against a schema, * returning a `Promise` that resolves with the decoded value or rejects with a * {@link SchemaError}. For `unknown` input use {@link decodeUnknownPromise}. * * @category Decoding * @since 4.0.0 */ export declare const decodePromise: typeof Parser.decodePromise; /** * Decodes an `unknown` input against a schema synchronously, throwing a * {@link SchemaError} on failure. Use this when you want to validate data at a * boundary and treat a schema mismatch as an unrecoverable error. For * non-throwing alternatives see {@link decodeUnknownOption}, * {@link decodeUnknownExit}, or {@link decodeUnknownEffect}. For typed input * use {@link decodeSync}. * * **Example** (Decoding with a transformation schema) * * ```ts * import { Schema } from "effect" * * const NumberFromString = Schema.NumberFromString * * console.log(Schema.decodeUnknownSync(NumberFromString)("42")) * // Output: 42 * * Schema.decodeUnknownSync(NumberFromString)("not a number") * // throws SchemaError: NumberFromString * // └─ Encoded side transformation failure * // └─ NumberFromString * // └─ Expected a numeric string, actual "not a number" * ``` * * @category Decoding * @since 4.0.0 */ export declare const decodeUnknownSync: typeof Parser.decodeUnknownSync; /** * Decodes a typed input (the schema's `Encoded` type) against a schema * synchronously, throwing a {@link SchemaError} on failure. For `unknown` input * use {@link decodeUnknownSync}. * * @category Decoding * @since 4.0.0 */ export declare const decodeSync: >(schema: S) => (input: S["Encoded"], options?: AST.ParseOptions) => S["Type"]; /** * Encodes an `unknown` input against a schema, returning an `Effect` that * succeeds with the encoded value or fails with a {@link SchemaError}. Use this * when the input type is not statically known. Prefer {@link encodeEffect} when * the input is already typed as the schema's `Type`. * * **Example** (Encoding a value to a string) * * ```ts * import { Effect, Schema } from "effect" * * const NumberFromString = Schema.NumberFromString * * Effect.runPromise(Schema.encodeUnknownEffect(NumberFromString)(42)).then(console.log) * // Output: "42" * ``` * * @category Encoding * @since 4.0.0 */ export declare function encodeUnknownEffect(schema: S): (input: unknown, options?: AST.ParseOptions) => Effect.Effect; /** * Encodes a typed input (the schema's `Type`) against a schema, returning an * `Effect` that succeeds with the encoded value or fails with a * {@link SchemaError}. Use this when the input is already typed; for `unknown` * input use {@link encodeUnknownEffect}. * * @category Encoding * @since 4.0.0 */ export declare const encodeEffect: (schema: S) => (input: S["Type"], options?: AST.ParseOptions) => Effect.Effect; /** * Encodes an `unknown` input against a schema synchronously, returning an * `Exit` that is either a `Success` with the encoded value or a `Failure` with * a {@link SchemaError}. Only usable with schemas that have no * `EncodingServices` requirement. Prefer {@link encodeExit} when the input is * already typed as the schema's `Type`. * * @category Encoding * @since 4.0.0 */ export declare function encodeUnknownExit>(schema: S): (input: unknown, options?: AST.ParseOptions) => Exit_.Exit; /** * Encodes a typed input (the schema's `Type`) against a schema synchronously, * returning an `Exit` that is either a `Success` with the encoded value or a * `Failure` with a {@link SchemaError}. Only usable with schemas that have no * `EncodingServices` requirement. For `unknown` input use * {@link encodeUnknownExit}. * * @category Encoding * @since 4.0.0 */ export declare const encodeExit: >(schema: S) => (input: S["Type"], options?: AST.ParseOptions) => Exit_.Exit; /** * Encodes an `unknown` input against a schema, returning an `Option` that is * `Some` with the encoded value on success or `None` on failure. Prefer this * over {@link encodeUnknownExit} or {@link encodeUnknownEffect} when you only * need to know whether encoding succeeded and don't need error details. For * typed input use {@link encodeOption}. * * @category Encoding * @since 4.0.0 */ export declare const encodeUnknownOption: typeof Parser.encodeUnknownOption; /** * Encodes a typed input (the schema's `Type`) against a schema, returning an * `Option` that is `Some` with the encoded value on success or `None` on * failure. For `unknown` input use {@link encodeUnknownOption}. * * @category Encoding * @since 4.0.0 */ export declare const encodeOption: >(schema: S) => (input: S["Type"], options?: AST.ParseOptions) => Option_.Option; /** * Encodes an `unknown` input against a schema, returning a `Promise` that * resolves with the encoded value or rejects with a {@link SchemaError}. Useful * for integrating with Promise-based APIs. For typed input use * {@link encodePromise}. * * @category Encoding * @since 4.0.0 */ export declare const encodeUnknownResult: typeof Parser.encodeUnknownResult; /** * @category Encoding * @since 4.0.0 */ export declare const encodeResult: >(schema: S) => (input: S["Type"], options?: AST.ParseOptions) => Result_.Result; /** * @category Encoding * @since 4.0.0 */ export declare const encodeUnknownPromise: >(schema: S) => (input: unknown, options?: AST.ParseOptions) => Promise; /** * Encodes a typed input (the schema's `Type`) against a schema, returning a * `Promise` that resolves with the encoded value or rejects with a * {@link SchemaError}. For `unknown` input use {@link encodeUnknownPromise}. * * @category Encoding * @since 4.0.0 */ export declare const encodePromise: >(schema: S) => (input: S["Type"], options?: AST.ParseOptions) => Promise; /** * Encodes an `unknown` input against a schema synchronously, throwing a * {@link SchemaError} on failure. Use this when you want to serialize data at a * boundary and treat a schema mismatch as an unrecoverable error. For * non-throwing alternatives see {@link encodeUnknownOption}, * {@link encodeUnknownExit}, or {@link encodeUnknownEffect}. For typed input * use {@link encodeSync}. * * @category Encoding * @since 4.0.0 */ export declare const encodeUnknownSync: typeof Parser.encodeUnknownSync; /** * Encodes a typed input (the schema's `Type`) against a schema synchronously, * throwing a {@link SchemaError} on failure. For `unknown` input use * {@link encodeUnknownSync}. * * @category Encoding * @since 4.0.0 */ export declare const encodeSync: >(schema: S) => (input: S["Type"], options?: AST.ParseOptions) => S["Encoded"]; /** * Creates a schema from an AST (Abstract Syntax Tree) node. * * This is the fundamental constructor for all schemas in the Effect Schema * library. It takes an AST node and wraps it in a fully-typed schema that * preserves all type information and provides the complete schema API. * * The `make` function is used internally to create all primitive schemas like * `String`, `Number`, `Boolean`, etc., as well as more complex schemas. It's * the bridge between the untyped AST representation and the strongly-typed * schema. * * @category Constructors * @since 4.0.0 */ export declare const make: (ast: S["ast"], options?: object) => S; /** * Transforms a schema into a class that can be extended with `extends`. The * resulting class inherits the full schema API (e.g. `annotate`) and can define * static methods that reference `this`. * * **Example** (Wrapping a primitive schema) * * ```ts * import { Schema } from "effect" * * class MyString extends Schema.asClass(Schema.String) { * static readonly decodeUnknownSync = Schema.decodeUnknownSync(this) * } * * console.log(MyString.decodeUnknownSync("a")) * // "a" * ``` * * @since 4.0.0 */ export declare function asClass(schema: S): S & { new (_: never): {}; }; /** * Tests if a value is a `Schema`. * * @category Guards * @since 4.0.0 */ export declare function isSchema(u: unknown): u is Top; /** * Companion type for an exact optional struct key. The key may be absent, but * when present must match the wrapped schema (no implicit `undefined`). * Produced by {@link optionalKey}. * * @since 4.0.0 */ export interface optionalKey extends Bottom, S["~type.make.in"], S["Iso"], S["~type.parameters"], S["~type.make"], S["~type.mutability"], "optional", S["~type.constructor.default"], S["~encoded.mutability"], "optional"> { readonly schema: S; } interface optionalKeyLambda extends Lambda { (self: S): optionalKey; readonly "~lambda.out": this["~lambda.in"] extends Top ? optionalKey : never; } /** * Creates an exact optional key schema for struct fields. Unlike `optional`, * this creates exact optional properties (not `| undefined`) that can be * completely omitted from the object. * * **Example** (Creating a struct with optional key) * * ```ts * import { Schema } from "effect" * * const schema = Schema.Struct({ * name: Schema.String, * age: Schema.optionalKey(Schema.Number) * }) * * // Type: { readonly name: string; readonly age?: number } * type Person = typeof schema["Type"] * ``` * * @since 4.0.0 */ export declare const optionalKey: optionalKeyLambda; interface requiredKeyLambda extends Lambda { (self: optionalKey): S; readonly "~lambda.out": this["~lambda.in"] extends optionalKey ? this["~lambda.in"]["schema"] : "Error: schema not eligible for requiredKey"; } /** * Reverses {@link optionalKey}, returning the inner required schema. Only * applicable to schemas already wrapped with `optionalKey`. * * @since 4.0.0 */ export declare const requiredKey: requiredKeyLambda; /** * Companion type for an optional struct key that also accepts `undefined`. * Equivalent to `optionalKey>`. Produced by {@link optional}. * * @since 4.0.0 */ export interface optional extends optionalKey> { readonly "Rebuild": optional; } interface optionalLambda extends Lambda { (self: S): optional; readonly "~lambda.out": this["~lambda.in"] extends Top ? optional : never; } /** * Marks a struct field as optional, allowing the key to be absent or * `undefined`. * * explicitly set to `undefined`. Equivalent to `optionalKey(UndefinedOr(S))`. * * Use {@link optionalKey} instead if you want exact optional semantics (absent * only, not `undefined`). * * **Example** (Optional field accepting undefined) * * ```ts * import { Schema } from "effect" * * const schema = Schema.Struct({ * name: Schema.String, * age: Schema.optional(Schema.Number) * }) * * // { readonly name: string; readonly age?: number | undefined } * type Person = typeof schema.Type * ``` * * @since 4.0.0 */ export declare const optional: optionalLambda; interface requiredLambda extends Lambda { (self: optional): S; readonly "~lambda.out": this["~lambda.in"] extends optional ? this["~lambda.in"]["schema"]["members"][0] : "Error: schema not eligible for required"; } /** * Reverses {@link optional}, returning the inner schema (unwrapping `UndefinedOr`). * Only applicable to schemas already wrapped with `optional`. * * @since 4.0.0 */ export declare const required: requiredLambda; /** * Companion type for a mutable struct key. The key's property is writable. * Produced by {@link mutableKey}. * * @since 4.0.0 */ export interface mutableKey extends Bottom, S["~type.make.in"], S["Iso"], S["~type.parameters"], S["~type.make"], "mutable", S["~type.optionality"], S["~type.constructor.default"], "mutable", S["~encoded.optionality"]> { readonly schema: S; } interface mutableKeyLambda extends Lambda { (self: S): mutableKey; readonly "~lambda.out": this["~lambda.in"] extends Top ? mutableKey : never; } /** * Makes a struct field mutable (removes the `readonly` modifier on the property). * Use {@link readonlyKey} to reverse. * * @since 4.0.0 */ export declare const mutableKey: mutableKeyLambda; interface readonlyKeyLambda extends Lambda { (self: mutableKey): S; readonly "~lambda.out": this["~lambda.in"] extends mutableKey ? this["~lambda.in"]["schema"] : "Error: schema not eligible for readonlyKey"; } /** * Reverses {@link mutableKey}, returning the inner schema as readonly again. * Only applicable to schemas already wrapped with `mutableKey`. * * @since 4.0.0 */ export declare const readonlyKey: readonlyKeyLambda; /** * Schema type that collapses a transformation schema to its decoded `Type` on * both sides (Type = Encoded = S["Type"]). Produced by {@link toType}. * * @since 4.0.0 */ export interface toType extends Bottom, S["~type.make.in"], S["Iso"], S["~type.parameters"], S["~type.make"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> { } interface toTypeLambda extends Lambda { (self: S): toType; readonly "~lambda.out": this["~lambda.in"] extends Top ? toType : never; } /** * Extracts the type-side schema: sets `Encoded` to equal the decoded `Type`, * discarding the encoding transformation path. * * @since 4.0.0 */ export declare const toType: toTypeLambda; /** * Schema type that collapses a transformation schema to its `Encoded` side on * both sides (Type = Encoded = S["Encoded"]). Produced by {@link toEncoded}. * * @since 4.0.0 */ export interface toEncoded extends Bottom, S["Encoded"], S["Encoded"], ReadonlyArray, S["Encoded"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> { } interface toEncodedLambda extends Lambda { (self: S): toEncoded; readonly "~lambda.out": this["~lambda.in"] extends Top ? toEncoded : never; } /** * Extracts the encoded-side schema: sets `Type` to equal the `Encoded`, * discarding the decoding transformation path. * * @since 4.0.0 */ export declare const toEncoded: toEncodedLambda; declare const FlipTypeId = "~effect/Schema/flip"; /** * Schema type representing a flipped schema where `Type` and `Encoded` are * swapped. Produced by {@link flip}. * * @since 4.0.0 */ export interface flip extends Bottom, S["Encoded"], S["Encoded"], ReadonlyArray, S["Encoded"], S["~encoded.mutability"], S["~encoded.optionality"], ConstructorDefault, S["~type.mutability"], S["~type.optionality"]> { readonly [FlipTypeId]: typeof FlipTypeId; readonly schema: S; } /** * Swaps the `Type` and `Encoded` of a schema, inverting the transformation * direction. Calling `flip` twice returns the original schema. * * **Example** (Flip a number-from-string schema) * * ```ts * import { Schema } from "effect" * * // NumberFromString: decodes string → number * const flipped = Schema.flip(Schema.NumberFromString) * // flipped: decodes number → string * ``` * * @since 4.0.0 */ export declare function flip(schema: S): S extends flip ? F["Rebuild"] : flip; /** * Represents a schema for a single literal value. * * @see {@link Literal} for the constructor function. * @since 4.0.0 */ export interface Literal extends Bottom> { readonly literal: L; transform(to: L2): decodeTo, Literal>; } /** * Creates a schema for a single literal value (string, number, bigint, boolean, or null). * * **Example** (String literal) * ```ts * import { Schema } from "effect" * * const schema = Schema.Literal("hello") * // Type: Schema.Literal<"hello"> * ``` * * @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 * used as a discriminator field in tagged unions and has a constructor default. * @since 4.0.0 */ export declare function Literal(literal: L): Literal; /** * Namespace for {@link TemplateLiteral} helper types. * * @since 4.0.0 */ export declare namespace TemplateLiteral { /** * @since 4.0.0 */ interface SchemaPart extends Top { readonly Encoded: string | number | bigint; } /** * @since 4.0.0 */ type LiteralPart = string | number | bigint; /** * @since 4.0.0 */ type Part = SchemaPart | LiteralPart; /** * @since 4.0.0 */ type Parts = ReadonlyArray; type AppendType