Skip to content
Effect Days 2026 Get your ticket

SchemaRepresentation

Open, compiler-extensible representation of Effect schemas.

67 exports Added in v4.0.0 Source

Annotations

Open persistence identity and schema dependencies carried by opaque checks.

Signature

interface CheckRepresentationAnnotation<S> extends RepresentationAnnotation {
readonly schemas?: readonly Array<S>;
}

RepresentationAnnotation interface

Added in v4.0.0 Source

Open persistence identity carried by declarations and opaque checks.

Signature

interface RepresentationAnnotation {
readonly id: string;
readonly payload: Json;
}

Configuration

ToRepresentationOptions interface

Added in v4.0.0 Source

Options for generating schema representations.

Signature

interface ToRepresentationOptions {
readonly referencePolicy?: ReferencePolicy;
}

Constructors

Imports a JSON Schema Draft 2020-12 document as a runtime schema.

When to use

Use when you need to validate or transform values described by an external JSON Schema document.

Details

For the Draft 2020-12 subset translated exactly by this importer, compiling the imported schema through toRepresentation and toJsonSchemaDocument produces a document that accepts the same JSON values as the input. This is a semantic round-trip guarantee; keyword layout, definitions, and annotations may be normalized.

Gotchas

  • $dynamicRef, contains, dependentRequired, dependentSchemas, not, active if / then / else, unevaluatedItems, and unevaluatedProperties throw an Unsupported JSON Schema keyword error. Inactive conditional keywords and minContains / maxContains without contains have no validation effect and are ignored.
  • Objects and arrays used as const values or enum members throw an Unsupported structured JSON Schema value error.
  • Intersections of overlapping unions are limited to disjoint root-type partitions and finite primitive anyOf literal sets. Other union intersections, including cases that would duplicate a nested choice, throw an Unsupported intersection of overlapping unions error.
  • Unknown extension keywords are ignored and their semantics are not enforced.
  • Only direct local references to top-level definitions in the form #/$defs/<escaped-token> are supported. Root references, external references, and pointers below a definition throw an Unsupported reference error. A direct reference to a missing definition throws an Invalid reference error.
  • Built-in declarations and checks are reconstructed with importer-owned revivers.
  • Pattern constraints reached during translation cause an error by default. Use patterns: "apply" only for trusted documents, or patterns: "ignore" to weaken validation explicitly; ignored patterns are outside the round-trip guarantee.
  • onEnter results replace the corresponding input nodes, so the round-trip guarantee applies to the rewritten document.
  • Callback results are used directly, and exceptions raised by a callback pass through unchanged.

See

Signature

declare function fromJsonSchemaDocument(document: Document<"draft-2020-12">, options?: FromJsonSchemaOptions): Top

Imports multiple JSON Schema Draft 2020-12 roots as runtime schemas with shared definitions.

When to use

Use when multiple imported roots share reachable definitions, aliases, or recursion.

Gotchas

  • Only definitions reachable from a root are translated.
  • Unsupported standard validation and applicator keywords throw an Unsupported JSON Schema keyword error. Unknown extension keywords are ignored and their semantics are not enforced.
  • Objects and arrays used as const values or enum members throw an Unsupported structured JSON Schema value error.
  • Intersections of overlapping unions are limited to disjoint root-type partitions and finite primitive anyOf literal sets. Other union intersections, including cases that would duplicate a nested choice, throw an Unsupported intersection of overlapping unions error.
  • Only direct local references to top-level definitions in the form #/$defs/<escaped-token> are supported. Root references, external references, and pointers below a definition throw an Unsupported reference error. A direct reference to a missing definition throws an Invalid reference error.
  • Pattern constraints reached during translation cause an error by default. Use patterns: "apply" only for trusted documents, or patterns: "ignore" to weaken validation explicitly.
  • Callback results are used directly, and exceptions raised by a callback pass through unchanged.

See

Signature

declare function fromJsonSchemaMultiDocument(document: MultiDocument<"draft-2020-12">, options?: FromJsonSchemaOptions): readonly [Top, Top]

makeCode

Added in v4.0.0 Source

Creates generated runtime and TypeScript source strings for a schema.

Signature

declare const makeCode: (runtime: string, Type: string) => Code

Creates a declaration reviver while inferring its payload type from payloadSchema.

Signature

declare const makeDeclarationReviver: <P>(id: string, payloadSchema: Schema.Decoder<P>, revive: DeclarationReviver<P>["revive"]) => DeclarationReviver<P>

Creates a filter group reviver while inferring its payload type from payloadSchema.

Signature

declare const makeFilterGroupReviver: <P>(id: string, payloadSchema: Schema.Decoder<P>, revive: FilterGroupReviver<P>["revive"]) => FilterGroupReviver<P>

Creates a filter reviver while inferring its payload type from payloadSchema.

Signature

declare const makeFilterReviver: <P>(id: string, payloadSchema: Schema.Decoder<P>, revive: FilterReviver<P>["revive"]) => FilterReviver<P>

Lowers the encoded side of an AST to a live representation document.

When to use

Use when you have one SchemaAST.AST and need a live Document for inspection, persistence, or compilation.

Details

Apply SchemaAST.toType to the AST first to lower its type side instead. The optional reference policy controls which candidates are moved into the document's shared reference table.

See

Signature

declare function toRepresentation(ast: AST, options?: ToRepresentationOptions): Document

Lowers one or more AST encoded sides in a shared reference environment.

When to use

Use when several AST roots must share identifiers, occurrence counts, recursion, and allocated reference names.

Details

Apply SchemaAST.toType to an AST first to lower its type side instead. The reference policy observes candidates from every root before any representation is emitted.

See

Signature

declare function toRepresentations(asts: readonly [AST, AST], options?: ToRepresentationOptions): MultiDocument

Decoding

fromJson

Added in v4.0.0 Source

Decodes a persisted single-root representation document from JSON.

When to use

Use when reading a representation document from storage or transport before inspecting it or passing it to fromRepresentation.

Gotchas

Invalid documents throw a schema decoding error. Decoding does not reconstruct runtime callbacks.

See

Signature

declare function fromJson(input: Json): Document

Decodes a persisted multi-root representation document from JSON.

When to use

Use when reading multiple representation roots that share references before inspecting them or passing them to fromRepresentations.

Gotchas

Invalid documents throw a schema decoding error. Decoding does not reconstruct runtime callbacks.

See

Signature

declare function fromJsonMultiDocument(input: Json): MultiDocument

Encoding

toJson

Added in v4.0.0 Source

Projects a live single-root representation document and encodes it as JSON.

When to use

Use when you need a stable JSON value for storage or transport after calling toRepresentation.

Gotchas

Generic annotations that are not JSON are omitted. Invalid persistence identities and unsupported structural values throw an Error containing their representation path.

See

Signature

declare function toJson(document: Document): Json

Projects a live multi-root representation document and encodes it as JSON.

When to use

Use when you need one JSON value for multiple live roots that share a reference environment.

Gotchas

The root order and shared reference keys are preserved, while non-JSON generic annotations are omitted.

See

Signature

declare function toJsonMultiDocument(document: MultiDocument): Json

Models

Any interface

Added in v4.0.0 Source

The any keyword representation.

Signature

interface Any extends Keyword<"Any"> {}

AnyReviver type

Added in v4.0.0 Source

A reviver erased only at collection boundaries.

Signature

type AnyReviver = Reviver<any>

Arrays interface

Added in v4.0.0 Source

An array or tuple representation.

Signature

interface Arrays extends Keyword<"Arrays"> {
readonly elements: readonly Array<Element>;
readonly rest: readonly Array<Representation>;
}

Artifact type

Added in v4.0.0 Source

Auxiliary source artifact emitted while generating schema code.

Signature

type Artifact = {
readonly _tag: "Symbol";
readonly code: Code;
readonly identifier: string;
} | {
readonly _tag: "Enum";
readonly code: Code;
readonly identifier: string;
} | {
readonly _tag: "Import";
readonly importDeclaration: string;
}

BigInt interface

Added in v4.0.0 Source

A bigint representation.

Signature

interface BigInt extends Keyword<"BigInt"> {}

Boolean interface

Added in v4.0.0 Source

A boolean representation.

Signature

interface Boolean extends Keyword<"Boolean"> {}

Check type

Added in v4.0.0 Source

A structural check.

Signature

type Check = Filter | FilterGroup

CheckReviver type

Added in v4.0.0 Source

A check reviver.

Signature

type CheckReviver<P> = FilterReviver<P> | FilterGroupReviver<P>

Code interface

Added in v4.0.0 Source

Runtime and TypeScript source generated for one schema.

Signature

interface Code {
readonly runtime: string;
readonly Type: string;
}

CodeDocument interface

Added in v4.0.0 Source

Generated schema code together with named references and auxiliary artifacts.

Signature

interface CodeDocument {
readonly artifacts: readonly Array<Artifact>;
readonly codes: readonly Array<Code>;
readonly references: {
readonly nonRecursives: readonly Array<{
readonly $ref: string;
readonly code: Code;
}>;
readonly recursives: Readonly<Record<string, Code>>;
};
}

Declaration interface

Added in v4.0.0 Source

A custom opaque declaration.

Signature

interface Declaration {
readonly _tag: "Declaration";
readonly annotations?: Annotations;
readonly checks: readonly Array<Check>;
readonly representation?: RepresentationAnnotation;
readonly typeParameters: readonly Array<Representation>;
}

DeclarationReviver interface

Added in v4.0.0 Source

Reviver for a declaration.

Signature

interface DeclarationReviver<P> {
readonly id: string;
readonly payloadSchema: Decoder<P>;
readonly revive: (input: {
readonly annotations: Annotations | undefined;
readonly payload: P;
readonly typeParameters: readonly Array<Top>;
}) => Top;
}

Document interface

Added in v4.0.0 Source

A single representation and its definitions.

Signature

interface Document {
readonly references: References;
readonly representation: Representation;
}

Element interface

Added in v4.0.0 Source

A tuple element.

Signature

interface Element {
readonly annotations?: Annotations;
readonly isOptional: boolean;
readonly type: Representation;
}

Enum interface

Added in v4.0.0 Source

An enum representation.

Details

Enum members are stored as native string or number values. Persistent codecs add an explicit type discriminator when encoding them.

Signature

interface Enum extends Keyword<"Enum"> {
readonly enums: readonly Array<readonly [string, string | number]>;
}

Filter interface

Added in v4.0.0 Source

An opaque leaf check.

Signature

interface Filter {
readonly _tag: "Filter";
readonly aborted: boolean;
readonly annotations?: Annotations;
readonly representation?: CheckRepresentationAnnotation<Representation>;
}

FilterGroup interface

Added in v4.0.0 Source

A non-empty group of checks.

Signature

interface FilterGroup {
readonly _tag: "FilterGroup";
readonly annotations?: Annotations;
readonly checks: readonly [Check, Check];
readonly representation?: CheckRepresentationAnnotation<Representation>;
}

FilterGroupReviver interface

Added in v4.0.0 Source

Reviver for a check group.

Signature

interface FilterGroupReviver<P> {
readonly id: string;
readonly payloadSchema: Decoder<P>;
readonly revive: (input: {
readonly annotations: Filter | undefined;
readonly payload: P;
readonly schemas: readonly Array<Top>;
}) => FilterGroup<any>;
}

FilterReviver interface

Added in v4.0.0 Source

Reviver for a leaf check.

Signature

interface FilterReviver<P> {
readonly id: string;
readonly payloadSchema: Decoder<P>;
readonly revive: (input: {
readonly annotations: Filter | undefined;
readonly payload: P;
readonly schemas: readonly Array<Top>;
}) => Filter<any>;
}

FromJsonSchemaOptions interface

Added in v4.0.0 Source

Options for importing JSON Schema Draft 2020-12 documents.

When to use

Use when you need to configure pattern handling or transform each JSON Schema node before translation.

Details

patterns controls pattern constraints reached during best-effort translation, including pattern, the keys of patternProperties, and patterns nested in propertyNames:

  • "error" rejects the document and is the default.
  • "ignore" skips the constraint.
  • "apply" compiles and enforces the constraint with the runtime's native regular expression engine.

Gotchas

Use patterns: "apply" only for trusted documents because regular expression evaluation may block for an unbounded amount of time. patterns: "ignore" weakens validation by accepting values that the source document may reject. Ignoring patternProperties also skips its value constraints and additionalProperties, because matching keys cannot be determined without evaluating the patterns. onEnter must return a JSON Schema object. Its result is used directly, and exceptions raised by the callback pass through unchanged.

Signature

interface FromJsonSchemaOptions {
readonly onEnter?: (schema: JsonSchema) => JsonSchema;
readonly patterns?: "error" | "ignore" | "apply";
}

IndexSignature interface

Added in v4.0.0 Source

An index signature.

Signature

interface IndexSignature {
readonly parameter: Representation;
readonly type: Representation;
}

Literal interface

Added in v4.0.0 Source

A literal representation.

Details

The live representation stores the native literal value. Persistent codecs add an explicit type discriminator when encoding it.

Signature

interface Literal extends Keyword<"Literal"> {
readonly literal: LiteralValue;
}

MultiDocument interface

Added in v4.0.0 Source

Multiple representations sharing definitions.

Signature

interface MultiDocument {
readonly references: References;
readonly representations: readonly [Representation, Representation];
}

Never interface

Added in v4.0.0 Source

The never keyword representation.

Signature

interface Never extends Keyword<"Never"> {}

Null interface

Added in v4.0.0 Source

The null keyword representation.

Signature

interface Null extends Keyword<"Null"> {}

Number interface

Added in v4.0.0 Source

A number representation.

Signature

interface Number extends Keyword<"Number"> {}

ObjectKeyword interface

Added in v4.0.0 Source

The object keyword representation.

Signature

interface ObjectKeyword extends Keyword<"ObjectKeyword"> {}

Objects interface

Added in v4.0.0 Source

An object representation.

Signature

interface Objects extends Keyword<"Objects"> {
readonly indexSignatures: readonly Array<IndexSignature>;
readonly propertySignatures: readonly Array<PropertySignature>;
}

PropertySignature interface

Added in v4.0.0 Source

A property signature.

Details

The live representation stores the native property key. Persistent codecs add an explicit type discriminator when encoding it.

Gotchas

Local symbols can be represented while the schema is live, but persistent codecs reject them because they cannot be reconstructed by identity.

Signature

interface PropertySignature {
readonly annotations?: Annotations;
readonly isMutable: boolean;
readonly isOptional: boolean;
readonly name: PropertyKey;
readonly type: Representation;
}

Reference interface

Added in v4.0.0 Source

A named reference.

Signature

interface Reference {
readonly _tag: "Reference";
readonly $ref: string;
}

ReferencePolicy type

Added in v4.0.0 Source

Function that chooses whether a representation candidate is emitted as a named reference.

When to use

Use when you need reference allocation based on schema identity, occurrence counts, identifiers, or another application-specific rule.

Details

Return a reference name to extract the candidate, or undefined to keep it inline. The policy is called once per candidate after all occurrences have been counted. The identifier is the resolved identifier for the encoded AST, including an Encoded suffix when an identifier is inherited from the source side of an encoding. If different candidates request the same name, later names receive numeric suffixes in encounter order.

Gotchas

Recursive candidates always require a reference. When the policy returns undefined for one, the generator assigns a synthetic name. Treat the input AST as immutable and keep the policy deterministic.

See

Signature

type ReferencePolicy = (input: ReferencePolicyInput) => string | undefined

ReferencePolicyInput interface

Added in v4.0.0 Source

Information supplied to a reference policy for one representation candidate.

Signature

interface ReferencePolicyInput {
readonly ast: AST;
readonly identifier: string | undefined;
readonly occurrences: number;
}

References interface

Added in v4.0.0 Source

Named representation definitions.

Signature

interface References {
[$ref: string]: Representation;
}

Representation type

Added in v4.0.0 Source

The structural schema representation.

Signature

type Representation = Declaration | Reference | Suspend | Null | Undefined | Void | Never | Unknown | Any | String | Number | Boolean | BigInt | Symbol | Literal | UniqueSymbol | ObjectKeyword | Enum | TemplateLiteral | Arrays | Objects | Union

Reviver type

Added in v4.0.0 Source

A typed reviver.

Signature

type Reviver<P> = DeclarationReviver<P> | CheckReviver<P>

String interface

Added in v4.0.0 Source

A string representation.

Signature

interface String extends Keyword<"String"> {}

Suspend interface

Added in v4.0.0 Source

A lazily resolved representation.

Signature

interface Suspend {
readonly _tag: "Suspend";
readonly annotations?: Annotations;
readonly checks: readonly [];
readonly thunk: Representation;
}

Symbol interface

Added in v4.0.0 Source

A symbol representation.

Signature

interface Symbol extends Keyword<"Symbol"> {}

TemplateLiteral interface

Added in v4.0.0 Source

A template literal representation.

Signature

interface TemplateLiteral extends Keyword<"TemplateLiteral"> {
readonly parts: readonly Array<Representation>;
}

Undefined interface

Added in v4.0.0 Source

The undefined keyword representation.

Signature

interface Undefined extends Keyword<"Undefined"> {}

Union interface

Added in v4.0.0 Source

A union representation.

Signature

interface Union extends Keyword<"Union"> {
readonly mode: "anyOf" | "oneOf";
readonly types: readonly Array<Representation>;
}

UniqueSymbol interface

Added in v4.0.0 Source

A unique global symbol representation.

Signature

interface UniqueSymbol extends Keyword<"UniqueSymbol"> {
readonly symbol: symbol;
}

Unknown interface

Added in v4.0.0 Source

The unknown keyword representation.

Signature

interface Unknown extends Keyword<"Unknown"> {}

Void interface

Added in v4.0.0 Source

The void keyword representation.

Signature

interface Void extends Keyword<"Void"> {}

Other

Generation

Added in v4.0.0 Source

Input and output contracts for code generation annotations.

ToJsonSchema

Added in v4.0.0 Source

Input passed to JSON Schema compiler annotations.

Transforming

Reconstructs a runtime schema from a representation document.

When to use

Use when you have decoded or constructed a document whose declaration and check annotations may require revivers.

Gotchas

Revivers are resolved locally by id; none are installed implicitly. Reviver results are used directly, and exceptions raised by a reviver pass through unchanged.

See

Signature

declare function fromRepresentation(document: Document, options: {
readonly revivers: readonly Array<AnyReviver>;
}): Top

Example

(Restoring a persisted schema)

import { Schema, SchemaRepresentation } from "effect"
const document = SchemaRepresentation.toRepresentation(Schema.Struct({ name: Schema.String }).ast)
const persisted = SchemaRepresentation.toJson(document)
const restored = SchemaRepresentation.fromJson(persisted)
const schema = SchemaRepresentation.fromRepresentation(restored, { revivers: [] })
const Person = Schema.make<Schema.Codec<{ readonly name: string }>>(schema.ast)
Schema.decodeUnknownSync(Person)({ name: "Ada" }) // => { name: "Ada" }

Reconstructs multiple runtime schemas from a representation multi-document.

When to use

Use when multiple roots must be rebuilt in one shared reference environment.

Gotchas

Only references reachable from a root are revived. Revivers are resolved locally by id; none are installed implicitly.

See

Signature

declare function fromRepresentations(document: MultiDocument, options: {
readonly revivers: readonly Array<AnyReviver>;
}): readonly [Top, Top]

Generates TypeScript source for live schema representations and their definitions.

When to use

Use when custom declarations and checks provide toCode callbacks and must be emitted without a central handler registry.

Gotchas

Opaque declarations and leaf checks require toCode callbacks. Callback results are used directly, and exceptions raised by a callback pass through unchanged.

Signature

declare function toCodeDocument(document: MultiDocument): CodeDocument

Compiles a live representation document to JSON Schema Draft 2020-12.

When to use

Use when you need JSON Schema output from a representation whose checks carry compiler annotations.

Details

For representation documents whose validation semantics can be expressed exactly in JSON Schema, importing the emitted document with fromJsonSchemaDocument reconstructs a schema that accepts the same JSON values. This is a semantic round-trip guarantee; the emitted document and reconstructed representation may have different shapes.

Gotchas

  • Reference allocation is already fixed in the input Document. The inherited referencePolicy option has no effect here; pass it to toRepresentation when creating the document.
  • Opaque declarations are represented by an unconstrained JSON Schema and are outside the exact round-trip subset.
  • Check callback results are used directly, and exceptions raised by a callback pass through unchanged. Callbacks must treat their input schemas as immutable. Each returned value must be a valid JSON Schema object graph and must not be mutated after the callback returns.
  • Local definition references returned by callbacks are resolved together with compiler-generated references.
  • Effect decoding may discard excess object properties by default. Use onExcessProperty: "error" when comparing validation semantics with the emitted JSON Schema.

See

Signature

declare function toJsonSchemaDocument(document: Document, options?: ToJsonSchemaOptions): Document<"draft-2020-12">

Compiles multiple live representations to a shared JSON Schema Draft 2020-12 document.

When to use

Use when several representation roots must share the same JSON Schema definitions.

Gotchas

  • Reference allocation is already fixed in the input MultiDocument. The inherited referencePolicy option has no effect here; pass it to toRepresentations when creating the document.
  • Every definition is compiled, including definitions that are not reachable from a root. Check callbacks must treat their input schemas as immutable. Each returned value must be a valid JSON Schema object graph and must not be mutated after the callback returns. Local definition references returned by callbacks are resolved together with compiler-generated references.

See

Signature

declare function toJsonSchemaMultiDocument(document: MultiDocument, options?: ToJsonSchemaOptions): MultiDocument<"draft-2020-12">

Wraps a single representation document as a multi-document with one root.

When to use

Use when an API such as toCodeDocument requires a MultiDocument.

Signature

declare function toMultiDocument(document: Document): MultiDocument