import { type ErrorConfig, OmpErrors } from "./errors.js"; import type { InferDef, InferDefIn, InferObjectLiteral, InferObjectLiteralIn, InferString } from "./infer.js"; import { type Constructor, type Def, hasMorph, type IR, IR_BRAND } from "./ir.js"; import { type JsonSchemaOptions } from "./json-schema.js"; export interface NarrowErrorInput { readonly expected: string; readonly actual?: unknown; readonly path?: readonly PropertyKey[]; readonly relativePath?: readonly PropertyKey[]; } /** Context passed to `.narrow()` / `.pipe()` callbacks. */ export interface NarrowContext { readonly path: readonly PropertyKey[]; error(error: string | NarrowErrorInput): OmpErrors; mustBe(expectation: string): false; reject(problem: string | NarrowErrorInput): OmpErrors | false; } /** Schema metadata and validation-message overrides accepted by `.configure()`. */ export interface SchemaConfig extends ErrorConfig { readonly description?: string; } /** Options accepted by `Type.toJsonSchema`. */ export interface ToJsonSchemaOptions extends JsonSchemaOptions { } declare const brand: unique symbol; /** Inference-only nominal brand attached by `.brand(name)`. */ export type Brand = t & { readonly [brand]: name; }; interface SchemaInference { readonly [IR_BRAND]: true; readonly infer: t; readonly inferIn: i; } /** Property descriptor exposed by object schemas and consumed by `.map()`. */ export interface TypeProperty { readonly kind: "required" | "optional"; readonly key: PropertyKey; readonly value: FluentType; readonly default?: unknown; readonly meta: Readonly>; } /** Structural node returned by `.select()`. */ export interface SelectedNode { readonly kind: string; readonly node: IR; readonly unit?: unknown; } /** * Standard Schema V1 (https://standardschema.dev) — the cross-library * validation interface consumed by tools like @t3-oss/env, tRPC, and * Hono validators. Inlined per the spec's recommendation; no dependency. */ export interface StandardSchemaV1 { readonly "~standard": StandardSchemaV1.Props; } export declare namespace StandardSchemaV1 { interface Props { readonly version: 1; readonly vendor: string; readonly validate: (value: unknown) => Result | Promise>; readonly types?: Types | undefined; readonly jsonSchema: { readonly input: (options: StandardJsonSchemaOptions) => Record; readonly output: (options: StandardJsonSchemaOptions) => Record; }; } type Result = SuccessResult | FailureResult; interface SuccessResult { readonly value: Output; readonly issues?: undefined; } interface FailureResult { readonly issues: readonly Issue[]; } interface Issue { readonly message: string; readonly path?: readonly PropertyKey[] | undefined; } interface Types { readonly input: Input; readonly output: Output; } } export interface StandardJsonSchemaOptions { readonly target: "draft-2020-12" | "draft-07" | string; readonly libraryOptions?: { readonly dialect?: string | null; readonly fallback?: JsonSchemaOptions["fallback"]; }; } /** A compiled schema: callable validator plus composition methods. */ export interface Type { (data: unknown): t | OmpErrors; readonly [IR_BRAND]: true; /** Structural IR (base type; runtime steps live in `steps`). */ readonly ir: IR; /** `.pipe()` / `.narrow()` steps applied after structural validation. */ readonly hasSteps: boolean; readonly hasDefault: boolean; readonly defaultValue?: unknown; readonly description?: string; /** Canonical ArkType-compatible expression for diagnostics. */ readonly expression: string; /** Canonical structural node representation. */ readonly json: unknown; /** Full validate+morph pipeline; identical to calling the schema. */ readonly run: (data: unknown) => unknown; /** ArkType-compatible inference alias (type-only; undefined at runtime). */ readonly t: t; /** Scope that parsed this schema (or the ambient Ark-compatible scope). */ readonly $: TypeScope | { readonly internal: { readonly name: "ark"; }; }; /** Inference-only output type (no runtime value). */ readonly infer: t; /** Standalone validator for the schema's accepted input. */ readonly in: FluentType; /** Standalone validator for its known output, or `unknown` after an opaque morph. */ readonly out: FluentType; /** Inference-only input type (no runtime value). */ readonly inferIn: i; /** Structural + narrow check without running pipes. */ allows(data: unknown): data is i; /** Validate and return output, throwing `TraversalError` on failure. */ assert(data: unknown): t; /** Validate a statically typed input and return its output. */ from(data: i): t; /** JSON Schema for this schema's structural base. */ toJsonSchema(options?: ToJsonSchemaOptions): Record; /** Standard Schema V1 interop (synchronous validation). */ readonly "~standard": StandardSchemaV1.Props; } type MergeTypes = left extends object ? right extends object ? Omit & right : right : right; type SimplifyNary = t extends object ? { [key in keyof t]: t[key]; } : t; type UnionToIntersection = (union extends unknown ? (value: union) => void : never) extends (value: infer intersection) => void ? intersection : never; type NaryOrOutput = InferDef; type NaryOrInput = InferDefIn; type NaryAndOutput = definitions extends readonly [] ? unknown : SimplifyNary>>; type NaryAndInput = definitions extends readonly [] ? unknown : SimplifyNary>>; type ReduceNaryMergeOutput = definitions extends readonly [ infer head, ...infer tail ] ? ReduceNaryMergeOutput>>> : definitions extends readonly [] ? result : {}; type ReduceNaryMergeInput = definitions extends readonly [ infer head, ...infer tail ] ? ReduceNaryMergeInput>>> : definitions extends readonly [] ? result : {}; type NaryMergeOutput = definitions extends readonly [] ? object : ReduceNaryMergeOutput; type NaryMergeInput = definitions extends readonly [] ? object : ReduceNaryMergeInput; type PipeItemOutput = item extends SchemaInference ? output : item extends (data: never, ...arguments_: never[]) => infer output ? Exclude : InferDef; type NaryPipeOutput = items extends readonly [...(readonly unknown[]), infer last] ? PipeItemOutput : unknown; type NaryPipeInput = items extends readonly [infer first, ...(readonly unknown[])] ? first extends SchemaInference ? input : first extends (data: infer input, ...arguments_: never[]) => unknown ? input : InferDefIn : unknown; interface FluentMethods { describe(description: string): FluentType; configure(config: SchemaConfig, selector?: "self" | ConfigureSelector): FluentType; default(value: i | (() => i)): FluentType; optional(): readonly [SchemaInference, "?"]; or(def: SchemaInference): FluentType; or(def: def): FluentType, i | InferString>; or>(def: def): FluentType, i | InferObjectLiteralIn>; or(def: Def): FluentType; and(def: SchemaInference): FluentType; and>(def: def): FluentType, i & InferObjectLiteralIn>; and(def: Def): FluentType; equals(def: Def): boolean; ifEquals(def: Def): FluentType | undefined; ifExtends(def: Def): FluentType | undefined; extends(def: Def): boolean; overlaps(def: Def): boolean; distribute(mapper: (branch: FluentType) => SchemaInference, reducer?: (branches: readonly SchemaInference[]) => SchemaInference): FluentType; select(kind: string): readonly SelectedNode[]; array(): FluentType; atLeastLength(bound: number): FluentType; atMostLength(bound: number): FluentType; moreThanLength(bound: number): FluentType; lessThanLength(bound: number): FluentType; exactlyLength(bound: number): FluentType; atLeast(bound: number): FluentType; atMost(bound: number): FluentType; moreThan(bound: number): FluentType; lessThan(bound: number): FluentType; divisibleBy(divisor: number): FluentType; positive(): FluentType; negative(): FluentType; nonNegative(): FluentType; nonPositive(): FluentType; matching(pattern: RegExp): FluentType; atOrAfter(bound: Date | number): FluentType; atOrBefore(bound: Date | number): FluentType; laterThan(bound: Date | number): FluentType; earlierThan(bound: Date | number): FluentType; readonly pipe: PipeMethod; to(def: def): FluentType, i>; filter(fn: (data: i, ctx: NarrowContext) => data is narrowed): FluentType; filter(fn: (data: i, ctx: NarrowContext) => boolean | OmpErrors): FluentType; narrow(fn: (data: t, ctx: NarrowContext) => data is narrowed): FluentType; narrow(fn: (data: t, ctx: NarrowContext) => boolean | OmpErrors): FluentType; brand(name: name): FluentType, i>; as(): FluentType; readonly(): FluentType, i>; extract(def: SchemaInference): FluentType, Extract>; extract(def: def): FluentType>, Extract>>; extract(def: Def): FluentType; exclude(def: SchemaInference): FluentType, Exclude>; exclude(def: def): FluentType>, Exclude>>; exclude(def: Def): FluentType; onUndeclaredKey(behavior: "ignore" | "reject" | "delete"): FluentType; onDeepUndeclaredKey(behavior: "ignore" | "reject" | "delete"): FluentType; } interface PipeMethod { (fn: (data: t, ctx: NarrowContext) => r): FluentType, i>; (schema: SchemaInference): FluentType; (...steps: readonly unknown[]): FluentType; readonly try: { (fn: (data: t, ctx: NarrowContext) => r): FluentType, i>; (...steps: readonly unknown[]): FluentType; }; } type InputObject = i extends object ? i : object; interface ObjectMethods { readonly props: readonly TypeProperty[]; map(mapper: (property: TypeProperty) => TypeProperty | readonly TypeProperty[]): FluentType>; keyof(): FluentType, Extract, PropertyKey>>; get(...path: path): FluentType; pick(...keys: keys): FluentType, Pick, Extract>>>; omit(...keys: keys): FluentType, Omit, Extract>>>; partial(): FluentType, Partial>>; required(): FluentType, Required>>; merge(def: SchemaInference): FluentType, MergeTypes>; merge>(def: def): FluentType>, MergeTypes>>; merge(def: Def): FluentType; } type ObjectMethodsFor = [t] extends [never] ? unknown : [t] extends [readonly unknown[]] ? unknown : [t] extends [object] ? ObjectMethods : unknown; /** Callable schema with fluent methods specialized to its output and input. */ export type FluentType = Type & FluentMethods & ObjectMethodsFor; type FnDefinition = Def | SchemaInference; /** Function returned by `type.fn`: arguments and an optional return are validated at every call. */ export type TypedFunction = ((...arguments_: parameters) => returns) & { readonly params: FluentType; readonly returns: FluentType; readonly expression: string; readonly raw: (...arguments_: parameters) => returns; }; type InferFnDefinition = definition extends SchemaInference ? output : InferDef; type InferFnParameters = definitions extends readonly [infer head, ...infer tail] ? head extends ":" ? accumulator : InferFnParameters]> : accumulator; type InferFnReturn = definitions extends readonly [ ...(readonly unknown[]), ":", infer returns ] ? InferFnDefinition : inferred; type DeclaredFnReturn = definitions extends readonly [ ...(readonly unknown[]), ":", infer returns ] ? InferFnDefinition : unknown; type FnFactory = (implementation: (...arguments_: InferFnParameters) => InferFnReturn) => TypedFunction, InferFnReturn, DeclaredFnReturn>; /** Parses function parameter schemas and validates calls and declared returns. */ export interface FnParser { (...definitions: definitions): FnFactory; raw(...definitions: definitions): FnFactory; } /** Runtime constructor-like value used by ArkType-compatible `instanceof Type` checks. */ export declare const Type: () => void; export interface ConfigureSelector { readonly kind?: string; readonly where?: (node: { readonly domain?: string; readonly kind: string; }) => boolean; } /** Callable runtime generic returned by `type("", def)` and `type.generic(...)`. */ export type Generic = (...arguments_: readonly unknown[]) => BaseType; /** Schema arguments passed to a callback-bodied runtime generic. */ export interface GenericArguments { readonly [name: string]: BaseType; } export interface GenericBuilder { (definition: (arguments_: GenericArguments) => unknown, hkt?: unknown): Generic; (definition: unknown, hkt?: unknown): Generic; } export declare function type(parameters: `<${string}>`, definition: definition): Generic; export declare function type(def: def): FluentType, InferDefIn>; export declare function type(def: SchemaInference | string, operator: "=>", morph: (data: input, ctx: NarrowContext) => output): FluentType, input>; export declare function type(def: input, operator: "|>", out: output): FluentType, InferDefIn>; export declare function type(...definition: expression): FluentType, InferDefIn>; /** String keyword with a parser that morphs validated text to another output. */ export interface ParsedStringKeyword extends FluentType { readonly parse: FluentType; } /** Morphing string keyword paired with its non-morphing preformatted validator. */ export interface PreformattedKeyword extends FluentType { readonly preformatted: FluentType; } /** Base64 keyword with its URL-safe alphabet variant. */ export interface Base64Keyword extends FluentType { readonly url: FluentType; } /** Date-string keyword family. */ export interface DateStringKeyword extends ParsedStringKeyword { readonly iso: ParsedStringKeyword; readonly epoch: ParsedStringKeyword; } /** IP address keyword family. */ export interface IpKeyword extends FluentType { readonly v4: FluentType; readonly v6: FluentType; } /** UUID keyword family. */ export interface UuidKeyword extends FluentType { readonly v1: FluentType; readonly v2: FluentType; readonly v3: FluentType; readonly v4: FluentType; readonly v5: FluentType; readonly v6: FluentType; readonly v7: FluentType; readonly v8: FluentType; } /** String normalization keyword family. */ export interface NormalizeKeyword extends PreformattedKeyword { readonly NFC: PreformattedKeyword; readonly NFD: PreformattedKeyword; readonly NFKC: PreformattedKeyword; readonly NFKD: PreformattedKeyword; } /** Runtime string parsers exposed under `type.parse`. */ export interface ParseKeyword { readonly number: FluentType; readonly integer: FluentType; readonly json: FluentType; readonly date: FluentType; readonly url: FluentType; readonly boolean: FluentType; readonly bigint: FluentType; } /** Full string keyword module attached to `type.string`. */ export interface StringKeyword extends FluentType { readonly alpha: FluentType; readonly alphanumeric: FluentType; readonly base64: Base64Keyword; readonly capitalize: PreformattedKeyword; readonly creditCard: FluentType; readonly date: DateStringKeyword; readonly digits: FluentType; readonly email: FluentType; readonly hex: FluentType; readonly integer: ParsedStringKeyword; readonly ip: IpKeyword; readonly json: ParsedStringKeyword; readonly lower: PreformattedKeyword; readonly normalize: NormalizeKeyword; readonly numeric: ParsedStringKeyword; readonly regex: FluentType; readonly semver: FluentType; readonly trim: PreformattedKeyword; readonly upper: PreformattedKeyword; readonly url: ParsedStringKeyword; readonly uuid: UuidKeyword; } /** Number keyword module attached to `type.number`. */ export interface NumberKeyword extends FluentType { readonly integer: FluentType; } type Constructed = ctor extends abstract new (...args: never[]) => infer instance ? instance : never; type MatchDefault = "assert" | "never" | "reject" | ((input: input, ...args: readonly unknown[]) => output); type MatchCaseOutput = { [key in keyof cases]: cases[key] extends (...args: never[]) => infer output ? output : never; }[keyof cases]; /** A finalized matcher. Like a schema, it returns structured errors unless finalized with `"assert"`. */ export type Matcher = FluentType & ((value: value, ...args: readonly unknown[]) => output | OmpErrors); /** Fluent first-match parser exposed as `match` and `type.match`. */ export interface MatchParser { >(cases: cases): MatchParser> | Matcher>; case(definition: definition, resolver: (value: InferDef, ...args: readonly unknown[]) => result): MatchParser; match>(cases: cases): MatchParser> | Matcher>; default(fallback: MatchDefault): Matcher; at(key: key): MatchParser; at>(key: key, cases: cases): MatchParser> | Matcher>; strings>(cases: cases): MatchParser> | Matcher>; in(): MatchParser; in(definition: definition): MatchParser, output>; } /** Build a fluent first-match dispatcher from schema definitions. */ declare const matchBuilder: MatchParser; export { matchBuilder as match }; /** Declares a schema output type while preserving its inferred input. */ export interface DeclaredParser { type(definition: definition): FluentType>; } /** Fix a schema's externally declared static type without changing its runtime validation. */ export declare function declare(): DeclaredParser; export declare namespace type { /** Error aggregate returned by failed validations (`result instanceof type.errors`). */ export const errors: typeof OmpErrors; export type errors = OmpErrors; /** Build a union from zero or more definitions. */ export function or(...definitions: definitions): FluentType, NaryOrInput>; /** Build an array schema from an element definition. */ export function array(definition: definition): FluentType[], InferDefIn[]>; /** Build a union from a runtime array of definitions. */ export function union(definitions: definitions): FluentType, NaryOrInput>; /** Build a tuple schema from a runtime array of definitions. */ export function tuple(definitions: definitions): FluentType, InferDefIn>; /** Build an open record schema from key and value definitions. */ export function record(key: key, value: value): FluentType, PropertyKey>, InferDef>, Record, PropertyKey>, InferDefIn>>; /** Build an intersection from zero or more definitions. */ export function and(...definitions: definitions): FluentType, NaryAndInput>; /** Right-biased object merge over zero or more definitions. */ export function merge(...definitions: definitions): FluentType, NaryMergeInput>; /** Compose Types, definitions, and morph callbacks from left to right. */ export function pipe(...definitions: definitions): FluentType, NaryPipeInput>; /** String validator and its refinement/morph keyword module. */ export const string: StringKeyword; /** Runtime parser keyword family. */ export const parse: ParseKeyword; /** Number validator with integer refinement. */ export const number: NumberKeyword; /** Schema-valued key representing any non-negative integer array index. */ export const arrayIndex: FluentType; /** Boolean validator. */ export const boolean: FluentType; /** Bigint validator. */ export const bigint: FluentType; /** Symbol validator. */ export const symbol: FluentType; /** Non-null object validator. */ export const object: FluentType; /** Unknown validator. */ export const unknown: FluentType; /** Alias of the unknown validator. */ export const any: FluentType; /** Validator that rejects every value. */ export const never: FluentType; /** ArkType's built-in keyword namespace, including invokable utility generics. */ export const keywords: { number: { integer: FluentType; }; Map: FluentType, Map>; Set: FluentType, Set>; RegExp: FluentType; File: FluentType; Error: FluentType; Function: FluentType; Array: { liftFrom(definition: definition): FluentType[], InferDefIn | InferDefIn[]>; }; Record(key: key, value: value): FluentType, PropertyKey>, InferDef>, Record, PropertyKey>, InferDefIn>>; Partial(definition: definition): FluentType>, Partial>>>; Required(definition: definition): FluentType>, Required>>>; Pick(definition: definition, ...keys: keys): FluentType, Extract>>, Pick>, Extract>>>>; Omit(definition: definition, ...keys: keys): FluentType, Extract>>, Omit>, Extract>>>>; Merge(left: left, right: right): FluentType, InferDef>, MergeTypes, InferDefIn>>; object: { json: FluentType; }; unknown: { any: FluentType; }; }; /** Date instance validator. */ export const Date: FluentType; /** Validate instances of `ctor`. */ export function instanceOf(ctor: ctor): FluentType>; /** Validate one exact unit value. */ export function unit(value: value): FluentType; /** Union of literal values from a runtime array. */ export function enumerated(...values: values): FluentType; /** Build a literal union from a runtime array. */ export function enumeration(values: values): FluentType; /** Enumerate an enum-like object's forward values, excluding numeric reverse mappings. */ export function valueOf>(values: values): FluentType; /** Fluent first-match dispatcher, also exported as standalone `match`. */ export const match: MatchParser; /** Preserve a definition's literal type while authoring reusable modules. */ export function define(definition: definition): definition; /** Build a function whose arguments and optional declared return are validated. */ export const fn: FnParser; /** Fix an externally declared static type while retaining runtime validation. */ export const declare: () => DeclaredParser; /** Build a lazy named scope from aliases and recursive definitions. */ export function scope(aliases: Record, options?: ScopeOptions): TypeScope; /** Compile a named schema module whose definitions may reference each other. */ export function module>(definitions: definitions, options?: ScopeOptions): { [name in keyof definitions]: Type, InferDefIn>; }; type GenericParameterSpec = string | readonly [name: string, constraint: unknown]; /** Build a generic directly from an angle-bracket declaration. */ export function generic(parameters: `<${string}>`, definition: definition): Generic; /** Build a curried generic from named, optionally constrained parameters. */ export function generic(...parameters: readonly GenericParameterSpec[]): GenericBuilder; /** Untyped builder for runtime-assembled definitions. */ export function raw(def: unknown): BaseType; /** * Return a validation-only schema that emits `json` verbatim — even when * embedded in an object, array, or union. * * A `.toJsonSchema()` method override cannot survive nesting: a parent schema * emits each child's IR directly and never calls the child's method, so the * override silently disappears from the wire schema. This stores the override * on the IR instead. * * # Errors * * Throws when `schema` has a default or output-changing morph/pipe. A refine * can preserve validation and the input value, but silently discarding a * transformed output would violate the returned {@link Type}. */ export function withJsonSchema(schema: Type, json: Record): Type; export {}; } export interface ScopeOptions { jitless?: boolean; clone?: false | ((input: unknown) => unknown); divisor?: SchemaConfig; } /** Callable builder bound to one alias scope. */ export type ScopedBuilder = ((definition: definition) => FluentType, InferDefIn>) & typeof type; /** Named schema scope with scoped parsing, imports, and bound module exports. */ export interface TypeScope { readonly type: ScopedBuilder; readonly match: MatchParser; readonly json: Record; define(definition: definition): definition; resolve(name: string): BaseType; import(...names: readonly string[]): Record; export(...names: readonly string[]): Record; } /** Build a scope whose aliases resolve lazily, including recursive cycles. */ export declare function scope(aliases: Record, options?: ScopeOptions): TypeScope; export declare namespace scope { /** Preserve a scope definition's literal shape without constructing it. */ function define(definitions: aliases): aliases; } /** A schema whose output type is not statically known (`type.raw` results). */ export type BaseType = FluentType; /** * Minimal structural constraint matching any omptype schema. * * `FluentType`'s recursive fluent surface makes `T extends FluentType<...>` * checks descend until TypeScript's depth limiter reports spurious * incompatibilities, and its invariant input parameter rejects concrete * schemas outright. This interface exposes only the schema marker plus the * members generic helpers commonly need — method syntax keeps parameter * positions bivariant, and returns recurse shallowly through `AnyType`. */ export interface AnyType { (data: unknown): unknown; readonly [IR_BRAND]: true; readonly ir: IR; readonly infer: unknown; readonly inferIn: unknown; readonly hasDefault: boolean; readonly description?: string; run(data: unknown): unknown; assert(data: unknown): unknown; allows(data: unknown): boolean; toJsonSchema(options?: ToJsonSchemaOptions): Record; describe(description: string): AnyType; default(value: unknown): AnyType; or(def: Def): AnyType; and(def: Def): AnyType; pipe(fn: (data: never, ctx: NarrowContext) => unknown): AnyType; narrow(fn: (data: never, ctx: NarrowContext) => unknown): AnyType; array(): AnyType; } declare const submoduleType: unique symbol; type BoundAlias = value extends Submodule ? Submodule : FluentType; /** Exported aliases from a scope, each bound to that scope's resolver. */ export type Module> = { readonly [name in keyof aliases]: BoundAlias; }; /** A module nested under an alias rather than directly parseable as a schema. */ export type Submodule> = { readonly [submoduleType]?: aliases; } & { readonly [name in keyof aliases]: BoundAlias; }; /** A selected module export whose schemas retain access to the full scope. */ export type BoundModule, _allAliases extends Record = exports> = Module; /** Type-level view of a named scope. */ export type Scope> = TypeScope & { readonly t: aliases; }; /** `hasMorph` re-export for diagnostics/tooling. */ export { hasMorph };