import { Middleware } from "@oomfware/fetch-router"; import { StandardSchemaV1 } from "@standard-schema/spec"; //#region src/lib/types.d.ts type MaybePromise = T | Promise; type MaybeArray = T | T[]; /** * valid structure for form input data */ interface FormInput { [key: string]: MaybeArray; } /** * a validation issue with path information */ interface FormIssue { message: string; path: (string | number)[]; } /** * maps input types to their corresponding value types */ type InputTypeMap = { text: string; email: string; password: string; url: string; tel: string; search: string; number: number; range: number; date: string; 'datetime-local': string; time: string; month: string; week: string; color: string; checkbox: boolean | string[]; radio: string; file: File; 'file multiple': File[]; hidden: string; submit: string; button: string; reset: string; image: string; select: string; 'select multiple': string[]; }; /** * valid input types for a given value type */ type FieldInputType = { [K in keyof InputTypeMap]: T extends InputTypeMap[K] ? K : never }[keyof InputTypeMap]; /** * value argument for the `as()` method based on input type. * returns `[value]` tuple for types that require a value, or `[]` otherwise. * * note: separating `type` from `value` in the `.as()` signature ensures TypeScript * can properly infer the type parameter before resolving the value constraint. * using `...args: [type, value?]` with a union of tuple types causes inference issues. */ type AsValueArgs = Type extends 'checkbox' ? Value extends string[] ? [value: Value[number] | (string & {})] : [] : Type extends 'radio' | 'submit' | 'hidden' ? [value: Value | (string & {})] : []; interface CheckboxRadioProps { name: string; type: T; value: string; 'aria-invalid'?: 'true'; readonly checked: boolean; } interface FileProps { name: string; type: 'file'; 'aria-invalid'?: 'true'; } interface FileMultipleProps { name: string; type: 'file'; multiple: true; 'aria-invalid'?: 'true'; } interface SelectProps { name: string; multiple: false; 'aria-invalid'?: 'true'; readonly value: string; } interface SelectMultipleProps { name: string; multiple: true; 'aria-invalid'?: 'true'; readonly value: string[]; } interface TextProps { name: string; 'aria-invalid'?: 'true'; readonly value: string; } interface TypedInputProps { name: string; type: T; 'aria-invalid'?: 'true'; readonly value: string; } /** * input element properties based on input type */ type InputElementProps = T extends 'checkbox' | 'radio' ? CheckboxRadioProps : T extends 'file' ? FileProps : T extends 'file multiple' ? FileMultipleProps : T extends 'select' ? SelectProps : T extends 'select multiple' ? SelectMultipleProps : T extends 'text' ? TextProps : TypedInputProps; /** valid leaf value types for form fields */ type FormFieldValue = string | string[] | number | boolean | File | File[]; /** guard to prevent infinite recursion when T is unknown or has an index signature */ type WillRecurseIndefinitely = unknown extends T ? true : string extends keyof T ? true : false; /** base methods available on all form fields */ interface FieldMethods { /** get the current value */ value(): T | undefined; /** set the value */ set(value: T): T; /** get validation issues for this field */ issues(): FormIssue[] | undefined; } /** * leaf field type for primitive values with `.as()` method */ type FormFieldLeaf = FieldMethods & { /** * get props for binding to an input element. * returns an object with `name`, `aria-invalid`, and type-specific props. * * @example * ```ts * * * * * ``` */ as>(type: K$1, ...value: AsValueArgs): InputElementProps; }; /** * container field type for objects/arrays with `.allIssues()` method */ type FormFieldContainer = FieldMethods & { /** get all issues for this field and descendants */ allIssues(): FormIssue[] | undefined; }; /** * fallback field type when recursion would be infinite */ type UnknownField = FieldMethods & { /** get all issues for this field and descendants */ allIssues(): FormIssue[] | undefined; /** get props for an input element */ as>(type: K$1, ...value: AsValueArgs): InputElementProps; } & { [key: string | number]: UnknownField; }; type RecursiveFormFields = FormFieldContainer & { [key: string | number]: UnknownField; }; /** * recursive type to build form fields structure with proxy access. * preserves type information through the object hierarchy. */ type FormFields = WillRecurseIndefinitely extends true ? RecursiveFormFields : NonNullable extends string | number | boolean | File ? FormFieldLeaf> : [T] extends [string[] | File[]] ? FormFieldLeaf & { [K in number]: FormFieldLeaf } : [T] extends [Array] ? FormFieldContainer & { [K in number]: FormFields } : FormFieldContainer & { [K in keyof T]-?: FormFields }; //#endregion //#region src/lib/form.d.ts /** * the issue creator proxy passed to form callbacks. * allows creating field-specific validation issues via property access. * * @example * ```ts * form(schema, async (data, issue) => { * if (emailTaken(data.email)) { * invalid(issue.email('Email already in use')); * } * // nested fields: issue.user.profile.name('Invalid name') * // array fields: issue.items[0].name('Invalid item name') * }); * ``` */ type InvalidField = ((message: string) => StandardSchemaV1.Issue) & { [K in keyof T]-?: T[K] extends (infer U)[] ? InvalidFieldArray : T[K] extends object ? InvalidField : (message: string) => StandardSchemaV1.Issue }; type InvalidFieldArray = { [index: number]: T extends object ? InvalidField : (message: string) => StandardSchemaV1.Issue; } & ((message: string) => StandardSchemaV1.Issue); /** * symbol used to identify form instances. */ /** * options for configuring form behavior. */ interface FormOptions { /** * if true, preserves existing search params instead of replacing them. * @default false */ preserveParams?: boolean; } /** * the return value of a form() function. * can be spread onto a
element. */ interface Form { /** HTTP method */ readonly method: 'POST'; /** the form action URL */ readonly action: string; /** the handler result, if submission was successful */ readonly result: Output | undefined; /** access form fields using object notation */ readonly fields: FormFields; /** * returns a configured form with the given options. * @param options form configuration options * @returns a new form object with the options applied */ with(options: FormOptions): ConfiguredForm; } /** * creates a form without validation. */ declare function form(fn: () => MaybePromise): Form; /** * creates a form with unchecked input (no validation). */ declare function form(validate: 'unchecked', fn: (data: Input, issue: InvalidField) => MaybePromise): Form; /** * creates a form with Standard Schema validation. */ declare function form>, Output>(validate: Schema, fn: (data: StandardSchemaV1.InferOutput, issue: InvalidField>) => MaybePromise): Form, Output>; /** * configured form props for spreading onto a form element. */ interface ConfiguredForm { readonly method: 'POST'; readonly action: string; with(options: FormOptions): ConfiguredForm; } //#endregion //#region src/lib/middleware.d.ts /** * a record of form instances to register with the middleware. */ type FormDefinitions = Record>; /** * creates a forms middleware that registers forms and handles form submissions. * * @example * ```ts * import { form, forms } from '@oomfware/forms'; * import * as v from 'valibot'; * * const createUserForm = form( * v.object({ name: v.string(), password: v.string() }), * async (input, issue) => { * // handle form submission * }, * ); * * router.map(routes.admin, { * middleware: [forms({ createUserForm })], * action() { * return render( * * * * ); * }, * }); * ``` */ declare function forms(definitions: FormDefinitions): Middleware; //#endregion //#region src/lib/errors.d.ts /** * error thrown when form validation fails imperatively */ declare class ValidationError extends Error { issues: StandardSchemaV1.Issue[]; constructor(issues: StandardSchemaV1.Issue[]); } /** * use this to throw a validation error to imperatively fail form validation. * can be used in combination with `issue` passed to form actions to create field-specific issues. * * @example * ```ts * import { invalid, form } from '@oomfware/forms'; * import * as v from 'valibot'; * * export const login = form( * v.object({ name: v.string(), _password: v.string() }), * async ({ name, _password }, issue) => { * const success = tryLogin(name, _password); * if (!success) { * invalid('Incorrect username or password'); * } * * // ... * } * ); * ``` */ declare function invalid(...issues: (StandardSchemaV1.Issue | string)[]): never; /** * checks whether this is a validation error thrown by {@link invalid}. */ declare function isValidationError(e: unknown): e is ValidationError; //#endregion export { type ConfiguredForm, type Form, type FormInput, type FormIssue, type FormOptions, ValidationError, form, forms, invalid, isValidationError }; //# sourceMappingURL=index.d.mts.map