diff --git a/node_modules/@headlessui/react/LICENSE b/node_modules/@headlessui/react/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..634e7f20855319d08ba17e062386c3394708142c --- /dev/null +++ b/node_modules/@headlessui/react/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Tailwind Labs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/@headlessui/react/README.md b/node_modules/@headlessui/react/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b1d7528a90ce1d6056a011d25ed4ec46f4d39fe0 --- /dev/null +++ b/node_modules/@headlessui/react/README.md @@ -0,0 +1,30 @@ +

+ @headlessui/react +

+ +

+ A set of completely unstyled, fully accessible UI components for React, designed to integrate + beautifully with Tailwind CSS. +

+ +

+ Total Downloads + Latest Release + License +

+ +## Installation + +```sh +npm install @headlessui/react +``` + +## Documentation + +For full documentation, visit [headlessui.dev](https://headlessui.dev/react/menu). + +## Community + +For help, discussion about best practices, or feature ideas: + +[Discuss Headless UI on GitHub](https://github.com/tailwindlabs/headlessui/discussions) diff --git a/node_modules/@headlessui/react/dist/hooks/use-quick-release.js b/node_modules/@headlessui/react/dist/hooks/use-quick-release.js new file mode 100644 index 0000000000000000000000000000000000000000..7a8bfe41cc134927e8d5ec5a0b97fa173c1a8e26 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-quick-release.js @@ -0,0 +1 @@ +import{useRef as o}from"react";import*as E from'../utils/dom.js';import{useDocumentEvent as d}from'./use-document-event.js';var H=(e=>(e[e.Ignore=0]="Ignore",e[e.Select=1]="Select",e[e.Close=2]="Close",e))(H||{});const S={Ignore:{kind:0},Select:r=>({kind:1,target:r}),Close:{kind:2}},M=200,f=5;function L(r,{trigger:n,action:T,close:e,select:p}){let l=o(null),i=o(null),u=o(null);d(r&&n!==null,"pointerdown",t=>{E.isNode(t==null?void 0:t.target)&&n!=null&&n.contains(t.target)&&(i.current=t.x,u.current=t.y,l.current=t.timeStamp)}),d(r&&n!==null,"pointerup",t=>{var s,m;let c=l.current;if(c===null||(l.current=null,!E.isHTMLorSVGElement(t.target))||Math.abs(t.x-((s=i.current)!=null?s:t.x))M&&(p(a.target),e());break}case 2:{e();break}}},{capture:!0})}export{S as Action,L as useQuickRelease}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-refocusable-input.d.ts b/node_modules/@headlessui/react/dist/hooks/use-refocusable-input.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..edfc74c2d3e302954d21028c2d9e03cecb5dee76 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-refocusable-input.d.ts @@ -0,0 +1,7 @@ +/** + * The `useRefocusableInput` hook exposes a function to re-focus the input element. + * + * This hook will also keep the cursor position into account to make sure the + * cursor is placed at the correct position as-if we didn't loose focus at all. + */ +export declare function useRefocusableInput(input: HTMLInputElement | null): () => void; diff --git a/node_modules/@headlessui/react/dist/hooks/use-refocusable-input.js b/node_modules/@headlessui/react/dist/hooks/use-refocusable-input.js new file mode 100644 index 0000000000000000000000000000000000000000..f1c261452016efe4a6e44e2863f1aab825a3d581 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-refocusable-input.js @@ -0,0 +1 @@ +import{useRef as u}from"react";import*as r from'../utils/dom.js';import{isActiveElement as o}from'../utils/owner.js';import{useEvent as s}from'./use-event.js';import{useEventListener as c}from'./use-event-listener.js';function v(e){let l=u({value:"",selectionStart:null,selectionEnd:null});return c(e,"blur",n=>{let t=n.target;r.isHTMLInputElement(t)&&(l.current={value:t.value,selectionStart:t.selectionStart,selectionEnd:t.selectionEnd})}),s(()=>{if(!o(e)&&r.isHTMLInputElement(e)&&e.isConnected){if(e.focus({preventScroll:!0}),e.value!==l.current.value)e.setSelectionRange(e.value.length,e.value.length);else{let{selectionStart:n,selectionEnd:t}=l.current;n!==null&&t!==null&&e.setSelectionRange(n,t)}l.current={value:"",selectionStart:null,selectionEnd:null}}})}export{v as useRefocusableInput}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-resolve-button-type.d.ts b/node_modules/@headlessui/react/dist/hooks/use-resolve-button-type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c14088b20649b8015f2463fb6efbbf438234e28 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-resolve-button-type.d.ts @@ -0,0 +1,4 @@ +export declare function useResolveButtonType(props: { + type?: string; + as?: TTag; +}, element: HTMLElement | null): string | undefined; diff --git a/node_modules/@headlessui/react/dist/hooks/use-resolve-button-type.js b/node_modules/@headlessui/react/dist/hooks/use-resolve-button-type.js new file mode 100644 index 0000000000000000000000000000000000000000..e5b5408eaf59d63d12f10490db83d72741647ac8 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-resolve-button-type.js @@ -0,0 +1 @@ +import{useMemo as a}from"react";function e(t,u){return a(()=>{var n;if(t.type)return t.type;let r=(n=t.as)!=null?n:"button";if(typeof r=="string"&&r.toLowerCase()==="button"||(u==null?void 0:u.tagName)==="BUTTON"&&!u.hasAttribute("type"))return"button"},[t.type,t.as,u])}export{e as useResolveButtonType}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-resolved-tag.d.ts b/node_modules/@headlessui/react/dist/hooks/use-resolved-tag.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..edb9f2135e9abf9997ac950bbbd5c0bfe85362dc --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-resolved-tag.d.ts @@ -0,0 +1,10 @@ +/// +/** + * Resolve the actual rendered tag of a DOM node. If the `tag` provided is + * already a string we can use that as-is. This will happen when the `as` prop is + * not used or when it's used with a string value. + * + * If an actual component is used, then we need to do some more work because + * then we actually need to render the component to know what the tag name is. + */ +export declare function useResolvedTag(tag: T): readonly [string | undefined, (ref: any) => void]; diff --git a/node_modules/@headlessui/react/dist/hooks/use-resolved-tag.js b/node_modules/@headlessui/react/dist/hooks/use-resolved-tag.js new file mode 100644 index 0000000000000000000000000000000000000000..7b65097ee796c410142c971cd9d8f41f976b2b0f --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-resolved-tag.js @@ -0,0 +1 @@ +import{useCallback as r,useState as a}from"react";import*as i from'../utils/dom.js';function d(t){let e=typeof t=="string"?t:void 0,[s,o]=a(e);return[e!=null?e:s,r(n=>{e||i.isHTMLElement(n)&&o(n.tagName.toLowerCase())},[e])]}export{d as useResolvedTag}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-root-containers.d.ts b/node_modules/@headlessui/react/dist/hooks/use-root-containers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..683b2cd89ecbb30b450995dda2c0b735ebf54b5e --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-root-containers.d.ts @@ -0,0 +1,40 @@ +import React, { type MutableRefObject } from 'react'; +export declare function useRootContainers({ defaultContainers, portals, mainTreeNode, }?: { + defaultContainers?: (Element | null | MutableRefObject)[]; + portals?: MutableRefObject; + mainTreeNode?: Element | null; +}): { + resolveContainers: () => Element[]; + contains: (element: Element) => boolean; +}; +/** + * A provider for the main tree node. + * + * When a component is rendered in a `Portal`, it is no longer part of the main + * tree. This provider helps to find the main tree node and pass it along to the + * components that need it. + * + * The main tree node is used for features such as outside click behavior, where + * we allow clicks in 3rd party containers, but not in the parent of the "main + * tree". + * + * In case of a `Popover`, we can use the `PopoverButton` as a marker in the + * "main tree", the `PopoverPanel` can't be used because it could be rendered in + * a `Portal` (e.g. when using the `anchor` props). + * + * However, we can't use the `PopoverButton` when it's nested inside of another + * `Popover`'s `PopoverPanel` component if the parent `PopoverPanel` is + * rendered in a `Portal`. + * + * This is where the `MainTreeProvider` comes in. It will find the "main tree" + * node and pass it on. The top-level `PopoverButton` will be used as a marker + * in the "main tree" and nested `Popover` will use this button as well. + */ +export declare function MainTreeProvider({ children, node, }: { + children: React.ReactNode; + node?: Element | null; +}): React.JSX.Element; +/** + * Get the main tree node from context or fallback to the optionally provided node. + */ +export declare function useMainTreeNode(fallbackMainTreeNode?: Element | null): Element | null; diff --git a/node_modules/@headlessui/react/dist/hooks/use-root-containers.js b/node_modules/@headlessui/react/dist/hooks/use-root-containers.js new file mode 100644 index 0000000000000000000000000000000000000000..504e4002e8a5aacd28ab5b7baca65552d6f6ac7b --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-root-containers.js @@ -0,0 +1 @@ +import s,{createContext as h,useContext as b,useState as p}from"react";import{Hidden as M,HiddenFeatures as v}from'../internal/hidden.js';import*as f from'../utils/dom.js';import{getOwnerDocument as a}from'../utils/owner.js';import{useEvent as m}from'./use-event.js';function S({defaultContainers:l=[],portals:n,mainTreeNode:o}={}){let c=m(()=>{var r,u;let i=a(o),t=[];for(let e of l)e!==null&&(f.isElement(e)?t.push(e):"current"in e&&f.isElement(e.current)&&t.push(e.current));if(n!=null&&n.current)for(let e of n.current)t.push(e);for(let e of(r=i==null?void 0:i.querySelectorAll("html > *, body > *"))!=null?r:[])e!==document.body&&e!==document.head&&f.isElement(e)&&e.id!=="headlessui-portal-root"&&(o&&(e.contains(o)||e.contains((u=o==null?void 0:o.getRootNode())==null?void 0:u.host))||t.some(E=>e.contains(E))||t.push(e));return t});return{resolveContainers:c,contains:m(i=>c().some(t=>t.contains(i)))}}let d=h(null);function j({children:l,node:n}){let[o,c]=p(null),i=x(n!=null?n:o);return s.createElement(d.Provider,{value:i},l,i===null&&s.createElement(M,{features:v.Hidden,ref:t=>{var r,u;if(t){for(let e of(u=(r=a(t))==null?void 0:r.querySelectorAll("html > *, body > *"))!=null?u:[])if(e!==document.body&&e!==document.head&&f.isElement(e)&&e!=null&&e.contains(t)){c(e);break}}}}))}function x(l=null){var n;return(n=b(d))!=null?n:l}export{j as MainTreeProvider,x as useMainTreeNode,S as useRootContainers}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-scroll-lock.d.ts b/node_modules/@headlessui/react/dist/hooks/use-scroll-lock.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..72908fdc1ce3289f91e73e582f20b620dd896790 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-scroll-lock.d.ts @@ -0,0 +1 @@ +export declare function useScrollLock(enabled: boolean, ownerDocument: Document | null, resolveAllowedContainers?: () => Element[]): void; diff --git a/node_modules/@headlessui/react/dist/hooks/use-scroll-lock.js b/node_modules/@headlessui/react/dist/hooks/use-scroll-lock.js new file mode 100644 index 0000000000000000000000000000000000000000..253cd5eec78abe48f0af3b84fc10e1ecd914b3be --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-scroll-lock.js @@ -0,0 +1 @@ +import{useDocumentOverflowLockedEffect as l}from'./document-overflow/use-document-overflow.js';import{useIsTopLayer as m}from'./use-is-top-layer.js';function f(e,c,n=()=>[document.body]){let r=m(e,"scroll-lock");l(r,c,t=>{var o;return{containers:[...(o=t.containers)!=null?o:[],n]}})}export{f as useScrollLock}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-server-handoff-complete.d.ts b/node_modules/@headlessui/react/dist/hooks/use-server-handoff-complete.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82ff255c9e14fa28b66f2be07600a42cc79ba192 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-server-handoff-complete.d.ts @@ -0,0 +1 @@ +export declare function useServerHandoffComplete(): boolean; diff --git a/node_modules/@headlessui/react/dist/hooks/use-server-handoff-complete.js b/node_modules/@headlessui/react/dist/hooks/use-server-handoff-complete.js new file mode 100644 index 0000000000000000000000000000000000000000..dc25c3c3dea8ab725d1ca1f88b51d9aae4d173c7 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-server-handoff-complete.js @@ -0,0 +1 @@ +import*as t from"react";import{env as f}from'../utils/env.js';function s(){let r=typeof document=="undefined";return"useSyncExternalStore"in t?(o=>o.useSyncExternalStore)(t)(()=>()=>{},()=>!1,()=>!r):!1}function l(){let r=s(),[e,n]=t.useState(f.isHandoffComplete);return e&&f.isHandoffComplete===!1&&n(!1),t.useEffect(()=>{e!==!0&&n(!0)},[e]),t.useEffect(()=>f.handoff(),[]),r?!1:e}export{l as useServerHandoffComplete}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-slot.d.ts b/node_modules/@headlessui/react/dist/hooks/use-slot.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73648318ee8d693ba6870c8ddb086c112d6dc23d --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-slot.d.ts @@ -0,0 +1 @@ +export declare function useSlot>(object: ExpectedType): ExpectedType; diff --git a/node_modules/@headlessui/react/dist/hooks/use-slot.js b/node_modules/@headlessui/react/dist/hooks/use-slot.js new file mode 100644 index 0000000000000000000000000000000000000000..44c234ab8f6c9dfaeaf0e46957efd56f5efff4e6 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-slot.js @@ -0,0 +1 @@ +import{useMemo as t}from"react";function n(e){return t(()=>e,Object.values(e))}export{n as useSlot}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-store.d.ts b/node_modules/@headlessui/react/dist/hooks/use-store.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..badd43a7e73d7173c5ad4a5d1394b64bdd517bb6 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-store.d.ts @@ -0,0 +1,2 @@ +import type { Store } from '../utils/store.js'; +export declare function useStore(store: Store): T; diff --git a/node_modules/@headlessui/react/dist/hooks/use-store.js b/node_modules/@headlessui/react/dist/hooks/use-store.js new file mode 100644 index 0000000000000000000000000000000000000000..4ee878099c5c7da85166b00571a0e1552cf7bdf6 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-store.js @@ -0,0 +1 @@ +import{useSyncExternalStore as e}from"react";function o(t){return e(t.subscribe,t.getSnapshot,t.getSnapshot)}export{o as useStore}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-sync-refs.d.ts b/node_modules/@headlessui/react/dist/hooks/use-sync-refs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0bfe042df0fd4ccfd247e4cdf2050201bf67b539 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-sync-refs.d.ts @@ -0,0 +1,5 @@ +/// +export declare function optionalRef(cb: (ref: T) => void, isOptional?: boolean): ((ref: T) => void) & { + [x: symbol]: boolean; +}; +export declare function useSyncRefs(...refs: (React.MutableRefObject | ((instance: TType) => void) | null)[]): ((value: TType) => void) | undefined; diff --git a/node_modules/@headlessui/react/dist/hooks/use-sync-refs.js b/node_modules/@headlessui/react/dist/hooks/use-sync-refs.js new file mode 100644 index 0000000000000000000000000000000000000000..67c31a8f0d0c83cd1a9e7b5dfaff3def9e8799ef --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-sync-refs.js @@ -0,0 +1 @@ +import{useEffect as l,useRef as i}from"react";import{useEvent as r}from'./use-event.js';let u=Symbol();function T(t,n=!0){return Object.assign(t,{[u]:n})}function y(...t){let n=i(t);l(()=>{n.current=t},[t]);let c=r(e=>{for(let o of n.current)o!=null&&(typeof o=="function"?o(e):o.current=e)});return t.every(e=>e==null||(e==null?void 0:e[u]))?void 0:c}export{T as optionalRef,y as useSyncRefs}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-tab-direction.d.ts b/node_modules/@headlessui/react/dist/hooks/use-tab-direction.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce42110b47a0582cb9964d604c99c485734d2432 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-tab-direction.d.ts @@ -0,0 +1,6 @@ +/// +export declare enum Direction { + Forwards = 0, + Backwards = 1 +} +export declare function useTabDirection(): import("react").MutableRefObject; diff --git a/node_modules/@headlessui/react/dist/hooks/use-tab-direction.js b/node_modules/@headlessui/react/dist/hooks/use-tab-direction.js new file mode 100644 index 0000000000000000000000000000000000000000..f7ceaee10bf1a3c590cefd3e81a656bfaebbc53f --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-tab-direction.js @@ -0,0 +1 @@ +import{useRef as o}from"react";import{useWindowEvent as t}from'./use-window-event.js';var a=(r=>(r[r.Forwards=0]="Forwards",r[r.Backwards=1]="Backwards",r))(a||{});function u(){let e=o(0);return t(!0,"keydown",r=>{r.key==="Tab"&&(e.current=r.shiftKey?1:0)},!0),e}export{a as Direction,u as useTabDirection}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-text-value.d.ts b/node_modules/@headlessui/react/dist/hooks/use-text-value.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a56f3c94c18705fd2a93020e74b30a2ff2cb5a5 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-text-value.d.ts @@ -0,0 +1,2 @@ +import { type MutableRefObject } from 'react'; +export declare function useTextValue(element: MutableRefObject): () => string; diff --git a/node_modules/@headlessui/react/dist/hooks/use-text-value.js b/node_modules/@headlessui/react/dist/hooks/use-text-value.js new file mode 100644 index 0000000000000000000000000000000000000000..5026bf0838a780fc8fcc68fc1399d37e4864634c --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-text-value.js @@ -0,0 +1 @@ +import{useRef as l}from"react";import{getTextValue as i}from'../utils/get-text-value.js';import{useEvent as o}from'./use-event.js';function s(c){let t=l(""),r=l("");return o(()=>{let e=c.current;if(!e)return"";let u=e.innerText;if(t.current===u)return r.current;let n=i(e).trim().toLowerCase();return t.current=u,r.current=n,n})}export{s as useTextValue}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-tracked-pointer.d.ts b/node_modules/@headlessui/react/dist/hooks/use-tracked-pointer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..749dbf33feb3c2e57a1b5c5999b485085dd37c0b --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-tracked-pointer.d.ts @@ -0,0 +1,4 @@ +export declare function useTrackedPointer(): { + wasMoved(evt: PointerEvent): boolean; + update(evt: PointerEvent): void; +}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-tracked-pointer.js b/node_modules/@headlessui/react/dist/hooks/use-tracked-pointer.js new file mode 100644 index 0000000000000000000000000000000000000000..442fe84bda5ef5695b78b783cff8089c19570622 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-tracked-pointer.js @@ -0,0 +1 @@ +import{useRef as o}from"react";function t(e){return[e.screenX,e.screenY]}function u(){let e=o([-1,-1]);return{wasMoved(r){let n=t(r);return e.current[0]===n[0]&&e.current[1]===n[1]?!1:(e.current=n,!0)},update(r){e.current=t(r)}}}export{u as useTrackedPointer}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-transition.d.ts b/node_modules/@headlessui/react/dist/hooks/use-transition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd1a6ac98ecd9087ec85efad69beac076567149d --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-transition.d.ts @@ -0,0 +1,12 @@ +type TransitionData = { + closed?: boolean; + enter?: boolean; + leave?: boolean; + transition?: boolean; +}; +export declare function transitionDataAttributes(data: TransitionData): Record; +export declare function useTransition(enabled: boolean, element: HTMLElement | null, show: boolean, events?: { + start?: (show: boolean) => void; + end?: (show: boolean) => void; +}): [visible: boolean, data: TransitionData]; +export {}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-transition.js b/node_modules/@headlessui/react/dist/hooks/use-transition.js new file mode 100644 index 0000000000000000000000000000000000000000..034297154aa4f3f8197e12440766cb0633c63524 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-transition.js @@ -0,0 +1,2 @@ +var T,S;import{useRef as c,useState as b}from"react";import{disposables as m}from'../utils/disposables.js';import{useDisposables as g}from'./use-disposables.js';import{useFlags as y}from'./use-flags.js';import{useIsoMorphicEffect as L}from'./use-iso-morphic-effect.js';typeof process!="undefined"&&typeof globalThis!="undefined"&&typeof Element!="undefined"&&((T=process==null?void 0:process.env)==null?void 0:T["NODE_ENV"])==="test"&&typeof((S=Element==null?void 0:Element.prototype)==null?void 0:S.getAnimations)=="undefined"&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` +`)),[]});var A=(i=>(i[i.None=0]="None",i[i.Closed=1]="Closed",i[i.Enter=2]="Enter",i[i.Leave=4]="Leave",i))(A||{});function x(e){let r={};for(let t in e)e[t]===!0&&(r[`data-${t}`]="");return r}function N(e,r,t,n){let[i,a]=b(t),{hasFlag:s,addFlag:o,removeFlag:l}=y(e&&i?3:0),u=c(!1),f=c(!1),E=g();return L(()=>{var d;if(e){if(t&&a(!0),!r){t&&o(3);return}return(d=n==null?void 0:n.start)==null||d.call(n,t),C(r,{inFlight:u,prepare(){f.current?f.current=!1:f.current=u.current,u.current=!0,!f.current&&(t?(o(3),l(4)):(o(4),l(2)))},run(){f.current?t?(l(3),o(4)):(l(4),o(3)):t?l(1):o(1)},done(){var p;f.current&&D(r)||(u.current=!1,l(7),t||a(!1),(p=n==null?void 0:n.end)==null||p.call(n,t))}})}},[e,t,r,E]),e?[i,{closed:s(1),enter:s(2),leave:s(4),transition:s(2)||s(4)}]:[t,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function C(e,{prepare:r,run:t,done:n,inFlight:i}){let a=m();return j(e,{prepare:r,inFlight:i}),a.nextFrame(()=>{t(),a.requestAnimationFrame(()=>{a.add(M(e,n))})}),a.dispose}function M(e,r){var a,s;let t=m();if(!e)return t.dispose;let n=!1;t.add(()=>{n=!0});let i=(s=(a=e.getAnimations)==null?void 0:a.call(e).filter(o=>o instanceof CSSTransition))!=null?s:[];return i.length===0?(r(),t.dispose):(Promise.allSettled(i.map(o=>o.finished)).then(()=>{n||r()}),t.dispose)}function j(e,{inFlight:r,prepare:t}){if(r!=null&&r.current){t();return}let n=e.style.transition;e.style.transition="none",t(),e.offsetHeight,e.style.transition=n}function D(e){var t,n;return((n=(t=e.getAnimations)==null?void 0:t.call(e))!=null?n:[]).some(i=>i instanceof CSSTransition&&i.playState!=="finished")}export{x as transitionDataAttributes,N as useTransition}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-tree-walker.d.ts b/node_modules/@headlessui/react/dist/hooks/use-tree-walker.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2e2130b5072c48071fed9c89a0c01ff9b0bf45a --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-tree-walker.d.ts @@ -0,0 +1,7 @@ +type AcceptNode = (node: HTMLElement) => typeof NodeFilter.FILTER_ACCEPT | typeof NodeFilter.FILTER_SKIP | typeof NodeFilter.FILTER_REJECT; +export declare function useTreeWalker(enabled: boolean, { container, accept, walk, }: { + container: HTMLElement | null; + accept: AcceptNode; + walk(node: HTMLElement): void; +}): void; +export {}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-tree-walker.js b/node_modules/@headlessui/react/dist/hooks/use-tree-walker.js new file mode 100644 index 0000000000000000000000000000000000000000..8c751d5417bf28053222bfa30115502120b27714 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-tree-walker.js @@ -0,0 +1 @@ +import{useEffect as T,useRef as E}from"react";import{getOwnerDocument as d}from'../utils/owner.js';import{useIsoMorphicEffect as N}from'./use-iso-morphic-effect.js';function F(c,{container:e,accept:t,walk:r}){let o=E(t),l=E(r);T(()=>{o.current=t,l.current=r},[t,r]),N(()=>{if(!e||!c)return;let n=d(e);if(!n)return;let f=o.current,p=l.current,i=Object.assign(m=>f(m),{acceptNode:f}),u=n.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,i,!1);for(;u.nextNode();)p(u.currentNode)},[e,c,o,l])}export{F as useTreeWalker}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-watch.d.ts b/node_modules/@headlessui/react/dist/hooks/use-watch.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3acfb82b603bdb325eb2e8864da3ce7ca1c2adb3 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-watch.d.ts @@ -0,0 +1 @@ +export declare function useWatch(cb: (newValues: [...T], oldValues: [...T]) => void | (() => void), dependencies: [...T]): void; diff --git a/node_modules/@headlessui/react/dist/hooks/use-watch.js b/node_modules/@headlessui/react/dist/hooks/use-watch.js new file mode 100644 index 0000000000000000000000000000000000000000..c25cf4b04a766156c28e2773b1afba3899c8e5f4 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-watch.js @@ -0,0 +1 @@ +import{useEffect as f,useRef as s}from"react";import{useEvent as i}from'./use-event.js';function m(u,t){let e=s([]),r=i(u);f(()=>{let o=[...e.current];for(let[a,l]of t.entries())if(e.current[a]!==l){let n=r(t,o);return e.current=t,n}},[r,...t])}export{m as useWatch}; diff --git a/node_modules/@headlessui/react/dist/hooks/use-window-event.d.ts b/node_modules/@headlessui/react/dist/hooks/use-window-event.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..636e0fbb93d47089039df1f935f74d872efed669 --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-window-event.d.ts @@ -0,0 +1 @@ +export declare function useWindowEvent(enabled: boolean, type: TType, listener: (ev: WindowEventMap[TType]) => any, options?: boolean | AddEventListenerOptions): void; diff --git a/node_modules/@headlessui/react/dist/hooks/use-window-event.js b/node_modules/@headlessui/react/dist/hooks/use-window-event.js new file mode 100644 index 0000000000000000000000000000000000000000..deded2a6e2b08c48e0746e39b713032e92360e1a --- /dev/null +++ b/node_modules/@headlessui/react/dist/hooks/use-window-event.js @@ -0,0 +1 @@ +import{useEffect as a}from"react";import{useLatestValue as f}from'./use-latest-value.js';function s(t,e,o,n){let i=f(o);a(()=>{if(!t)return;function r(d){i.current(d)}return window.addEventListener(e,r,n),()=>window.removeEventListener(e,r,n)},[t,e,n])}export{s as useWindowEvent}; diff --git a/node_modules/@headlessui/react/dist/index.cjs b/node_modules/@headlessui/react/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..92466f45072d9dab91287dddaa6aaaff2060c806 --- /dev/null +++ b/node_modules/@headlessui/react/dist/index.cjs @@ -0,0 +1,7 @@ +'use strict' + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./headlessui.prod.cjs') +} else { + module.exports = require('./headlessui.dev.cjs') +} diff --git a/node_modules/@headlessui/react/dist/index.d.cts b/node_modules/@headlessui/react/dist/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..5b62317c78b50a326d6881a0ec5acd1fceab6bbf --- /dev/null +++ b/node_modules/@headlessui/react/dist/index.d.cts @@ -0,0 +1,25 @@ +export * from './components/button/button'; +export * from './components/checkbox/checkbox'; +export * from './components/close-button/close-button'; +export * from './components/combobox/combobox'; +export * from './components/data-interactive/data-interactive'; +export { Description, type DescriptionProps } from './components/description/description'; +export * from './components/dialog/dialog'; +export * from './components/disclosure/disclosure'; +export * from './components/field/field'; +export * from './components/fieldset/fieldset'; +export * from './components/focus-trap/focus-trap'; +export * from './components/input/input'; +export { Label, type LabelProps } from './components/label/label'; +export * from './components/legend/legend'; +export * from './components/listbox/listbox'; +export * from './components/menu/menu'; +export * from './components/popover/popover'; +export { Portal } from './components/portal/portal'; +export * from './components/radio-group/radio-group'; +export * from './components/select/select'; +export * from './components/switch/switch'; +export * from './components/tabs/tabs'; +export * from './components/textarea/textarea'; +export { useClose } from './internal/close-provider'; +export * from './components/transition/transition'; diff --git a/node_modules/@headlessui/react/dist/index.d.ts b/node_modules/@headlessui/react/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d094b27ea5f0964faaef5a46ef2a17d5f771a26f --- /dev/null +++ b/node_modules/@headlessui/react/dist/index.d.ts @@ -0,0 +1,25 @@ +export * from './components/button/button.js'; +export * from './components/checkbox/checkbox.js'; +export * from './components/close-button/close-button.js'; +export * from './components/combobox/combobox.js'; +export * from './components/data-interactive/data-interactive.js'; +export { Description, type DescriptionProps } from './components/description/description.js'; +export * from './components/dialog/dialog.js'; +export * from './components/disclosure/disclosure.js'; +export * from './components/field/field.js'; +export * from './components/fieldset/fieldset.js'; +export * from './components/focus-trap/focus-trap.js'; +export * from './components/input/input.js'; +export { Label, type LabelProps } from './components/label/label.js'; +export * from './components/legend/legend.js'; +export * from './components/listbox/listbox.js'; +export * from './components/menu/menu.js'; +export * from './components/popover/popover.js'; +export { Portal } from './components/portal/portal.js'; +export * from './components/radio-group/radio-group.js'; +export * from './components/select/select.js'; +export * from './components/switch/switch.js'; +export * from './components/tabs/tabs.js'; +export * from './components/textarea/textarea.js'; +export { useClose } from './internal/close-provider.js'; +export * from './components/transition/transition.js'; diff --git a/node_modules/@headlessui/react/dist/index.js b/node_modules/@headlessui/react/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9898e27d59a18aa89ed95ad27c496b00845c1d51 --- /dev/null +++ b/node_modules/@headlessui/react/dist/index.js @@ -0,0 +1 @@ +export*from'./components/button/button.js';export*from'./components/checkbox/checkbox.js';export*from'./components/close-button/close-button.js';export*from'./components/combobox/combobox.js';export*from'./components/data-interactive/data-interactive.js';import{Description as x}from'./components/description/description.js';export*from'./components/dialog/dialog.js';export*from'./components/disclosure/disclosure.js';export*from'./components/field/field.js';export*from'./components/fieldset/fieldset.js';export*from'./components/focus-trap/focus-trap.js';export*from'./components/input/input.js';import{Label as n}from'./components/label/label.js';export*from'./components/legend/legend.js';export*from'./components/listbox/listbox.js';export*from'./components/menu/menu.js';export*from'./components/popover/popover.js';import{Portal as d}from'./components/portal/portal.js';export*from'./components/radio-group/radio-group.js';export*from'./components/select/select.js';export*from'./components/switch/switch.js';export*from'./components/tabs/tabs.js';export*from'./components/textarea/textarea.js';import{useClose as w}from'./internal/close-provider.js';export*from'./components/transition/transition.js';export{x as Description,n as Label,d as Portal,w as useClose}; diff --git a/node_modules/@headlessui/react/dist/internal/close-provider.d.ts b/node_modules/@headlessui/react/dist/internal/close-provider.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c80188c92eb43b75cee0612c03f5354183c792ee --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/close-provider.d.ts @@ -0,0 +1,5 @@ +import React from 'react'; +export declare function useClose(): () => void; +export declare function CloseProvider({ value, children }: React.PropsWithChildren<{ + value: () => void; +}>): React.JSX.Element; diff --git a/node_modules/@headlessui/react/dist/internal/close-provider.js b/node_modules/@headlessui/react/dist/internal/close-provider.js new file mode 100644 index 0000000000000000000000000000000000000000..99c48cacdad753a19d88a2d3eeb4eda0bb6465c4 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/close-provider.js @@ -0,0 +1 @@ +"use client";import r,{createContext as n,useContext as i}from"react";let e=n(()=>{});function u(){return i(e)}function C({value:t,children:o}){return r.createElement(e.Provider,{value:t},o)}export{C as CloseProvider,u as useClose}; diff --git a/node_modules/@headlessui/react/dist/internal/disabled.d.ts b/node_modules/@headlessui/react/dist/internal/disabled.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8219d32f0fd8d84a96a3732e19bd5c75c9e3614e --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/disabled.d.ts @@ -0,0 +1,5 @@ +import React from 'react'; +export declare function useDisabled(): boolean | undefined; +export declare function DisabledProvider({ value, children, }: React.PropsWithChildren<{ + value?: boolean; +}>): React.JSX.Element; diff --git a/node_modules/@headlessui/react/dist/internal/disabled.js b/node_modules/@headlessui/react/dist/internal/disabled.js new file mode 100644 index 0000000000000000000000000000000000000000..2ed2b2bcdce3d0baedd270aa1a4514e5f3a39fd0 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/disabled.js @@ -0,0 +1 @@ +import n,{createContext as r,useContext as i}from"react";let e=r(void 0);function a(){return i(e)}function l({value:t,children:o}){return n.createElement(e.Provider,{value:t},o)}export{l as DisabledProvider,a as useDisabled}; diff --git a/node_modules/@headlessui/react/dist/internal/floating.d.ts b/node_modules/@headlessui/react/dist/internal/floating.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6bfb882f449174d1f738ece21a225e3a8d8a1703 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/floating.d.ts @@ -0,0 +1,52 @@ +import { type InnerProps } from '@floating-ui/react'; +import * as React from 'react'; +type Align = 'start' | 'end'; +type Placement = 'top' | 'right' | 'bottom' | 'left'; +type AnchorTo = `${Placement}` | `${Placement} ${Align}`; +type AnchorToWithSelection = `${Placement | 'selection'}` | `${Placement | 'selection'} ${Align}`; +type BaseAnchorProps = { + /** + * The `gap` is the space between the trigger and the panel. + */ + gap: number | string; + /** + * The `offset` is the amount the panel should be nudged from its original position. + */ + offset: number | string; + /** + * The `padding` is the minimum space between the panel and the viewport. + */ + padding: number | string; +}; +export type AnchorProps = false | AnchorTo | Partial; +export type AnchorPropsWithSelection = false | AnchorToWithSelection | Partial; +export type InternalFloatingPanelProps = Partial<{ + inner: { + listRef: InnerProps['listRef']; + index: InnerProps['index']; + }; +}>; +export declare function useResolvedAnchor(anchor?: T): Exclude | null; +export declare function useFloatingReference(): ((node: import("@floating-ui/react-dom").ReferenceType | null) => void) & ((node: any) => void); +export declare function useFloatingReferenceProps(): (userProps?: React.HTMLProps | undefined) => Record; +export declare function useFloatingPanelProps(): (userProps?: React.HTMLProps | undefined) => Record & { + 'data-anchor': AnchorToWithSelection | undefined; +}; +export declare function useFloatingPanel(placement?: (AnchorPropsWithSelection & InternalFloatingPanelProps) | null): readonly [((node: HTMLElement | null) => void) & ((node: HTMLElement | null) => void), React.CSSProperties | undefined]; +export declare function FloatingProvider({ children, enabled, }: { + children: React.ReactNode; + enabled?: boolean; +}): React.JSX.Element; +export {}; diff --git a/node_modules/@headlessui/react/dist/internal/floating.js b/node_modules/@headlessui/react/dist/internal/floating.js new file mode 100644 index 0000000000000000000000000000000000000000..46b9710a645241fab584fb9ef60d0c13e9c1427a --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/floating.js @@ -0,0 +1 @@ +import{autoUpdate as Z,flip as ee,inner as te,offset as ne,shift as re,size as le,useFloating as oe,useInnerOffset as ie,useInteractions as se}from"@floating-ui/react";import*as j from"react";import{createContext as _,useCallback as ae,useContext as T,useMemo as R,useRef as ue,useState as v}from"react";import{useDisposables as fe}from'../hooks/use-disposables.js';import{useEvent as z}from'../hooks/use-event.js';import{useIsoMorphicEffect as C}from'../hooks/use-iso-morphic-effect.js';import*as pe from'../utils/dom.js';let y=_({styles:void 0,setReference:()=>{},setFloating:()=>{},getReferenceProps:()=>({}),getFloatingProps:()=>({}),slot:{}});y.displayName="FloatingContext";let $=_(null);$.displayName="PlacementContext";function ye(e){return R(()=>e?typeof e=="string"?{to:e}:e:null,[e])}function Fe(){return T(y).setReference}function be(){return T(y).getReferenceProps}function Te(){let{getFloatingProps:e,slot:t}=T(y);return ae((...n)=>Object.assign({},e(...n),{"data-anchor":t.anchor}),[e,t])}function Re(e=null){e===!1&&(e=null),typeof e=="string"&&(e={to:e});let t=T($),n=R(()=>e,[JSON.stringify(e,(l,o)=>{var u;return(u=o==null?void 0:o.outerHTML)!=null?u:o})]);C(()=>{t==null||t(n!=null?n:null)},[t,n]);let r=T(y);return R(()=>[r.setFloating,e?r.styles:{}],[r.setFloating,e,r.styles])}let D=4;function Ae({children:e,enabled:t=!0}){let[n,r]=v(null),[l,o]=v(0),u=ue(null),[f,s]=v(null);ce(f);let i=t&&n!==null&&f!==null,{to:F="bottom",gap:E=0,offset:A=0,padding:c=0,inner:h}=ge(n,f),[a,p="center"]=F.split(" ");C(()=>{i&&o(0)},[i]);let{refs:b,floatingStyles:S,context:g}=oe({open:i,placement:a==="selection"?p==="center"?"bottom":`bottom-${p}`:p==="center"?`${a}`:`${a}-${p}`,strategy:"absolute",transform:!1,middleware:[ne({mainAxis:a==="selection"?0:E,crossAxis:A}),re({padding:c}),a!=="selection"&&ee({padding:c}),a==="selection"&&h?te({...h,padding:c,overflowRef:u,offset:l,minItemsVisible:D,referenceOverflowThreshold:c,onFallbackChange(P){var L,N;if(!P)return;let d=g.elements.floating;if(!d)return;let M=parseFloat(getComputedStyle(d).scrollPaddingBottom)||0,I=Math.min(D,d.childElementCount),W=0,B=0;for(let m of(N=(L=g.elements.floating)==null?void 0:L.childNodes)!=null?N:[])if(pe.isHTMLElement(m)){let x=m.offsetTop,k=x+m.clientHeight+M,H=d.scrollTop,U=H+d.clientHeight;if(x>=H&&k<=U)I--;else{B=Math.max(0,Math.min(k,U)-Math.max(x,H)),W=m.clientHeight;break}}I>=1&&o(m=>{let x=W*I-B+M;return m>=x?m:x})}}):null,le({padding:c,apply({availableWidth:P,availableHeight:d,elements:M}){Object.assign(M.floating.style,{overflow:"auto",maxWidth:`${P}px`,maxHeight:`min(var(--anchor-max-height, 100vh), ${d}px)`})}})].filter(Boolean),whileElementsMounted:Z}),[w=a,V=p]=g.placement.split("-");a==="selection"&&(w="selection");let G=R(()=>({anchor:[w,V].filter(Boolean).join(" ")}),[w,V]),K=ie(g,{overflowRef:u,onChange:o}),{getReferenceProps:Q,getFloatingProps:X}=se([K]),Y=z(P=>{s(P),b.setFloating(P)});return j.createElement($.Provider,{value:r},j.createElement(y.Provider,{value:{setFloating:Y,setReference:b.setReference,styles:S,getReferenceProps:Q,getFloatingProps:X,slot:G}},e))}function ce(e){C(()=>{if(!e)return;let t=new MutationObserver(()=>{let n=window.getComputedStyle(e).maxHeight,r=parseFloat(n);if(isNaN(r))return;let l=parseInt(n);isNaN(l)||r!==l&&(e.style.maxHeight=`${Math.ceil(r)}px`)});return t.observe(e,{attributes:!0,attributeFilter:["style"]}),()=>{t.disconnect()}},[e])}function ge(e,t){var o,u,f;let n=O((o=e==null?void 0:e.gap)!=null?o:"var(--anchor-gap, 0)",t),r=O((u=e==null?void 0:e.offset)!=null?u:"var(--anchor-offset, 0)",t),l=O((f=e==null?void 0:e.padding)!=null?f:"var(--anchor-padding, 0)",t);return{...e,gap:n,offset:r,padding:l}}function O(e,t,n=void 0){let r=fe(),l=z((s,i)=>{if(s==null)return[n,null];if(typeof s=="number")return[s,null];if(typeof s=="string"){if(!i)return[n,null];let F=J(s,i);return[F,E=>{let A=q(s);{let c=A.map(h=>window.getComputedStyle(i).getPropertyValue(h));r.requestAnimationFrame(function h(){r.nextFrame(h);let a=!1;for(let[b,S]of A.entries()){let g=window.getComputedStyle(i).getPropertyValue(S);if(c[b]!==g){c[b]=g,a=!0;break}}if(!a)return;let p=J(s,i);F!==p&&(E(p),F=p)})}return r.dispose}]}return[n,null]}),o=R(()=>l(e,t)[0],[e,t]),[u=o,f]=v();return C(()=>{let[s,i]=l(e,t);if(f(s),!!i)return i(f)},[e,t]),u}function q(e){let t=/var\((.*)\)/.exec(e);if(t){let n=t[1].indexOf(",");if(n===-1)return[t[1]];let r=t[1].slice(0,n).trim(),l=t[1].slice(n+1).trim();return l?[r,...q(l)]:[r]}return[]}function J(e,t){let n=document.createElement("div");t.appendChild(n),n.style.setProperty("margin-top","0px","important"),n.style.setProperty("margin-top",e,"important");let r=parseFloat(window.getComputedStyle(n).marginTop)||0;return t.removeChild(n),r}export{Ae as FloatingProvider,Re as useFloatingPanel,Te as useFloatingPanelProps,Fe as useFloatingReference,be as useFloatingReferenceProps,ye as useResolvedAnchor}; diff --git a/node_modules/@headlessui/react/dist/internal/focus-sentinel.d.ts b/node_modules/@headlessui/react/dist/internal/focus-sentinel.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ddde9fcab16201c45990c9ba8f84aa55e10d183 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/focus-sentinel.d.ts @@ -0,0 +1,6 @@ +import React from 'react'; +interface FocusSentinelProps { + onFocus(): boolean; +} +export declare function FocusSentinel({ onFocus }: FocusSentinelProps): React.JSX.Element | null; +export {}; diff --git a/node_modules/@headlessui/react/dist/internal/focus-sentinel.js b/node_modules/@headlessui/react/dist/internal/focus-sentinel.js new file mode 100644 index 0000000000000000000000000000000000000000..bc7b50c9521468967e65b8ab661115e88962e87d --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/focus-sentinel.js @@ -0,0 +1 @@ +import s,{useState as c}from"react";import{useIsMounted as m}from'../hooks/use-is-mounted.js';import{Hidden as f,HiddenFeatures as l}from'./hidden.js';function b({onFocus:n}){let[r,o]=c(!0),u=m();return r?s.createElement(f,{as:"button",type:"button",features:l.Focusable,onFocus:a=>{a.preventDefault();let e,i=50;function t(){if(i--<=0){e&&cancelAnimationFrame(e);return}if(n()){if(cancelAnimationFrame(e),!u.current)return;o(!1);return}e=requestAnimationFrame(t)}e=requestAnimationFrame(t)}}):null}export{b as FocusSentinel}; diff --git a/node_modules/@headlessui/react/dist/internal/form-fields.d.ts b/node_modules/@headlessui/react/dist/internal/form-fields.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5dc1691bcaecc629b51147de67f0861e42d5f785 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/form-fields.d.ts @@ -0,0 +1,10 @@ +import React from 'react'; +export declare function FormFieldsProvider(props: React.PropsWithChildren<{}>): React.JSX.Element; +export declare function HoistFormFields({ children }: React.PropsWithChildren<{}>): React.JSX.Element | null; +export declare function FormFields({ data, form: formId, disabled, onReset, overrides, }: { + data: Record; + overrides?: Record; + form?: string; + disabled?: boolean; + onReset?: (e: Event) => void; +}): React.JSX.Element; diff --git a/node_modules/@headlessui/react/dist/internal/form-fields.js b/node_modules/@headlessui/react/dist/internal/form-fields.js new file mode 100644 index 0000000000000000000000000000000000000000..232c3b9cde663d2e1a1efc44b83715142b6fdd7f --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/form-fields.js @@ -0,0 +1 @@ +import o,{createContext as H,useContext as E,useEffect as m,useState as u}from"react";import{createPortal as g}from"react-dom";import{useDisposables as h}from'../hooks/use-disposables.js';import{objectToFormEntries as x}from'../utils/form.js';import{compact as y}from'../utils/render.js';import{Hidden as l,HiddenFeatures as d}from'./hidden.js';let f=H(null);function W(t){let[e,r]=u(null);return o.createElement(f.Provider,{value:{target:e}},t.children,o.createElement(l,{features:d.Hidden,ref:r}))}function c({children:t}){let e=E(f);if(!e)return o.createElement(o.Fragment,null,t);let{target:r}=e;return r?g(o.createElement(o.Fragment,null,t),r):null}function j({data:t,form:e,disabled:r,onReset:n,overrides:F}){let[i,a]=u(null),p=h();return m(()=>{if(n&&i)return p.addEventListener(i,"reset",n)},[i,e,n]),o.createElement(c,null,o.createElement(C,{setForm:a,formId:e}),x(t).map(([s,v])=>o.createElement(l,{features:d.Hidden,...y({key:s,as:"input",type:"hidden",hidden:!0,readOnly:!0,form:e,disabled:r,name:s,value:v,...F})})))}function C({setForm:t,formId:e}){return m(()=>{if(e){let r=document.getElementById(e);r&&t(r)}},[t,e]),e?null:o.createElement(l,{features:d.Hidden,as:"input",type:"hidden",hidden:!0,readOnly:!0,ref:r=>{if(!r)return;let n=r.closest("form");n&&t(n)}})}export{j as FormFields,W as FormFieldsProvider,c as HoistFormFields}; diff --git a/node_modules/@headlessui/react/dist/internal/frozen.d.ts b/node_modules/@headlessui/react/dist/internal/frozen.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41f1a1b9a9fafb8e69977ceaa4ceb3622acae1f1 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/frozen.d.ts @@ -0,0 +1,6 @@ +import React from 'react'; +export declare const Frozen: React.ForwardRefExoticComponent<{ + children: React.ReactNode; + freeze: boolean; +} & React.RefAttributes>; +export declare function useFrozenData(freeze: boolean, data: T): T; diff --git a/node_modules/@headlessui/react/dist/internal/frozen.js b/node_modules/@headlessui/react/dist/internal/frozen.js new file mode 100644 index 0000000000000000000000000000000000000000..6519148144e0151b4edbe631174aaa0ef15178b1 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/frozen.js @@ -0,0 +1 @@ +import r,{cloneElement as l,isValidElement as c,useState as a}from"react";function f({children:t,freeze:e},o){let n=u(e,t);return c(n)?l(n,{ref:o}):r.createElement(r.Fragment,null,n)}const s=r.forwardRef(f);function u(t,e){let[o,n]=a(e);return!t&&o!==e&&n(e),t?o:e}export{s as Frozen,u as useFrozenData}; diff --git a/node_modules/@headlessui/react/dist/internal/hidden.d.ts b/node_modules/@headlessui/react/dist/internal/hidden.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d01f22aa8f826f9ce233f4232d849172a961d853 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/hidden.d.ts @@ -0,0 +1,20 @@ +import type { ElementType, Ref } from 'react'; +import type { Props } from '../types.js'; +import { type HasDisplayName, type RefProp } from '../utils/render.js'; +declare let DEFAULT_VISUALLY_HIDDEN_TAG: "span"; +export declare enum HiddenFeatures { + None = 1, + Focusable = 2, + Hidden = 4 +} +type HiddenRenderPropArg = {}; +type HiddenPropsWeControl = never; +export type HiddenProps = Props; +declare function VisuallyHidden(props: HiddenProps, ref: Ref): import("react").ReactElement> | null; +interface ComponentHidden extends HasDisplayName { + (props: HiddenProps & RefProp): React.JSX.Element; +} +export declare let Hidden: ComponentHidden; +export {}; diff --git a/node_modules/@headlessui/react/dist/internal/hidden.js b/node_modules/@headlessui/react/dist/internal/hidden.js new file mode 100644 index 0000000000000000000000000000000000000000..c553cb7dd5ab9e0ca3b24b617b6ee38156d75d1a --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/hidden.js @@ -0,0 +1 @@ +import{forwardRefWithAs as i,useRender as p}from'../utils/render.js';let a="span";var s=(e=>(e[e.None=1]="None",e[e.Focusable=2]="Focusable",e[e.Hidden=4]="Hidden",e))(s||{});function l(t,r){var n;let{features:d=1,...e}=t,o={ref:r,"aria-hidden":(d&2)===2?!0:(n=e["aria-hidden"])!=null?n:void 0,hidden:(d&4)===4?!0:void 0,style:{position:"fixed",top:1,left:1,width:1,height:0,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0",...(d&4)===4&&(d&2)!==2&&{display:"none"}}};return p()({ourProps:o,theirProps:e,slot:{},defaultTag:a,name:"Hidden"})}let f=i(l);export{f as Hidden,s as HiddenFeatures}; diff --git a/node_modules/@headlessui/react/dist/internal/id.d.ts b/node_modules/@headlessui/react/dist/internal/id.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5f42afab994c7ad9cfafeb7bd48d3a110330452 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/id.d.ts @@ -0,0 +1,5 @@ +import React from 'react'; +export declare function useProvidedId(): string | undefined; +export declare function IdProvider({ id, children }: React.PropsWithChildren<{ + id: string | undefined; +}>): React.JSX.Element; diff --git a/node_modules/@headlessui/react/dist/internal/id.js b/node_modules/@headlessui/react/dist/internal/id.js new file mode 100644 index 0000000000000000000000000000000000000000..7c4277c44ad172bfa2af5451844ae1d05ae54383 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/id.js @@ -0,0 +1 @@ +import n,{createContext as d,useContext as i}from"react";let e=d(void 0);function u(){return i(e)}function f({id:t,children:r}){return n.createElement(e.Provider,{value:t},r)}export{f as IdProvider,u as useProvidedId}; diff --git a/node_modules/@headlessui/react/dist/internal/open-closed.d.ts b/node_modules/@headlessui/react/dist/internal/open-closed.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7210141e7888460a06d6960c763cc3a761741b5 --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/open-closed.d.ts @@ -0,0 +1,17 @@ +import React, { type ReactElement, type ReactNode } from 'react'; +export declare enum State { + Open = 1, + Closed = 2, + Closing = 4, + Opening = 8 +} +export declare function useOpenClosed(): State | null; +interface Props { + value: State; + children: ReactNode; +} +export declare function OpenClosedProvider({ value, children }: Props): ReactElement; +export declare function ResetOpenClosedProvider({ children }: { + children: React.ReactNode; +}): ReactElement; +export {}; diff --git a/node_modules/@headlessui/react/dist/internal/open-closed.js b/node_modules/@headlessui/react/dist/internal/open-closed.js new file mode 100644 index 0000000000000000000000000000000000000000..c3283c5f351b9660d0a1661963934f36b3bdea2d --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/open-closed.js @@ -0,0 +1 @@ +import r,{createContext as l,useContext as d}from"react";let n=l(null);n.displayName="OpenClosedContext";var i=(e=>(e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Closing=4]="Closing",e[e.Opening=8]="Opening",e))(i||{});function u(){return d(n)}function c({value:o,children:t}){return r.createElement(n.Provider,{value:o},t)}function s({children:o}){return r.createElement(n.Provider,{value:null},o)}export{c as OpenClosedProvider,s as ResetOpenClosedProvider,i as State,u as useOpenClosed}; diff --git a/node_modules/@headlessui/react/dist/internal/portal-force-root.d.ts b/node_modules/@headlessui/react/dist/internal/portal-force-root.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f8c680e75044ac9c75549ec571e275caf9239df --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/portal-force-root.d.ts @@ -0,0 +1,8 @@ +import React, { type ReactNode } from 'react'; +export declare function usePortalRoot(): boolean; +interface ForcePortalRootProps { + force: boolean; + children: ReactNode; +} +export declare function ForcePortalRoot(props: ForcePortalRootProps): React.JSX.Element; +export {}; diff --git a/node_modules/@headlessui/react/dist/internal/portal-force-root.js b/node_modules/@headlessui/react/dist/internal/portal-force-root.js new file mode 100644 index 0000000000000000000000000000000000000000..ad5954434bae3b8c39bd0b4df4328982ff8dd7aa --- /dev/null +++ b/node_modules/@headlessui/react/dist/internal/portal-force-root.js @@ -0,0 +1 @@ +import t,{createContext as r,useContext as c}from"react";let e=r(!1);function a(){return c(e)}function l(o){return t.createElement(e.Provider,{value:o.force},o.children)}export{l as ForcePortalRoot,a as usePortalRoot}; diff --git a/node_modules/@headlessui/react/dist/machine.d.ts b/node_modules/@headlessui/react/dist/machine.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a4f46019538a2f4eb89b4e87601e6d192c072d8 --- /dev/null +++ b/node_modules/@headlessui/react/dist/machine.d.ts @@ -0,0 +1,37 @@ +export declare abstract class Machine { + #private; + disposables: { + addEventListener(element: Window | Document | HTMLElement, name: TEventName, listener: (event: WindowEventMap[TEventName]) => any, options?: boolean | AddEventListenerOptions | undefined): () => void; + requestAnimationFrame(callback: FrameRequestCallback): () => void; + nextFrame(callback: FrameRequestCallback): () => void; + setTimeout(callback: (...args: any[]) => void, ms?: number | undefined, ...args: any[]): () => void; + microTask(cb: () => void): () => void; + style(node: ElementCSSInlineStyle, property: string, value: string): () => void; + group(cb: (d: { + addEventListener(element: Window | Document | HTMLElement, name: TEventName, listener: (event: WindowEventMap[TEventName]) => any, options?: boolean | AddEventListenerOptions | undefined): () => void; + requestAnimationFrame(callback: FrameRequestCallback): () => void; + nextFrame(callback: FrameRequestCallback): () => void; + setTimeout(callback: (...args: any[]) => void, ms?: number | undefined, ...args: any[]): () => void; + microTask(cb: () => void): () => void; + style(node: ElementCSSInlineStyle, property: string, value: string): () => void; + group(cb: any): () => void; + add(cb: () => void): () => void; + dispose(): void; + }) => void): () => void; + add(cb: () => void): () => void; + dispose(): void; + }; + constructor(initialState: State); + dispose(): void; + get state(): Readonly; + abstract reduce(state: Readonly, event: Event): Readonly; + subscribe(selector: (state: Readonly) => Slice, callback: (state: Slice) => void): () => void; + on(type: T, callback: (state: State, event: Extract) => void): () => void; + send(event: Event): void; +} +export declare function shallowEqual(a: any, b: any): boolean; +export declare function batch void, P extends any[] = Parameters>(setup: () => [callback: F, handle: () => void]): (...args: P) => void; diff --git a/node_modules/@headlessui/react/dist/machine.js b/node_modules/@headlessui/react/dist/machine.js new file mode 100644 index 0000000000000000000000000000000000000000..d1c8ca355ddc99439e0ef36430de005fd6ee97fe --- /dev/null +++ b/node_modules/@headlessui/react/dist/machine.js @@ -0,0 +1 @@ +var h=Object.defineProperty;var v=(t,e,r)=>e in t?h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var S=(t,e,r)=>(v(t,typeof e!="symbol"?e+"":e,r),r),b=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var i=(t,e,r)=>(b(t,e,"read from private field"),r?r.call(t):e.get(t)),c=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},u=(t,e,r,s)=>(b(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r);var n,a,o;import{DefaultMap as m}from'./utils/default-map.js';import{disposables as y}from'./utils/disposables.js';import{env as d}from'./utils/env.js';class T{constructor(e){c(this,n,{});c(this,a,new m(()=>new Set));c(this,o,new Set);S(this,"disposables",y());u(this,n,e),d.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return i(this,n)}subscribe(e,r){if(d.isServer)return()=>{};let s={selector:e,callback:r,current:e(i(this,n))};return i(this,o).add(s),this.disposables.add(()=>{i(this,o).delete(s)})}on(e,r){return d.isServer?()=>{}:(i(this,a).get(e).add(r),this.disposables.add(()=>{i(this,a).get(e).delete(r)}))}send(e){let r=this.reduce(i(this,n),e);if(r!==i(this,n)){u(this,n,r);for(let s of i(this,o)){let l=s.selector(i(this,n));j(s.current,l)||(s.current=l,s.callback(l))}for(let s of i(this,a).get(e.type))s(i(this,n),e)}}}n=new WeakMap,a=new WeakMap,o=new WeakMap;function j(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null?!1:Array.isArray(t)&&Array.isArray(e)?t.length!==e.length?!1:f(t[Symbol.iterator](),e[Symbol.iterator]()):t instanceof Map&&e instanceof Map||t instanceof Set&&e instanceof Set?t.size!==e.size?!1:f(t.entries(),e.entries()):p(t)&&p(e)?f(Object.entries(t)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function f(t,e){do{let r=t.next(),s=e.next();if(r.done&&s.done)return!0;if(r.done||s.done||!Object.is(r.value,s.value))return!1}while(!0)}function p(t){if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function k(t){let[e,r]=t(),s=y();return(...l)=>{e(...l),s.dispose(),s.microTask(r)}}export{T as Machine,k as batch,j as shallowEqual}; diff --git a/node_modules/@headlessui/react/dist/machines/stack-machine.d.ts b/node_modules/@headlessui/react/dist/machines/stack-machine.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b4144564a73085670de09bbbb721e68b2903723 --- /dev/null +++ b/node_modules/@headlessui/react/dist/machines/stack-machine.d.ts @@ -0,0 +1,32 @@ +import { Machine } from '../machine.js'; +import { DefaultMap } from '../utils/default-map.js'; +type Scope = string | null; +type Id = string; +interface State { + stack: Id[]; +} +export declare enum ActionTypes { + Push = 0, + Pop = 1 +} +export type Actions = { + type: ActionTypes.Push; + id: Id; +} | { + type: ActionTypes.Pop; + id: Id; +}; +declare class StackMachine extends Machine { + static new(): StackMachine; + reduce(state: Readonly, action: Actions): State; + actions: { + push: (id: Id) => void; + pop: (id: Id) => void; + }; + selectors: { + isTop: (state: State, id: Id) => boolean; + inStack: (state: State, id: Id) => boolean; + }; +} +export declare const stackMachines: DefaultMap; +export {}; diff --git a/node_modules/@headlessui/react/dist/machines/stack-machine.js b/node_modules/@headlessui/react/dist/machines/stack-machine.js new file mode 100644 index 0000000000000000000000000000000000000000..4c30376863ce11d41684e8e8ace7788b2c9b0579 --- /dev/null +++ b/node_modules/@headlessui/react/dist/machines/stack-machine.js @@ -0,0 +1 @@ +var a=Object.defineProperty;var r=(e,c,t)=>c in e?a(e,c,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[c]=t;var p=(e,c,t)=>(r(e,typeof c!="symbol"?c+"":c,t),t);import{Machine as d}from'../machine.js';import{DefaultMap as l}from'../utils/default-map.js';import{match as u}from'../utils/match.js';var k=(t=>(t[t.Push=0]="Push",t[t.Pop=1]="Pop",t))(k||{});let y={[0](e,c){let t=c.id,s=e.stack,i=e.stack.indexOf(t);if(i!==-1){let n=e.stack.slice();return n.splice(i,1),n.push(t),s=n,{...e,stack:s}}return{...e,stack:[...e.stack,t]}},[1](e,c){let t=c.id,s=e.stack.indexOf(t);if(s===-1)return e;let i=e.stack.slice();return i.splice(s,1),{...e,stack:i}}};class o extends d{constructor(){super(...arguments);p(this,"actions",{push:t=>this.send({type:0,id:t}),pop:t=>this.send({type:1,id:t})});p(this,"selectors",{isTop:(t,s)=>t.stack[t.stack.length-1]===s,inStack:(t,s)=>t.stack.includes(s)})}static new(){return new o({stack:[]})}reduce(t,s){return u(s.type,y,t,s)}}const x=new l(()=>o.new());export{k as ActionTypes,x as stackMachines}; diff --git a/node_modules/@headlessui/react/dist/react-glue.d.ts b/node_modules/@headlessui/react/dist/react-glue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8bc570aca5c72abc78f1ecd1d422126d8b6a372 --- /dev/null +++ b/node_modules/@headlessui/react/dist/react-glue.d.ts @@ -0,0 +1,2 @@ +import { shallowEqual, type Machine } from './machine.js'; +export declare function useSlice, Slice>(machine: M, selector: (state: Readonly ? State : never>) => Slice, compare?: typeof shallowEqual): Slice; diff --git a/node_modules/@headlessui/react/dist/react-glue.js b/node_modules/@headlessui/react/dist/react-glue.js new file mode 100644 index 0000000000000000000000000000000000000000..071fc1209f3241dd2c5a90a9be575c8c6dd93fec --- /dev/null +++ b/node_modules/@headlessui/react/dist/react-glue.js @@ -0,0 +1 @@ +import{useSyncExternalStoreWithSelector as a}from"use-sync-external-store/with-selector";import{useEvent as t}from'./hooks/use-event.js';import{shallowEqual as o}from'./machine.js';function S(e,n,r=o){return a(t(i=>e.subscribe(s,i)),t(()=>e.state),t(()=>e.state),t(n),r)}function s(e){return e}export{S as useSlice}; diff --git a/node_modules/@headlessui/react/dist/types.d.ts b/node_modules/@headlessui/react/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5a7d88a148f4015e3cb3c9b2dbcc2f1d9c00140 --- /dev/null +++ b/node_modules/@headlessui/react/dist/types.d.ts @@ -0,0 +1,20 @@ +import type { JSXElementConstructor, ReactElement, ReactNode } from 'react'; +export type ReactTag = keyof React.JSX.IntrinsicElements | JSXElementConstructor; +export type Expand = T extends infer O ? { + [K in keyof O]: O[K]; +} : never; +export type PropsOf = TTag extends React.ElementType ? Omit, 'ref'> : never; +type PropsWeControl = 'as' | 'children' | 'refName' | 'className'; +type CleanProps = Omit, TOmittableProps | PropsWeControl>; +type OurProps = { + as?: TTag; + children?: ReactNode | ((bag: TSlot) => ReactElement); + refName?: string; +}; +type HasProperty = T extends never ? never : K extends keyof T ? true : never; +type ClassNameOverride = true extends HasProperty, 'className'> ? { + className?: PropsOf['className'] | ((bag: TSlot) => string); +} : {}; +export type Props = CleanProps & OurProps & ClassNameOverride & Overrides; +export type EnsureArray = T extends any[] ? T : Expand[]; +export {}; diff --git a/node_modules/@headlessui/react/dist/types.js b/node_modules/@headlessui/react/dist/types.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/@headlessui/react/dist/utils/active-element-history.d.ts b/node_modules/@headlessui/react/dist/utils/active-element-history.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..252779cee523a7472fcd432c4697623957e13e03 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/active-element-history.d.ts @@ -0,0 +1 @@ +export declare let history: (HTMLOrSVGElement & Element)[]; diff --git a/node_modules/@headlessui/react/dist/utils/active-element-history.js b/node_modules/@headlessui/react/dist/utils/active-element-history.js new file mode 100644 index 0000000000000000000000000000000000000000..582efa1df5636f0310d263a2c0b6262124b81921 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/active-element-history.js @@ -0,0 +1 @@ +import{onDocumentReady as d}from'./document-ready.js';import*as u from'./dom.js';import{focusableSelector as i}from'./focus-management.js';let n=[];d(()=>{function e(t){if(!u.isHTMLorSVGElement(t.target)||t.target===document.body||n[0]===t.target)return;let r=t.target;r=r.closest(i),n.unshift(r!=null?r:t.target),n=n.filter(o=>o!=null&&o.isConnected),n.splice(10)}window.addEventListener("click",e,{capture:!0}),window.addEventListener("mousedown",e,{capture:!0}),window.addEventListener("focus",e,{capture:!0}),document.body.addEventListener("click",e,{capture:!0}),document.body.addEventListener("mousedown",e,{capture:!0}),document.body.addEventListener("focus",e,{capture:!0})});export{n as history}; diff --git a/node_modules/@headlessui/react/dist/utils/bugs.d.ts b/node_modules/@headlessui/react/dist/utils/bugs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77ab9943a88db4c7172f530105d249871249af11 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/bugs.d.ts @@ -0,0 +1 @@ +export declare function isDisabledReactIssue7711(element: Element): boolean; diff --git a/node_modules/@headlessui/react/dist/utils/bugs.js b/node_modules/@headlessui/react/dist/utils/bugs.js new file mode 100644 index 0000000000000000000000000000000000000000..8bcca5243be14f0a35a6be20d220ff30712a98ac --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/bugs.js @@ -0,0 +1 @@ +import*as n from'./dom.js';function s(l){let e=l.parentElement,t=null;for(;e&&!n.isHTMLFieldSetElement(e);)n.isHTMLLegendElement(e)&&(t=e),e=e.parentElement;let i=(e==null?void 0:e.getAttribute("disabled"))==="";return i&&r(t)?!1:i}function r(l){if(!l)return!1;let e=l.previousElementSibling;for(;e!==null;){if(n.isHTMLLegendElement(e))return!1;e=e.previousElementSibling}return!0}export{s as isDisabledReactIssue7711}; diff --git a/node_modules/@headlessui/react/dist/utils/calculate-active-index.d.ts b/node_modules/@headlessui/react/dist/utils/calculate-active-index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..011d94d7e4356d2c6ae76ca05074fddbac2c29fe --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/calculate-active-index.d.ts @@ -0,0 +1,25 @@ +export declare enum Focus { + /** Focus the first non-disabled item. */ + First = 0, + /** Focus the previous non-disabled item. */ + Previous = 1, + /** Focus the next non-disabled item. */ + Next = 2, + /** Focus the last non-disabled item. */ + Last = 3, + /** Focus a specific item based on the `id` of the item. */ + Specific = 4, + /** Focus no items at all. */ + Nothing = 5 +} +export declare function calculateActiveIndex(action: { + focus: Focus.Specific; + id: string; +} | { + focus: Exclude; +}, resolvers: { + resolveItems(): TItem[]; + resolveActiveIndex(): number | null; + resolveId(item: TItem, index: number, items: TItem[]): string; + resolveDisabled(item: TItem, index: number, items: TItem[]): boolean; +}): number | null; diff --git a/node_modules/@headlessui/react/dist/utils/calculate-active-index.js b/node_modules/@headlessui/react/dist/utils/calculate-active-index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d0d76182ab3960bfbe9d986715d9dea6de25709 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/calculate-active-index.js @@ -0,0 +1 @@ +function u(l){throw new Error("Unexpected object: "+l)}var c=(i=>(i[i.First=0]="First",i[i.Previous=1]="Previous",i[i.Next=2]="Next",i[i.Last=3]="Last",i[i.Specific=4]="Specific",i[i.Nothing=5]="Nothing",i))(c||{});function f(l,n){let t=n.resolveItems();if(t.length<=0)return null;let r=n.resolveActiveIndex(),s=r!=null?r:-1;switch(l.focus){case 0:{for(let e=0;e=0;--e)if(!n.resolveDisabled(t[e],e,t))return e;return r}case 2:{for(let e=s+1;e=0;--e)if(!n.resolveDisabled(t[e],e,t))return e;return r}case 4:{for(let e=0;etypeof n=="string"?n.split(" "):[]))).filter(Boolean).join(" ")}export{t as classNames}; diff --git a/node_modules/@headlessui/react/dist/utils/default-map.d.ts b/node_modules/@headlessui/react/dist/utils/default-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..65e0364ff9b2c85ffc43bc3c298db600b9938ef6 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/default-map.d.ts @@ -0,0 +1,5 @@ +export declare class DefaultMap extends Map { + private factory; + constructor(factory: (key: T) => V); + get(key: T): V; +} diff --git a/node_modules/@headlessui/react/dist/utils/default-map.js b/node_modules/@headlessui/react/dist/utils/default-map.js new file mode 100644 index 0000000000000000000000000000000000000000..506ea7516c9ce52d2603de3be43ca2650327d167 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/default-map.js @@ -0,0 +1 @@ +class a extends Map{constructor(t){super();this.factory=t}get(t){let e=super.get(t);return e===void 0&&(e=this.factory(t),this.set(t,e)),e}}export{a as DefaultMap}; diff --git a/node_modules/@headlessui/react/dist/utils/disposables.d.ts b/node_modules/@headlessui/react/dist/utils/disposables.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ad8d96b923504db3851d9815100709d2b47d87b --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/disposables.d.ts @@ -0,0 +1,24 @@ +export type Disposables = ReturnType; +/** + * Disposables are a way to manage event handlers and functions like + * `setTimeout` and `requestAnimationFrame` that need to be cleaned up when they + * are no longer needed. + * + * + * When you register a disposable function, it is added to a collection of + * disposables. Each disposable in the collection provides a `dispose` clean up + * function that can be called when it's no longer needed. There is also a + * `dispose` function on the collection itself that can be used to clean up all + * pending disposables in that collection. + */ +export declare function disposables(): { + addEventListener(element: HTMLElement | Window | Document, name: TEventName, listener: (event: WindowEventMap[TEventName]) => any, options?: boolean | AddEventListenerOptions): () => void; + requestAnimationFrame(callback: FrameRequestCallback): () => void; + nextFrame(callback: FrameRequestCallback): () => void; + setTimeout(callback: (...args: any[]) => void, ms?: number | undefined, ...args: any[]): () => void; + microTask(cb: () => void): () => void; + style(node: ElementCSSInlineStyle, property: string, value: string): () => void; + group(cb: (d: typeof this) => void): () => void; + add(cb: () => void): () => void; + dispose(): void; +}; diff --git a/node_modules/@headlessui/react/dist/utils/disposables.js b/node_modules/@headlessui/react/dist/utils/disposables.js new file mode 100644 index 0000000000000000000000000000000000000000..f1b151794297ac42e15e31fef7e066797a990c00 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/disposables.js @@ -0,0 +1 @@ +import{microTask as a}from'./micro-task.js';function o(){let s=[],r={addEventListener(e,t,n,i){return e.addEventListener(t,n,i),r.add(()=>e.removeEventListener(t,n,i))},requestAnimationFrame(...e){let t=requestAnimationFrame(...e);return r.add(()=>cancelAnimationFrame(t))},nextFrame(...e){return r.requestAnimationFrame(()=>r.requestAnimationFrame(...e))},setTimeout(...e){let t=setTimeout(...e);return r.add(()=>clearTimeout(t))},microTask(...e){let t={current:!0};return a(()=>{t.current&&e[0]()}),r.add(()=>{t.current=!1})},style(e,t,n){let i=e.style.getPropertyValue(t);return Object.assign(e.style,{[t]:n}),this.add(()=>{Object.assign(e.style,{[t]:i})})},group(e){let t=o();return e(t),this.add(()=>t.dispose())},add(e){return s.includes(e)||s.push(e),()=>{let t=s.indexOf(e);if(t>=0)for(let n of s.splice(t,1))n()}},dispose(){for(let e of s.splice(0))e()}};return r}export{o as disposables}; diff --git a/node_modules/@headlessui/react/dist/utils/document-ready.d.ts b/node_modules/@headlessui/react/dist/utils/document-ready.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a872936a8b2e1e4d7307193f67517c020e62baa6 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/document-ready.d.ts @@ -0,0 +1 @@ +export declare function onDocumentReady(cb: () => void): void; diff --git a/node_modules/@headlessui/react/dist/utils/document-ready.js b/node_modules/@headlessui/react/dist/utils/document-ready.js new file mode 100644 index 0000000000000000000000000000000000000000..0ddda1cdf4d7378ac22ca7cdef5a34260e5effd1 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/document-ready.js @@ -0,0 +1 @@ +function t(n){function e(){document.readyState!=="loading"&&(n(),document.removeEventListener("DOMContentLoaded",e))}typeof window!="undefined"&&typeof document!="undefined"&&(document.addEventListener("DOMContentLoaded",e),e())}export{t as onDocumentReady}; diff --git a/node_modules/@headlessui/react/dist/utils/dom.d.ts b/node_modules/@headlessui/react/dist/utils/dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e2ad3e3c7b3e907c0146ac58b4998e8d5d10b0c --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/dom.d.ts @@ -0,0 +1,12 @@ +export declare function isNode(element: unknown): element is Node; +export declare function isElement(element: unknown): element is Element; +export declare function isHTMLElement(element: unknown): element is HTMLElement; +export declare function isHTMLorSVGElement(element: unknown): element is HTMLOrSVGElement & Element; +export declare function hasInlineStyle(element: unknown): element is ElementCSSInlineStyle; +export declare function isHTMLIframeElement(element: unknown): element is HTMLIFrameElement; +export declare function isHTMLInputElement(element: unknown): element is HTMLInputElement; +export declare function isHTMLTextAreaElement(element: unknown): element is HTMLTextAreaElement; +export declare function isHTMLLabelElement(element: unknown): element is HTMLLabelElement; +export declare function isHTMLFieldSetElement(element: unknown): element is HTMLFieldSetElement; +export declare function isHTMLLegendElement(element: unknown): element is HTMLLegendElement; +export declare function isInteractiveElement(element: unknown): element is Element; diff --git a/node_modules/@headlessui/react/dist/utils/dom.js b/node_modules/@headlessui/react/dist/utils/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..79699d71ce434fabba36b871245ae8285bd8d1d3 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/dom.js @@ -0,0 +1 @@ +function o(e){return typeof e!="object"||e===null?!1:"nodeType"in e}function t(e){return o(e)&&"tagName"in e}function n(e){return t(e)&&"accessKey"in e}function i(e){return t(e)&&"tabIndex"in e}function r(e){return t(e)&&"style"in e}function u(e){return n(e)&&e.nodeName==="IFRAME"}function l(e){return n(e)&&e.nodeName==="INPUT"}function s(e){return n(e)&&e.nodeName==="TEXTAREA"}function m(e){return n(e)&&e.nodeName==="LABEL"}function a(e){return n(e)&&e.nodeName==="FIELDSET"}function E(e){return n(e)&&e.nodeName==="LEGEND"}function L(e){return t(e)?e.matches('a[href],audio[controls],button,details,embed,iframe,img[usemap],input:not([type="hidden"]),label,select,textarea,video[controls]'):!1}export{r as hasInlineStyle,t as isElement,n as isHTMLElement,a as isHTMLFieldSetElement,u as isHTMLIframeElement,l as isHTMLInputElement,m as isHTMLLabelElement,E as isHTMLLegendElement,s as isHTMLTextAreaElement,i as isHTMLorSVGElement,L as isInteractiveElement,o as isNode}; diff --git a/node_modules/@headlessui/react/dist/utils/element-movement.d.ts b/node_modules/@headlessui/react/dist/utils/element-movement.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..86146cf3f247a65b34289ab77e7add91f1a254fc --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/element-movement.d.ts @@ -0,0 +1,19 @@ +export declare const ElementPositionState: { + Idle: { + kind: "Idle"; + }; + Tracked: (position: string) => { + kind: "Tracked"; + position: string; + }; + Moved: { + kind: "Moved"; + }; +}; +type ResolvedStates> = { + [K in keyof T]: T[K] extends (...args: any[]) => infer R ? R : T[K]; +}[keyof T]; +export type ElementPositionState = ResolvedStates; +export declare function computeVisualPosition(element: HTMLElement): string; +export declare function detectMovement(target: HTMLElement, state: ResolvedStates, onMove: () => void): () => void; +export {}; diff --git a/node_modules/@headlessui/react/dist/utils/element-movement.js b/node_modules/@headlessui/react/dist/utils/element-movement.js new file mode 100644 index 0000000000000000000000000000000000000000..59df24eb5149344261bda1c3589a1fc6e3e1c045 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/element-movement.js @@ -0,0 +1 @@ +import{disposables as r}from'./disposables.js';const c={Idle:{kind:"Idle"},Tracked:e=>({kind:"Tracked",position:e}),Moved:{kind:"Moved"}};function a(e){let t=e.getBoundingClientRect();return`${t.x},${t.y}`}function p(e,t,i){let n=r();if(t.kind==="Tracked"){let o=function(){d!==a(e)&&(n.dispose(),i())};var f=o;let{position:d}=t,s=new ResizeObserver(o);s.observe(e),n.add(()=>s.disconnect()),n.addEventListener(window,"scroll",o,{passive:!0}),n.addEventListener(window,"resize",o)}return()=>n.dispose()}export{c as ElementPositionState,a as computeVisualPosition,p as detectMovement}; diff --git a/node_modules/@headlessui/react/dist/utils/env.d.ts b/node_modules/@headlessui/react/dist/utils/env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc5b0b61ffd2fca93c078a5349ae61e28566efbd --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/env.d.ts @@ -0,0 +1,17 @@ +type RenderEnv = 'client' | 'server'; +type HandoffState = 'pending' | 'complete'; +declare class Env { + current: RenderEnv; + handoffState: HandoffState; + currentId: number; + set(env: RenderEnv): void; + reset(): void; + nextId(): number; + get isServer(): boolean; + get isClient(): boolean; + private detect; + handoff(): void; + get isHandoffComplete(): boolean; +} +export declare let env: Env; +export {}; diff --git a/node_modules/@headlessui/react/dist/utils/env.js b/node_modules/@headlessui/react/dist/utils/env.js new file mode 100644 index 0000000000000000000000000000000000000000..be4399df4886c062d1339adafb315d5549ea8fc5 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/env.js @@ -0,0 +1 @@ +var i=Object.defineProperty;var d=(t,e,n)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var r=(t,e,n)=>(d(t,typeof e!="symbol"?e+"":e,n),n);class o{constructor(){r(this,"current",this.detect());r(this,"handoffState","pending");r(this,"currentId",0)}set(e){this.current!==e&&(this.handoffState="pending",this.currentId=0,this.current=e)}reset(){this.set(this.detect())}nextId(){return++this.currentId}get isServer(){return this.current==="server"}get isClient(){return this.current==="client"}detect(){return typeof window=="undefined"||typeof document=="undefined"?"server":"client"}handoff(){this.handoffState==="pending"&&(this.handoffState="complete")}get isHandoffComplete(){return this.handoffState==="complete"}}let s=new o;export{s as env}; diff --git a/node_modules/@headlessui/react/dist/utils/focus-management.d.ts b/node_modules/@headlessui/react/dist/utils/focus-management.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f44e1f1444ca7dc10e0284ce0e5b881501b7df5b --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/focus-management.d.ts @@ -0,0 +1,50 @@ +import type { MutableRefObject } from 'react'; +export declare let focusableSelector: string; +export declare enum Focus { + /** Focus the first non-disabled element */ + First = 1, + /** Focus the previous non-disabled element */ + Previous = 2, + /** Focus the next non-disabled element */ + Next = 4, + /** Focus the last non-disabled element */ + Last = 8, + /** Wrap tab around */ + WrapAround = 16, + /** Prevent scrolling the focusable elements into view */ + NoScroll = 32, + /** Focus the first focusable element with the `data-autofocus` attribute. */ + AutoFocus = 64 +} +export declare enum FocusResult { + /** Something went wrong while trying to focus. */ + Error = 0, + /** When `Focus.WrapAround` is enabled, going from position `N` to `N+1` where `N` is the last index in the array, then we overflow. */ + Overflow = 1, + /** Focus was successful. */ + Success = 2, + /** When `Focus.WrapAround` is enabled, going from position `N` to `N-1` where `N` is the first index in the array, then we underflow. */ + Underflow = 3 +} +interface QuerySelectorAll { + querySelectorAll(selectors: string): NodeListOf; +} +export declare function getFocusableElements(container?: QuerySelectorAll | null): HTMLElement[]; +export declare function getAutoFocusableElements(container?: HTMLElement | null): HTMLElement[]; +export declare enum FocusableMode { + /** The element itself must be focusable. */ + Strict = 0, + /** The element should be inside of a focusable element. */ + Loose = 1 +} +export declare function isFocusableElement(element: HTMLOrSVGElement & Element, mode?: FocusableMode): boolean; +export declare function restoreFocusIfNecessary(element: HTMLElement | null): void; +export declare function focusElement(element: HTMLOrSVGElement | null): void; +export declare function sortByDomNode(nodes: T[], resolveKey?: (item: T) => HTMLElement | null): T[]; +export declare function focusFrom(current: HTMLElement | null, focus: Focus, container?: Document | ShadowRoot | HTMLElement | null): FocusResult; +export declare function focusIn(container: HTMLElement | HTMLElement[], focus: Focus, { sorted, relativeTo, skipElements, }?: Partial<{ + sorted: boolean; + relativeTo: HTMLElement | null; + skipElements: (HTMLElement | MutableRefObject)[]; +}>): FocusResult; +export {}; diff --git a/node_modules/@headlessui/react/dist/utils/focus-management.js b/node_modules/@headlessui/react/dist/utils/focus-management.js new file mode 100644 index 0000000000000000000000000000000000000000..756515c679ee1655a72c78ffbb3534207289d563 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/focus-management.js @@ -0,0 +1 @@ +import{disposables as p}from'./disposables.js';import*as y from'./dom.js';import{match as L}from'./match.js';import{getActiveElement as b,getOwnerDocument as F,getRootNode as f}from'./owner.js';let E=["[contentEditable=true]","[tabindex]","a[href]","area[href]","button:not([disabled])","iframe","input:not([disabled])","select:not([disabled])","details>summary","textarea:not([disabled])"].map(e=>`${e}:not([tabindex='-1'])`).join(","),S=["[data-autofocus]"].map(e=>`${e}:not([tabindex='-1'])`).join(",");var T=(o=>(o[o.First=1]="First",o[o.Previous=2]="Previous",o[o.Next=4]="Next",o[o.Last=8]="Last",o[o.WrapAround=16]="WrapAround",o[o.NoScroll=32]="NoScroll",o[o.AutoFocus=64]="AutoFocus",o))(T||{}),A=(n=>(n[n.Error=0]="Error",n[n.Overflow=1]="Overflow",n[n.Success=2]="Success",n[n.Underflow=3]="Underflow",n))(A||{}),O=(t=>(t[t.Previous=-1]="Previous",t[t.Next=1]="Next",t))(O||{});function x(e=document.body){return e==null?[]:Array.from(e.querySelectorAll(E)).sort((r,t)=>Math.sign((r.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}function h(e=document.body){return e==null?[]:Array.from(e.querySelectorAll(S)).sort((r,t)=>Math.sign((r.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var I=(t=>(t[t.Strict=0]="Strict",t[t.Loose=1]="Loose",t))(I||{});function H(e,r=0){var t;return e===((t=F(e))==null?void 0:t.body)?!1:L(r,{[0](){return e.matches(E)},[1](){let l=e;for(;l!==null;){if(l.matches(E))return!0;l=l.parentElement}return!1}})}function K(e){p().nextFrame(()=>{let r=b(e);r&&y.isHTMLorSVGElement(r)&&!H(r,0)&&w(e)})}var g=(t=>(t[t.Keyboard=0]="Keyboard",t[t.Mouse=1]="Mouse",t))(g||{});typeof window!="undefined"&&typeof document!="undefined"&&(document.addEventListener("keydown",e=>{e.metaKey||e.altKey||e.ctrlKey||(document.documentElement.dataset.headlessuiFocusVisible="")},!0),document.addEventListener("click",e=>{e.detail===1?delete document.documentElement.dataset.headlessuiFocusVisible:e.detail===0&&(document.documentElement.dataset.headlessuiFocusVisible="")},!0));function w(e){e==null||e.focus({preventScroll:!0})}let _=["textarea","input"].join(",");function P(e){var r,t;return(t=(r=e==null?void 0:e.matches)==null?void 0:r.call(e,_))!=null?t:!1}function G(e,r=t=>t){return e.slice().sort((t,l)=>{let n=r(t),a=r(l);if(n===null||a===null)return 0;let u=n.compareDocumentPosition(a);return u&Node.DOCUMENT_POSITION_FOLLOWING?-1:u&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function R(e,r,t=e===null?document.body:f(e)){return v(x(t),r,{relativeTo:e})}function v(e,r,{sorted:t=!0,relativeTo:l=null,skipElements:n=[]}={}){let a=Array.isArray(e)?e.length>0?f(e[0]):document:f(e),u=Array.isArray(e)?t?G(e):e:r&64?h(e):x(e);n.length>0&&u.length>1&&(u=u.filter(i=>!n.some(d=>d!=null&&"current"in d?(d==null?void 0:d.current)===i:d===i))),l=l!=null?l:a==null?void 0:a.activeElement;let o=(()=>{if(r&5)return 1;if(r&10)return-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),M=(()=>{if(r&1)return 0;if(r&2)return Math.max(0,u.indexOf(l))-1;if(r&4)return Math.max(0,u.indexOf(l))+1;if(r&8)return u.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),N=r&32?{preventScroll:!0}:{},m=0,c=u.length,s;do{if(m>=c||m+c<=0)return 0;let i=M+m;if(r&16)i=(i+c)%c;else{if(i<0)return 3;if(i>=c)return 1}s=u[i],s==null||s.focus(N),m+=o}while(s!==b(s));return r&6&&P(s)&&s.select(),2}export{T as Focus,A as FocusResult,I as FocusableMode,w as focusElement,R as focusFrom,v as focusIn,E as focusableSelector,h as getAutoFocusableElements,x as getFocusableElements,H as isFocusableElement,K as restoreFocusIfNecessary,G as sortByDomNode}; diff --git a/node_modules/@headlessui/react/dist/utils/form.d.ts b/node_modules/@headlessui/react/dist/utils/form.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d39fbc7d8e68fb195e52f39e38a2858eaf7aa8c9 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/form.d.ts @@ -0,0 +1,4 @@ +type Entries = [string, string][]; +export declare function objectToFormEntries(source?: Record, parentKey?: string | null, entries?: Entries): Entries; +export declare function attemptSubmit(elementInForm: HTMLElement): void; +export {}; diff --git a/node_modules/@headlessui/react/dist/utils/form.js b/node_modules/@headlessui/react/dist/utils/form.js new file mode 100644 index 0000000000000000000000000000000000000000..83bce5b303e97c39d8c0e192bc3c2f933711cb5c --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/form.js @@ -0,0 +1 @@ +import{isValidElement as f}from"react";function p(t={},i=null,n=[]){for(let[e,o]of Object.entries(t))s(n,r(i,e),o);return n}function r(t,i){return t?t+"["+i+"]":i}function s(t,i,n){if(Array.isArray(n))for(let[e,o]of n.entries())s(t,r(i,e.toString()),o);else n instanceof Date?t.push([i,n.toISOString()]):typeof n=="boolean"?t.push([i,n?"1":"0"]):typeof n=="string"?t.push([i,n]):typeof n=="number"?t.push([i,`${n}`]):n==null?t.push([i,""]):c(n)&&!f(n)&&p(n,i,t)}function g(t){var n,e;let i=(n=t==null?void 0:t.form)!=null?n:t.closest("form");if(i){for(let o of i.elements)if(o!==t&&(o.tagName==="INPUT"&&o.type==="submit"||o.tagName==="BUTTON"&&o.type==="submit"||o.nodeName==="INPUT"&&o.type==="image")){o.click();return}(e=i.requestSubmit)==null||e.call(i)}}function c(t){if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let i=Object.getPrototypeOf(t);return i===null||Object.getPrototypeOf(i)===null}export{g as attemptSubmit,p as objectToFormEntries}; diff --git a/node_modules/@headlessui/react/dist/utils/get-text-value.d.ts b/node_modules/@headlessui/react/dist/utils/get-text-value.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7fb96d7f00bc8239837c6827deae29302eb9a1a3 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/get-text-value.d.ts @@ -0,0 +1 @@ +export declare function getTextValue(element: HTMLElement): string; diff --git a/node_modules/@headlessui/react/dist/utils/get-text-value.js b/node_modules/@headlessui/react/dist/utils/get-text-value.js new file mode 100644 index 0000000000000000000000000000000000000000..e5a01c1ed00a041d5b3a90b072fdf61df966cdc5 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/get-text-value.js @@ -0,0 +1 @@ +import*as g from'./dom.js';let a=/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;function o(e){var l,n;let i=(l=e.innerText)!=null?l:"",t=e.cloneNode(!0);if(!g.isHTMLElement(t))return i;let u=!1;for(let f of t.querySelectorAll('[hidden],[aria-hidden],[role="img"]'))f.remove(),u=!0;let r=u?(n=t.innerText)!=null?n:"":i;return a.test(r)&&(r=r.replace(a,"")),r}function F(e){let i=e.getAttribute("aria-label");if(typeof i=="string")return i.trim();let t=e.getAttribute("aria-labelledby");if(t){let u=t.split(" ").map(r=>{let l=document.getElementById(r);if(l){let n=l.getAttribute("aria-label");return typeof n=="string"?n.trim():o(l).trim()}return null}).filter(Boolean);if(u.length>0)return u.join(", ")}return o(e).trim()}export{F as getTextValue}; diff --git a/node_modules/@headlessui/react/dist/utils/match.d.ts b/node_modules/@headlessui/react/dist/utils/match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc266b60c339002ab264707b0b90dd02b7721f5a --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/match.d.ts @@ -0,0 +1 @@ +export declare function match(value: TValue, lookup: Record TReturnValue)>, ...args: any[]): TReturnValue; diff --git a/node_modules/@headlessui/react/dist/utils/match.js b/node_modules/@headlessui/react/dist/utils/match.js new file mode 100644 index 0000000000000000000000000000000000000000..f80912d7a5b193c3602cf431b776ffedd8cdb3d7 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/match.js @@ -0,0 +1 @@ +function u(r,n,...a){if(r in n){let e=n[r];return typeof e=="function"?e(...a):e}let t=new Error(`Tried to handle "${r}" but there is no handler defined. Only defined handlers are: ${Object.keys(n).map(e=>`"${e}"`).join(", ")}.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,u),t}export{u as match}; diff --git a/node_modules/@headlessui/react/dist/utils/micro-task.d.ts b/node_modules/@headlessui/react/dist/utils/micro-task.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..140784256cbf38c356b79d67e445a3dc8f6f0b4b --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/micro-task.d.ts @@ -0,0 +1 @@ +export declare function microTask(cb: () => void): void; diff --git a/node_modules/@headlessui/react/dist/utils/micro-task.js b/node_modules/@headlessui/react/dist/utils/micro-task.js new file mode 100644 index 0000000000000000000000000000000000000000..b3e4c777ea5a5a7e6a0da2fc8460f51d38a1e4ac --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/micro-task.js @@ -0,0 +1 @@ +function t(e){typeof queueMicrotask=="function"?queueMicrotask(e):Promise.resolve().then(e).catch(o=>setTimeout(()=>{throw o}))}export{t as microTask}; diff --git a/node_modules/@headlessui/react/dist/utils/once.d.ts b/node_modules/@headlessui/react/dist/utils/once.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc1f09b5025da13aebaf4028c8eb6a7ef4d5c542 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/once.d.ts @@ -0,0 +1 @@ +export declare function once(cb: (...args: T[]) => void): (...args: T[]) => void; diff --git a/node_modules/@headlessui/react/dist/utils/once.js b/node_modules/@headlessui/react/dist/utils/once.js new file mode 100644 index 0000000000000000000000000000000000000000..12f474065f5e954287e56a1fb7614b8d3a6a5952 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/once.js @@ -0,0 +1 @@ +function l(r){let e={called:!1};return(...t)=>{if(!e.called)return e.called=!0,r(...t)}}export{l as once}; diff --git a/node_modules/@headlessui/react/dist/utils/owner.d.ts b/node_modules/@headlessui/react/dist/utils/owner.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8758ceddad16763de5639d119427ece2fbea942c --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/owner.d.ts @@ -0,0 +1,4 @@ +export declare function getOwnerDocument(element: T | null | undefined): Document | null; +export declare function getRootNode(element: T | null | undefined): Document | ShadowRoot | null; +export declare function getActiveElement(element: Element | null | undefined): Element | null; +export declare function isActiveElement(element: Element | null | undefined): boolean; diff --git a/node_modules/@headlessui/react/dist/utils/owner.js b/node_modules/@headlessui/react/dist/utils/owner.js new file mode 100644 index 0000000000000000000000000000000000000000..c14be927c87c1033a930efe0a04a72aefb187bdc --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/owner.js @@ -0,0 +1 @@ +import{env as t}from'./env.js';function l(n){var u;return t.isServer?null:n==null?document:(u=n==null?void 0:n.ownerDocument)!=null?u:document}function r(n){var u,o;return t.isServer?null:n==null?document:(o=(u=n==null?void 0:n.getRootNode)==null?void 0:u.call(n))!=null?o:document}function e(n){var u,o;return(o=(u=r(n))==null?void 0:u.activeElement)!=null?o:null}function d(n){return e(n)===n}export{e as getActiveElement,l as getOwnerDocument,r as getRootNode,d as isActiveElement}; diff --git a/node_modules/@headlessui/react/dist/utils/platform.d.ts b/node_modules/@headlessui/react/dist/utils/platform.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0df3bb0c6f4432353aa75a1ed71d677f52ff47cd --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/platform.d.ts @@ -0,0 +1,3 @@ +export declare function isIOS(): boolean; +export declare function isAndroid(): boolean; +export declare function isMobile(): boolean; diff --git a/node_modules/@headlessui/react/dist/utils/platform.js b/node_modules/@headlessui/react/dist/utils/platform.js new file mode 100644 index 0000000000000000000000000000000000000000..5fd20ab753246a9add0cfb5124d18878c78ee58a --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/platform.js @@ -0,0 +1 @@ +function t(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function i(){return/Android/gi.test(window.navigator.userAgent)}function n(){return t()||i()}export{i as isAndroid,t as isIOS,n as isMobile}; diff --git a/node_modules/@headlessui/react/dist/utils/render.d.ts b/node_modules/@headlessui/react/dist/utils/render.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43dd50649205885b1c01502d86cabdc668b3bd1a --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/render.d.ts @@ -0,0 +1,81 @@ +import React, { Fragment, type ElementType, type Ref } from 'react'; +import type { Expand, Props } from '../types.js'; +export declare enum RenderFeatures { + /** No features at all */ + None = 0, + /** + * When used, this will allow us to use one of the render strategies. + * + * **The render strategies are:** + * - **Unmount** _(Will unmount the component.)_ + * - **Hidden** _(Will hide the component using the [hidden] attribute.)_ + */ + RenderStrategy = 1, + /** + * When used, this will allow the user of our component to be in control. This can be used when + * you want to transition based on some state. + */ + Static = 2 +} +export declare enum RenderStrategy { + Unmount = 0, + Hidden = 1 +} +type UnionToIntersection = (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R : never; +type PropsForFeature = TPassedInFeatures extends TForFeature ? TProps : {}; +export type PropsForFeatures = Expand | PropsForFeature>>; +export declare function useRender(): typeof render; +declare function render({ ourProps, theirProps, slot, defaultTag, features, visible, name, mergeRefs, }: { + ourProps: Expand & PropsForFeatures> & { + ref?: Ref; + }; + theirProps: Expand>; + slot?: TSlot; + defaultTag: ElementType; + features?: TFeature; + visible?: boolean; + name: string; + mergeRefs?: ReturnType; +}): ReturnType | null; +declare function _render(props: Props & { + ref?: unknown; +}, slot: TSlot | undefined, tag: ElementType, name: string, mergeRefs: ReturnType): React.ReactElement>; +/** + * This is a singleton hook. **You can ONLY call the returned + * function *once* to produce expected results.** If you need + * to call `mergeRefs()` multiple times you need to create a + * separate function for each invocation. This happens as we + * store the list of `refs` to update and always return the + * same function that refers to that list of refs. + * + * You shouldn't normally read refs during render but this + * should actually be okay because React itself is calling + * the `function` that updates these refs and can only do + * so once the ref that contains the list is updated. + */ +declare function useMergeRefsFn(): (...refs: any[]) => ((value: any) => void) | undefined; +export type HasDisplayName = { + displayName: string; +}; +export type RefProp = T extends (props: any, ref: Ref) => any ? { + ref?: Ref; +} : never; +export declare function mergeProps[]>(...listOfProps: T): Props; +/** + * This is a hack, but basically we want to keep the full 'API' of the component, but we do want to + * wrap it in a forwardRef so that we _can_ passthrough the ref + */ +export declare function forwardRefWithAs(component: T): T & { + displayName: string; +}; +export declare function compact>(object: T): {} & T; +export declare function isFragment(element: any): element is typeof Fragment; +export declare function isFragmentInstance(element: React.ReactElement): boolean; +export {}; diff --git a/node_modules/@headlessui/react/dist/utils/render.js b/node_modules/@headlessui/react/dist/utils/render.js new file mode 100644 index 0000000000000000000000000000000000000000..2110491ecf427d530faffadee51048390abe253c --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/render.js @@ -0,0 +1,4 @@ +import v,{Fragment as S,cloneElement as j,createElement as w,forwardRef as k,isValidElement as M,useCallback as x,useRef as O}from"react";import{classNames as N}from'./class-names.js';import{match as $}from'./match.js';var A=(a=>(a[a.None=0]="None",a[a.RenderStrategy=1]="RenderStrategy",a[a.Static=2]="Static",a))(A||{}),C=(t=>(t[t.Unmount=0]="Unmount",t[t.Hidden=1]="Hidden",t))(C||{});function K(){let e=I();return x(r=>U({mergeRefs:e,...r}),[e])}function U({ourProps:e,theirProps:r,slot:t,defaultTag:a,features:o,visible:n=!0,name:i,mergeRefs:l}){l=l!=null?l:H;let s=P(r,e);if(n)return F(s,t,a,i,l);let y=o!=null?o:0;if(y&2){let{static:f=!1,...u}=s;if(f)return F(u,t,a,i,l)}if(y&1){let{unmount:f=!0,...u}=s;return $(f?0:1,{[0](){return null},[1](){return F({...u,hidden:!0,style:{display:"none"}},t,a,i,l)}})}return F(s,t,a,i,l)}function F(e,r={},t,a,o){let{as:n=t,children:i,refName:l="ref",...s}=h(e,["unmount","static"]),y=e.ref!==void 0?{[l]:e.ref}:{},f=typeof i=="function"?i(r):i;f=E(f),"className"in s&&s.className&&typeof s.className=="function"&&(s.className=s.className(r)),s["aria-labelledby"]&&s["aria-labelledby"]===s.id&&(s["aria-labelledby"]=void 0);let u={};if(r){let d=!1,p=[];for(let[c,T]of Object.entries(r))typeof T=="boolean"&&(d=!0),T===!0&&p.push(c.replace(/([A-Z])/g,g=>`-${g.toLowerCase()}`));if(d){u["data-headlessui-state"]=p.join(" ");for(let c of p)u[`data-${c}`]=""}}if(b(n)&&(Object.keys(m(s)).length>0||Object.keys(m(u)).length>0))if(!M(f)||Array.isArray(f)&&f.length>1||L(f)){if(Object.keys(m(s)).length>0)throw new Error(['Passing props on "Fragment"!',"",`The current component <${a} /> is rendering a "Fragment".`,"However we need to passthrough the following props:",Object.keys(m(s)).concat(Object.keys(m(u))).map(d=>` - ${d}`).join(` +`),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(d=>` - ${d}`).join(` +`)].join(` +`))}else{let d=f.props,p=d==null?void 0:d.className,c=typeof p=="function"?(...R)=>N(p(...R),s.className):N(p,s.className),T=c?{className:c}:{},g=P(f.props,m(h(s,["ref"])));for(let R in u)R in g&&delete u[R];return j(f,Object.assign({},g,u,y,{ref:o(D(f),y.ref)},T))}return w(n,Object.assign({},h(s,["ref"]),!b(n)&&y,!b(n)&&u),f)}function I(){let e=O([]),r=x(t=>{for(let a of e.current)a!=null&&(typeof a=="function"?a(t):a.current=t)},[]);return(...t)=>{if(!t.every(a=>a==null))return e.current=t,r}}function H(...e){return e.every(r=>r==null)?void 0:r=>{for(let t of e)t!=null&&(typeof t=="function"?t(r):t.current=r)}}function P(...e){var a;if(e.length===0)return{};if(e.length===1)return e[0];let r={},t={};for(let o of e)for(let n in o)n.startsWith("on")&&typeof o[n]=="function"?((a=t[n])!=null||(t[n]=[]),t[n].push(o[n])):r[n]=o[n];if(r.disabled||r["aria-disabled"])for(let o in t)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(o)&&(t[o]=[n=>{var i;return(i=n==null?void 0:n.preventDefault)==null?void 0:i.call(n)}]);for(let o in t)Object.assign(r,{[o](n,...i){let l=t[o];for(let s of l){if((n instanceof Event||(n==null?void 0:n.nativeEvent)instanceof Event)&&n.defaultPrevented)return;s(n,...i)}}});return r}function V(...e){var a;if(e.length===0)return{};if(e.length===1)return e[0];let r={},t={};for(let o of e)for(let n in o)n.startsWith("on")&&typeof o[n]=="function"?((a=t[n])!=null||(t[n]=[]),t[n].push(o[n])):r[n]=o[n];for(let o in t)Object.assign(r,{[o](...n){let i=t[o];for(let l of i)l==null||l(...n)}});return r}function Y(e){var r;return Object.assign(k(e),{displayName:(r=e.displayName)!=null?r:e.name})}function m(e){let r=Object.assign({},e);for(let t in r)r[t]===void 0&&delete r[t];return r}function h(e,r=[]){let t=Object.assign({},e);for(let a of r)a in t&&delete t[a];return t}function D(e){return v.version.split(".")[0]>="19"?e.props.ref:e.ref}function E(e){if(e!=null&&e.$$typeof===Symbol.for("react.lazy")){let r=e._payload;if(r!=null&&r.status==="fulfilled")return E(r.value)}return e}function b(e){return e===S||e===Symbol.for("react.fragment")}function L(e){return b(e.type)}export{A as RenderFeatures,C as RenderStrategy,m as compact,Y as forwardRefWithAs,b as isFragment,L as isFragmentInstance,V as mergeProps,K as useRender}; diff --git a/node_modules/@headlessui/react/dist/utils/stable-collection.d.ts b/node_modules/@headlessui/react/dist/utils/stable-collection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..44790c542a3f9b6dd2a986e4143443a8ffce5e99 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/stable-collection.d.ts @@ -0,0 +1,5 @@ +import * as React from 'react'; +export declare function StableCollection({ children }: { + children: React.ReactNode | React.ReactNode[]; +}): React.JSX.Element; +export declare function useStableCollectionIndex(group: string): number; diff --git a/node_modules/@headlessui/react/dist/utils/stable-collection.js b/node_modules/@headlessui/react/dist/utils/stable-collection.js new file mode 100644 index 0000000000000000000000000000000000000000..4cc02770856ee938874a36ce858234b8fd3692b5 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/stable-collection.js @@ -0,0 +1 @@ +import*as l from"react";const s=l.createContext(null);function a(){return{groups:new Map,get(o,e){var i;let t=this.groups.get(o);t||(t=new Map,this.groups.set(o,t));let n=(i=t.get(e))!=null?i:0;t.set(e,n+1);let r=Array.from(t.keys()).indexOf(e);function u(){let c=t.get(e);c>1?t.set(e,c-1):t.delete(e)}return[r,u]}}}function f({children:o}){let e=l.useRef(a());return l.createElement(s.Provider,{value:e},o)}function C(o){let e=l.useContext(s);if(!e)throw new Error("You must wrap your component in a ");let t=l.useId(),[n,r]=e.current.get(o,t);return l.useEffect(()=>r,[]),n}export{f as StableCollection,C as useStableCollectionIndex}; diff --git a/node_modules/@headlessui/react/dist/utils/start-transition.d.ts b/node_modules/@headlessui/react/dist/utils/start-transition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01cc687afe569bd175125f0da54cbdbb9683c2dd --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/start-transition.d.ts @@ -0,0 +1,2 @@ +import React from 'react'; +export declare let startTransition: typeof React.startTransition; diff --git a/node_modules/@headlessui/react/dist/utils/start-transition.js b/node_modules/@headlessui/react/dist/utils/start-transition.js new file mode 100644 index 0000000000000000000000000000000000000000..f4b61d7aba74f0d8d8c98bb934d3d4e5c37c8d3a --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/start-transition.js @@ -0,0 +1 @@ +var t;import r from"react";let a=(t=r.startTransition)!=null?t:function(i){i()};export{a as startTransition}; diff --git a/node_modules/@headlessui/react/dist/utils/store.d.ts b/node_modules/@headlessui/react/dist/utils/store.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0db445f44e61e199798d80d26dc6c9aa52181d93 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/store.d.ts @@ -0,0 +1,11 @@ +type ChangeFn = () => void; +type UnsubscribeFn = () => void; +type ActionFn = (this: T, ...args: any[]) => T | void; +type StoreActions = Record>; +export interface Store { + getSnapshot(): T; + subscribe(onChange: ChangeFn): UnsubscribeFn; + dispatch(action: ActionKey, ...args: any[]): void; +} +export declare function createStore(initial: () => T, actions: StoreActions): Store; +export {}; diff --git a/node_modules/@headlessui/react/dist/utils/store.js b/node_modules/@headlessui/react/dist/utils/store.js new file mode 100644 index 0000000000000000000000000000000000000000..14116c6732f198e4f140b256ca53e7ceb5a4f506 --- /dev/null +++ b/node_modules/@headlessui/react/dist/utils/store.js @@ -0,0 +1 @@ +function a(o,r){let t=o(),n=new Set;return{getSnapshot(){return t},subscribe(e){return n.add(e),()=>n.delete(e)},dispatch(e,...s){let i=r[e].call(t,...s);i&&(t=i,n.forEach(c=>c()))}}}export{a as createStore}; diff --git a/node_modules/@headlessui/react/package.json b/node_modules/@headlessui/react/package.json new file mode 100644 index 0000000000000000000000000000000000000000..79ec21e8b9fc77ac73b975a6438d92ad1012e34a --- /dev/null +++ b/node_modules/@headlessui/react/package.json @@ -0,0 +1,65 @@ +{ + "name": "@headlessui/react", + "version": "2.2.10", + "description": "A set of completely unstyled, fully accessible UI components for React, designed to integrate beautifully with Tailwind CSS.", + "main": "dist/index.cjs", + "typings": "dist/index.d.ts", + "module": "dist/headlessui.esm.js", + "license": "MIT", + "files": [ + "README.md", + "dist" + ], + "exports": { + "types": { + "import": "./dist/index.d.ts", + "require": "./dist/index.d.cts" + }, + "import": "./dist/headlessui.esm.js", + "require": "./dist/index.cjs" + }, + "type": "module", + "sideEffects": false, + "engines": { + "node": ">=10" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/tailwindlabs/headlessui.git", + "directory": "packages/@headlessui-react" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "prepublishOnly": "npm run build", + "build": "../../scripts/build.sh --external:react --external:react-dom --external:use-sync-external-store", + "watch": "../../scripts/watch.sh --external:react --external:react-dom --external:use-sync-external-store", + "test": "../../scripts/test.sh", + "lint": "../../scripts/lint.sh", + "lint-types": "npm run attw -P --workspaces --if-present", + "playground": "npm run dev --workspace=playground-react", + "clean": "rimraf ./dist" + }, + "peerDependencies": { + "react": "^18 || ^19 || ^19.0.0-rc", + "react-dom": "^18 || ^19 || ^19.0.0-rc" + }, + "devDependencies": { + "@testing-library/react": "^15.0.7", + "@types/react": "^18.3.3", + "@types/react-dom": "^18.3.0", + "@types/use-sync-external-store": "^1.5.0", + "jsdom-testing-mocks": "^1.13.1", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "snapshot-diff": "^0.10.0" + }, + "dependencies": { + "@floating-ui/react": "^0.26.16", + "@react-aria/focus": "^3.20.2", + "@react-aria/interactions": "^3.25.0", + "@tanstack/react-virtual": "^3.13.9", + "use-sync-external-store": "^1.5.0" + } +} diff --git a/node_modules/@hookform/resolvers/LICENSE b/node_modules/@hookform/resolvers/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..139faf48e1b4926a8743bc7a5bd67287f43f0dd0 --- /dev/null +++ b/node_modules/@hookform/resolvers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-present Beier(Bill) Luo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@hookform/resolvers/README.md b/node_modules/@hookform/resolvers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..25b0aa8457ca3eb952aa392641a93c7a79fea9f3 --- /dev/null +++ b/node_modules/@hookform/resolvers/README.md @@ -0,0 +1,1038 @@ +
+

+ + React Hook Form Logo - React hook custom hook for form validation + +

+
+ +

Performant, flexible and extensible forms with easy to use validation.

+ +
+ +[![npm downloads](https://img.shields.io/npm/dm/@hookform/resolvers.svg?style=for-the-badge)](https://www.npmjs.com/package/@hookform/resolvers) +[![npm](https://img.shields.io/npm/dt/@hookform/resolvers.svg?style=for-the-badge)](https://www.npmjs.com/package/@hookform/resolvers) +[![npm](https://img.shields.io/bundlephobia/minzip/@hookform/resolvers?style=for-the-badge)](https://bundlephobia.com/result?p=@hookform/resolvers) + +
+ +## React Hook Form Resolvers + +This function allows you to use any external validation library such as Yup, Zod, Joi, Vest, Ajv and many others. The goal is to make sure you can seamlessly integrate whichever validation library you prefer. If you're not using a library, you can always write your own logic to validate your forms. + +## Install + +Install your preferred validation library alongside `@hookform/resolvers`. + + npm install @hookform/resolvers # npm + yarn add @hookform/resolvers # yarn + pnpm install @hookform/resolvers # pnpm + bun install @hookform/resolvers # bun + +
+ Resolver Comparison + +| resolver | Infer values
from schema | [criteriaMode](https://react-hook-form.com/docs/useform#criteriaMode) | +| -------------------- | -------------------------------- | ----------------------------------------------------------------------- | +| AJV | ❌ | `firstError \| all` | +| ata-validator | ❌ | `firstError \| all` | +| Arktype | ✅ | `firstError` | +| class-validator | ✅ | `firstError \| all` | +| computed-types | ✅ | `firstError` | +| Effect | ✅ | `firstError \| all` | +| fluentvalidation-ts | ❌ | `firstError` | +| io-ts | ✅ | `firstError` | +| joi | ❌ | `firstError \| all` | +| Nope | ❌ | `firstError` | +| Standard Schema | ✅ | `firstError \| all` | +| Superstruct | ✅ | `firstError` | +| typanion | ✅ | `firstError` | +| typebox | ✅ | `firstError \| all` | +| typeschema | ❌ | `firstError \| all` | +| valibot | ✅ | `firstError \| all` | +| vest | ❌ | `firstError \| all` | +| vine | ✅ | `firstError \| all` | +| yup | ✅ | `firstError \| all` | +| zod | ✅ | `firstError \| all` | + +
+ +## TypeScript + +Most of the resolvers can infer the output type from the schema. See comparison table for more details. + +```tsx +useForm() +``` + +Example: + +```tsx +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { z } from 'zod'; // or 'zod/v4' + +const schema = z.object({ + id: z.number(), +}); + +// Automatically infers the output type from the schema +useForm({ + resolver: zodResolver(schema), +}); + +// Force the output type +useForm, any, z.output>({ + resolver: zodResolver(schema), +}); +``` + +## Links + +- [React-hook-form validation resolver documentation](https://react-hook-form.com/docs/useform#resolver) + +### Table of Contents + +- [Install](#install) +- [TypeScript](#typescript) +- [Links](#links) + - [Table of Contents](#table-of-contents) +- [API](#api) +- [Quickstart](#quickstart) + - [Yup](#yup) + - [Zod](#zod) + - [Superstruct](#superstruct) + - [Joi](#joi) + - [Vest](#vest) + - [Class Validator](#class-validator) + - [io-ts](#io-ts) + - [Nope](#nope) + - [computed-types](#computed-types) + - [typanion](#typanion) + - [Ajv](#ajv) + - [TypeBox](#typebox) + - [With `ValueCheck`](#with-valuecheck) + - [With `TypeCompiler`](#with-typecompiler) + - [Custom/third-party types](#customthird-party-types-eg-elysiajss-tfiles) + - [ArkType](#arktype) + - [Valibot](#valibot) + - [TypeSchema](#typeschema) + - [effect-ts](#effect-ts) + - [VineJS](#vinejs) + - [fluentvalidation-ts](#fluentvalidation-ts) + - [standard-schema](#standard-schema) + - [ata-validator](#ata-validator) +- [Backers](#backers) +- [Contributors](#contributors) + +## API + +``` +type Options = { + mode: 'async' | 'sync', + raw?: boolean +} + +resolver(schema: object, schemaOptions?: object, resolverOptions: Options) +``` + +| | type | Required | Description | +| --------------- | -------- | -------- | --------------------------------------------- | +| schema | `object` | ✓ | validation schema | +| schemaOptions | `object` | | validation library schema options | +| resolverOptions | `object` | | resolver options, `async` is the default mode | + +## Quickstart + +### [Yup](https://github.com/jquense/yup) + +Dead simple Object schema validation. + +[![npm](https://img.shields.io/bundlephobia/minzip/yup?style=for-the-badge)](https://bundlephobia.com/result?p=yup) + +> ⚠️ Pass context via `useForm({ context })`, not via `yupResolver`'s `schemaOptions`. `schemaOptions.context` is overridden by the form context, so use the `useForm` context object instead. + +```tsx +// Correct +useForm({ + resolver: yupResolver(schema), + context: { foo: true }, +}); + +// Avoid - schemaOptions.context will be ignored/overridden +yupResolver(schema, { context: { foo: true } }); +``` + +```tsx +import { useForm } from 'react-hook-form'; +import { yupResolver } from '@hookform/resolvers/yup'; +import * as yup from 'yup'; + +const schema = yup + .object() + .shape({ + name: yup.string().required(), + age: yup.number().required(), + }) + .required(); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: yupResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +### [Zod](https://github.com/colinhacks/zod) + +TypeScript-first schema validation with static type inference + +[![npm](https://img.shields.io/bundlephobia/minzip/zod?style=for-the-badge)](https://bundlephobia.com/result?p=zod) + +> ⚠️ Example below uses the `valueAsNumber`, which requires `react-hook-form` v6.12.0 (released Nov 28, 2020) or later. + +```tsx +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { z } from 'zod'; // or 'zod/v4' + +const schema = z.object({ + name: z.string().min(1, { message: 'Required' }), + age: z.number().min(10), +}); + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: zodResolver(schema), + }); + + return ( +
console.log(d))}> + + {errors.name?.message &&

{errors.name?.message}

} + + {errors.age?.message &&

{errors.age?.message}

} + +
+ ); +}; +``` + +> ⚠️ If your schema uses `.default(...)` on a field, that field becomes optional on the schema's _input_ type (`z.input`) but stays required on its _output_ type (`z.output`/`z.infer`) — the default only fills it in after validation. Passing a single generic to `useForm` pins both to the same type and will conflict with `zodResolver`, which infers input and output separately. Either omit the generic and let it infer from `resolver`, or specify all three explicitly: +> +> ```tsx +> const schema = z.object({ debug_mode: z.boolean().default(true) }); +> +> useForm, unknown, z.output>({ +> resolver: zodResolver(schema), +> }); +> ``` + +### [Superstruct](https://github.com/ianstormtaylor/superstruct) + +A simple and composable way to validate data in JavaScript (or TypeScript). + +[![npm](https://img.shields.io/bundlephobia/minzip/superstruct?style=for-the-badge)](https://bundlephobia.com/result?p=superstruct) + +```tsx +import { useForm } from 'react-hook-form'; +import { superstructResolver } from '@hookform/resolvers/superstruct'; +import { object, string, number } from 'superstruct'; + +const schema = object({ + name: string(), + age: number(), +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: superstructResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +### [Joi](https://github.com/sideway/joi) + +The most powerful data validation library for JS. + +[![npm](https://img.shields.io/bundlephobia/minzip/joi?style=for-the-badge)](https://bundlephobia.com/result?p=joi) + +```tsx +import { useForm } from 'react-hook-form'; +import { joiResolver } from '@hookform/resolvers/joi'; +import Joi from 'joi'; + +const schema = Joi.object({ + name: Joi.string().required(), + age: Joi.number().required(), +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: joiResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +### [Vest](https://github.com/ealush/vest) + +Vest 🦺 Declarative Validation Testing. + +[![npm](https://img.shields.io/bundlephobia/minzip/vest?style=for-the-badge)](https://bundlephobia.com/result?p=vest) + +```tsx +import { useForm } from 'react-hook-form'; +import { vestResolver } from '@hookform/resolvers/vest'; +import { create, test, enforce } from 'vest'; + +const validationSuite = create((data = {}) => { + test('username', 'Username is required', () => { + enforce(data.username).isNotEmpty(); + }); + + test('password', 'Password is required', () => { + enforce(data.password).isNotEmpty(); + }); +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: vestResolver(validationSuite), + }); + + return ( +
console.log(data))}> + + + +
+ ); +}; +``` + +### [Class Validator](https://github.com/typestack/class-validator) + +Decorator-based property validation for classes. + +[![npm](https://img.shields.io/bundlephobia/minzip/class-validator?style=for-the-badge)](https://bundlephobia.com/result?p=class-validator) + +> ⚠️ Remember to add these options to your `tsconfig.json`! + +``` +"strictPropertyInitialization": false, +"experimentalDecorators": true +``` + +```tsx +import { useForm } from 'react-hook-form'; +import { classValidatorResolver } from '@hookform/resolvers/class-validator'; +import { Length, Min, IsEmail } from 'class-validator'; + +class User { + @Length(2, 30) + username: string; + + @IsEmail() + email: string; +} + +const resolver = classValidatorResolver(User); + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ resolver }); + + return ( +
console.log(data))}> + + {errors.username && {errors.username.message}} + + {errors.email && {errors.email.message}} + +
+ ); +}; +``` + +### [io-ts](https://github.com/gcanti/io-ts) + +Validate your data with powerful decoders. + +[![npm](https://img.shields.io/bundlephobia/minzip/io-ts?style=for-the-badge)](https://bundlephobia.com/result?p=io-ts) + +```tsx +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { ioTsResolver } from '@hookform/resolvers/io-ts'; +import t from 'io-ts'; +// you don't have to use io-ts-types, but it's very useful +import tt from 'io-ts-types'; + +const schema = t.type({ + username: t.string, + age: tt.NumberFromString, +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: ioTsResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; + +export default App; +``` + +### [Nope](https://github.com/bvego/nope-validator) + +A small, simple, and fast JS validator + +[![npm](https://img.shields.io/bundlephobia/minzip/nope-validator?style=for-the-badge)](https://bundlephobia.com/result?p=nope-validator) + +```tsx +import { useForm } from 'react-hook-form'; +import { nopeResolver } from '@hookform/resolvers/nope'; +import Nope from 'nope-validator'; + +const schema = Nope.object().shape({ + name: Nope.string().required(), + age: Nope.number().required(), +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: nopeResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +### [computed-types](https://github.com/neuledge/computed-types) + +TypeScript-first schema validation with static type inference + +[![npm](https://img.shields.io/bundlephobia/minzip/computed-types?style=for-the-badge)](https://bundlephobia.com/result?p=computed-types) + +```tsx +import { useForm } from 'react-hook-form'; +import { computedTypesResolver } from '@hookform/resolvers/computed-types'; +import Schema, { number, string } from 'computed-types'; + +const schema = Schema({ + username: string.min(1).error('username field is required'), + age: number, +}); + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: computedTypesResolver(schema), + }); + + return ( +
console.log(d))}> + + {errors.name?.message &&

{errors.name?.message}

} + + {errors.age?.message &&

{errors.age?.message}

} + +
+ ); +}; +``` + +### [typanion](https://github.com/arcanis/typanion) + +Static and runtime type assertion library with no dependencies + +[![npm](https://img.shields.io/bundlephobia/minzip/typanion?style=for-the-badge)](https://bundlephobia.com/result?p=typanion) + +```tsx +import { useForm } from 'react-hook-form'; +import { typanionResolver } from '@hookform/resolvers/typanion'; +import * as t from 'typanion'; + +const isUser = t.isObject({ + username: t.applyCascade(t.isString(), [t.hasMinLength(1)]), + age: t.applyCascade(t.isNumber(), [ + t.isInteger(), + t.isInInclusiveRange(1, 100), + ]), +}); + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: typanionResolver(isUser), + }); + + return ( +
console.log(d))}> + + {errors.name?.message &&

{errors.name?.message}

} + + {errors.age?.message &&

{errors.age?.message}

} + +
+ ); +}; +``` + +### [Ajv](https://github.com/ajv-validator/ajv) + +The fastest JSON validator for Node.js and browser + +[![npm](https://img.shields.io/bundlephobia/minzip/ajv?style=for-the-badge)](https://bundlephobia.com/result?p=ajv) + +```tsx +import { useForm } from 'react-hook-form'; +import { ajvResolver } from '@hookform/resolvers/ajv'; + +// must use `minLength: 1` to implement required field +const schema = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 1, + errorMessage: { minLength: 'username field is required' }, + }, + password: { + type: 'string', + minLength: 1, + errorMessage: { minLength: 'password field is required' }, + }, + }, + required: ['username', 'password'], + additionalProperties: false, +}; + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: ajvResolver(schema), + }); + + return ( +
console.log(data))}> + + {errors.username && {errors.username.message}} + + {errors.password && {errors.password.message}} + +
+ ); +}; +``` + +### [TypeBox](https://github.com/sinclairzx81/typebox) + +JSON Schema Type Builder with Static Type Resolution for TypeScript + +[![npm](https://img.shields.io/bundlephobia/minzip/@sinclair/typebox?style=for-the-badge)](https://bundlephobia.com/result?p=@sinclair/typebox) + +#### With `ValueCheck` + +```tsx +import { useForm } from 'react-hook-form'; +import { typeboxResolver } from '@hookform/resolvers/typebox'; +import { Type } from '@sinclair/typebox'; + +const schema = Type.Object({ + username: Type.String({ minLength: 1 }), + password: Type.String({ minLength: 1 }), +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: typeboxResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +#### With `TypeCompiler` + +A high-performance JIT of `TypeBox`, [read more](https://github.com/sinclairzx81/typebox#typecompiler) + +```tsx +import { useForm } from 'react-hook-form'; +import { typeboxResolver } from '@hookform/resolvers/typebox'; +import { Type } from '@sinclair/typebox'; +import { TypeCompiler } from '@sinclair/typebox/compiler'; + +const schema = Type.Object({ + username: Type.String({ minLength: 1 }), + password: Type.String({ minLength: 1 }), +}); + +const typecheck = TypeCompiler.Compile(schema); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: typeboxResolver(typecheck), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +#### Custom/third-party types (e.g. ElysiaJS's `t.Files()`) + +`typeboxResolver` validates using `@sinclair/typebox`'s own `Value.Errors`/`Value.Check`, so any schema +`Kind` not built into TypeBox (custom types, or ones defined by a third-party library such as ElysiaJS) +must be registered with TypeBox's own `TypeRegistry` (and `FormatRegistry` for string formats) before +it's used — this is a TypeBox-level extension point, not something `@hookform/resolvers` wraps or needs +to expose separately: + +```tsx +import { TypeRegistry } from '@sinclair/typebox'; + +if (!TypeRegistry.Has('Files')) { + TypeRegistry.Set('Files', (schema, value) => Array.isArray(value)); +} +``` + +Make sure this registration runs against the same `@sinclair/typebox` module instance the schema was +built with — if a library vendors its own copy of `@sinclair/typebox` instead of relying on the shared +peer dependency, its registrations won't be visible here, and you'll see a runtime `"Unknown type"` error. + +### [ArkType](https://github.com/arktypeio/arktype) + +TypeScript's 1:1 validator, optimized from editor to runtime + +[![npm](https://img.shields.io/bundlephobia/minzip/arktype?style=for-the-badge)](https://bundlephobia.com/result?p=arktype) + +```tsx +import { useForm } from 'react-hook-form'; +import { arktypeResolver } from '@hookform/resolvers/arktype'; +import { type } from 'arktype'; + +const schema = type({ + username: 'string>1', + password: 'string>1', +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: arktypeResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +### [Valibot](https://github.com/fabian-hiller/valibot) + +The modular and type safe schema library for validating structural data + +[![npm](https://img.shields.io/bundlephobia/minzip/valibot?style=for-the-badge)](https://bundlephobia.com/result?p=valibot) + +```tsx +import { useForm } from 'react-hook-form'; +import { valibotResolver } from '@hookform/resolvers/valibot'; +import * as v from 'valibot'; + +const schema = v.object({ + username: v.pipe( + v.string('username is required'), + v.minLength(3, 'Needs to be at least 3 characters'), + v.endsWith('cool', 'Needs to end with `cool`'), + ), + password: v.string('password is required'), +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: valibotResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +> ⚠️ If your schema uses `v.transform(...)` (or `v.pipe(..., v.transform(...))`) on a field, that field's +> parsed _output_ type can differ from what the user actually types (its _input_ type) — e.g. a string +> input transformed into a number. Passing a single generic to `useForm` pins both the submitted values +> and the `handleSubmit` payload to that one type, which conflicts with `valibotResolver`, since it infers +> input and output separately. Either omit the generic and let it infer from `resolver`, or specify all +> three explicitly: +> +> ```tsx +> const schema = v.object({ +> name: v.string(), +> number: v.pipe(v.string(), v.transform(Number)), +> }); +> +> useForm, unknown, v.InferOutput>({ +> resolver: valibotResolver(schema), +> }); +> ``` + +### [TypeSchema](https://typeschema.com) + +Universal adapter for schema validation, compatible with [any validation library](https://typeschema.com/#coverage) + +[![npm](https://img.shields.io/bundlephobia/minzip/@typeschema/main?style=for-the-badge)](https://bundlephobia.com/result?p=@typeschema/main) + +```tsx +import { useForm } from 'react-hook-form'; +import { typeschemaResolver } from '@hookform/resolvers/typeschema'; +import { z } from 'zod'; + +// Use your favorite validation library +const schema = z.object({ + username: z.string().min(1, { message: 'Required' }), + password: z.number().min(1, { message: 'Required' }), +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: typeschemaResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +### [effect-ts](https://github.com/Effect-TS/effect) + +A powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library. + +[![npm](https://img.shields.io/bundlephobia/minzip/effect?style=for-the-badge)](https://bundlephobia.com/result?p=effect) + +```tsx +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { effectTsResolver } from '@hookform/resolvers/effect-ts'; +import { Schema } from 'effect'; + +const schema = Schema.Struct({ + username: Schema.String.pipe( + Schema.nonEmptyString({ message: () => 'username required' }), + ), + password: Schema.String.pipe( + Schema.nonEmptyString({ message: () => 'password required' }), + ), +}); + +type FormData = typeof schema.Type; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { + register, + handleSubmit, + formState: { errors }, + // provide generic if TS has issues inferring types + } = useForm({ + resolver: effectTsResolver(schema), + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} +``` + +### [VineJS](https://github.com/vinejs/vine) + +VineJS is a form data validation library for Node.js + +[![npm](https://img.shields.io/bundlephobia/minzip/@vinejs/vine?style=for-the-badge)](https://bundlephobia.com/result?p=@vinejs/vine) + +```tsx +import { useForm } from 'react-hook-form'; +import { vineResolver } from '@hookform/resolvers/vine'; +import vine from '@vinejs/vine'; + +const schema = vine.create({ + username: vine.string().minLength(1), + password: vine.string().minLength(1), +}); + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: vineResolver(schema), + }); + + return ( +
console.log(d))}> + + {errors.username && {errors.username.message}} + + {errors.password && {errors.password.message}} + +
+ ); +}; +``` + +### [fluentvalidation-ts](https://github.com/AlexJPotter/fluentvalidation-ts) + +A TypeScript-first library for building strongly-typed validation rules + +[![npm](https://img.shields.io/bundlephobia/minzip/fluentvalidation-ts?style=for-the-badge)](https://bundlephobia.com/result?p=fluentvalidation-ts) + +```tsx +import { useForm } from 'react-hook-form'; +import { fluentValidationResolver } from '@hookform/resolvers/fluentvalidation-ts'; +import { Validator } from 'fluentvalidation-ts'; + +class FormDataValidator extends Validator { + constructor() { + super(); + + this.ruleFor('username') + .notEmpty() + .withMessage('username is a required field'); + this.ruleFor('password') + .notEmpty() + .withMessage('password is a required field'); + } +} + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: fluentValidationResolver(new FormDataValidator()), + }); + + return ( +
console.log(d))}> + + {errors.username && {errors.username.message}} + + {errors.password && {errors.password.message}} + +
+ ); +}; +``` + +### [standard-schema](https://github.com/standard-schema/standard-schema) + +A standard interface for TypeScript schema validation libraries + +[![npm](https://img.shields.io/bundlephobia/minzip/@standard-schema/spec?style=for-the-badge)](https://bundlephobia.com/result?p=@standard-schema/spec) + +Example zod + +```tsx +import { useForm } from 'react-hook-form'; +import { standardSchemaResolver } from '@hookform/resolvers/standard-schema'; +import { z } from 'zod'; + +const schema = z.object({ + name: z.string().min(1, { message: 'Required' }), + age: z.number().min(10), +}); + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: standardSchemaResolver(schema), + }); + + return ( +
console.log(d))}> + + {errors.name?.message &&

{errors.name?.message}

} + + {errors.age?.message &&

{errors.age?.message}

} + +
+ ); +}; +``` + +Example arkType + +```tsx +import { useForm } from 'react-hook-form'; +import { standardSchemaResolver } from '@hookform/resolvers/standard-schema'; +import { type } from 'arktype'; + +const schema = type({ + username: 'string>1', + password: 'string>1', +}); + +const App = () => { + const { register, handleSubmit } = useForm({ + resolver: standardSchemaResolver(schema), + }); + + return ( +
console.log(d))}> + + + +
+ ); +}; +``` + +### [ata-validator](https://github.com/nicholasgasior/ata-validator) + +A JSON Schema-based validator for JavaScript and TypeScript + +[![npm](https://img.shields.io/bundlephobia/minzip/ata-validator?style=for-the-badge)](https://bundlephobia.com/result?p=ata-validator) + +```tsx +import { useForm } from 'react-hook-form'; +import { ataResolver } from '@hookform/resolvers/ata-validator'; + +const schema = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 1, + }, + password: { + type: 'string', + minLength: 1, + }, + }, + required: ['username', 'password'], +}; + +const App = () => { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: ataResolver(schema), + }); + + return ( +
console.log(data))}> + + {errors.username && {errors.username.message}} + + {errors.password && {errors.password.message}} + +
+ ); +}; +``` + +## Backers + +Thanks go to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)]. + + + React Hook Form backers + + +## Contributors + +Thanks go to these wonderful people! [[Become a contributor](CONTRIBUTING.md)]. diff --git a/node_modules/@hookform/resolvers/ajv/dist/ajv.d.ts b/node_modules/@hookform/resolvers/ajv/dist/ajv.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b06aec3048c6a4e3e107beab0b370050797dae7 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/dist/ajv.d.ts @@ -0,0 +1,22 @@ +import { Resolver } from './types'; +/** + * Creates a resolver for react-hook-form using Ajv schema validation + * @param {Schema} schema - The Ajv schema to validate against + * @param {Object} schemaOptions - Additional schema validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='async'] - Validation mode + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * const schema = ajv.compile({ + * type: 'object', + * properties: { + * name: { type: 'string' }, + * age: { type: 'number' } + * } + * }); + * + * useForm({ + * resolver: ajvResolver(schema) + * }); + */ +export declare const ajvResolver: Resolver; diff --git a/node_modules/@hookform/resolvers/ajv/dist/ajv.js b/node_modules/@hookform/resolvers/ajv/dist/ajv.js new file mode 100644 index 0000000000000000000000000000000000000000..01e1c4fbfd11f1a0be6ecf1618decd694e142357 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/dist/ajv.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers"),r=require("ajv"),a=require("ajv-errors"),s=require("ajv-formats"),t=require("react-hook-form");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/o(r),n=/*#__PURE__*/o(a),u=/*#__PURE__*/o(s),c=function(e,r){for(var a=Object.create(null),s=function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty);var s=e.instancePath.substring(1).replace(/\//g,".");if(a[s]||(a[s]={message:e.message,type:e.keyword}),r){var o=a[s].types,i=o&&o[e.keyword];a[s]=t.appendErrors(s,r,a,e.keyword,i?[].concat(i,e.message||""):e.message)}},o=function(){var r=e[i];"errorMessage"===r.keyword?r.params.errors.forEach(function(e){e.message=r.message,s(e)}):s(r)},i=0;i {\n // A null-prototype object avoids false-positive hits from inherited\n // members (e.g. `toString`, `constructor`) when a field is named after\n // one of them — a plain `{}` would make `!parsedErrors[path]` truthy-skip\n // those paths and silently drop their errors.\n const parsedErrors: Record = Object.create(null);\n\n const reduceError = (error: AjvError) => {\n // Ajv will return empty instancePath when require error\n if (error.keyword === 'required') {\n error.instancePath += `/${error.params.missingProperty}`;\n }\n\n // `/deepObject/data` -> `deepObject.data`\n const path = error.instancePath.substring(1).replace(/\\//g, '.');\n\n if (!parsedErrors[path]) {\n parsedErrors[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = parsedErrors[path].types;\n const messages = types && types[error.keyword];\n\n parsedErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n parsedErrors,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n };\n\n for (let index = 0; index < ajvErrors.length; index += 1) {\n const error = ajvErrors[index];\n\n if (error.keyword === 'errorMessage') {\n error.params.errors.forEach((originalError) => {\n originalError.message = error.message;\n reduceError(originalError);\n });\n } else {\n reduceError(error);\n }\n }\n\n return parsedErrors;\n};\n\n/**\n * Creates a resolver for react-hook-form using Ajv schema validation\n * @param {Schema} schema - The Ajv schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = ajv.compile({\n * type: 'object',\n * properties: {\n * name: { type: 'string' },\n * age: { type: 'number' }\n * }\n * });\n *\n * useForm({\n * resolver: ajvResolver(schema)\n * });\n */\nexport const ajvResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, options) => {\n const ajv = new Ajv(\n Object.assign(\n {},\n {\n allErrors: true,\n validateSchema: true,\n },\n schemaOptions,\n ),\n );\n\n ajvErrors(ajv);\n addFormats(ajv);\n\n const validate = ajv.compile(\n Object.assign(\n { $async: resolverOptions && resolverOptions.mode === 'async' },\n schema,\n ),\n );\n\n // Ajv mutates the object passed to `validate` in place (e.g. to apply\n // `useDefaults`, `removeAdditional`, or `coerceTypes`). Validating a\n // clone keeps those mutations from leaking into react-hook-form's\n // internal form values, which are passed in by reference.\n const parsedValues = structuredClone(values);\n const valid = validate(parsedValues);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return valid\n ? { values: parsedValues, errors: {} }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validate.errors as DefinedError[],\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n"],"names":["parseErrorSchema","ajvErrors","validateAllFieldCriteria","parsedErrors","Object","create","reduceError","error","keyword","instancePath","params","missingProperty","path","substring","replace","message","type","types","messages","appendErrors","concat","_loop","index","errors","forEach","originalError","length","schema","schemaOptions","resolverOptions","values","_","options","ajv","Ajv","assign","allErrors","validateSchema","addFormats","validate","compile","$async","mode","parsedValues","structuredClone","valid","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","toNestErrors","criteriaMode","e","reject"],"mappings":"4QAOMA,EAAmB,SACvBC,EACAC,GAwCA,IAlCA,IAAMC,EAA2CC,OAAOC,OAAO,MAEzDC,EAAc,SAACC,GAEG,aAAlBA,EAAMC,UACRD,EAAME,cAAY,IAAQF,EAAMG,OAAOC,iBAIzC,IAAMC,EAAOL,EAAME,aAAaI,UAAU,GAAGC,QAAQ,MAAO,KAS5D,GAPKX,EAAaS,KAChBT,EAAaS,GAAQ,CACnBG,QAASR,EAAMQ,QACfC,KAAMT,EAAMC,UAIZN,EAA0B,CAC5B,IAAMe,EAAQd,EAAaS,GAAMK,MAC3BC,EAAWD,GAASA,EAAMV,EAAMC,SAEtCL,EAAaS,GAAQO,eACnBP,EACAV,EACAC,EACAI,EAAMC,QACNU,EACK,GAAgBE,OAAOF,EAAsBX,EAAMQ,SAAW,IAC/DR,EAAMQ,QAEd,CACF,EAAEM,EAAAA,WAGA,IAAMd,EAAQN,EAAUqB,GAEF,iBAAlBf,EAAMC,QACRD,EAAMG,OAAOa,OAAOC,QAAQ,SAACC,GAC3BA,EAAcV,QAAUR,EAAMQ,QAC9BT,EAAYmB,EACd,GAEAnB,EAAYC,EAEhB,EAXSe,EAAQ,EAAGA,EAAQrB,EAAUyB,OAAQJ,GAAS,EAACD,IAaxD,OAAOlB,CACT,sBAuBE,SAACwB,EAAQC,EAAeC,GAAoB,YAApBA,IAAAA,IAAAA,EAAkB,CAAA,GAAE,SACrCC,EAAQC,EAAGC,GAAW,IAC3B,IAAMC,EAAM,IAAIC,EAAG,QACjB9B,OAAO+B,OACL,CAAA,EACA,CACEC,WAAW,EACXC,gBAAgB,GAElBT,IAIJ3B,EAAAA,QAAUgC,GACVK,EAAAA,QAAWL,GAEX,IAAMM,EAAWN,EAAIO,QACnBpC,OAAO+B,OACL,CAAEM,OAAQZ,GAA4C,UAAzBA,EAAgBa,MAC7Cf,IAQEgB,EAAeC,gBAAgBd,GAC/Be,EAAQN,EAASI,GAIvB,OAFAX,EAAQc,2BAA6BC,EAAAA,uBAAuB,CAAE,EAAEf,GAEhEgB,QAAAC,QAAOJ,EACH,CAAEf,OAAQa,EAAcpB,OAAQ,CAAA,GAChC,CACEO,OAAQ,CAAE,EACVP,OAAQ2B,EAAAA,aACNlD,EACEuC,EAAShB,QACRS,EAAQc,2BACkB,QAAzBd,EAAQmB,cAEZnB,IAGV,CAAC,MAAAoB,GAAA,OAAAJ,QAAAK,OAAAD,EAAA,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/ajv/dist/ajv.mjs b/node_modules/@hookform/resolvers/ajv/dist/ajv.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f080d385bfa3475cd98ccba435aa25d1706690dd --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/dist/ajv.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import o from"ajv";import a from"ajv-errors";import s from"ajv-formats";import{appendErrors as t}from"react-hook-form";var i=function(r,e){for(var o=Object.create(null),a=function(r){"required"===r.keyword&&(r.instancePath+="/"+r.params.missingProperty);var a=r.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:r.message,type:r.keyword}),e){var s=o[a].types,i=s&&s[r.keyword];o[a]=t(a,e,o,r.keyword,i?[].concat(i,r.message||""):r.message)}},s=function(){var e=r[i];"errorMessage"===e.keyword?e.params.errors.forEach(function(r){r.message=e.message,a(r)}):a(e)},i=0;i{const s=Object.create(null),o=e=>{"required"===e.keyword&&(e.instancePath+=`/${e.params.missingProperty}`);const o=e.instancePath.substring(1).replace(/\//g,".");if(s[o]||(s[o]={message:e.message,type:e.keyword}),r){const a=s[o].types,n=a&&a[e.keyword];s[o]=t(o,r,s,e.keyword,n?[].concat(n,e.message||""):e.message)}};for(let r=0;r{e.message=s.message,o(e)}):o(s)}return s},c=(t,c,m={})=>async(i,l,d)=>{const g=new s(Object.assign({},{allErrors:!0,validateSchema:!0},c));o(g),a(g);const p=g.compile(Object.assign({$async:m&&"async"===m.mode},t)),f=structuredClone(i),u=p(f);return d.shouldUseNativeValidation&&e({},d),u?{values:f,errors:{}}:{values:{},errors:r(n(p.errors,!d.shouldUseNativeValidation&&"all"===d.criteriaMode),d)}};export{c as ajvResolver}; +//# sourceMappingURL=ajv.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/ajv/dist/ajv.modern.mjs.map b/node_modules/@hookform/resolvers/ajv/dist/ajv.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e6609801380a1ad7e6d43f549952467d9cd48501 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/dist/ajv.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv.modern.mjs","sources":["../src/ajv.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport Ajv, { DefinedError } from 'ajv';\nimport ajvErrors from 'ajv-errors';\nimport addFormats from 'ajv-formats';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { AjvError, Resolver } from './types';\n\nconst parseErrorSchema = (\n ajvErrors: AjvError[],\n validateAllFieldCriteria: boolean,\n) => {\n // A null-prototype object avoids false-positive hits from inherited\n // members (e.g. `toString`, `constructor`) when a field is named after\n // one of them — a plain `{}` would make `!parsedErrors[path]` truthy-skip\n // those paths and silently drop their errors.\n const parsedErrors: Record = Object.create(null);\n\n const reduceError = (error: AjvError) => {\n // Ajv will return empty instancePath when require error\n if (error.keyword === 'required') {\n error.instancePath += `/${error.params.missingProperty}`;\n }\n\n // `/deepObject/data` -> `deepObject.data`\n const path = error.instancePath.substring(1).replace(/\\//g, '.');\n\n if (!parsedErrors[path]) {\n parsedErrors[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = parsedErrors[path].types;\n const messages = types && types[error.keyword];\n\n parsedErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n parsedErrors,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n };\n\n for (let index = 0; index < ajvErrors.length; index += 1) {\n const error = ajvErrors[index];\n\n if (error.keyword === 'errorMessage') {\n error.params.errors.forEach((originalError) => {\n originalError.message = error.message;\n reduceError(originalError);\n });\n } else {\n reduceError(error);\n }\n }\n\n return parsedErrors;\n};\n\n/**\n * Creates a resolver for react-hook-form using Ajv schema validation\n * @param {Schema} schema - The Ajv schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = ajv.compile({\n * type: 'object',\n * properties: {\n * name: { type: 'string' },\n * age: { type: 'number' }\n * }\n * });\n *\n * useForm({\n * resolver: ajvResolver(schema)\n * });\n */\nexport const ajvResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, options) => {\n const ajv = new Ajv(\n Object.assign(\n {},\n {\n allErrors: true,\n validateSchema: true,\n },\n schemaOptions,\n ),\n );\n\n ajvErrors(ajv);\n addFormats(ajv);\n\n const validate = ajv.compile(\n Object.assign(\n { $async: resolverOptions && resolverOptions.mode === 'async' },\n schema,\n ),\n );\n\n // Ajv mutates the object passed to `validate` in place (e.g. to apply\n // `useDefaults`, `removeAdditional`, or `coerceTypes`). Validating a\n // clone keeps those mutations from leaking into react-hook-form's\n // internal form values, which are passed in by reference.\n const parsedValues = structuredClone(values);\n const valid = validate(parsedValues);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return valid\n ? { values: parsedValues, errors: {} }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validate.errors as DefinedError[],\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n"],"names":["parseErrorSchema","ajvErrors","validateAllFieldCriteria","parsedErrors","Object","create","reduceError","error","keyword","instancePath","params","missingProperty","path","substring","replace","message","type","types","messages","appendErrors","concat","index","length","errors","forEach","originalError","ajvResolver","schema","schemaOptions","resolverOptions","async","values","_","options","ajv","Ajv","assign","allErrors","validateSchema","addFormats","validate","compile","$async","mode","parsedValues","structuredClone","valid","shouldUseNativeValidation","validateFieldsNatively","toNestErrors","criteriaMode"],"mappings":"sMAOA,MAAMA,EAAmBA,CACvBC,EACAC,KAMA,MAAMC,EAA2CC,OAAOC,OAAO,MAEzDC,EAAeC,IAEG,aAAlBA,EAAMC,UACRD,EAAME,cAAgB,IAAIF,EAAMG,OAAOC,mBAIzC,MAAMC,EAAOL,EAAME,aAAaI,UAAU,GAAGC,QAAQ,MAAO,KAS5D,GAPKX,EAAaS,KAChBT,EAAaS,GAAQ,CACnBG,QAASR,EAAMQ,QACfC,KAAMT,EAAMC,UAIZN,EAA0B,CAC5B,MAAMe,EAAQd,EAAaS,GAAMK,MAC3BC,EAAWD,GAASA,EAAMV,EAAMC,SAEtCL,EAAaS,GAAQO,EACnBP,EACAV,EACAC,EACAI,EAAMC,QACNU,EACK,GAAgBE,OAAOF,EAAsBX,EAAMQ,SAAW,IAC/DR,EAAMQ,QAEd,GAGF,IAAK,IAAIM,EAAQ,EAAGA,EAAQpB,EAAUqB,OAAQD,GAAS,EAAG,CACxD,MAAMd,EAAQN,EAAUoB,GAEF,iBAAlBd,EAAMC,QACRD,EAAMG,OAAOa,OAAOC,QAASC,IAC3BA,EAAcV,QAAUR,EAAMQ,QAC9BT,EAAYmB,EAAc,GAG5BnB,EAAYC,EAEhB,CAEA,OAAOJ,CAAY,EAuBRuB,EACXA,CAACC,EAAQC,EAAeC,EAAkB,KAC1CC,MAAOC,EAAQC,EAAGC,KAChB,MAAMC,EAAM,IAAIC,EACd/B,OAAOgC,OACL,CAAA,EACA,CACEC,WAAW,EACXC,gBAAgB,GAElBV,IAIJ3B,EAAUiC,GACVK,EAAWL,GAEX,MAAMM,EAAWN,EAAIO,QACnBrC,OAAOgC,OACL,CAAEM,OAAQb,GAA4C,UAAzBA,EAAgBc,MAC7ChB,IAQEiB,EAAeC,gBAAgBd,GAC/Be,EAAQN,EAASI,GAIvB,OAFAX,EAAQc,2BAA6BC,EAAuB,GAAIf,GAEzDa,EACH,CAAEf,OAAQa,EAAcrB,OAAQ,IAChC,CACEQ,OAAQ,CAAE,EACVR,OAAQ0B,EACNjD,EACEwC,EAASjB,QACRU,EAAQc,2BACkB,QAAzBd,EAAQiB,cAEZjB,GAEH"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/ajv/dist/ajv.module.js b/node_modules/@hookform/resolvers/ajv/dist/ajv.module.js new file mode 100644 index 0000000000000000000000000000000000000000..f080d385bfa3475cd98ccba435aa25d1706690dd --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/dist/ajv.module.js @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import o from"ajv";import a from"ajv-errors";import s from"ajv-formats";import{appendErrors as t}from"react-hook-form";var i=function(r,e){for(var o=Object.create(null),a=function(r){"required"===r.keyword&&(r.instancePath+="/"+r.params.missingProperty);var a=r.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:r.message,type:r.keyword}),e){var s=o[a].types,i=s&&s[r.keyword];o[a]=t(a,e,o,r.keyword,i?[].concat(i,r.message||""):r.message)}},s=function(){var e=r[i];"errorMessage"===e.keyword?e.params.errors.forEach(function(r){r.message=e.message,a(r)}):a(e)},i=0;i {\n // A null-prototype object avoids false-positive hits from inherited\n // members (e.g. `toString`, `constructor`) when a field is named after\n // one of them — a plain `{}` would make `!parsedErrors[path]` truthy-skip\n // those paths and silently drop their errors.\n const parsedErrors: Record = Object.create(null);\n\n const reduceError = (error: AjvError) => {\n // Ajv will return empty instancePath when require error\n if (error.keyword === 'required') {\n error.instancePath += `/${error.params.missingProperty}`;\n }\n\n // `/deepObject/data` -> `deepObject.data`\n const path = error.instancePath.substring(1).replace(/\\//g, '.');\n\n if (!parsedErrors[path]) {\n parsedErrors[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = parsedErrors[path].types;\n const messages = types && types[error.keyword];\n\n parsedErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n parsedErrors,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n };\n\n for (let index = 0; index < ajvErrors.length; index += 1) {\n const error = ajvErrors[index];\n\n if (error.keyword === 'errorMessage') {\n error.params.errors.forEach((originalError) => {\n originalError.message = error.message;\n reduceError(originalError);\n });\n } else {\n reduceError(error);\n }\n }\n\n return parsedErrors;\n};\n\n/**\n * Creates a resolver for react-hook-form using Ajv schema validation\n * @param {Schema} schema - The Ajv schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = ajv.compile({\n * type: 'object',\n * properties: {\n * name: { type: 'string' },\n * age: { type: 'number' }\n * }\n * });\n *\n * useForm({\n * resolver: ajvResolver(schema)\n * });\n */\nexport const ajvResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, options) => {\n const ajv = new Ajv(\n Object.assign(\n {},\n {\n allErrors: true,\n validateSchema: true,\n },\n schemaOptions,\n ),\n );\n\n ajvErrors(ajv);\n addFormats(ajv);\n\n const validate = ajv.compile(\n Object.assign(\n { $async: resolverOptions && resolverOptions.mode === 'async' },\n schema,\n ),\n );\n\n // Ajv mutates the object passed to `validate` in place (e.g. to apply\n // `useDefaults`, `removeAdditional`, or `coerceTypes`). Validating a\n // clone keeps those mutations from leaking into react-hook-form's\n // internal form values, which are passed in by reference.\n const parsedValues = structuredClone(values);\n const valid = validate(parsedValues);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return valid\n ? { values: parsedValues, errors: {} }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validate.errors as DefinedError[],\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n"],"names":["parseErrorSchema","ajvErrors","validateAllFieldCriteria","parsedErrors","Object","create","reduceError","error","keyword","instancePath","params","missingProperty","path","substring","replace","message","type","types","messages","appendErrors","concat","_loop","index","errors","forEach","originalError","length","ajvResolver","schema","schemaOptions","resolverOptions","values","_","options","ajv","Ajv","assign","allErrors","validateSchema","addFormats","validate","compile","$async","mode","parsedValues","structuredClone","valid","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","toNestErrors","criteriaMode","e","reject"],"mappings":"sMAOA,IAAMA,EAAmB,SACvBC,EACAC,GAwCA,IAlCA,IAAMC,EAA2CC,OAAOC,OAAO,MAEzDC,EAAc,SAACC,GAEG,aAAlBA,EAAMC,UACRD,EAAME,cAAY,IAAQF,EAAMG,OAAOC,iBAIzC,IAAMC,EAAOL,EAAME,aAAaI,UAAU,GAAGC,QAAQ,MAAO,KAS5D,GAPKX,EAAaS,KAChBT,EAAaS,GAAQ,CACnBG,QAASR,EAAMQ,QACfC,KAAMT,EAAMC,UAIZN,EAA0B,CAC5B,IAAMe,EAAQd,EAAaS,GAAMK,MAC3BC,EAAWD,GAASA,EAAMV,EAAMC,SAEtCL,EAAaS,GAAQO,EACnBP,EACAV,EACAC,EACAI,EAAMC,QACNU,EACK,GAAgBE,OAAOF,EAAsBX,EAAMQ,SAAW,IAC/DR,EAAMQ,QAEd,CACF,EAAEM,EAAAA,WAGA,IAAMd,EAAQN,EAAUqB,GAEF,iBAAlBf,EAAMC,QACRD,EAAMG,OAAOa,OAAOC,QAAQ,SAACC,GAC3BA,EAAcV,QAAUR,EAAMQ,QAC9BT,EAAYmB,EACd,GAEAnB,EAAYC,EAEhB,EAXSe,EAAQ,EAAGA,EAAQrB,EAAUyB,OAAQJ,GAAS,EAACD,IAaxD,OAAOlB,CACT,EAsBawB,EACX,SAACC,EAAQC,EAAeC,GAAoB,YAApBA,IAAAA,IAAAA,EAAkB,CAAA,GAAE,SACrCC,EAAQC,EAAGC,GAAW,IAC3B,IAAMC,EAAM,IAAIC,EACd/B,OAAOgC,OACL,CAAA,EACA,CACEC,WAAW,EACXC,gBAAgB,GAElBT,IAIJ5B,EAAUiC,GACVK,EAAWL,GAEX,IAAMM,EAAWN,EAAIO,QACnBrC,OAAOgC,OACL,CAAEM,OAAQZ,GAA4C,UAAzBA,EAAgBa,MAC7Cf,IAQEgB,EAAeC,gBAAgBd,GAC/Be,EAAQN,EAASI,GAIvB,OAFAX,EAAQc,2BAA6BC,EAAuB,CAAE,EAAEf,GAEhEgB,QAAAC,QAAOJ,EACH,CAAEf,OAAQa,EAAcrB,OAAQ,CAAA,GAChC,CACEQ,OAAQ,CAAE,EACVR,OAAQ4B,EACNnD,EACEwC,EAASjB,QACRU,EAAQc,2BACkB,QAAzBd,EAAQmB,cAEZnB,IAGV,CAAC,MAAAoB,GAAA,OAAAJ,QAAAK,OAAAD,EAAA,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js b/node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..2391b432976f26ef2a592a585d3aee99567c8e23 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("ajv"),require("ajv-errors"),require("ajv-formats"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","ajv","ajv-errors","ajv-formats","react-hook-form"],r):r((e||self).hookformResolversAjv={},e.hookformResolvers,e.ajv,e.ajvErrors,e.ajvFormats,e.ReactHookForm)}(this,function(e,r,o,a,s,t){function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/n(o),f=/*#__PURE__*/n(a),l=/*#__PURE__*/n(s),u=function(e,r){for(var o=Object.create(null),a=function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty);var a=e.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:e.message,type:e.keyword}),r){var s=o[a].types,n=s&&s[e.keyword];o[a]=t.appendErrors(a,r,o,e.keyword,n?[].concat(n,e.message||""):e.message)}},s=function(){var r=e[n];"errorMessage"===r.keyword?r.params.errors.forEach(function(e){e.message=r.message,a(e)}):a(r)},n=0;n {\n // A null-prototype object avoids false-positive hits from inherited\n // members (e.g. `toString`, `constructor`) when a field is named after\n // one of them — a plain `{}` would make `!parsedErrors[path]` truthy-skip\n // those paths and silently drop their errors.\n const parsedErrors: Record = Object.create(null);\n\n const reduceError = (error: AjvError) => {\n // Ajv will return empty instancePath when require error\n if (error.keyword === 'required') {\n error.instancePath += `/${error.params.missingProperty}`;\n }\n\n // `/deepObject/data` -> `deepObject.data`\n const path = error.instancePath.substring(1).replace(/\\//g, '.');\n\n if (!parsedErrors[path]) {\n parsedErrors[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = parsedErrors[path].types;\n const messages = types && types[error.keyword];\n\n parsedErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n parsedErrors,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n };\n\n for (let index = 0; index < ajvErrors.length; index += 1) {\n const error = ajvErrors[index];\n\n if (error.keyword === 'errorMessage') {\n error.params.errors.forEach((originalError) => {\n originalError.message = error.message;\n reduceError(originalError);\n });\n } else {\n reduceError(error);\n }\n }\n\n return parsedErrors;\n};\n\n/**\n * Creates a resolver for react-hook-form using Ajv schema validation\n * @param {Schema} schema - The Ajv schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = ajv.compile({\n * type: 'object',\n * properties: {\n * name: { type: 'string' },\n * age: { type: 'number' }\n * }\n * });\n *\n * useForm({\n * resolver: ajvResolver(schema)\n * });\n */\nexport const ajvResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, options) => {\n const ajv = new Ajv(\n Object.assign(\n {},\n {\n allErrors: true,\n validateSchema: true,\n },\n schemaOptions,\n ),\n );\n\n ajvErrors(ajv);\n addFormats(ajv);\n\n const validate = ajv.compile(\n Object.assign(\n { $async: resolverOptions && resolverOptions.mode === 'async' },\n schema,\n ),\n );\n\n // Ajv mutates the object passed to `validate` in place (e.g. to apply\n // `useDefaults`, `removeAdditional`, or `coerceTypes`). Validating a\n // clone keeps those mutations from leaking into react-hook-form's\n // internal form values, which are passed in by reference.\n const parsedValues = structuredClone(values);\n const valid = validate(parsedValues);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return valid\n ? { values: parsedValues, errors: {} }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validate.errors as DefinedError[],\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n"],"names":["parseErrorSchema","ajvErrors","validateAllFieldCriteria","parsedErrors","Object","create","reduceError","error","keyword","instancePath","params","missingProperty","path","substring","replace","message","type","types","messages","appendErrors","concat","_loop","index","errors","forEach","originalError","length","schema","schemaOptions","resolverOptions","values","_","options","ajv","Ajv","assign","allErrors","validateSchema","addFormats","validate","compile","$async","mode","parsedValues","structuredClone","valid","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","toNestErrors","criteriaMode","e","reject"],"mappings":"koBAOMA,EAAmB,SACvBC,EACAC,GAwCA,IAlCA,IAAMC,EAA2CC,OAAOC,OAAO,MAEzDC,EAAc,SAACC,GAEG,aAAlBA,EAAMC,UACRD,EAAME,cAAY,IAAQF,EAAMG,OAAOC,iBAIzC,IAAMC,EAAOL,EAAME,aAAaI,UAAU,GAAGC,QAAQ,MAAO,KAS5D,GAPKX,EAAaS,KAChBT,EAAaS,GAAQ,CACnBG,QAASR,EAAMQ,QACfC,KAAMT,EAAMC,UAIZN,EAA0B,CAC5B,IAAMe,EAAQd,EAAaS,GAAMK,MAC3BC,EAAWD,GAASA,EAAMV,EAAMC,SAEtCL,EAAaS,GAAQO,eACnBP,EACAV,EACAC,EACAI,EAAMC,QACNU,EACK,GAAgBE,OAAOF,EAAsBX,EAAMQ,SAAW,IAC/DR,EAAMQ,QAEd,CACF,EAAEM,EAAAA,WAGA,IAAMd,EAAQN,EAAUqB,GAEF,iBAAlBf,EAAMC,QACRD,EAAMG,OAAOa,OAAOC,QAAQ,SAACC,GAC3BA,EAAcV,QAAUR,EAAMQ,QAC9BT,EAAYmB,EACd,GAEAnB,EAAYC,EAEhB,EAXSe,EAAQ,EAAGA,EAAQrB,EAAUyB,OAAQJ,GAAS,EAACD,IAaxD,OAAOlB,CACT,gBAuBE,SAACwB,EAAQC,EAAeC,GAAoB,YAApBA,IAAAA,IAAAA,EAAkB,CAAA,GAAE,SACrCC,EAAQC,EAAGC,GAAW,IAC3B,IAAMC,EAAM,IAAIC,EAAG,QACjB9B,OAAO+B,OACL,CAAA,EACA,CACEC,WAAW,EACXC,gBAAgB,GAElBT,IAIJ3B,EAAAA,QAAUgC,GACVK,EAAAA,QAAWL,GAEX,IAAMM,EAAWN,EAAIO,QACnBpC,OAAO+B,OACL,CAAEM,OAAQZ,GAA4C,UAAzBA,EAAgBa,MAC7Cf,IAQEgB,EAAeC,gBAAgBd,GAC/Be,EAAQN,EAASI,GAIvB,OAFAX,EAAQc,2BAA6BC,EAAAA,uBAAuB,CAAE,EAAEf,GAEhEgB,QAAAC,QAAOJ,EACH,CAAEf,OAAQa,EAAcpB,OAAQ,CAAA,GAChC,CACEO,OAAQ,CAAE,EACVP,OAAQ2B,EAAAA,aACNlD,EACEuC,EAAShB,QACRS,EAAQc,2BACkB,QAAzBd,EAAQmB,cAEZnB,IAGV,CAAC,MAAAoB,GAAA,OAAAJ,QAAAK,OAAAD,EAAA,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/ajv/dist/index.d.ts b/node_modules/@hookform/resolvers/ajv/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5844f91ee3d7a5dfb05ed84e3bdc6356993bb060 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/dist/index.d.ts @@ -0,0 +1,2 @@ +export * from './ajv'; +export * from './types'; diff --git a/node_modules/@hookform/resolvers/ajv/dist/types.d.ts b/node_modules/@hookform/resolvers/ajv/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4b8f88a3a6f31e78c25115f1cfd202c09b193f3 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/dist/types.d.ts @@ -0,0 +1,13 @@ +import * as Ajv from 'ajv'; +import type { DefinedError, ErrorObject } from 'ajv'; +import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form'; +export type Resolver = (schema: Ajv.JSONSchemaType, schemaOptions?: Ajv.Options, factoryOptions?: { + mode?: 'async' | 'sync'; +}) => (values: TFieldValues, context: TContext | undefined, options: ResolverOptions) => Promise>; +type ErrorMessage = ErrorObject<'errorMessage', { + errors: (DefinedError & { + emUsed: boolean; + })[]; +}>; +export type AjvError = ErrorMessage | DefinedError; +export {}; diff --git a/node_modules/@hookform/resolvers/ajv/package.json b/node_modules/@hookform/resolvers/ajv/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6200a8112d1deb003d4780c852bc6585d4e3c5e6 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/package.json @@ -0,0 +1,20 @@ +{ + "name": "@hookform/resolvers/ajv", + "amdName": "hookformResolversAjv", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: ajv", + "main": "dist/ajv.js", + "module": "dist/ajv.module.js", + "umd:main": "dist/ajv.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0", + "ajv": "^8.12.0", + "ajv-errors": "^3.0.0", + "ajv-formats": "^2.1.1" + } +} diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/ajv/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0de3716d0c82a2ec0ea52bbef73b71a746baffd1 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,94 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { JSONSchemaType } from 'ajv'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { ajvResolver } from '..'; + +const USERNAME_REQUIRED_MESSAGE = 'username field is required'; +const PASSWORD_REQUIRED_MESSAGE = 'password field is required'; + +type FormData = { username: string; password: string }; + +const schema: JSONSchemaType = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 1, + errorMessage: { minLength: USERNAME_REQUIRED_MESSAGE }, + }, + password: { + type: 'string', + minLength: 1, + errorMessage: { minLength: PASSWORD_REQUIRED_MESSAGE }, + }, + }, + required: ['username', 'password'], + additionalProperties: false, +}; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: ajvResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with Ajv", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/ajv/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5504f6029c8ed0a9329309dc42523e688a7515fd --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/Form.tsx @@ -0,0 +1,65 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { JSONSchemaType } from 'ajv'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { ajvResolver } from '..'; + +type FormData = { username: string; password: string }; + +const schema: JSONSchemaType = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 1, + errorMessage: { minLength: 'username field is required' }, + }, + password: { + type: 'string', + minLength: 1, + errorMessage: { minLength: 'password field is required' }, + }, + }, + required: ['username', 'password'], + additionalProperties: false, +}; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: ajvResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with Ajv and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect(screen.getByText(/username field is required/i)).toBeInTheDocument(); + expect(screen.getByText(/password field is required/i)).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data-errors.ts b/node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data-errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5b3e5777413d7470fecd171ef172e8adeb3c9a6 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data-errors.ts @@ -0,0 +1,216 @@ +import { JSONSchemaType } from 'ajv'; +import { Field, InternalFieldName } from 'react-hook-form'; + +interface DataA { + username: string; + password: string; +} + +export const schemaA: JSONSchemaType = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 3, + errorMessage: { + minLength: 'username should be at least three characters long', + }, + }, + password: { + type: 'string', + pattern: '.*[A-Z].*', + minLength: 8, + errorMessage: { + pattern: 'One uppercase character', + minLength: 'passwords should be at least eight characters long', + }, + }, + }, + required: ['username', 'password'], + additionalProperties: false, + errorMessage: { + required: { + username: 'username field is required', + password: 'password field is required', + }, + }, +}; + +export const validDataA: DataA = { + username: 'kt666', + password: 'validPassword', +}; + +export const invalidDataA = { + username: 'kt', + password: 'invalid', +}; + +export const undefinedDataA = { + username: undefined, + password: undefined, +}; + +export const fieldsA: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; + +// examples from [ajv-errors](https://github.com/ajv-validator/ajv-errors) + +interface DataB { + foo: number; +} + +export const schemaB: JSONSchemaType = { + type: 'object', + required: ['foo'], + properties: { + foo: { type: 'integer' }, + }, + additionalProperties: false, + errorMessage: 'should be an object with an integer property foo only', +}; + +export const validDataB: DataB = { foo: 666 }; +export const invalidDataB = { foo: 'kt', bar: 6 }; +export const undefinedDataB = { foo: undefined }; + +interface DataC { + foo: number; +} + +export const schemaC: JSONSchemaType = { + type: 'object', + required: ['foo'], + properties: { + foo: { type: 'integer' }, + }, + additionalProperties: false, + errorMessage: { + type: 'should be an object', + required: 'should have property foo', + additionalProperties: 'should not have properties other than foo', + }, +}; + +export const validDataC: DataC = { foo: 666 }; +export const invalidDataC = { foo: 'kt', bar: 6 }; +export const undefinedDataC = { foo: undefined }; +export const invalidTypeDataC = 'something'; + +interface DataD { + foo: number; + bar: string; +} + +export const schemaD: JSONSchemaType = { + type: 'object', + required: ['foo', 'bar'], + properties: { + foo: { type: 'integer' }, + bar: { type: 'string' }, + }, + errorMessage: { + type: 'should be an object', // will not replace internal "type" error for the property "foo" + required: { + foo: 'should have an integer property "foo"', + bar: 'should have a string property "bar"', + }, + }, +}; + +export const validDataD: DataD = { foo: 666, bar: 'kt' }; +export const invalidDataD = { foo: 'kt', bar: 6 }; +export const undefinedDataD = { foo: undefined, bar: undefined }; +export const invalidTypeDataD = 'something'; + +interface DataE { + foo: number; + bar: string; +} + +export const schemaE: JSONSchemaType = { + type: 'object', + required: ['foo', 'bar'], + allOf: [ + { + properties: { + foo: { type: 'integer', minimum: 2 }, + bar: { type: 'string', minLength: 2 }, + }, + additionalProperties: false, + }, + ], + errorMessage: { + properties: { + foo: 'data.foo should be integer >= 2', + bar: 'data.bar should be string with length >= 2', + }, + }, +}; + +export const validDataE: DataE = { foo: 666, bar: 'kt' }; +export const invalidDataE = { foo: 1, bar: 'k' }; +export const undefinedDataE = { foo: undefined, bar: undefined }; + +interface DataF { + foo: number; + bar: string; +} + +export const schemaF: JSONSchemaType = { + type: 'object', + required: ['foo', 'bar'], + allOf: [ + { + properties: { + foo: { type: 'integer', minimum: 2 }, + bar: { type: 'string', minLength: 2 }, + }, + additionalProperties: false, + }, + ], + errorMessage: { + type: 'data should be an object', + properties: { + foo: 'data.foo should be integer >= 2', + bar: 'data.bar should be string with length >= 2', + }, + _: 'data should have properties "foo" and "bar" only', + }, +}; + +export const validDataF: DataF = { foo: 666, bar: 'kt' }; +export const invalidDataF = {}; +export const undefinedDataF = { foo: 1, bar: undefined }; +export const invalidTypeDataF = 'something'; + +export const fieldsRest: Record = { + foo: { + ref: { name: 'foo' }, + name: 'foo', + }, + bar: { + ref: { name: 'bar' }, + name: 'bar', + }, + lorem: { + ref: { name: 'lorem' }, + name: 'lorem', + }, +}; diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..edcdf77736bbb6138d81b491eed7d97af6bbd062 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,90 @@ +import { JSONSchemaType } from 'ajv'; +import { Field, InternalFieldName } from 'react-hook-form'; + +interface Data { + username: string; + password: string; + deepObject: { data: string; twoLayersDeep: { name: string } }; +} + +export const schema: JSONSchemaType = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 3, + }, + password: { + type: 'string', + pattern: '.*[A-Z].*', + errorMessage: { + pattern: 'One uppercase character', + }, + }, + deepObject: { + type: 'object', + properties: { + data: { type: 'string' }, + twoLayersDeep: { + type: 'object', + properties: { name: { type: 'string' } }, + additionalProperties: false, + required: ['name'], + }, + }, + required: ['data', 'twoLayersDeep'], + }, + }, + required: ['username', 'password', 'deepObject'], + additionalProperties: false, +}; + +export const validData: Data = { + username: 'jsun969', + password: 'validPassword', + deepObject: { + twoLayersDeep: { + name: 'deeper', + }, + data: 'data', + }, +}; + +export const invalidData = { + username: '__', + password: 'invalid-password', + deepObject: { + data: 233, + twoLayersDeep: { name: 123 }, + }, +}; + +export const invalidDataWithUndefined = { + username: 'jsun969', + password: undefined, + deepObject: { + twoLayersDeep: { + name: 'deeper', + }, + data: undefined, + }, +}; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv-errors.ts.snap b/node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv-errors.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..56062b23a2e8187602cb2fd57b668ace6f001a86 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv-errors.ts.snap @@ -0,0 +1,462 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when requirement fails 1`] = ` +{ + "errors": { + "bar": { + "message": "data should have properties "foo" and "bar" only", + "ref": { + "name": "bar", + }, + "type": "required", + "types": { + "required": "data should have properties "foo" and "bar" only", + }, + }, + "foo": { + "message": "data should have properties "foo" and "bar" only", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "data should have properties "foo" and "bar" only", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when some properties are undefined 1`] = ` +{ + "errors": { + "bar": { + "message": "data should have properties "foo" and "bar" only", + "ref": { + "name": "bar", + }, + "type": "required", + "types": { + "required": "data should have properties "foo" and "bar" only", + }, + }, + "foo": { + "message": "data.foo should be integer >= 2", + "ref": { + "name": "foo", + }, + "type": "minimum", + "types": { + "minimum": "data.foo should be integer >= 2", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when walidation fails 1`] = ` +{ + "errors": { + "bar": { + "message": "data should have properties "foo" and "bar" only", + "ref": { + "name": "bar", + }, + "type": "required", + "types": { + "required": "data should have properties "foo" and "bar" only", + }, + }, + "foo": { + "message": "data should have properties "foo" and "bar" only", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "data should have properties "foo" and "bar" only", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when requirement fails 1`] = ` +{ + "errors": { + "foo": { + "message": "should have property foo", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "should have property foo", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when some properties are undefined 1`] = ` +{ + "errors": { + "foo": { + "message": "should have property foo", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "should have property foo", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when walidation fails 1`] = ` +{ + "errors": { + "": { + "message": "should not have properties other than foo", + "ref": undefined, + "type": "additionalProperties", + "types": { + "additionalProperties": "should not have properties other than foo", + }, + }, + "foo": { + "message": "must be integer", + "ref": { + "name": "foo", + }, + "type": "type", + "types": { + "type": "must be integer", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized error messages when requirement fails 1`] = ` +{ + "errors": { + "password": { + "message": "password field is required", + "ref": { + "name": "password", + }, + "type": "required", + "types": { + "required": "password field is required", + }, + }, + "username": { + "message": "username field is required", + "ref": { + "name": "username", + }, + "type": "required", + "types": { + "required": "username field is required", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized error messages when some properties are undefined 1`] = ` +{ + "errors": { + "password": { + "message": "password field is required", + "ref": { + "name": "password", + }, + "type": "required", + "types": { + "required": "password field is required", + }, + }, + "username": { + "message": "username field is required", + "ref": { + "name": "username", + }, + "type": "required", + "types": { + "required": "username field is required", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized error messages when validation fails 1`] = ` +{ + "errors": { + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "pattern", + "types": { + "minLength": "passwords should be at least eight characters long", + "pattern": "One uppercase character", + }, + }, + "username": { + "message": "username should be at least three characters long", + "ref": { + "name": "username", + }, + "type": "minLength", + "types": { + "minLength": "username should be at least three characters long", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized errors for properties/items when requirement fails 1`] = ` +{ + "errors": { + "bar": { + "message": "must have required property 'bar'", + "ref": { + "name": "bar", + }, + "type": "required", + "types": { + "required": "must have required property 'bar'", + }, + }, + "foo": { + "message": "must have required property 'foo'", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "must have required property 'foo'", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized errors for properties/items when some properties are undefined 1`] = ` +{ + "errors": { + "bar": { + "message": "must have required property 'bar'", + "ref": { + "name": "bar", + }, + "type": "required", + "types": { + "required": "must have required property 'bar'", + }, + }, + "foo": { + "message": "must have required property 'foo'", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "must have required property 'foo'", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return customized errors for properties/items when walidation fails 1`] = ` +{ + "errors": { + "bar": { + "message": "data.bar should be string with length >= 2", + "ref": { + "name": "bar", + }, + "type": "minLength", + "types": { + "minLength": "data.bar should be string with length >= 2", + }, + }, + "foo": { + "message": "data.foo should be integer >= 2", + "ref": { + "name": "foo", + }, + "type": "minimum", + "types": { + "minimum": "data.foo should be integer >= 2", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return different messages for different properties when requirement fails 1`] = ` +{ + "errors": { + "bar": { + "message": "should have a string property "bar"", + "ref": { + "name": "bar", + }, + "type": "required", + "types": { + "required": "should have a string property "bar"", + }, + }, + "foo": { + "message": "should have an integer property "foo"", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "should have an integer property "foo"", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return different messages for different properties when some properties are undefined 1`] = ` +{ + "errors": { + "bar": { + "message": "should have a string property "bar"", + "ref": { + "name": "bar", + }, + "type": "required", + "types": { + "required": "should have a string property "bar"", + }, + }, + "foo": { + "message": "should have an integer property "foo"", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "should have an integer property "foo"", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return different messages for different properties when walidation fails 1`] = ` +{ + "errors": { + "bar": { + "message": "must be string", + "ref": { + "name": "bar", + }, + "type": "type", + "types": { + "type": "must be string", + }, + }, + "foo": { + "message": "must be integer", + "ref": { + "name": "foo", + }, + "type": "type", + "types": { + "type": "must be integer", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return the same customized error message when requirement fails 1`] = ` +{ + "errors": { + "foo": { + "message": "should be an object with an integer property foo only", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "should be an object with an integer property foo only", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return the same customized message for all validation failures 1`] = ` +{ + "errors": { + "": { + "message": "should be an object with an integer property foo only", + "ref": undefined, + "type": "additionalProperties", + "types": { + "additionalProperties": "should be an object with an integer property foo only", + }, + }, + "foo": { + "message": "should be an object with an integer property foo only", + "ref": { + "name": "foo", + }, + "type": "type", + "types": { + "type": "should be an object with an integer property foo only", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver with errorMessage > should return the same customized message when some properties are undefined 1`] = ` +{ + "errors": { + "foo": { + "message": "should be an object with an integer property foo only", + "ref": { + "name": "foo", + }, + "type": "required", + "types": { + "required": "should be an object with an integer property foo only", + }, + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv.ts.snap b/node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..a113c0e80b1a1b99914a524b4a8978f34c79b84d --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv.ts.snap @@ -0,0 +1,245 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true 1`] = ` +{ + "errors": { + "deepObject": { + "message": "must have required property 'deepObject'", + "ref": undefined, + "type": "required", + }, + "password": { + "message": "must have required property 'password'", + "ref": { + "name": "password", + }, + "type": "required", + }, + "username": { + "message": "must have required property 'username'", + "ref": { + "name": "username", + }, + "type": "required", + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true and \`mode: sync\` 1`] = ` +{ + "errors": { + "deepObject": { + "message": "must have required property 'deepObject'", + "ref": undefined, + "type": "required", + }, + "password": { + "message": "must have required property 'password'", + "ref": { + "name": "password", + }, + "type": "required", + }, + "username": { + "message": "must have required property 'username'", + "ref": { + "name": "username", + }, + "type": "required", + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver > should return all the error messages from ajvResolver when some property is undefined and result will keep the input data structure 1`] = ` +{ + "errors": { + "deepObject": { + "data": { + "message": "must have required property 'data'", + "ref": undefined, + "type": "required", + }, + }, + "password": { + "message": "must have required property 'password'", + "ref": { + "name": "password", + }, + "type": "required", + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver > should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true 1`] = ` +{ + "errors": { + "deepObject": { + "data": { + "message": "must be string", + "ref": undefined, + "type": "type", + "types": { + "type": "must be string", + }, + }, + "twoLayersDeep": { + "name": { + "message": "must be string", + "ref": undefined, + "type": "type", + "types": { + "type": "must be string", + }, + }, + }, + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "pattern", + "types": { + "pattern": "One uppercase character", + }, + }, + "username": { + "message": "must NOT have fewer than 3 characters", + "ref": { + "name": "username", + }, + "type": "minLength", + "types": { + "minLength": "must NOT have fewer than 3 characters", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver > should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true and \`mode: sync\` 1`] = ` +{ + "errors": { + "deepObject": { + "data": { + "message": "must be string", + "ref": undefined, + "type": "type", + "types": { + "type": "must be string", + }, + }, + "twoLayersDeep": { + "name": { + "message": "must be string", + "ref": undefined, + "type": "type", + "types": { + "type": "must be string", + }, + }, + }, + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "pattern", + "types": { + "pattern": "One uppercase character", + }, + }, + "username": { + "message": "must NOT have fewer than 3 characters", + "ref": { + "name": "username", + }, + "type": "minLength", + "types": { + "minLength": "must NOT have fewer than 3 characters", + }, + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver > should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false 1`] = ` +{ + "errors": { + "deepObject": { + "data": { + "message": "must be string", + "ref": undefined, + "type": "type", + }, + "twoLayersDeep": { + "name": { + "message": "must be string", + "ref": undefined, + "type": "type", + }, + }, + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "pattern", + }, + "username": { + "message": "must NOT have fewer than 3 characters", + "ref": { + "name": "username", + }, + "type": "minLength", + }, + }, + "values": {}, +} +`; + +exports[`ajvResolver > should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false and \`mode: sync\` 1`] = ` +{ + "errors": { + "deepObject": { + "data": { + "message": "must be string", + "ref": undefined, + "type": "type", + }, + "twoLayersDeep": { + "name": { + "message": "must be string", + "ref": undefined, + "type": "type", + }, + }, + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "pattern", + }, + "username": { + "message": "must NOT have fewer than 3 characters", + "ref": { + "name": "username", + }, + "type": "minLength", + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/ajv-errors.ts b/node_modules/@hookform/resolvers/ajv/src/__tests__/ajv-errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..63726ce2ebffcacc16ce68fa8ac3d31b8c6f6c6a --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/ajv-errors.ts @@ -0,0 +1,227 @@ +import { ajvResolver } from '..'; +import * as fixture from './__fixtures__/data-errors'; + +const shouldUseNativeValidation = false; + +describe('ajvResolver with errorMessage', () => { + it('should return values when validation pass', async () => { + expect( + await ajvResolver(fixture.schemaA)(fixture.validDataA, undefined, { + fields: fixture.fieldsA, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toEqual({ + values: fixture.validDataA, + errors: {}, + }); + }); + + it('should return customized error messages when validation fails', async () => { + expect( + await ajvResolver(fixture.schemaA)( + fixture.invalidDataA, + {}, + { + fields: fixture.fieldsA, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ), + ).toMatchSnapshot(); + }); + + it('should return customized error messages when requirement fails', async () => { + expect( + await ajvResolver(fixture.schemaA)({}, undefined, { + fields: fixture.fieldsA, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return customized error messages when some properties are undefined', async () => { + expect( + await ajvResolver(fixture.schemaA, undefined, { mode: 'sync' })( + fixture.undefinedDataA, + undefined, + { + fields: fixture.fieldsA, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ), + ).toMatchSnapshot(); + }); + + it('should return the same customized message for all validation failures', async () => { + expect( + await ajvResolver(fixture.schemaB)( + fixture.invalidDataB, + {}, + { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ), + ).toMatchSnapshot(); + }); + + it('should return the same customized error message when requirement fails', async () => { + expect( + await ajvResolver(fixture.schemaB)({}, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return the same customized message when some properties are undefined', async () => { + expect( + await ajvResolver(fixture.schemaB)(fixture.undefinedDataB, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return customized error messages for certain keywords when walidation fails', async () => { + expect( + await ajvResolver(fixture.schemaC)( + fixture.invalidDataC, + {}, + { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ), + ).toMatchSnapshot(); + }); + + it('should return customized error messages for certain keywords when requirement fails', async () => { + expect( + await ajvResolver(fixture.schemaC)({}, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return customized error messages for certain keywords when some properties are undefined', async () => { + expect( + await ajvResolver(fixture.schemaC)(fixture.undefinedDataC, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return different messages for different properties when walidation fails', async () => { + expect( + await ajvResolver(fixture.schemaD)( + fixture.invalidDataD, + {}, + { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ), + ).toMatchSnapshot(); + }); + + it('should return different messages for different properties when requirement fails', async () => { + expect( + await ajvResolver(fixture.schemaD)({}, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return different messages for different properties when some properties are undefined', async () => { + expect( + await ajvResolver(fixture.schemaD)(fixture.undefinedDataD, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return customized errors for properties/items when walidation fails', async () => { + expect( + await ajvResolver(fixture.schemaE)( + fixture.invalidDataE, + {}, + { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ), + ).toMatchSnapshot(); + }); + + it('should return customized errors for properties/items when requirement fails', async () => { + expect( + await ajvResolver(fixture.schemaE)({}, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return customized errors for properties/items when some properties are undefined', async () => { + expect( + await ajvResolver(fixture.schemaE)(fixture.undefinedDataE, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return a default message if there is no specific message for the error when walidation fails', async () => { + expect( + await ajvResolver(fixture.schemaF)( + fixture.invalidDataF, + {}, + { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ), + ).toMatchSnapshot(); + }); + + it('should return a default message if there is no specific message for the error when requirement fails', async () => { + expect( + await ajvResolver(fixture.schemaF)({}, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return a default message if there is no specific message for the error when some properties are undefined', async () => { + expect( + await ajvResolver(fixture.schemaF)(fixture.undefinedDataF, undefined, { + fields: fixture.fieldsRest, + criteriaMode: 'all', + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); +}); diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/ajv.ts b/node_modules/@hookform/resolvers/ajv/src/__tests__/ajv.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a1d246478e8856856f14a32a7c3b4f81df963d0 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/ajv.ts @@ -0,0 +1,143 @@ +import { JSONSchemaType } from 'ajv'; +import { ajvResolver } from '..'; +import { + fields, + invalidData, + invalidDataWithUndefined, + schema, + validData, +} from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('ajvResolver', () => { + it('should return values from ajvResolver when validation pass', async () => { + expect( + await ajvResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }), + ).toEqual({ + values: validData, + errors: {}, + }); + }); + + it('should return values from ajvResolver with `mode: sync` when validation pass', async () => { + expect( + await ajvResolver(schema, undefined, { + mode: 'sync', + })(validData, undefined, { fields, shouldUseNativeValidation }), + ).toEqual({ + values: validData, + errors: {}, + }); + }); + + it('should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false', async () => { + expect( + await ajvResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false and `mode: sync`', async () => { + expect( + await ajvResolver(schema, undefined, { + mode: 'sync', + })(invalidData, undefined, { fields, shouldUseNativeValidation }), + ).toMatchSnapshot(); + }); + + it('should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true', async () => { + expect( + await ajvResolver(schema)( + invalidData, + {}, + { fields, criteriaMode: 'all', shouldUseNativeValidation }, + ), + ).toMatchSnapshot(); + }); + + it('should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true and `mode: sync`', async () => { + expect( + await ajvResolver(schema, undefined, { mode: 'sync' })( + invalidData, + {}, + { fields, criteriaMode: 'all', shouldUseNativeValidation }, + ), + ).toMatchSnapshot(); + }); + + it('should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true', async () => { + expect( + await ajvResolver(schema)({}, undefined, { + fields, + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true and `mode: sync`', async () => { + expect( + await ajvResolver(schema, undefined, { mode: 'sync' })({}, undefined, { + fields, + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return all the error messages from ajvResolver when some property is undefined and result will keep the input data structure', async () => { + expect( + await ajvResolver(schema, undefined, { mode: 'sync' })( + invalidDataWithUndefined, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ), + ).toMatchSnapshot(); + }); + + it('should not mutate the input values object when `useDefaults` fills in missing properties (#647)', async () => { + interface DataWithDefaults { + user: { name: string; lastName: string }; + } + + const schemaWithDefaults: JSONSchemaType = { + type: 'object', + properties: { + user: { + type: 'object', + properties: { + name: { type: 'string', default: 'Camilo' }, + lastName: { type: 'string', default: 'A random lastName' }, + }, + required: ['name', 'lastName'], + }, + }, + required: ['user'], + }; + + // Simulates react-hook-form's internal form values, which are passed + // into the resolver by reference and must not be mutated as a side + // effect of validation. + const formValues: Partial = { user: {} as any }; + + const result = await ajvResolver(schemaWithDefaults, { + useDefaults: true, + })(formValues as DataWithDefaults, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(formValues).toEqual({ user: {} }); + expect(result).toEqual({ + values: { user: { name: 'Camilo', lastName: 'A random lastName' } }, + errors: {}, + }); + }); +}); diff --git a/node_modules/@hookform/resolvers/ajv/src/__tests__/special-path-names.ts b/node_modules/@hookform/resolvers/ajv/src/__tests__/special-path-names.ts new file mode 100644 index 0000000000000000000000000000000000000000..4318a49c727b45393b41f2a89dc0a8980b5ac0fc --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/__tests__/special-path-names.ts @@ -0,0 +1,27 @@ +import { ajvResolver } from '..'; + +const shouldUseNativeValidation = false; + +describe('ajvResolver special path names', () => { + it.each(['hasOwnProperty', 'toString'])( + 'reports a validation error for a field named "%s"', + async (name) => { + const schema = { + type: 'object', + properties: { [name]: { type: 'string', minLength: 1 } }, + required: [name], + } as any; + + const result = await ajvResolver(schema)( + { [name]: '' } as any, + undefined, + { + fields: {}, + shouldUseNativeValidation, + } as any, + ); + + expect(result.errors[name]).toBeDefined(); + }, + ); +}); diff --git a/node_modules/@hookform/resolvers/ajv/src/ajv.ts b/node_modules/@hookform/resolvers/ajv/src/ajv.ts new file mode 100644 index 0000000000000000000000000000000000000000..f2a63fe40fdd66b06a471bfae72362f1ff045dd1 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/ajv.ts @@ -0,0 +1,132 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import Ajv, { DefinedError } from 'ajv'; +import ajvErrors from 'ajv-errors'; +import addFormats from 'ajv-formats'; +import { FieldError, appendErrors } from 'react-hook-form'; +import { AjvError, Resolver } from './types'; + +const parseErrorSchema = ( + ajvErrors: AjvError[], + validateAllFieldCriteria: boolean, +) => { + // A null-prototype object avoids false-positive hits from inherited + // members (e.g. `toString`, `constructor`) when a field is named after + // one of them — a plain `{}` would make `!parsedErrors[path]` truthy-skip + // those paths and silently drop their errors. + const parsedErrors: Record = Object.create(null); + + const reduceError = (error: AjvError) => { + // Ajv will return empty instancePath when require error + if (error.keyword === 'required') { + error.instancePath += `/${error.params.missingProperty}`; + } + + // `/deepObject/data` -> `deepObject.data` + const path = error.instancePath.substring(1).replace(/\//g, '.'); + + if (!parsedErrors[path]) { + parsedErrors[path] = { + message: error.message, + type: error.keyword, + }; + } + + if (validateAllFieldCriteria) { + const types = parsedErrors[path].types; + const messages = types && types[error.keyword]; + + parsedErrors[path] = appendErrors( + path, + validateAllFieldCriteria, + parsedErrors, + error.keyword, + messages + ? ([] as string[]).concat(messages as string[], error.message || '') + : error.message, + ) as FieldError; + } + }; + + for (let index = 0; index < ajvErrors.length; index += 1) { + const error = ajvErrors[index]; + + if (error.keyword === 'errorMessage') { + error.params.errors.forEach((originalError) => { + originalError.message = error.message; + reduceError(originalError); + }); + } else { + reduceError(error); + } + } + + return parsedErrors; +}; + +/** + * Creates a resolver for react-hook-form using Ajv schema validation + * @param {Schema} schema - The Ajv schema to validate against + * @param {Object} schemaOptions - Additional schema validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='async'] - Validation mode + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * const schema = ajv.compile({ + * type: 'object', + * properties: { + * name: { type: 'string' }, + * age: { type: 'number' } + * } + * }); + * + * useForm({ + * resolver: ajvResolver(schema) + * }); + */ +export const ajvResolver: Resolver = + (schema, schemaOptions, resolverOptions = {}) => + async (values, _, options) => { + const ajv = new Ajv( + Object.assign( + {}, + { + allErrors: true, + validateSchema: true, + }, + schemaOptions, + ), + ); + + ajvErrors(ajv); + addFormats(ajv); + + const validate = ajv.compile( + Object.assign( + { $async: resolverOptions && resolverOptions.mode === 'async' }, + schema, + ), + ); + + // Ajv mutates the object passed to `validate` in place (e.g. to apply + // `useDefaults`, `removeAdditional`, or `coerceTypes`). Validating a + // clone keeps those mutations from leaking into react-hook-form's + // internal form values, which are passed in by reference. + const parsedValues = structuredClone(values); + const valid = validate(parsedValues); + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return valid + ? { values: parsedValues, errors: {} } + : { + values: {}, + errors: toNestErrors( + parseErrorSchema( + validate.errors as DefinedError[], + !options.shouldUseNativeValidation && + options.criteriaMode === 'all', + ), + options, + ), + }; + }; diff --git a/node_modules/@hookform/resolvers/ajv/src/index.ts b/node_modules/@hookform/resolvers/ajv/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5844f91ee3d7a5dfb05ed84e3bdc6356993bb060 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/index.ts @@ -0,0 +1,2 @@ +export * from './ajv'; +export * from './types'; diff --git a/node_modules/@hookform/resolvers/ajv/src/types.ts b/node_modules/@hookform/resolvers/ajv/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..6726ccda71be2d544df21d08bb65f35472308fb4 --- /dev/null +++ b/node_modules/@hookform/resolvers/ajv/src/types.ts @@ -0,0 +1,20 @@ +import * as Ajv from 'ajv'; +import type { DefinedError, ErrorObject } from 'ajv'; +import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form'; + +export type Resolver = ( + schema: Ajv.JSONSchemaType, + schemaOptions?: Ajv.Options, + factoryOptions?: { mode?: 'async' | 'sync' }, +) => ( + values: TFieldValues, + context: TContext | undefined, + options: ResolverOptions, +) => Promise>; + +// ajv doesn't export any types for errors with `keyword='errorMessage'` +type ErrorMessage = ErrorObject< + 'errorMessage', + { errors: (DefinedError & { emUsed: boolean })[] } +>; +export type AjvError = ErrorMessage | DefinedError; diff --git a/node_modules/@hookform/resolvers/arktype/dist/arktype.d.ts b/node_modules/@hookform/resolvers/arktype/dist/arktype.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c82f612297535dcb7d5503b7e201dc678c44f0c6 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/dist/arktype.d.ts @@ -0,0 +1,8 @@ +import { StandardSchemaV1 } from '@standard-schema/spec'; +import { FieldValues, Resolver } from 'react-hook-form'; +export declare function arktypeResolver(schema: StandardSchemaV1, _schemaOptions?: never, resolverOptions?: { + raw?: false; +}): Resolver; +export declare function arktypeResolver(schema: StandardSchemaV1, _schemaOptions: never | undefined, resolverOptions: { + raw: true; +}): Resolver; diff --git a/node_modules/@hookform/resolvers/arktype/dist/arktype.js b/node_modules/@hookform/resolvers/arktype/dist/arktype.js new file mode 100644 index 0000000000000000000000000000000000000000..8d1ad14dbf01cfe18bf1b380e69780a48f69afb3 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/dist/arktype.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers");function r(){return r=Object.assign?Object.assign.bind():function(e){for(var r=1;r = Object.create(null);\n\n for (let i = 0; i < issues.length; i++) {\n const error = issues[i];\n const path = getDotPath(error);\n\n if (path) {\n if (!errors[path]) {\n errors[path] = { message: error.message, type: '' };\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[path].types || {};\n\n errors[path].types = {\n ...types,\n [Object.keys(types).length]: error.message,\n };\n }\n }\n }\n\n return errors;\n}\n\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions?: {\n raw?: false;\n },\n): Resolver;\n\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions: never | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Arktype schema validation\n * @param {Schema} schema - The Arktype schema to validate against\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='raw'] - Return the raw input values rather than the parsed values\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = type({\n * username: 'string>2'\n * });\n *\n * useForm({\n * resolver: arktypeResolver(schema)\n * });\n */\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return async (values: Input, _, options) => {\n let result = schema['~standard'].validate(values);\n if (result instanceof Promise) {\n result = await result;\n }\n\n if (result.issues) {\n const errors = parseErrorSchema(\n result.issues,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n );\n\n return {\n values: {},\n errors: toNestErrors(errors, options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result.value,\n errors: {},\n };\n };\n}\n"],"names":["getDotPath","issue","path","length","dotPath","item","key","schema","_schemaOptions","resolverOptions","values","_","options","_temp2","result","issues","errors","validateAllFieldCriteria","Object","create","i","error","message","type","_extends2","types","_extends","keys","parseErrorSchema","shouldUseNativeValidation","criteriaMode","toNestErrors","validateFieldsNatively","raw","assign","value","validate","_temp","Promise","resolve","then","_result","e","reject"],"mappings":"6PACA,SAASA,EAAWC,GAClB,GAAIA,EAAMC,MAAMC,OAAQ,CACtB,IAAIC,EAAU,GACd,IAAK,MAAMC,KAAQJ,EAAMC,KAAM,CAC7B,MAAMI,EAAsB,iBAATD,EAAoBA,EAAKC,IAAMD,EAClD,GAAmB,iBAARC,GAAmC,iBAARA,EAOpC,OAAO,KALLF,GADEA,EACS,IAAIE,IAEJA,CAKhB,CACD,OAAOF,CACR,CACD,OAAO,IACT,yBC+CgB,SACdG,EACAC,EACAC,GAIA,gBAJAA,IAAAA,EAEI,IAEUC,SAAAA,EAAeC,EAAGC,GAAO,QAAIC,EAAA,WAMzC,GAAIC,EAAOC,OAAQ,CACjB,IAAMC,EA3EZ,SACED,EACAE,GAKA,IAFA,IAAMD,EAAqCE,OAAOC,OAAO,MAEhDC,EAAI,EAAGA,EAAIL,EAAOZ,OAAQiB,IAAK,CACtC,IAAMC,EAAQN,EAAOK,GACflB,EAAOF,EAAWqB,GAExB,GAAInB,IACGc,EAAOd,KACVc,EAAOd,GAAQ,CAAEoB,QAASD,EAAMC,QAASC,KAAM,KAG7CN,GAA0B,CAAAO,IAAAA,EACtBC,EAAQT,EAAOd,GAAMuB,OAAS,CAAA,EAEpCT,EAAOd,GAAMuB,MAAKC,EACbD,CAAAA,EAAAA,IAAKD,MACPN,OAAOS,KAAKF,GAAOtB,QAASkB,EAAMC,QAAOE,GAE9C,CAEJ,CAEA,OAAOR,CACT,CA+CqBY,CACbd,EAAOC,QACNH,EAAQiB,2BAAsD,QAAzBjB,EAAQkB,cAGhD,MAAO,CACLpB,OAAQ,CAAA,EACRM,OAAQe,eAAaf,EAAQJ,GAEjC,CAIA,OAFAA,EAAQiB,2BAA6BG,EAAAA,uBAAuB,CAAA,EAAIpB,GAEzD,CACLF,OAAQD,EAAgBwB,IAAMf,OAAOgB,OAAO,CAAA,EAAIxB,GAAUI,EAAOqB,MACjEnB,OAAQ,CAAA,EACR,EAtBEF,EAASP,EAAO,aAAa6B,SAAS1B,GAAQ2B,gBAC9CvB,aAAkBwB,QAAO,OAAAA,QAAAC,QACZzB,GAAM0B,KAAA,SAAAC,GAArB3B,EAAM2B,CAAgB,EAAA,IAAA,OAAAH,QAAAC,QAAAF,GAAAA,EAAAG,KAAAH,EAAAG,KAAA3B,GAAAA,IAqB1B,CAAC,MAAA6B,GAAAJ,OAAAA,QAAAK,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/arktype/dist/arktype.mjs b/node_modules/@hookform/resolvers/arktype/dist/arktype.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f189972d6f33a0f56a400072d769d4ab58e5eb54 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/dist/arktype.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r{let u=s["~standard"].validate(o);if(u instanceof Promise&&(u=await u),u.issues){const t=function(e,t){const s=Object.create(null);for(let o=0;o = Object.create(null);\n\n for (let i = 0; i < issues.length; i++) {\n const error = issues[i];\n const path = getDotPath(error);\n\n if (path) {\n if (!errors[path]) {\n errors[path] = { message: error.message, type: '' };\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[path].types || {};\n\n errors[path].types = {\n ...types,\n [Object.keys(types).length]: error.message,\n };\n }\n }\n }\n\n return errors;\n}\n\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions?: {\n raw?: false;\n },\n): Resolver;\n\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions: never | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Arktype schema validation\n * @param {Schema} schema - The Arktype schema to validate against\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='raw'] - Return the raw input values rather than the parsed values\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = type({\n * username: 'string>2'\n * });\n *\n * useForm({\n * resolver: arktypeResolver(schema)\n * });\n */\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return async (values: Input, _, options) => {\n let result = schema['~standard'].validate(values);\n if (result instanceof Promise) {\n result = await result;\n }\n\n if (result.issues) {\n const errors = parseErrorSchema(\n result.issues,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n );\n\n return {\n values: {},\n errors: toNestErrors(errors, options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result.value,\n errors: {},\n };\n };\n}\n"],"names":["getDotPath","issue","path","length","dotPath","item","key","arktypeResolver","schema","_schemaOptions","resolverOptions","async","values","_","options","result","validate","Promise","issues","errors","validateAllFieldCriteria","Object","create","i","error","message","type","types","_extends","keys","parseErrorSchema","shouldUseNativeValidation","criteriaMode","toNestErrors","validateFieldsNatively","raw","assign","value"],"mappings":"uSACA,SAASA,EAAWC,GAClB,GAAIA,EAAMC,MAAMC,OAAQ,CACtB,IAAIC,EAAU,GACd,IAAK,MAAMC,KAAQJ,EAAMC,KAAM,CAC7B,MAAMI,EAAsB,iBAATD,EAAoBA,EAAKC,IAAMD,EAClD,GAAmB,iBAARC,GAAmC,iBAARA,EAOpC,OAAO,KALLF,GADEA,EACS,IAAIE,IAEJA,CAKhB,CACD,OAAOF,CACR,CACD,OAAO,IACT,UC+CgBG,EACdC,EACAC,EACAC,EAEI,CAAA,GAEJ,OAAOC,MAAOC,EAAeC,EAAGC,KAC9B,IAAIC,EAASP,EAAO,aAAaQ,SAASJ,GAK1C,GAJIG,aAAkBE,UACpBF,QAAeA,GAGbA,EAAOG,OAAQ,CACjB,MAAMC,EA3EZ,SACED,EACAE,GAGA,MAAMD,EAAqCE,OAAOC,OAAO,MAEzD,IAAK,IAAIC,EAAI,EAAGA,EAAIL,EAAOf,OAAQoB,IAAK,CACtC,MAAMC,EAAQN,EAAOK,GACfrB,EAAOF,EAAWwB,GAExB,GAAItB,IACGiB,EAAOjB,KACViB,EAAOjB,GAAQ,CAAEuB,QAASD,EAAMC,QAASC,KAAM,KAG7CN,GAA0B,CAC5B,MAAMO,EAAQR,EAAOjB,GAAMyB,OAAS,CAAA,EAEpCR,EAAOjB,GAAMyB,MAAKC,EACbD,CAAAA,EAAAA,EACH,CAAA,CAACN,OAAOQ,KAAKF,GAAOxB,QAASqB,EAAMC,SAEvC,CAEJ,CAEA,OAAON,CACT,CA+CqBW,CACbf,EAAOG,QACNJ,EAAQiB,2BAAsD,QAAzBjB,EAAQkB,cAGhD,MAAO,CACLpB,OAAQ,CAAA,EACRO,OAAQc,EAAad,EAAQL,GAEjC,CAIA,OAFAA,EAAQiB,2BAA6BG,EAAuB,CAAA,EAAIpB,GAEzD,CACLF,OAAQF,EAAgByB,IAAMd,OAAOe,OAAO,CAAE,EAAExB,GAAUG,EAAOsB,MACjElB,OAAQ,CAAA,EACT,CAEL"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/arktype/dist/arktype.module.js b/node_modules/@hookform/resolvers/arktype/dist/arktype.module.js new file mode 100644 index 0000000000000000000000000000000000000000..f189972d6f33a0f56a400072d769d4ab58e5eb54 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/dist/arktype.module.js @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r = Object.create(null);\n\n for (let i = 0; i < issues.length; i++) {\n const error = issues[i];\n const path = getDotPath(error);\n\n if (path) {\n if (!errors[path]) {\n errors[path] = { message: error.message, type: '' };\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[path].types || {};\n\n errors[path].types = {\n ...types,\n [Object.keys(types).length]: error.message,\n };\n }\n }\n }\n\n return errors;\n}\n\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions?: {\n raw?: false;\n },\n): Resolver;\n\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions: never | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Arktype schema validation\n * @param {Schema} schema - The Arktype schema to validate against\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='raw'] - Return the raw input values rather than the parsed values\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = type({\n * username: 'string>2'\n * });\n *\n * useForm({\n * resolver: arktypeResolver(schema)\n * });\n */\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return async (values: Input, _, options) => {\n let result = schema['~standard'].validate(values);\n if (result instanceof Promise) {\n result = await result;\n }\n\n if (result.issues) {\n const errors = parseErrorSchema(\n result.issues,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n );\n\n return {\n values: {},\n errors: toNestErrors(errors, options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result.value,\n errors: {},\n };\n };\n}\n"],"names":["getDotPath","issue","path","length","dotPath","item","key","arktypeResolver","schema","_schemaOptions","resolverOptions","values","_","options","_temp2","result","issues","errors","validateAllFieldCriteria","Object","create","i","error","message","type","_extends2","types","_extends","keys","parseErrorSchema","shouldUseNativeValidation","criteriaMode","toNestErrors","validateFieldsNatively","raw","assign","value","validate","_temp","Promise","resolve","then","_result","e","reject"],"mappings":"uSACA,SAASA,EAAWC,GAClB,GAAIA,EAAMC,MAAMC,OAAQ,CACtB,IAAIC,EAAU,GACd,IAAK,MAAMC,KAAQJ,EAAMC,KAAM,CAC7B,MAAMI,EAAsB,iBAATD,EAAoBA,EAAKC,IAAMD,EAClD,GAAmB,iBAARC,GAAmC,iBAARA,EAOpC,OAAO,KALLF,GADEA,EACS,IAAIE,IAEJA,CAKhB,CACD,OAAOF,CACR,CACD,OAAO,IACT,CC+CgB,SAAAG,EACdC,EACAC,EACAC,GAIA,gBAJAA,IAAAA,EAEI,IAEUC,SAAAA,EAAeC,EAAGC,GAAO,QAAIC,EAAA,WAMzC,GAAIC,EAAOC,OAAQ,CACjB,IAAMC,EA3EZ,SACED,EACAE,GAKA,IAFA,IAAMD,EAAqCE,OAAOC,OAAO,MAEhDC,EAAI,EAAGA,EAAIL,EAAOb,OAAQkB,IAAK,CACtC,IAAMC,EAAQN,EAAOK,GACfnB,EAAOF,EAAWsB,GAExB,GAAIpB,IACGe,EAAOf,KACVe,EAAOf,GAAQ,CAAEqB,QAASD,EAAMC,QAASC,KAAM,KAG7CN,GAA0B,CAAAO,IAAAA,EACtBC,EAAQT,EAAOf,GAAMwB,OAAS,CAAA,EAEpCT,EAAOf,GAAMwB,MAAKC,EACbD,CAAAA,EAAAA,IAAKD,MACPN,OAAOS,KAAKF,GAAOvB,QAASmB,EAAMC,QAAOE,GAE9C,CAEJ,CAEA,OAAOR,CACT,CA+CqBY,CACbd,EAAOC,QACNH,EAAQiB,2BAAsD,QAAzBjB,EAAQkB,cAGhD,MAAO,CACLpB,OAAQ,CAAA,EACRM,OAAQe,EAAaf,EAAQJ,GAEjC,CAIA,OAFAA,EAAQiB,2BAA6BG,EAAuB,CAAA,EAAIpB,GAEzD,CACLF,OAAQD,EAAgBwB,IAAMf,OAAOgB,OAAO,CAAA,EAAIxB,GAAUI,EAAOqB,MACjEnB,OAAQ,CAAA,EACR,EAtBEF,EAASP,EAAO,aAAa6B,SAAS1B,GAAQ2B,gBAC9CvB,aAAkBwB,QAAO,OAAAA,QAAAC,QACZzB,GAAM0B,KAAA,SAAAC,GAArB3B,EAAM2B,CAAgB,EAAA,IAAA,OAAAH,QAAAC,QAAAF,GAAAA,EAAAG,KAAAH,EAAAG,KAAA3B,GAAAA,IAqB1B,CAAC,MAAA6B,GAAAJ,OAAAA,QAAAK,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/arktype/dist/arktype.umd.js b/node_modules/@hookform/resolvers/arktype/dist/arktype.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..4a6522257d05158b395e9411cf70b91b28030d49 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/dist/arktype.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],r):r((e||self).hookformResolversArktype={},e.hookformResolvers)}(this,function(e,r){function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r = Object.create(null);\n\n for (let i = 0; i < issues.length; i++) {\n const error = issues[i];\n const path = getDotPath(error);\n\n if (path) {\n if (!errors[path]) {\n errors[path] = { message: error.message, type: '' };\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[path].types || {};\n\n errors[path].types = {\n ...types,\n [Object.keys(types).length]: error.message,\n };\n }\n }\n }\n\n return errors;\n}\n\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions?: {\n raw?: false;\n },\n): Resolver;\n\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions: never | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Arktype schema validation\n * @param {Schema} schema - The Arktype schema to validate against\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='raw'] - Return the raw input values rather than the parsed values\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = type({\n * username: 'string>2'\n * });\n *\n * useForm({\n * resolver: arktypeResolver(schema)\n * });\n */\nexport function arktypeResolver(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return async (values: Input, _, options) => {\n let result = schema['~standard'].validate(values);\n if (result instanceof Promise) {\n result = await result;\n }\n\n if (result.issues) {\n const errors = parseErrorSchema(\n result.issues,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n );\n\n return {\n values: {},\n errors: toNestErrors(errors, options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result.value,\n errors: {},\n };\n };\n}\n"],"names":["getDotPath","issue","path","length","dotPath","item","key","schema","_schemaOptions","resolverOptions","values","_","options","_temp2","result","issues","errors","validateAllFieldCriteria","Object","create","i","error","message","type","_extends2","types","_extends","keys","parseErrorSchema","shouldUseNativeValidation","criteriaMode","toNestErrors","validateFieldsNatively","raw","assign","value","validate","_temp","Promise","resolve","then","_result","e","reject"],"mappings":"qhBACA,SAASA,EAAWC,GAClB,GAAIA,EAAMC,MAAMC,OAAQ,CACtB,IAAIC,EAAU,GACd,IAAK,MAAMC,KAAQJ,EAAMC,KAAM,CAC7B,MAAMI,EAAsB,iBAATD,EAAoBA,EAAKC,IAAMD,EAClD,GAAmB,iBAARC,GAAmC,iBAARA,EAOpC,OAAO,KALLF,GADEA,EACS,IAAIE,IAEJA,CAKhB,CACD,OAAOF,CACR,CACD,OAAO,IACT,mBC+CgB,SACdG,EACAC,EACAC,GAIA,gBAJAA,IAAAA,EAEI,IAEUC,SAAAA,EAAeC,EAAGC,GAAO,QAAIC,EAAA,WAMzC,GAAIC,EAAOC,OAAQ,CACjB,IAAMC,EA3EZ,SACED,EACAE,GAKA,IAFA,IAAMD,EAAqCE,OAAOC,OAAO,MAEhDC,EAAI,EAAGA,EAAIL,EAAOZ,OAAQiB,IAAK,CACtC,IAAMC,EAAQN,EAAOK,GACflB,EAAOF,EAAWqB,GAExB,GAAInB,IACGc,EAAOd,KACVc,EAAOd,GAAQ,CAAEoB,QAASD,EAAMC,QAASC,KAAM,KAG7CN,GAA0B,CAAAO,IAAAA,EACtBC,EAAQT,EAAOd,GAAMuB,OAAS,CAAA,EAEpCT,EAAOd,GAAMuB,MAAKC,EACbD,CAAAA,EAAAA,IAAKD,MACPN,OAAOS,KAAKF,GAAOtB,QAASkB,EAAMC,QAAOE,GAE9C,CAEJ,CAEA,OAAOR,CACT,CA+CqBY,CACbd,EAAOC,QACNH,EAAQiB,2BAAsD,QAAzBjB,EAAQkB,cAGhD,MAAO,CACLpB,OAAQ,CAAA,EACRM,OAAQe,eAAaf,EAAQJ,GAEjC,CAIA,OAFAA,EAAQiB,2BAA6BG,EAAAA,uBAAuB,CAAA,EAAIpB,GAEzD,CACLF,OAAQD,EAAgBwB,IAAMf,OAAOgB,OAAO,CAAA,EAAIxB,GAAUI,EAAOqB,MACjEnB,OAAQ,CAAA,EACR,EAtBEF,EAASP,EAAO,aAAa6B,SAAS1B,GAAQ2B,gBAC9CvB,aAAkBwB,QAAO,OAAAA,QAAAC,QACZzB,GAAM0B,KAAA,SAAAC,GAArB3B,EAAM2B,CAAgB,EAAA,IAAA,OAAAH,QAAAC,QAAAF,GAAAA,EAAAG,KAAAH,EAAAG,KAAA3B,GAAAA,IAqB1B,CAAC,MAAA6B,GAAAJ,OAAAA,QAAAK,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/arktype/dist/index.d.ts b/node_modules/@hookform/resolvers/arktype/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..686e84906fc723679cadd4fd0ded250d6cffa816 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/dist/index.d.ts @@ -0,0 +1 @@ +export * from './arktype'; diff --git a/node_modules/@hookform/resolvers/arktype/package.json b/node_modules/@hookform/resolvers/arktype/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7056cd37556e3410e7fee1f78f2dbf825dcd1eff --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/package.json @@ -0,0 +1,18 @@ +{ + "name": "@hookform/resolvers/arktype", + "amdName": "hookformResolversArktype", + "version": "2.0.0", + "private": true, + "description": "React Hook Form validation resolver: arktype", + "main": "dist/arktype.js", + "module": "dist/arktype.module.js", + "umd:main": "dist/arktype.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0", + "arktype": "^2.0.0" + } +} diff --git a/node_modules/@hookform/resolvers/arktype/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/arktype/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2e007dc91e17e7cc568328ae08c361d0f64c26b8 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,82 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { type } from 'arktype'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { arktypeResolver } from '..'; + +const schema = type({ + username: 'string>1', + password: 'string>1', +}); + +type FormData = typeof schema.infer; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: arktypeResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with Arktype", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe( + 'username must be at least length 2', + ); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe( + 'password must be at least length 2', + ); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/arktype/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/arktype/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5aec3a2898c51ff38a430954e1711b962e3c4f73 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/src/__tests__/Form.tsx @@ -0,0 +1,54 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { type } from 'arktype'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { arktypeResolver } from '..'; + +const schema = type({ + username: 'string>1', + password: 'string>1', +}); + +function TestComponent({ + onSubmit, +}: { + onSubmit: (data: typeof schema.infer) => void; +}) { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: arktypeResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with arkType and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect( + screen.getByText('username must be at least length 2'), + ).toBeInTheDocument(); + expect( + screen.getByText('password must be at least length 2'), + ).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/arktype/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/arktype/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..a84cdddf00fe4013c330dc2c8ff44f12e94aaf75 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,65 @@ +import { type } from 'arktype'; +import { Field, InternalFieldName } from 'react-hook-form'; + +export const schema = type({ + username: 'string>2', + password: '/.*[A-Za-z].*/>8|/.*\\d.*/', + repeatPassword: 'string>1', + accessToken: 'string|number', + birthYear: '19001', + 'like?': type({ + id: 'number', + name: 'string>3', + }).array(), + dateStr: 'Date', +}); + +export const validData: typeof schema.infer = { + username: 'Doe', + password: 'Password123_', + repeatPassword: 'Password123_', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + accessToken: 'accessToken', + url: 'https://react-hook-form.com/', + like: [ + { + id: 1, + name: 'name', + }, + ], + dateStr: new Date('2020-01-01'), +}; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: [{ id: 'z' }], + url: 'abc', +} as any as typeof schema.infer; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/arktype/src/__tests__/__snapshots__/arktype.ts.snap b/node_modules/@hookform/resolvers/arktype/src/__tests__/__snapshots__/arktype.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..4fea5e1536acc278c7b756383b7ed5bf927e4228 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/src/__tests__/__snapshots__/arktype.ts.snap @@ -0,0 +1,74 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`arktypeResolver > should return a single error from arktypeResolver when validation fails 1`] = ` +{ + "errors": { + "accessToken": { + "message": "accessToken must be a number or a string (was missing)", + "ref": undefined, + "type": "", + }, + "birthYear": { + "message": "birthYear must be a number (was a string)", + "ref": undefined, + "type": "", + }, + "dateStr": { + "message": "dateStr must be a Date (was missing)", + "ref": undefined, + "type": "", + }, + "email": { + "message": "email must be an email address (was "")", + "ref": { + "name": "email", + }, + "type": "", + }, + "enabled": { + "message": "enabled must be boolean (was missing)", + "ref": undefined, + "type": "", + }, + "like": [ + { + "id": { + "message": "like[0].id must be a number (was a string)", + "ref": undefined, + "type": "", + }, + "name": { + "message": "like[0].name must be a string (was missing)", + "ref": undefined, + "type": "", + }, + }, + ], + "password": { + "message": "password must be matched by .*[A-Za-z].* or matched by .*\\d.* (was "___")", + "ref": { + "name": "password", + }, + "type": "", + }, + "repeatPassword": { + "message": "repeatPassword must be a string (was missing)", + "ref": undefined, + "type": "", + }, + "tags": { + "message": "tags must be an array (was missing)", + "ref": undefined, + "type": "", + }, + "username": { + "message": "username must be a string (was missing)", + "ref": { + "name": "username", + }, + "type": "", + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/arktype/src/__tests__/arktype.ts b/node_modules/@hookform/resolvers/arktype/src/__tests__/arktype.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b010d3e904fe9fe719553ee3b111829a795cf75 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/src/__tests__/arktype.ts @@ -0,0 +1,91 @@ +import { renderHook } from '@testing-library/react'; +import { type } from 'arktype'; +import { Resolver, useForm } from 'react-hook-form'; +import { SubmitHandler } from 'react-hook-form'; +import { arktypeResolver } from '..'; +import { fields, invalidData, schema, validData } from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('arktypeResolver', () => { + it('should return values from arktypeResolver when validation pass & raw=true', async () => { + const result = await arktypeResolver(schema, undefined, { + raw: true, + })(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return a single error from arktypeResolver when validation fails', async () => { + const result = await arktypeResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + /** + * Type inference tests + */ + it('should correctly infer the output type from a arktype schema', () => { + const resolver = arktypeResolver(type({ id: 'number' })); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: number }, unknown, { id: number }> + >(); + }); + + it('should correctly infer the output type from a arktype schema using a transform', () => { + const resolver = arktypeResolver( + type({ id: type('string').pipe((s) => Number.parseInt(s)) }), + ); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: string }, unknown, { id: number }> + >(); + }); + + it('should correctly infer the output type from a arktype schema for the handleSubmit function in useForm', () => { + const schema = type({ id: 'number' }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: arktypeResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: number; + }> + >(); + }); + + it('should correctly infer the output type from a arktype schema with a transform for the handleSubmit function in useForm', () => { + const schema = type({ id: type('string').pipe((s) => Number.parseInt(s)) }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: arktypeResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: number; + }> + >(); + }); +}); diff --git a/node_modules/@hookform/resolvers/arktype/src/__tests__/special-path-names.ts b/node_modules/@hookform/resolvers/arktype/src/__tests__/special-path-names.ts new file mode 100644 index 0000000000000000000000000000000000000000..356d911f37a6c5f0f105d55df1b724abcc87f582 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/src/__tests__/special-path-names.ts @@ -0,0 +1,21 @@ +import { type } from 'arktype'; +import { arktypeResolver } from '..'; + +const shouldUseNativeValidation = false; + +describe('arktypeResolver special path names', () => { + it.each(['hasOwnProperty', 'toString'])( + 'reports a validation error for a field named "%s"', + async (name) => { + const schema = type({ [name]: 'string>0' } as any); + + const result = await arktypeResolver(schema as any)( + { [name]: '' } as any, + undefined, + { fields: {}, shouldUseNativeValidation } as any, + ); + + expect(result.errors[name]).toBeDefined(); + }, + ); +}); diff --git a/node_modules/@hookform/resolvers/arktype/src/arktype.ts b/node_modules/@hookform/resolvers/arktype/src/arktype.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b7c2fdd624fd00215a20fdb865d13fe553d6640 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/src/arktype.ts @@ -0,0 +1,99 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import { StandardSchemaV1 } from '@standard-schema/spec'; +import { getDotPath } from '@standard-schema/utils'; +import { FieldError, FieldValues, Resolver } from 'react-hook-form'; + +function parseErrorSchema( + issues: readonly StandardSchemaV1.Issue[], + validateAllFieldCriteria: boolean, +) { + // See the matching comment in the zod resolver's `parseZod3Issues`. + const errors: Record = Object.create(null); + + for (let i = 0; i < issues.length; i++) { + const error = issues[i]; + const path = getDotPath(error); + + if (path) { + if (!errors[path]) { + errors[path] = { message: error.message, type: '' }; + } + + if (validateAllFieldCriteria) { + const types = errors[path].types || {}; + + errors[path].types = { + ...types, + [Object.keys(types).length]: error.message, + }; + } + } + } + + return errors; +} + +export function arktypeResolver( + schema: StandardSchemaV1, + _schemaOptions?: never, + resolverOptions?: { + raw?: false; + }, +): Resolver; + +export function arktypeResolver( + schema: StandardSchemaV1, + _schemaOptions: never | undefined, + resolverOptions: { + raw: true; + }, +): Resolver; + +/** + * Creates a resolver for react-hook-form using Arktype schema validation + * @param {Schema} schema - The Arktype schema to validate against + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='raw'] - Return the raw input values rather than the parsed values + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * const schema = type({ + * username: 'string>2' + * }); + * + * useForm({ + * resolver: arktypeResolver(schema) + * }); + */ +export function arktypeResolver( + schema: StandardSchemaV1, + _schemaOptions?: never, + resolverOptions: { + raw?: boolean; + } = {}, +): Resolver { + return async (values: Input, _, options) => { + let result = schema['~standard'].validate(values); + if (result instanceof Promise) { + result = await result; + } + + if (result.issues) { + const errors = parseErrorSchema( + result.issues, + !options.shouldUseNativeValidation && options.criteriaMode === 'all', + ); + + return { + values: {}, + errors: toNestErrors(errors, options), + }; + } + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return { + values: resolverOptions.raw ? Object.assign({}, values) : result.value, + errors: {}, + }; + }; +} diff --git a/node_modules/@hookform/resolvers/arktype/src/index.ts b/node_modules/@hookform/resolvers/arktype/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..686e84906fc723679cadd4fd0ded250d6cffa816 --- /dev/null +++ b/node_modules/@hookform/resolvers/arktype/src/index.ts @@ -0,0 +1 @@ +export * from './arktype'; diff --git a/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.d.ts b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d94b9c08d197de319a0086e88f0cb28ea3f5d7f8 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.d.ts @@ -0,0 +1,2 @@ +import { Resolver } from './types'; +export declare const ataResolver: Resolver; diff --git a/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.js b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.js new file mode 100644 index 0000000000000000000000000000000000000000..9a3ea4f3900a89784aa7b7fce00864d9dceae2b1 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers"),r=require("ata-validator"),a=require("react-hook-form"),t=function(e,r){for(var t=Object.create(null),s=0;s {\n // See the matching comment in the ajv resolver's `parseErrorSchema`.\n const parsedErrors: Record = Object.create(null);\n\n for (let index = 0; index < ataErrors.length; index += 1) {\n const error = ataErrors[index];\n\n const instancePath =\n error.keyword === 'required'\n ? `${error.instancePath}/${error.params.missingProperty}`\n : error.instancePath;\n\n const path = instancePath.substring(1).replace(/\\//g, '.');\n\n if (!parsedErrors[path]) {\n parsedErrors[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = parsedErrors[path].types;\n const messages = types && types[error.keyword];\n\n parsedErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n parsedErrors,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n }\n\n return parsedErrors;\n};\n\nexport const ataResolver: Resolver = (\n schema,\n schemaOptions,\n resolverOptions = {},\n) => {\n const validator = new Validator(schema, schemaOptions);\n return async (values, _, options) => {\n const result = validator.validate(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return result.valid\n ? {\n values: resolverOptions.raw ? Object.assign({}, values) : values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n result.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n};\n"],"names":["parseErrorSchema","ataErrors","validateAllFieldCriteria","parsedErrors","Object","create","index","length","error","path","keyword","instancePath","params","missingProperty","substring","replace","message","type","types","messages","appendErrors","concat","schema","schemaOptions","resolverOptions","validator","Validator","values","_","options","result","validate","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","valid","raw","assign","errors","toNestErrors","criteriaMode","e","reject"],"mappings":"6FAKMA,EAAmB,SACvBC,EACAC,GAKA,IAFA,IAAMC,EAA2CC,OAAOC,OAAO,MAEtDC,EAAQ,EAAGA,EAAQL,EAAUM,OAAQD,GAAS,EAAG,CACxD,IAAME,EAAQP,EAAUK,GAOlBG,GAJc,aAAlBD,EAAME,QACCF,EAAMG,aAAY,IAAIH,EAAMI,OAAOC,gBACtCL,EAAMG,cAEcG,UAAU,GAAGC,QAAQ,MAAO,KAStD,GAPKZ,EAAaM,KAChBN,EAAaM,GAAQ,CACnBO,QAASR,EAAMQ,QACfC,KAAMT,EAAME,UAIZR,EAA0B,CAC5B,IAAMgB,EAAQf,EAAaM,GAAMS,MAC3BC,EAAWD,GAASA,EAAMV,EAAME,SAEtCP,EAAaM,GAAQW,eACnBX,EACAP,EACAC,EACAK,EAAME,QACNS,EACK,GAAgBE,OAAOF,EAAsBX,EAAMQ,SAAW,IAC/DR,EAAMQ,QAEd,CACF,CAEA,OAAOb,CACT,sBAEqC,SACnCmB,EACAC,EACAC,QAAe,IAAfA,IAAAA,EAAkB,CAAA,GAElB,IAAMC,EAAY,IAAIC,YAAUJ,EAAQC,GACxC,OAAA,SAAcI,EAAQC,EAAGC,GAAO,IAC9B,IAAMC,EAASL,EAAUM,SAASJ,GAIlC,OAFAE,EAAQG,2BAA6BC,yBAAuB,CAAA,EAAIJ,GAEhEK,QAAAC,QAAOL,EAAOM,MACV,CACET,OAAQH,EAAgBa,IAAMjC,OAAOkC,OAAO,CAAE,EAAEX,GAAUA,EAC1DY,OAAQ,IAEV,CACEZ,OAAQ,GACRY,OAAQC,EAAAA,aACNxC,EACE8B,EAAOS,QACNV,EAAQG,2BACkB,QAAzBH,EAAQY,cAEZZ,IAGV,CAAC,MAAAa,UAAAR,QAAAS,OAAAD,IACH"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.mjs b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8cc028fd3a1386e75bb0f1c9d289cbf615f78008 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{Validator as a}from"ata-validator";import{appendErrors as o}from"react-hook-form";var t=function(r,e){for(var a=Object.create(null),t=0;t{const o=Object.create(null);for(let t=0;t{const i=new o(s,a);return async(o,s,a)=>{const c=i.validate(o);return a.shouldUseNativeValidation&&e({},a),c.valid?{values:n.raw?Object.assign({},o):o,errors:{}}:{values:{},errors:r(t(c.errors,!a.shouldUseNativeValidation&&"all"===a.criteriaMode),a)}}};export{a as ataResolver}; +//# sourceMappingURL=ata-validator.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.modern.mjs.map b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e94c831099b51149ec3b8f5f7904107781299c89 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ata-validator.modern.mjs","sources":["../src/ata-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError, Validator } from 'ata-validator';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n ataErrors: ValidationError[],\n validateAllFieldCriteria: boolean,\n) => {\n // See the matching comment in the ajv resolver's `parseErrorSchema`.\n const parsedErrors: Record = Object.create(null);\n\n for (let index = 0; index < ataErrors.length; index += 1) {\n const error = ataErrors[index];\n\n const instancePath =\n error.keyword === 'required'\n ? `${error.instancePath}/${error.params.missingProperty}`\n : error.instancePath;\n\n const path = instancePath.substring(1).replace(/\\//g, '.');\n\n if (!parsedErrors[path]) {\n parsedErrors[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = parsedErrors[path].types;\n const messages = types && types[error.keyword];\n\n parsedErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n parsedErrors,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n }\n\n return parsedErrors;\n};\n\nexport const ataResolver: Resolver = (\n schema,\n schemaOptions,\n resolverOptions = {},\n) => {\n const validator = new Validator(schema, schemaOptions);\n return async (values, _, options) => {\n const result = validator.validate(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return result.valid\n ? {\n values: resolverOptions.raw ? Object.assign({}, values) : values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n result.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n};\n"],"names":["parseErrorSchema","ataErrors","validateAllFieldCriteria","parsedErrors","Object","create","index","length","error","path","keyword","instancePath","params","missingProperty","substring","replace","message","type","types","messages","appendErrors","concat","ataResolver","schema","schemaOptions","resolverOptions","validator","Validator","values","_","options","result","validate","shouldUseNativeValidation","validateFieldsNatively","valid","raw","assign","errors","toNestErrors","criteriaMode"],"mappings":"wKAKA,MAAMA,EAAmBA,CACvBC,EACAC,KAGA,MAAMC,EAA2CC,OAAOC,OAAO,MAE/D,IAAK,IAAIC,EAAQ,EAAGA,EAAQL,EAAUM,OAAQD,GAAS,EAAG,CACxD,MAAME,EAAQP,EAAUK,GAOlBG,GAJc,aAAlBD,EAAME,QACF,GAAGF,EAAMG,gBAAgBH,EAAMI,OAAOC,kBACtCL,EAAMG,cAEcG,UAAU,GAAGC,QAAQ,MAAO,KAStD,GAPKZ,EAAaM,KAChBN,EAAaM,GAAQ,CACnBO,QAASR,EAAMQ,QACfC,KAAMT,EAAME,UAIZR,EAA0B,CAC5B,MAAMgB,EAAQf,EAAaM,GAAMS,MAC3BC,EAAWD,GAASA,EAAMV,EAAME,SAEtCP,EAAaM,GAAQW,EACnBX,EACAP,EACAC,EACAK,EAAME,QACNS,EACK,GAAgBE,OAAOF,EAAsBX,EAAMQ,SAAW,IAC/DR,EAAMQ,QAEd,CACF,CAEA,OAAOb,CAAY,EAGRmB,EAAwBA,CACnCC,EACAC,EACAC,EAAkB,CAAE,KAEpB,MAAMC,EAAY,IAAIC,EAAUJ,EAAQC,GACxC,OAAcI,MAAAA,EAAQC,EAAGC,KACvB,MAAMC,EAASL,EAAUM,SAASJ,GAIlC,OAFAE,EAAQG,2BAA6BC,EAAuB,CAAA,EAAIJ,GAEzDC,EAAOI,MACV,CACEP,OAAQH,EAAgBW,IAAMhC,OAAOiC,OAAO,CAAE,EAAET,GAAUA,EAC1DU,OAAQ,CACT,GACD,CACEV,OAAQ,CAAA,EACRU,OAAQC,EACNvC,EACE+B,EAAOO,QACNR,EAAQG,2BACkB,QAAzBH,EAAQU,cAEZV,GAEH,CACN"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.module.js b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.module.js new file mode 100644 index 0000000000000000000000000000000000000000..8cc028fd3a1386e75bb0f1c9d289cbf615f78008 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.module.js @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{Validator as a}from"ata-validator";import{appendErrors as o}from"react-hook-form";var t=function(r,e){for(var a=Object.create(null),t=0;t {\n // See the matching comment in the ajv resolver's `parseErrorSchema`.\n const parsedErrors: Record = Object.create(null);\n\n for (let index = 0; index < ataErrors.length; index += 1) {\n const error = ataErrors[index];\n\n const instancePath =\n error.keyword === 'required'\n ? `${error.instancePath}/${error.params.missingProperty}`\n : error.instancePath;\n\n const path = instancePath.substring(1).replace(/\\//g, '.');\n\n if (!parsedErrors[path]) {\n parsedErrors[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = parsedErrors[path].types;\n const messages = types && types[error.keyword];\n\n parsedErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n parsedErrors,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n }\n\n return parsedErrors;\n};\n\nexport const ataResolver: Resolver = (\n schema,\n schemaOptions,\n resolverOptions = {},\n) => {\n const validator = new Validator(schema, schemaOptions);\n return async (values, _, options) => {\n const result = validator.validate(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return result.valid\n ? {\n values: resolverOptions.raw ? Object.assign({}, values) : values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n result.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n};\n"],"names":["parseErrorSchema","ataErrors","validateAllFieldCriteria","parsedErrors","Object","create","index","length","error","path","keyword","instancePath","params","missingProperty","substring","replace","message","type","types","messages","appendErrors","concat","ataResolver","schema","schemaOptions","resolverOptions","validator","Validator","values","_","options","result","validate","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","valid","raw","assign","errors","toNestErrors","criteriaMode","e","reject"],"mappings":"wKAKA,IAAMA,EAAmB,SACvBC,EACAC,GAKA,IAFA,IAAMC,EAA2CC,OAAOC,OAAO,MAEtDC,EAAQ,EAAGA,EAAQL,EAAUM,OAAQD,GAAS,EAAG,CACxD,IAAME,EAAQP,EAAUK,GAOlBG,GAJc,aAAlBD,EAAME,QACCF,EAAMG,aAAY,IAAIH,EAAMI,OAAOC,gBACtCL,EAAMG,cAEcG,UAAU,GAAGC,QAAQ,MAAO,KAStD,GAPKZ,EAAaM,KAChBN,EAAaM,GAAQ,CACnBO,QAASR,EAAMQ,QACfC,KAAMT,EAAME,UAIZR,EAA0B,CAC5B,IAAMgB,EAAQf,EAAaM,GAAMS,MAC3BC,EAAWD,GAASA,EAAMV,EAAME,SAEtCP,EAAaM,GAAQW,EACnBX,EACAP,EACAC,EACAK,EAAME,QACNS,EACK,GAAgBE,OAAOF,EAAsBX,EAAMQ,SAAW,IAC/DR,EAAMQ,QAEd,CACF,CAEA,OAAOb,CACT,EAEamB,EAAwB,SACnCC,EACAC,EACAC,QAAe,IAAfA,IAAAA,EAAkB,CAAA,GAElB,IAAMC,EAAY,IAAIC,EAAUJ,EAAQC,GACxC,OAAA,SAAcI,EAAQC,EAAGC,GAAO,IAC9B,IAAMC,EAASL,EAAUM,SAASJ,GAIlC,OAFAE,EAAQG,2BAA6BC,EAAuB,CAAA,EAAIJ,GAEhEK,QAAAC,QAAOL,EAAOM,MACV,CACET,OAAQH,EAAgBa,IAAMlC,OAAOmC,OAAO,CAAE,EAAEX,GAAUA,EAC1DY,OAAQ,IAEV,CACEZ,OAAQ,GACRY,OAAQC,EACNzC,EACE+B,EAAOS,QACNV,EAAQG,2BACkB,QAAzBH,EAAQY,cAEZZ,IAGV,CAAC,MAAAa,UAAAR,QAAAS,OAAAD,IACH"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.umd.js b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..d7d911ceb7ab4c31f3e11f3339278aeb559cbb9a --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/dist/ata-validator.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("ata-validator"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","ata-validator","react-hook-form"],r):r((e||self).hookformResolversAtaValidator={},e.hookformResolvers,e.ataValidator,e.ReactHookForm)}(this,function(e,r,o,a){var t=function(e,r){for(var o=Object.create(null),t=0;t {\n // See the matching comment in the ajv resolver's `parseErrorSchema`.\n const parsedErrors: Record = Object.create(null);\n\n for (let index = 0; index < ataErrors.length; index += 1) {\n const error = ataErrors[index];\n\n const instancePath =\n error.keyword === 'required'\n ? `${error.instancePath}/${error.params.missingProperty}`\n : error.instancePath;\n\n const path = instancePath.substring(1).replace(/\\//g, '.');\n\n if (!parsedErrors[path]) {\n parsedErrors[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = parsedErrors[path].types;\n const messages = types && types[error.keyword];\n\n parsedErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n parsedErrors,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n }\n\n return parsedErrors;\n};\n\nexport const ataResolver: Resolver = (\n schema,\n schemaOptions,\n resolverOptions = {},\n) => {\n const validator = new Validator(schema, schemaOptions);\n return async (values, _, options) => {\n const result = validator.validate(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return result.valid\n ? {\n values: resolverOptions.raw ? Object.assign({}, values) : values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n result.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n};\n"],"names":["parseErrorSchema","ataErrors","validateAllFieldCriteria","parsedErrors","Object","create","index","length","error","path","keyword","instancePath","params","missingProperty","substring","replace","message","type","types","messages","appendErrors","concat","schema","schemaOptions","resolverOptions","validator","Validator","values","_","options","result","validate","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","valid","raw","assign","errors","toNestErrors","criteriaMode","e","reject"],"mappings":"2bAKA,IAAMA,EAAmB,SACvBC,EACAC,GAKA,IAFA,IAAMC,EAA2CC,OAAOC,OAAO,MAEtDC,EAAQ,EAAGA,EAAQL,EAAUM,OAAQD,GAAS,EAAG,CACxD,IAAME,EAAQP,EAAUK,GAOlBG,GAJc,aAAlBD,EAAME,QACCF,EAAMG,aAAY,IAAIH,EAAMI,OAAOC,gBACtCL,EAAMG,cAEcG,UAAU,GAAGC,QAAQ,MAAO,KAStD,GAPKZ,EAAaM,KAChBN,EAAaM,GAAQ,CACnBO,QAASR,EAAMQ,QACfC,KAAMT,EAAME,UAIZR,EAA0B,CAC5B,IAAMgB,EAAQf,EAAaM,GAAMS,MAC3BC,EAAWD,GAASA,EAAMV,EAAME,SAEtCP,EAAaM,GAAQW,eACnBX,EACAP,EACAC,EACAK,EAAME,QACNS,EACK,GAAgBE,OAAOF,EAAsBX,EAAMQ,SAAW,IAC/DR,EAAMQ,QAEd,CACF,CAEA,OAAOb,CACT,gBAEqC,SACnCmB,EACAC,EACAC,QAAe,IAAfA,IAAAA,EAAkB,CAAA,GAElB,IAAMC,EAAY,IAAIC,YAAUJ,EAAQC,GACxC,OAAA,SAAcI,EAAQC,EAAGC,GAAO,IAC9B,IAAMC,EAASL,EAAUM,SAASJ,GAIlC,OAFAE,EAAQG,2BAA6BC,yBAAuB,CAAA,EAAIJ,GAEhEK,QAAAC,QAAOL,EAAOM,MACV,CACET,OAAQH,EAAgBa,IAAMjC,OAAOkC,OAAO,CAAE,EAAEX,GAAUA,EAC1DY,OAAQ,IAEV,CACEZ,OAAQ,GACRY,OAAQC,EAAAA,aACNxC,EACE8B,EAAOS,QACNV,EAAQG,2BACkB,QAAzBH,EAAQY,cAEZZ,IAGV,CAAC,MAAAa,UAAAR,QAAAS,OAAAD,IACH"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/ata-validator/dist/index.d.ts b/node_modules/@hookform/resolvers/ata-validator/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b86f12d189380a5ed16ead28abf6921186600b39 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/dist/index.d.ts @@ -0,0 +1,2 @@ +export * from './ata-validator'; +export * from './types'; diff --git a/node_modules/@hookform/resolvers/ata-validator/dist/types.d.ts b/node_modules/@hookform/resolvers/ata-validator/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1c5ff70ae6e71fa162c1b1b9869eeea9681f837 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/dist/types.d.ts @@ -0,0 +1,6 @@ +import type { ValidationError, ValidatorOptions } from 'ata-validator'; +import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form'; +export type Resolver = (schema: object, schemaOptions?: ValidatorOptions, resolverOptions?: { + raw?: boolean; +}) => (values: TFieldValues, context: TContext | undefined, options: ResolverOptions) => Promise>; +export type AtaValidationError = ValidationError; diff --git a/node_modules/@hookform/resolvers/ata-validator/package.json b/node_modules/@hookform/resolvers/ata-validator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9a250b33d3d3a6b0d337063711212b4b475d7e18 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/package.json @@ -0,0 +1,18 @@ +{ + "name": "@hookform/resolvers/ata-validator", + "amdName": "hookformResolversAtaValidator", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: ata-validator", + "main": "dist/ata-validator.js", + "module": "dist/ata-validator.module.js", + "umd:main": "dist/ata-validator.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0", + "ata-validator": "^1.2.0" + } +} diff --git a/node_modules/@hookform/resolvers/ata-validator/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f29f6ae02e2cc207d2bb0e64e393258f607b90eb --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,80 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { ataResolver } from '..'; + +type FormData = { username: string; password: string }; + +const schema = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 1, + }, + password: { + type: 'string', + minLength: 1, + }, + }, + required: ['username', 'password'], + additionalProperties: false, +}; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: ataResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with ata-validator", async () => { + const handleSubmit = vi.fn(); + render(); + + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/ata-validator/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3da951b39466b684ccbcd0dc18fbbe1d29727fa7 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/Form.tsx @@ -0,0 +1,61 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { ataResolver } from '..'; + +type FormData = { username: string; password: string }; + +const schema = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 1, + }, + password: { + type: 'string', + minLength: 1, + }, + }, + required: ['username', 'password'], + additionalProperties: false, +}; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: ataResolver(schema), + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with ata-validator and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect(screen.queryAllByRole('alert').length).toBeGreaterThan(0); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/ata-validator/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9ec5333a16f0c416794a60bd489a884a1682e12 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,134 @@ +import { Field, InternalFieldName } from 'react-hook-form'; + +interface Data { + username: string; + password: string; + email?: string; + birthday?: number; + tags: string[]; + enabled: boolean; + url: string; + like?: { id: number; name: string }[]; + deepObject: { data: string; twoLayersDeep: { name: string } }; +} + +export const schema = { + type: 'object', + properties: { + username: { + type: 'string', + minLength: 3, + maxLength: 30, + pattern: '^\\w+$', + }, + password: { + type: 'string', + minLength: 8, + pattern: '.*[A-Z].*', + }, + email: { + type: 'string', + format: 'email', + }, + birthday: { + type: 'integer', + minimum: 1900, + maximum: 2013, + }, + tags: { + type: 'array', + items: { type: 'string' }, + }, + enabled: { + type: 'boolean', + }, + url: { + type: 'string', + format: 'uri', + }, + like: { + type: 'array', + items: { + type: 'object', + properties: { + id: { type: 'number' }, + name: { type: 'string', minLength: 4, maxLength: 4 }, + }, + required: ['id', 'name'], + }, + }, + deepObject: { + type: 'object', + properties: { + data: { type: 'string' }, + twoLayersDeep: { + type: 'object', + properties: { name: { type: 'string' } }, + additionalProperties: false, + required: ['name'], + }, + }, + required: ['data', 'twoLayersDeep'], + }, + }, + required: ['username', 'password', 'tags', 'enabled', 'deepObject'], + additionalProperties: false, +}; + +export const validData: Data = { + username: 'Doe', + password: 'Password123_', + email: 'john@doe.com', + birthday: 2000, + tags: ['tag1', 'tag2'], + enabled: true, + url: 'https://react-hook-form.com/', + like: [{ id: 1, name: 'name' }], + deepObject: { + data: 'data', + twoLayersDeep: { name: 'deeper' }, + }, +}; + +export const invalidData = { + username: '__', + password: 'invalid', + email: '', + birthday: 'birthYear', + like: [{ id: 'z' }], + url: 'abc', + deepObject: { + data: 233, + twoLayersDeep: { name: 123 }, + }, +}; + +export const invalidDataWithUndefined = { + username: 'jsun969', + password: undefined, + deepObject: { + twoLayersDeep: { + name: 'deeper', + }, + data: undefined, + }, +}; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/ata-validator/src/__tests__/__snapshots__/ata-validator.ts.snap b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/__snapshots__/ata-validator.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..9026582ff7ae0d05996b8d4d0f46593cb984733d --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/__snapshots__/ata-validator.ts.snap @@ -0,0 +1,262 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`ataResolver > should return all the error messages from ataResolver when requirement fails 1`] = ` +{ + "errors": { + "deepObject": { + "message": "must have required property 'deepObject'", + "ref": undefined, + "type": "required", + }, + "enabled": { + "message": "must have required property 'enabled'", + "ref": undefined, + "type": "required", + }, + "password": { + "message": "must have required property 'password'", + "ref": { + "name": "password", + }, + "type": "required", + }, + "tags": { + "message": "must have required property 'tags'", + "ref": undefined, + "type": "required", + }, + "username": { + "message": "must have required property 'username'", + "ref": { + "name": "username", + }, + "type": "required", + }, + }, + "values": {}, +} +`; + +exports[`ataResolver > should return all the error messages from ataResolver when some property is undefined 1`] = ` +{ + "errors": { + "deepObject": { + "data": { + "message": "must have required property 'data'", + "ref": undefined, + "type": "required", + }, + }, + "enabled": { + "message": "must have required property 'enabled'", + "ref": undefined, + "type": "required", + }, + "password": { + "message": "must have required property 'password'", + "ref": { + "name": "password", + }, + "type": "required", + }, + "tags": { + "message": "must have required property 'tags'", + "ref": undefined, + "type": "required", + }, + }, + "values": {}, +} +`; + +exports[`ataResolver > should return all the error messages from ataResolver when validation fails and validateAllFieldCriteria set to true 1`] = ` +{ + "errors": { + "birthday": { + "message": "must be integer", + "ref": { + "name": "birthday", + }, + "type": "type", + "types": { + "type": "must be integer", + }, + }, + "deepObject": { + "data": { + "message": "must be string", + "ref": undefined, + "type": "type", + "types": { + "type": "must be string", + }, + }, + "twoLayersDeep": { + "name": { + "message": "must be string", + "ref": undefined, + "type": "type", + "types": { + "type": "must be string", + }, + }, + }, + }, + "email": { + "message": "must match format "email"", + "ref": { + "name": "email", + }, + "type": "format", + "types": { + "format": "must match format "email"", + }, + }, + "enabled": { + "message": "must have required property 'enabled'", + "ref": undefined, + "type": "required", + "types": { + "required": "must have required property 'enabled'", + }, + }, + "like": [ + { + "id": { + "message": "must be number", + "ref": undefined, + "type": "type", + "types": { + "type": "must be number", + }, + }, + "name": { + "message": "must have required property 'name'", + "ref": undefined, + "type": "required", + "types": { + "required": "must have required property 'name'", + }, + }, + }, + ], + "password": { + "message": "must NOT have fewer than 8 characters", + "ref": { + "name": "password", + }, + "type": "minLength", + "types": { + "minLength": "must NOT have fewer than 8 characters", + "pattern": "must match pattern ".*[A-Z].*"", + }, + }, + "tags": { + "message": "must have required property 'tags'", + "ref": undefined, + "type": "required", + "types": { + "required": "must have required property 'tags'", + }, + }, + "url": { + "message": "must match format "uri"", + "ref": undefined, + "type": "format", + "types": { + "format": "must match format "uri"", + }, + }, + "username": { + "message": "must NOT have fewer than 3 characters", + "ref": { + "name": "username", + }, + "type": "minLength", + "types": { + "minLength": "must NOT have fewer than 3 characters", + }, + }, + }, + "values": {}, +} +`; + +exports[`ataResolver > should return single error message from ataResolver when validation fails and validateAllFieldCriteria set to false 1`] = ` +{ + "errors": { + "birthday": { + "message": "must be integer", + "ref": { + "name": "birthday", + }, + "type": "type", + }, + "deepObject": { + "data": { + "message": "must be string", + "ref": undefined, + "type": "type", + }, + "twoLayersDeep": { + "name": { + "message": "must be string", + "ref": undefined, + "type": "type", + }, + }, + }, + "email": { + "message": "must match format "email"", + "ref": { + "name": "email", + }, + "type": "format", + }, + "enabled": { + "message": "must have required property 'enabled'", + "ref": undefined, + "type": "required", + }, + "like": [ + { + "id": { + "message": "must be number", + "ref": undefined, + "type": "type", + }, + "name": { + "message": "must have required property 'name'", + "ref": undefined, + "type": "required", + }, + }, + ], + "password": { + "message": "must NOT have fewer than 8 characters", + "ref": { + "name": "password", + }, + "type": "minLength", + }, + "tags": { + "message": "must have required property 'tags'", + "ref": undefined, + "type": "required", + }, + "url": { + "message": "must match format "uri"", + "ref": undefined, + "type": "format", + }, + "username": { + "message": "must NOT have fewer than 3 characters", + "ref": { + "name": "username", + }, + "type": "minLength", + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/ata-validator/src/__tests__/ata-validator.ts b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/ata-validator.ts new file mode 100644 index 0000000000000000000000000000000000000000..01eff7f79fdfc25818aa9ad5e67eb19dc9195657 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/ata-validator.ts @@ -0,0 +1,113 @@ +import { ataResolver } from '..'; +import { + fields, + invalidData, + invalidDataWithUndefined, + schema, + validData, +} from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('ataResolver', () => { + it('should return values from ataResolver when validation pass', async () => { + expect( + await ataResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }), + ).toEqual({ + values: validData, + errors: {}, + }); + }); + + it('should return values from ataResolver when validation pass & raw=true', async () => { + const result = await ataResolver(schema, undefined, { raw: true })( + validData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return single error message from ataResolver when validation fails and validateAllFieldCriteria set to false', async () => { + expect( + await ataResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return all the error messages from ataResolver when validation fails and validateAllFieldCriteria set to true', async () => { + expect( + await ataResolver(schema)( + invalidData, + {}, + { fields, criteriaMode: 'all', shouldUseNativeValidation }, + ), + ).toMatchSnapshot(); + }); + + it('should return all the error messages from ataResolver when requirement fails', async () => { + expect( + await ataResolver(schema)({}, undefined, { + fields, + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should return all the error messages from ataResolver when some property is undefined', async () => { + expect( + await ataResolver(schema)(invalidDataWithUndefined, undefined, { + fields, + shouldUseNativeValidation, + }), + ).toMatchSnapshot(); + }); + + it('should support coerceTypes option', async () => { + const coerceSchema = { + type: 'object', + properties: { + age: { type: 'integer' }, + active: { type: 'boolean' }, + }, + required: ['age', 'active'], + }; + + const result = await ataResolver(coerceSchema, { coerceTypes: true })( + { age: '25', active: 'true' }, + undefined, + { fields, shouldUseNativeValidation }, + ); + + expect(result.errors).toEqual({}); + }); + + it('should support removeAdditional option', async () => { + const strictSchema = { + type: 'object', + properties: { + name: { type: 'string' }, + }, + required: ['name'], + additionalProperties: false, + }; + + const result = await ataResolver(strictSchema, { + removeAdditional: true, + })({ name: 'test', extra: 'field' }, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result.errors).toEqual({}); + }); +}); diff --git a/node_modules/@hookform/resolvers/ata-validator/src/__tests__/special-path-names.ts b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/special-path-names.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ac8452a6c141ba1e57f15d29bd2ee33b4db564e --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/__tests__/special-path-names.ts @@ -0,0 +1,45 @@ +import { ataResolver } from '..'; + +const shouldUseNativeValidation = false; + +// The native binding's error shape varies by which schema keywords are +// involved (a detail unrelated to this fix), so the underlying validator is +// mocked here to isolate the resolver's own path-tracking logic — the thing +// this regression test targets. +vi.mock('ata-validator', () => ({ + Validator: class { + validate(values: any) { + const errors = Object.keys(values).flatMap((name) => + values[name] === '' + ? [ + { + keyword: 'minLength', + instancePath: `/${name}`, + params: { limit: 1 }, + message: 'must NOT have fewer than 1 characters', + }, + ] + : [], + ); + + return errors.length + ? { valid: false, errors } + : { valid: true, errors: [] }; + } + }, +})); + +describe('ataResolver special path names', () => { + it.each(['hasOwnProperty', 'toString'])( + 'reports a validation error for a field named "%s"', + async (name) => { + const result = await ataResolver({} as any)( + { [name]: '' } as any, + undefined, + { fields: {}, shouldUseNativeValidation } as any, + ); + + expect(result.errors[name]).toBeDefined(); + }, + ); +}); diff --git a/node_modules/@hookform/resolvers/ata-validator/src/ata-validator.ts b/node_modules/@hookform/resolvers/ata-validator/src/ata-validator.ts new file mode 100644 index 0000000000000000000000000000000000000000..06713b731f2cf4aaee7d5c4b819c9734f1dd5845 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/ata-validator.ts @@ -0,0 +1,77 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import { ValidationError, Validator } from 'ata-validator'; +import { FieldError, appendErrors } from 'react-hook-form'; +import { Resolver } from './types'; + +const parseErrorSchema = ( + ataErrors: ValidationError[], + validateAllFieldCriteria: boolean, +) => { + // See the matching comment in the ajv resolver's `parseErrorSchema`. + const parsedErrors: Record = Object.create(null); + + for (let index = 0; index < ataErrors.length; index += 1) { + const error = ataErrors[index]; + + const instancePath = + error.keyword === 'required' + ? `${error.instancePath}/${error.params.missingProperty}` + : error.instancePath; + + const path = instancePath.substring(1).replace(/\//g, '.'); + + if (!parsedErrors[path]) { + parsedErrors[path] = { + message: error.message, + type: error.keyword, + }; + } + + if (validateAllFieldCriteria) { + const types = parsedErrors[path].types; + const messages = types && types[error.keyword]; + + parsedErrors[path] = appendErrors( + path, + validateAllFieldCriteria, + parsedErrors, + error.keyword, + messages + ? ([] as string[]).concat(messages as string[], error.message || '') + : error.message, + ) as FieldError; + } + } + + return parsedErrors; +}; + +export const ataResolver: Resolver = ( + schema, + schemaOptions, + resolverOptions = {}, +) => { + const validator = new Validator(schema, schemaOptions); + return async (values, _, options) => { + const result = validator.validate(values); + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return result.valid + ? { + values: resolverOptions.raw ? Object.assign({}, values) : values, + errors: {}, + } + : { + values: {}, + errors: toNestErrors( + parseErrorSchema( + result.errors, + !options.shouldUseNativeValidation && + options.criteriaMode === 'all', + ), + options, + ), + }; + }; +}; diff --git a/node_modules/@hookform/resolvers/ata-validator/src/index.ts b/node_modules/@hookform/resolvers/ata-validator/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..b86f12d189380a5ed16ead28abf6921186600b39 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/index.ts @@ -0,0 +1,2 @@ +export * from './ata-validator'; +export * from './types'; diff --git a/node_modules/@hookform/resolvers/ata-validator/src/types.ts b/node_modules/@hookform/resolvers/ata-validator/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..182d4178b690427c5c17df25e68a6569315f52e1 --- /dev/null +++ b/node_modules/@hookform/resolvers/ata-validator/src/types.ts @@ -0,0 +1,16 @@ +import type { ValidationError, ValidatorOptions } from 'ata-validator'; +import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form'; + +export type Resolver = ( + schema: object, + schemaOptions?: ValidatorOptions, + resolverOptions?: { + raw?: boolean; + }, +) => ( + values: TFieldValues, + context: TContext | undefined, + options: ResolverOptions, +) => Promise>; + +export type AtaValidationError = ValidationError; diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.d.ts b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd58d715ad3e3015ae18662be7791531d88117bb --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.d.ts @@ -0,0 +1,29 @@ +import { ClassConstructor, ClassTransformOptions } from 'class-transformer'; +import { ValidatorOptions } from 'class-validator'; +import { Resolver } from 'react-hook-form'; +/** + * Creates a resolver for react-hook-form using class-validator schema validation + * @param {ClassConstructor} schema - The class-validator schema to validate against + * @param {Object} schemaOptions - Additional schema validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='async'] - Validation mode + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * class Schema { + * @Matches(/^\w+$/) + * @Length(3, 30) + * username: string; + * age: number + * } + * + * useForm({ + * resolver: classValidatorResolver(Schema) + * }); + */ +export declare function classValidatorResolver>(schema: ClassConstructor, schemaOptions?: { + validator?: ValidatorOptions; + transformer?: ClassTransformOptions; +}, resolverOptions?: { + mode?: 'async' | 'sync'; + raw?: boolean; +}): Resolver; diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.js b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.js new file mode 100644 index 0000000000000000000000000000000000000000..12556b6f5633ea5d7cec66a7575de74acd47b7c7 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.js @@ -0,0 +1,2 @@ +var r=require("@hookform/resolvers"),e=require("class-transformer"),t=require("class-validator");function s(r,e,t,a){return void 0===t&&(t={}),void 0===a&&(a=""),r.reduce(function(r,t){var i=a?a+"."+t.property:t.property;if(t.constraints){var o=Object.keys(t.constraints)[0];r[i]={type:o,message:t.constraints[o]};var n=r[i];e&&n&&Object.assign(n,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,i),r},t)}exports.classValidatorResolver=function(a,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),function(n,l,c){try{var v=i.validator,d=e.plainToClass(a,n,i.transformer);return Promise.resolve(("sync"===o.mode?t.validateSync:t.validate)(d,v)).then(function(e){return e.length?{values:{},errors:r.toNestErrors(s(e,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}:(c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{values:o.raw?Object.assign({},n):d,errors:{}})})}catch(r){return Promise.reject(r)}}}; +//# sourceMappingURL=class-validator.js.map diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.js.map b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e801c111d4076fd40c983e944f7ea87fbab465de --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"class-validator.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver>(\n schema: ClassConstructor,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"iGAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHAD,IAAAA,IAAAA,EAA4B,CAAE,QAC1B,IAAJC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAQG,IAAAA,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,yCAsBEkB,EACAC,EAIAC,GAEA,YANAD,IAAAA,IAAAA,EAGI,CAAE,YACNC,IAAAA,EAA8D,CAAE,YAElDC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,eAAaR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,EAAAA,aACAC,EAAQA,UAAEP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUjB,OACL,CACLI,OAAQ,CAAA,EACRvB,OAAQqC,EAAYA,aAClBtC,EACEqC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAAA,uBAAuB,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM9B,OAAOK,OAAO,CAAA,EAAIO,GAAUI,EAC1D3B,OAAQ,IACR,EACJ,CAAC,MAAA0C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.mjs b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5536f935c9862201369668d1d20826487bb323d5 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as o,validate as n}from"class-validator";function s(r,e,t,o){return void 0===t&&(t={}),void 0===o&&(o=""),r.reduce(function(r,t){var n=o?o+"."+t.property:t.property;if(t.constraints){var i=Object.keys(t.constraints)[0];r[n]={type:i,message:t.constraints[i]};var a=r[n];e&&a&&Object.assign(a,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,n),r},t)}function i(i,a,c){return void 0===a&&(a={}),void 0===c&&(c={}),function(l,d,u){try{var v=a.validator,m=t(i,l,a.transformer);return Promise.resolve(("sync"===c.mode?o:n)(m,v)).then(function(t){return t.length?{values:{},errors:r(s(t,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)}:(u.shouldUseNativeValidation&&e({},u),{values:c.raw?Object.assign({},l):m,errors:{}})})}catch(r){return Promise.reject(r)}}}export{i as classValidatorResolver}; +//# sourceMappingURL=class-validator.module.js.map diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5561dd2cd9f701f905f69a4176d959c791a76dd0 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as t}from"@hookform/resolvers";import{plainToClass as s}from"class-transformer";import{validateSync as e,validate as o}from"class-validator";function n(r,t,s={},e=""){return r.reduce((r,s)=>{const o=e?`${e}.${s.property}`:s.property;if(s.constraints){const e=Object.keys(s.constraints)[0];r[o]={type:e,message:s.constraints[e]};const n=r[o];t&&n&&Object.assign(n,{types:s.constraints})}return s.children&&s.children.length&&n(s.children,t,r,o),r},s)}function a(a,i={},c={}){return async(l,d,m)=>{const{transformer:u,validator:p}=i,f=s(a,l,u),h=await("sync"===c.mode?e:o)(f,p);return h.length?{values:{},errors:r(n(h,!m.shouldUseNativeValidation&&"all"===m.criteriaMode),m)}:(m.shouldUseNativeValidation&&t({},m),{values:c.raw?Object.assign({},l):f,errors:{}})}}export{a as classValidatorResolver}; +//# sourceMappingURL=class-validator.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs.map b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..29b81c5526e54cd2849995f77889037fc1774147 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"class-validator.modern.mjs","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver>(\n schema: ClassConstructor,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","classValidatorResolver","schema","schemaOptions","resolverOptions","async","values","_","options","transformer","validator","data","plainToClass","rawErrors","mode","validateSync","validate","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw"],"mappings":"6LAcA,SAASA,EACPC,EACAC,EACAC,EAA4B,CAAA,EAC5BC,EAAO,IAEP,OAAOH,EAAOI,OAAO,CAACC,EAAKC,KACzB,MAAMC,EAAQJ,EAAO,GAAGA,KAAQG,EAAME,WAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,MAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,MAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CAAG,EACTH,EACL,CAqBM,SAAUkB,EACdC,EACAC,EAGI,CAAE,EACNC,EAA8D,CAAE,GAEhE,OAAOC,MAAOC,EAAQC,EAAGC,KACvB,MAAMC,YAAEA,EAAWC,UAAEA,GAAcP,EAC7BQ,EAAOC,EAAaV,EAAQI,EAAQG,GAEpCI,QAA4C,SAAzBT,EAAgBU,KACrCC,EACAC,GAAUL,EAAMD,GAEpB,OAAIG,EAAUb,OACL,CACLM,OAAQ,CAAE,EACVzB,OAAQoC,EACNrC,EACEiC,GACCL,EAAQU,2BACkB,QAAzBV,EAAQW,cAEZX,KAKNA,EAAQU,2BAA6BE,EAAuB,CAAA,EAAIZ,GAEzD,CACLF,OAAQF,EAAgBiB,IAAM7B,OAAOK,OAAO,CAAE,EAAES,GAAUK,EAC1D9B,OAAQ,CAAA,GACT,CAEL"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js new file mode 100644 index 0000000000000000000000000000000000000000..5536f935c9862201369668d1d20826487bb323d5 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as o,validate as n}from"class-validator";function s(r,e,t,o){return void 0===t&&(t={}),void 0===o&&(o=""),r.reduce(function(r,t){var n=o?o+"."+t.property:t.property;if(t.constraints){var i=Object.keys(t.constraints)[0];r[n]={type:i,message:t.constraints[i]};var a=r[n];e&&a&&Object.assign(a,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,n),r},t)}function i(i,a,c){return void 0===a&&(a={}),void 0===c&&(c={}),function(l,d,u){try{var v=a.validator,m=t(i,l,a.transformer);return Promise.resolve(("sync"===c.mode?o:n)(m,v)).then(function(t){return t.length?{values:{},errors:r(s(t,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)}:(u.shouldUseNativeValidation&&e({},u),{values:c.raw?Object.assign({},l):m,errors:{}})})}catch(r){return Promise.reject(r)}}}export{i as classValidatorResolver}; +//# sourceMappingURL=class-validator.module.js.map diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js.map b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0932ec0bc446ae6d7bd021bc3dd4f11c742225a2 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"class-validator.module.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver>(\n schema: ClassConstructor,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","classValidatorResolver","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"6LAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHAD,IAAAA,IAAAA,EAA4B,CAAE,QAC1B,IAAJC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAQG,IAAAA,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,UAqBgBkB,EACdC,EACAC,EAIAC,GAEA,YANAD,IAAAA,IAAAA,EAGI,CAAE,YACNC,IAAAA,EAA8D,CAAE,YAElDC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,EAAaR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,EACAC,GAAUP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUlB,OACL,CACLK,OAAQ,CAAA,EACRxB,OAAQsC,EACNvC,EACEsC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAuB,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM/B,OAAOK,OAAO,CAAA,EAAIQ,GAAUI,EAC1D5B,OAAQ,IACR,EACJ,CAAC,MAAA2C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..05d69ef0f870bccef16ab8f693a705f01afc55f7 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("class-transformer"),require("class-validator")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","class-transformer","class-validator"],r):r((e||self).hookformResolversClassValidator={},e.hookformResolvers,e.classTransformer,e.classValidator)}(this,function(e,r,o,s){function t(e,r,o,s){return void 0===o&&(o={}),void 0===s&&(s=""),e.reduce(function(e,o){var a=s?s+"."+o.property:o.property;if(o.constraints){var i=Object.keys(o.constraints)[0];e[a]={type:i,message:o.constraints[i]};var n=e[a];r&&n&&Object.assign(n,{types:o.constraints})}return o.children&&o.children.length&&t(o.children,r,e,a),e},o)}e.classValidatorResolver=function(e,a,i){return void 0===a&&(a={}),void 0===i&&(i={}),function(n,l,c){try{var d=a.validator,f=o.plainToClass(e,n,a.transformer);return Promise.resolve(("sync"===i.mode?s.validateSync:s.validate)(f,d)).then(function(e){return e.length?{values:{},errors:r.toNestErrors(t(e,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}:(c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{values:i.raw?Object.assign({},n):f,errors:{}})})}catch(e){return Promise.reject(e)}}}}); +//# sourceMappingURL=class-validator.umd.js.map diff --git a/node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js.map b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..264eeb2614851f6f15b99cc08964567d40a088bc --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"class-validator.umd.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver>(\n schema: ClassConstructor,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"0cAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHAD,IAAAA,IAAAA,EAA4B,CAAE,QAC1B,IAAJC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAQG,IAAAA,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,mCAsBEkB,EACAC,EAIAC,GAEA,YANAD,IAAAA,IAAAA,EAGI,CAAE,YACNC,IAAAA,EAA8D,CAAE,YAElDC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,eAAaR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,EAAAA,aACAC,EAAQA,UAAEP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUjB,OACL,CACLI,OAAQ,CAAA,EACRvB,OAAQqC,EAAYA,aAClBtC,EACEqC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAAA,uBAAuB,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM9B,OAAOK,OAAO,CAAA,EAAIO,GAAUI,EAC1D3B,OAAQ,IACR,EACJ,CAAC,MAAA0C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/class-validator/dist/index.d.ts b/node_modules/@hookform/resolvers/class-validator/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1cc75cf6c630dbba08f437b6dbe820182605d8e --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/dist/index.d.ts @@ -0,0 +1 @@ +export * from './class-validator'; diff --git a/node_modules/@hookform/resolvers/class-validator/package.json b/node_modules/@hookform/resolvers/class-validator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1b6aef34f425d017b7092989c35f9a792ce5090f --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/package.json @@ -0,0 +1,19 @@ +{ + "name": "@hookform/resolvers/class-validator", + "amdName": "hookformResolversClassValidator", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: class-validator", + "main": "dist/class-validator.js", + "module": "dist/class-validator.module.js", + "umd:main": "dist/class-validator.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": ">=6.6.0", + "@hookform/resolvers": ">=2.0.0", + "class-transformer": "^0.4.0", + "class-validator": "^0.12.0" + } +} diff --git a/node_modules/@hookform/resolvers/class-validator/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/class-validator/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ba2945a1ae0b298cd8a5238178428732bc68fd45 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,79 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { IsNotEmpty } from 'class-validator'; +import React from 'react'; +import { SubmitHandler, useForm } from 'react-hook-form'; +import { classValidatorResolver } from '..'; + +class Schema { + @IsNotEmpty() + username: string; + + @IsNotEmpty() + password: string; +} + +interface Props { + onSubmit: SubmitHandler; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: classValidatorResolver(Schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with Class Validator", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe('username should not be empty'); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe('password should not be empty'); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/class-validator/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/class-validator/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..52984f67a4cd5ef3f590ea699a12dfe438c8b82e --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/src/__tests__/Form.tsx @@ -0,0 +1,53 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { IsNotEmpty } from 'class-validator'; +import React from 'react'; +import { SubmitHandler, useForm } from 'react-hook-form'; +import { classValidatorResolver } from '..'; + +class Schema { + @IsNotEmpty() + username: string; + + @IsNotEmpty() + password: string; +} + +interface Props { + onSubmit: SubmitHandler; +} + +function TestComponent({ onSubmit }: Props) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: classValidatorResolver(Schema), + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with Class Validator and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect(screen.getByText(/username should not be empty/i)).toBeInTheDocument(); + expect(screen.getByText(/password should not be empty/i)).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/class-validator/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/class-validator/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..5abd5ef224d3fd62a1fd9b00bf1cc8b3262d6b2b --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,88 @@ +import 'reflect-metadata'; +import { Type } from 'class-transformer'; +import { + IsEmail, + IsNotEmpty, + Length, + Matches, + Max, + Min, + ValidateNested, +} from 'class-validator'; +import { Field, InternalFieldName } from 'react-hook-form'; + +class Like { + @IsNotEmpty() + id: number; + + @Length(4) + name: string; +} + +export class Schema { + @Matches(/^\w+$/) + @Length(3, 30) + username: string; + + @Matches(/^[a-zA-Z0-9]{3,30}/) + password: string; + + @Min(1900) + @Max(2013) + birthYear: number; + + @IsEmail() + email: string; + + accessToken: string; + + tags: string[]; + + enabled: boolean; + + @ValidateNested({ each: true }) + @Type(() => Like) + like: Like[]; +} + +export const validData: Schema = { + username: 'Doe', + password: 'Password123', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + accessToken: 'accessToken', + like: [ + { + id: 1, + name: 'name', + }, + ], +}; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: [{ id: 'z' }], +} as any as Schema; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/class-validator/src/__tests__/__snapshots__/class-validator.ts.snap b/node_modules/@hookform/resolvers/class-validator/src/__tests__/__snapshots__/class-validator.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..0a61fa9664ee0944924c78a2ffeda0445ead5129 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/src/__tests__/__snapshots__/class-validator.ts.snap @@ -0,0 +1,242 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`classValidatorResolver > should return a single error from classValidatorResolver when validation fails 1`] = ` +{ + "errors": { + "birthYear": { + "message": "birthYear must not be greater than 2013", + "ref": undefined, + "type": "max", + }, + "email": { + "message": "email must be an email", + "ref": { + "name": "email", + }, + "type": "isEmail", + }, + "like": [ + { + "name": { + "message": "name must be longer than or equal to 4 characters", + "ref": undefined, + "type": "isLength", + }, + }, + ], + "password": { + "message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression", + "ref": { + "name": "password", + }, + "type": "matches", + }, + "username": { + "message": "username must be longer than or equal to 3 characters", + "ref": { + "name": "username", + }, + "type": "isLength", + }, + }, + "values": {}, +} +`; + +exports[`classValidatorResolver > should return a single error from classValidatorResolver with \`mode: sync\` when validation fails 1`] = ` +{ + "errors": { + "birthYear": { + "message": "birthYear must not be greater than 2013", + "ref": undefined, + "type": "max", + }, + "email": { + "message": "email must be an email", + "ref": { + "name": "email", + }, + "type": "isEmail", + }, + "like": [ + { + "name": { + "message": "name must be longer than or equal to 4 characters", + "ref": undefined, + "type": "isLength", + }, + }, + ], + "password": { + "message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression", + "ref": { + "name": "password", + }, + "type": "matches", + }, + "username": { + "message": "username must be longer than or equal to 3 characters", + "ref": { + "name": "username", + }, + "type": "isLength", + }, + }, + "values": {}, +} +`; + +exports[`classValidatorResolver > should return all the errors from classValidatorResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = ` +{ + "errors": { + "birthYear": { + "message": "birthYear must not be greater than 2013", + "ref": undefined, + "type": "max", + "types": { + "max": "birthYear must not be greater than 2013", + "min": "birthYear must not be less than 1900", + }, + }, + "email": { + "message": "email must be an email", + "ref": { + "name": "email", + }, + "type": "isEmail", + "types": { + "isEmail": "email must be an email", + }, + }, + "like": [ + { + "name": { + "message": "name must be longer than or equal to 4 characters", + "ref": undefined, + "type": "isLength", + "types": { + "isLength": "name must be longer than or equal to 4 characters", + }, + }, + }, + ], + "password": { + "message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression", + "ref": { + "name": "password", + }, + "type": "matches", + "types": { + "matches": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression", + }, + }, + "username": { + "message": "username must be longer than or equal to 3 characters", + "ref": { + "name": "username", + }, + "type": "isLength", + "types": { + "isLength": "username must be longer than or equal to 3 characters", + "matches": "username must match /^\\w+$/ regular expression", + }, + }, + }, + "values": {}, +} +`; + +exports[`classValidatorResolver > should return all the errors from classValidatorResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = ` +{ + "errors": { + "birthYear": { + "message": "birthYear must not be greater than 2013", + "ref": undefined, + "type": "max", + "types": { + "max": "birthYear must not be greater than 2013", + "min": "birthYear must not be less than 1900", + }, + }, + "email": { + "message": "email must be an email", + "ref": { + "name": "email", + }, + "type": "isEmail", + "types": { + "isEmail": "email must be an email", + }, + }, + "like": [ + { + "name": { + "message": "name must be longer than or equal to 4 characters", + "ref": undefined, + "type": "isLength", + "types": { + "isLength": "name must be longer than or equal to 4 characters", + }, + }, + }, + ], + "password": { + "message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression", + "ref": { + "name": "password", + }, + "type": "matches", + "types": { + "matches": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression", + }, + }, + "username": { + "message": "username must be longer than or equal to 3 characters", + "ref": { + "name": "username", + }, + "type": "isLength", + "types": { + "isLength": "username must be longer than or equal to 3 characters", + "matches": "username must match /^\\w+$/ regular expression", + }, + }, + }, + "values": {}, +} +`; + +exports[`validate data with transformer option 1`] = ` +{ + "errors": { + "random": { + "message": "All fields must be defined.", + "ref": undefined, + "type": "isDefined", + "types": { + "isDefined": "All fields must be defined.", + "isNumber": "Must be a number", + "max": "Cannot be greater than 255", + "min": "Cannot be lower than 0", + }, + }, + }, + "values": {}, +} +`; + +exports[`validate data with validator option 1`] = ` +{ + "errors": { + "random": { + "message": "All fields must be defined.", + "ref": undefined, + "type": "isDefined", + "types": { + "isDefined": "All fields must be defined.", + }, + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/class-validator/src/__tests__/class-validator.ts b/node_modules/@hookform/resolvers/class-validator/src/__tests__/class-validator.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e253deb49a6b232731f7bec4be4eccc8005b153 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/src/__tests__/class-validator.ts @@ -0,0 +1,199 @@ +import { Expose, Type } from 'class-transformer'; +import * as classValidator from 'class-validator'; +import { IsDefined, IsNumber, Max, Min } from 'class-validator'; +/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */ +import { classValidatorResolver } from '..'; +import { Schema, fields, invalidData, validData } from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('classValidatorResolver', () => { + it('should return values from classValidatorResolver when validation pass', async () => { + const schemaSpy = vi.spyOn(classValidator, 'validate'); + const schemaSyncSpy = vi.spyOn(classValidator, 'validateSync'); + + const result = await classValidatorResolver(Schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(schemaSpy).toHaveBeenCalledTimes(1); + expect(schemaSyncSpy).not.toHaveBeenCalled(); + expect(result).toEqual({ errors: {}, values: validData }); + expect(result.values).toBeInstanceOf(Schema); + }); + + it('should return values as a raw object from classValidatorResolver when `rawValues` set to true', async () => { + const result = await classValidatorResolver(Schema, undefined, { + raw: true, + })(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toEqual({ errors: {}, values: validData }); + expect(result.values).not.toBeInstanceOf(Schema); + }); + + it('should return values from classValidatorResolver with `mode: sync` when validation pass', async () => { + const validateSyncSpy = vi.spyOn(classValidator, 'validateSync'); + const validateSpy = vi.spyOn(classValidator, 'validate'); + + const result = await classValidatorResolver(Schema, undefined, { + mode: 'sync', + })(validData, undefined, { fields, shouldUseNativeValidation }); + + expect(validateSyncSpy).toHaveBeenCalledTimes(1); + expect(validateSpy).not.toHaveBeenCalled(); + expect(result).toEqual({ errors: {}, values: validData }); + expect(result.values).toBeInstanceOf(Schema); + }); + + it('should return a single error from classValidatorResolver when validation fails', async () => { + const result = await classValidatorResolver(Schema)( + invalidData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return a single error from classValidatorResolver with `mode: sync` when validation fails', async () => { + const validateSyncSpy = vi.spyOn(classValidator, 'validateSync'); + const validateSpy = vi.spyOn(classValidator, 'validate'); + + const result = await classValidatorResolver(Schema, undefined, { + mode: 'sync', + })(invalidData, undefined, { fields, shouldUseNativeValidation }); + + expect(validateSyncSpy).toHaveBeenCalledTimes(1); + expect(validateSpy).not.toHaveBeenCalled(); + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from classValidatorResolver when validation fails with `validateAllFieldCriteria` set to true', async () => { + const result = await classValidatorResolver(Schema)( + invalidData, + undefined, + { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from classValidatorResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => { + const result = await classValidatorResolver(Schema, undefined, { + mode: 'sync', + })(invalidData, undefined, { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); +}); + +it('validate data with transformer option', async () => { + class SchemaTest { + @Expose({ groups: ['find', 'create', 'update'] }) + @Type(() => Number) + @IsDefined({ + message: `All fields must be defined.`, + groups: ['publish'], + }) + @IsNumber({}, { message: `Must be a number`, always: true }) + @Min(0, { message: `Cannot be lower than 0`, always: true }) + @Max(255, { message: `Cannot be greater than 255`, always: true }) + random: number; + } + + const result = await classValidatorResolver( + SchemaTest, + { transformer: { groups: ['update'] } }, + { + mode: 'sync', + }, + )( + // @ts-expect-error - Just for testing purposes + invalidData, + undefined, + { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); +}); + +it('validate data with validator option', async () => { + class SchemaTest { + @Expose({ groups: ['find', 'create', 'update'] }) + @Type(() => Number) + @IsDefined({ + message: `All fields must be defined.`, + groups: ['publish'], + }) + @IsNumber({}, { message: `Must be a number`, always: true }) + @Min(0, { message: `Cannot be lower than 0`, always: true }) + @Max(255, { message: `Cannot be greater than 255`, always: true }) + random: number; + } + + const result = await classValidatorResolver( + SchemaTest, + { validator: { stopAtFirstError: true } }, + { + mode: 'sync', + }, + )( + // @ts-expect-error - Just for testing purposes + invalidData, + undefined, + { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); +}); + +it('should return from classValidatorResolver with `excludeExtraneousValues` set to true', async () => { + class SchemaTest { + @Expose() + @IsNumber({}, { message: `Must be a number`, always: true }) + random: number; + } + + const result = await classValidatorResolver(SchemaTest, { + transformer: { + excludeExtraneousValues: true, + }, + })( + { + random: 10, + // @ts-expect-error - Just for testing purposes + extraneousField: true, + }, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(result).toEqual({ errors: {}, values: { random: 10 } }); + expect(result.values).toBeInstanceOf(SchemaTest); +}); diff --git a/node_modules/@hookform/resolvers/class-validator/src/class-validator.ts b/node_modules/@hookform/resolvers/class-validator/src/class-validator.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4dc4804381519564d0b7e0dee5332c2b8ac6df6 --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/src/class-validator.ts @@ -0,0 +1,101 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import { + ClassConstructor, + ClassTransformOptions, + plainToClass, +} from 'class-transformer'; +import { + ValidationError, + ValidatorOptions, + validate, + validateSync, +} from 'class-validator'; +import { FieldErrors, Resolver } from 'react-hook-form'; + +function parseErrorSchema( + errors: ValidationError[], + validateAllFieldCriteria: boolean, + parsedErrors: FieldErrors = {}, + path = '', +) { + return errors.reduce((acc, error) => { + const _path = path ? `${path}.${error.property}` : error.property; + + if (error.constraints) { + const key = Object.keys(error.constraints)[0]; + acc[_path] = { + type: key, + message: error.constraints[key], + }; + + const _e = acc[_path]; + if (validateAllFieldCriteria && _e) { + Object.assign(_e, { types: error.constraints }); + } + } + + if (error.children && error.children.length) { + parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path); + } + + return acc; + }, parsedErrors); +} + +/** + * Creates a resolver for react-hook-form using class-validator schema validation + * @param {ClassConstructor} schema - The class-validator schema to validate against + * @param {Object} schemaOptions - Additional schema validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='async'] - Validation mode + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * class Schema { + * @Matches(/^\w+$/) + * @Length(3, 30) + * username: string; + * age: number + * } + * + * useForm({ + * resolver: classValidatorResolver(Schema) + * }); + */ +export function classValidatorResolver>( + schema: ClassConstructor, + schemaOptions: { + validator?: ValidatorOptions; + transformer?: ClassTransformOptions; + } = {}, + resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {}, +): Resolver { + return async (values, _, options) => { + const { transformer, validator } = schemaOptions; + const data = plainToClass(schema, values, transformer); + + const rawErrors = await (resolverOptions.mode === 'sync' + ? validateSync + : validate)(data, validator); + + if (rawErrors.length) { + return { + values: {}, + errors: toNestErrors( + parseErrorSchema( + rawErrors, + !options.shouldUseNativeValidation && + options.criteriaMode === 'all', + ), + options, + ), + }; + } + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return { + values: resolverOptions.raw ? Object.assign({}, values) : data, + errors: {}, + }; + }; +} diff --git a/node_modules/@hookform/resolvers/class-validator/src/index.ts b/node_modules/@hookform/resolvers/class-validator/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1cc75cf6c630dbba08f437b6dbe820182605d8e --- /dev/null +++ b/node_modules/@hookform/resolvers/class-validator/src/index.ts @@ -0,0 +1 @@ +export * from './class-validator'; diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.d.ts b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bab87dbb82476ddea8dd5a0726f24009c678d46 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.d.ts @@ -0,0 +1,17 @@ +import FunctionType from 'computed-types/lib/schema/FunctionType'; +import type { FieldValues, Resolver } from 'react-hook-form'; +/** + * Creates a resolver for react-hook-form using computed-types schema validation + * @param {Schema} schema - The computed-types schema to validate against + * @returns {Resolver>} A resolver function compatible with react-hook-form + * @example + * const schema = Schema({ + * name: string, + * age: number + * }); + * + * useForm({ + * resolver: computedTypesResolver(schema) + * }); + */ +export declare function computedTypesResolver(schema: FunctionType): Resolver; diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.js b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.js new file mode 100644 index 0000000000000000000000000000000000000000..be274669393663da4538963f07e87ec182c1f761 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.js @@ -0,0 +1,2 @@ +var r=require("@hookform/resolvers");exports.computedTypesResolver=function(e){return function(t,o,n){try{return Promise.resolve(function(o,s){try{var u=Promise.resolve(e(t)).then(function(e){return n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{errors:{},values:e}})}catch(r){return s(r)}return u&&u.then?u.then(void 0,s):u}(0,function(e){if(function(r){return null!=r.errors}(e))return{values:{},errors:r.toNestErrors((t=e,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),n)};var t;throw e}))}catch(r){return Promise.reject(r)}}}; +//# sourceMappingURL=computed-types.js.map diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.js.map b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4a617b137f07bd1959db67b729347952e3af039d --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"computed-types.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType): Resolver {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"mEAkCgB,SAIdA,GACA,OAAA,SAAcC,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAsBA,uBAAC,CAAE,EAAEN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GAAU,OACnB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAA,EACRS,OAAQI,EAAAA,cA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAA,IA4CoBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAA,OAAAnB,QAAAoB,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.mjs b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b2b821d320b4f56d9c188b95818c441eced1afd8 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(t){return function(n,o,u){try{return Promise.resolve(function(e,o){try{var s=Promise.resolve(t(n)).then(function(e){return u.shouldUseNativeValidation&&r({},u),{errors:{},values:e}})}catch(r){return o(r)}return s&&s.then?s.then(void 0,o):s}(0,function(r){if(function(r){return null!=r.errors}(r))return{values:{},errors:e((t=r,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),u)};var t;throw r}))}catch(r){return Promise.reject(r)}}}export{t as computedTypesResolver}; +//# sourceMappingURL=computed-types.module.js.map diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b90a84de27c44767cd9059f2408ebe94d52d769d --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function o(o){return async(s,t,a)=>{try{const e=await o(s);return a.shouldUseNativeValidation&&r({},a),{errors:{},values:e}}catch(r){if((r=>null!=r.errors)(r))return{values:{},errors:e((n=r,(n.errors||[]).reduce((r,e)=>(r[e.path.join(".")]={type:e.error.name,message:e.error.message},r),{})),a)};throw r}var n}}export{o as computedTypesResolver}; +//# sourceMappingURL=computed-types.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs.map b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..17713d2436135b105dc6684ee161129a5f5b4c36 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"computed-types.modern.mjs","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType): Resolver {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["computedTypesResolver","schema","async","values","_","options","data","shouldUseNativeValidation","validateFieldsNatively","errors","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message"],"mappings":"+EAkCM,SAAUA,EAIdC,GACA,OAAOC,MAAOC,EAAQC,EAAGC,KACvB,IACE,MAAMC,QAAaL,EAAOE,GAI1B,OAFAE,EAAQE,2BAA6BC,EAAuB,CAAE,EAAEH,GAEzD,CACLI,OAAQ,CAAA,EACRN,OAAQG,EAEZ,CAAE,MAAOI,GACP,GA7CqBA,IACT,MAAhBA,EAAMD,OA4CEE,CAAkBD,GACpB,MAAO,CACLP,OAAQ,CAAE,EACVM,OAAQG,GA7CQC,EA6CsBH,GA3CtCG,EAAmBJ,QAAU,IAAIK,OAAO,CAACC,EAAKL,KACpDK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,GAPyB,CAAA,IA4CoBV,IAIlD,MAAMK,CACR,CAlDJ,IAA0BG,CAkDtB,CAEJ"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js new file mode 100644 index 0000000000000000000000000000000000000000..b2b821d320b4f56d9c188b95818c441eced1afd8 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(t){return function(n,o,u){try{return Promise.resolve(function(e,o){try{var s=Promise.resolve(t(n)).then(function(e){return u.shouldUseNativeValidation&&r({},u),{errors:{},values:e}})}catch(r){return o(r)}return s&&s.then?s.then(void 0,o):s}(0,function(r){if(function(r){return null!=r.errors}(r))return{values:{},errors:e((t=r,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),u)};var t;throw r}))}catch(r){return Promise.reject(r)}}}export{t as computedTypesResolver}; +//# sourceMappingURL=computed-types.module.js.map diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js.map b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..26aaf609f2ebdd434502f86f140b1e821f524e93 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"computed-types.module.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType): Resolver {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["computedTypesResolver","schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"+EAkCgB,SAAAA,EAIdC,GACA,OAAA,SAAcC,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAuB,CAAE,EAAEN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GAAU,OACnB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAA,EACRS,OAAQI,GA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAA,IA4CoBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAA,OAAAnB,QAAAoB,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..deb91db2274f8f231b1d128412be173aa15939d7 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],r):r((e||self).hookformResolversComputedTypes={},e.hookformResolvers)}(this,function(e,r){e.computedTypesResolver=function(e){return function(o,t,n){try{return Promise.resolve(function(t,s){try{var i=Promise.resolve(e(o)).then(function(e){return n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{errors:{},values:e}})}catch(e){return s(e)}return i&&i.then?i.then(void 0,s):i}(0,function(e){if(function(e){return null!=e.errors}(e))return{values:{},errors:r.toNestErrors((o=e,(o.errors||[]).reduce(function(e,r){return e[r.path.join(".")]={type:r.error.name,message:r.error.message},e},{})),n)};var o;throw e}))}catch(e){return Promise.reject(e)}}}}); +//# sourceMappingURL=computed-types.umd.js.map diff --git a/node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js.map b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f57fe54bf35b8c5dbbd14a94187e90c3576598f3 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"computed-types.umd.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType): Resolver {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"2VAkCgB,SAIdA,GACA,OAAA,SAAcC,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAsBA,uBAAC,CAAE,EAAEN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GAAU,OACnB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAA,EACRS,OAAQI,EAAAA,cA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAA,IA4CoBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAA,OAAAnB,QAAAoB,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/computed-types/dist/index.d.ts b/node_modules/@hookform/resolvers/computed-types/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7bc7a057392cf5f3dc953054c699e5f396af35b --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/dist/index.d.ts @@ -0,0 +1 @@ +export * from './computed-types'; diff --git a/node_modules/@hookform/resolvers/computed-types/package.json b/node_modules/@hookform/resolvers/computed-types/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8290b7a9b10dc7a086298b0d437897ccc64bb752 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/package.json @@ -0,0 +1,17 @@ +{ + "name": "@hookform/resolvers/computed-types", + "amdName": "hookformResolversComputedTypes", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: computed-types", + "main": "dist/computed-types.js", + "module": "dist/computed-types.module.js", + "umd:main": "dist/computed-types.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0" + } +} diff --git a/node_modules/@hookform/resolvers/computed-types/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/computed-types/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..182adbb8d729e77cee26cd80824b2cd12dda8a06 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,79 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import Schema, { Type, string } from 'computed-types'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { computedTypesResolver } from '..'; + +const USERNAME_REQUIRED_MESSAGE = 'username field is required'; +const PASSWORD_REQUIRED_MESSAGE = 'password field is required'; + +const schema = Schema({ + username: string.min(2).error(USERNAME_REQUIRED_MESSAGE), + password: string.min(2).error(PASSWORD_REQUIRED_MESSAGE), +}); + +interface Props { + onSubmit: (data: Type) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: computedTypesResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with computed-types", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/computed-types/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/computed-types/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..15fcd931ad2e18037ad14b23fc28eb154d384338 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/src/__tests__/Form.tsx @@ -0,0 +1,57 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import Schema, { Type, string } from 'computed-types'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { computedTypesResolver } from '..'; + +const schema = Schema({ + username: string.min(2).error('username field is required'), + password: string.min(2).error('password field is required'), + address: Schema({ + zipCode: string.min(5).max(5).error('zipCode field is required'), + }), +}); + +function TestComponent({ + onSubmit, +}: { onSubmit: (data: Type) => void }) { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: computedTypesResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + + {errors.address?.zipCode && ( + {errors.address.zipCode.message} + )} + + +
+ ); +} + +test("form's validation with computed-types and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect(screen.getByText(/username field is required/i)).toBeInTheDocument(); + expect(screen.getByText(/password field is required/i)).toBeInTheDocument(); + expect(screen.getByText(/zipCode field is required/i)).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/computed-types/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/computed-types/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..adf9791cbd0f4a8cd27ad7a0bd3be9f30f32ff8f --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,86 @@ +import Schema, { Type, string, number, array, boolean } from 'computed-types'; +import { Field, InternalFieldName } from 'react-hook-form'; + +export const schema = Schema({ + username: string.regexp(/^\w+$/).min(3).max(30), + password: string + .regexp(new RegExp('.*[A-Z].*'), 'One uppercase character') + .regexp(new RegExp('.*[a-z].*'), 'One lowercase character') + .regexp(new RegExp('.*\\d.*'), 'One number') + .regexp( + new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'), + 'One special character', + ) + .min(8, 'Must be at least 8 characters in length'), + repeatPassword: string, + accessToken: Schema.either(string, number).optional(), + birthYear: number.min(1900).max(2013).optional(), + email: string + .regexp(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/) + .error('Incorrect email'), + tags: array.of(string), + enabled: boolean, + like: array + .of({ + id: number, + name: string.min(4).max(4), + }) + .optional(), + address: Schema({ + city: string.min(3, 'Is required'), + zipCode: string + .min(5, 'Must be 5 characters long') + .max(5, 'Must be 5 characters long'), + }), +}); + +export const validData: Type = { + username: 'Doe', + password: 'Password123_', + repeatPassword: 'Password123_', + accessToken: 'accessToken', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + like: [ + { + id: 1, + name: 'name', + }, + ], + address: { + city: 'Awesome city', + zipCode: '12345', + }, +}; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: [{ id: 'z' }], + address: { + city: '', + zipCode: '123', + }, +} as any as Type; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/computed-types/src/__tests__/__snapshots__/computed-types.ts.snap b/node_modules/@hookform/resolvers/computed-types/src/__tests__/__snapshots__/computed-types.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..d4ccb3a6c2a950bb4dd59e57ae192f0d2d85371c --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/src/__tests__/__snapshots__/computed-types.ts.snap @@ -0,0 +1,74 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`computedTypesResolver > should return a single error from computedTypesResolver when validation fails 1`] = ` +{ + "errors": { + "address": { + "city": { + "message": "Is required", + "ref": undefined, + "type": "ValidationError", + }, + "zipCode": { + "message": "Must be 5 characters long", + "ref": undefined, + "type": "ValidationError", + }, + }, + "birthYear": { + "message": "Expect value to be "number"", + "ref": undefined, + "type": "ValidationError", + }, + "email": { + "message": "Incorrect email", + "ref": { + "name": "email", + }, + "type": "ValidationError", + }, + "enabled": { + "message": "Expect value to be "boolean"", + "ref": undefined, + "type": "ValidationError", + }, + "like": { + "id": { + "message": "Expect value to be "number"", + "ref": undefined, + "type": "ValidationError", + }, + "name": { + "message": "Expect value to be "string"", + "ref": undefined, + "type": "ValidationError", + }, + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "ValidationError", + }, + "repeatPassword": { + "message": "Expect value to be "string"", + "ref": undefined, + "type": "ValidationError", + }, + "tags": { + "message": "Expecting value to be an array", + "ref": undefined, + "type": "ValidationError", + }, + "username": { + "message": "Expect value to be "string"", + "ref": { + "name": "username", + }, + "type": "ValidationError", + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/computed-types/src/__tests__/computed-types.ts b/node_modules/@hookform/resolvers/computed-types/src/__tests__/computed-types.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e5586925503fc9dffca5cad95f0ebe3a8a3b3d4 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/src/__tests__/computed-types.ts @@ -0,0 +1,105 @@ +import { renderHook } from '@testing-library/react'; +import Schema, { number } from 'computed-types'; +import { Resolver, SubmitHandler, useForm } from 'react-hook-form'; +import { computedTypesResolver } from '..'; +import { fields, invalidData, schema, validData } from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('computedTypesResolver', () => { + it('should return values from computedTypesResolver when validation pass', async () => { + const result = await computedTypesResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return a single error from computedTypesResolver when validation fails', async () => { + const result = await computedTypesResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should throw any error unrelated to computed-types', async () => { + const schemaWithCustomError = schema.transform(() => { + throw Error('custom error'); + }); + + const promise = computedTypesResolver(schemaWithCustomError)( + validData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + await expect(promise).rejects.toThrow('custom error'); + }); + + /** + * Type inference tests + */ + it('should correctly infer the output type from a computedTypes schema', () => { + const resolver = computedTypesResolver(Schema({ id: number })); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: number }, unknown, { id: number }> + >(); + }); + + it('should correctly infer the output type from a computedTypes schema using a transform', () => { + const resolver = computedTypesResolver( + Schema({ id: number.transform((val) => String(val)) }), + ); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: number }, unknown, { id: string }> + >(); + }); + + it('should correctly infer the output type from a computedTypes schema for the handleSubmit function in useForm', () => { + const schema = Schema({ id: number }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: computedTypesResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: number; + }> + >(); + }); + + it('should correctly infer the output type from a computedTypes schema with a transform for the handleSubmit function in useForm', () => { + const schema = Schema({ id: number.transform((val) => String(val)) }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: computedTypesResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: string; + }> + >(); + }); +}); diff --git a/node_modules/@hookform/resolvers/computed-types/src/computed-types.ts b/node_modules/@hookform/resolvers/computed-types/src/computed-types.ts new file mode 100644 index 0000000000000000000000000000000000000000..349f654a69ce9d0227b9f55c680628849857ff37 --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/src/computed-types.ts @@ -0,0 +1,61 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import { ValidationError } from 'computed-types'; +import FunctionType from 'computed-types/lib/schema/FunctionType'; +import type { FieldErrors, FieldValues, Resolver } from 'react-hook-form'; + +const isValidationError = (error: any): error is ValidationError => + error.errors != null; + +function parseErrorSchema(computedTypesError: ValidationError) { + const parsedErrors: FieldErrors = {}; + return (computedTypesError.errors || []).reduce((acc, error) => { + acc[error.path.join('.')] = { + type: error.error.name, + message: error.error.message, + }; + + return acc; + }, parsedErrors); +} + +/** + * Creates a resolver for react-hook-form using computed-types schema validation + * @param {Schema} schema - The computed-types schema to validate against + * @returns {Resolver>} A resolver function compatible with react-hook-form + * @example + * const schema = Schema({ + * name: string, + * age: number + * }); + * + * useForm({ + * resolver: computedTypesResolver(schema) + * }); + */ +export function computedTypesResolver< + Input extends FieldValues, + Context, + Output, +>(schema: FunctionType): Resolver { + return async (values, _, options) => { + try { + const data = await schema(values); + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return { + errors: {}, + values: data, + }; + } catch (error: any) { + if (isValidationError(error)) { + return { + values: {}, + errors: toNestErrors(parseErrorSchema(error), options), + }; + } + + throw error; + } + }; +} diff --git a/node_modules/@hookform/resolvers/computed-types/src/index.ts b/node_modules/@hookform/resolvers/computed-types/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7bc7a057392cf5f3dc953054c699e5f396af35b --- /dev/null +++ b/node_modules/@hookform/resolvers/computed-types/src/index.ts @@ -0,0 +1 @@ +export * from './computed-types'; diff --git a/node_modules/@hookform/resolvers/dist/index.d.ts b/node_modules/@hookform/resolvers/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd22ab17a6aebaed3d8c190a27d3738ca8128d0a --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/index.d.ts @@ -0,0 +1,2 @@ +export * from './toNestErrors'; +export * from './validateFieldsNatively'; diff --git a/node_modules/@hookform/resolvers/dist/resolvers.js b/node_modules/@hookform/resolvers/dist/resolvers.js new file mode 100644 index 0000000000000000000000000000000000000000..90ffea0cf6c59e66a6ef3eab06d12c8276a427b7 --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/resolvers.js @@ -0,0 +1,2 @@ +var e=require("react-hook-form"),r=function(r,t,i){if(r&&"reportValidity"in r){var a=e.get(i,t);r.setCustomValidity(a&&a.message||""),r.reportValidity()}},t=function(e,t){var i=function(i){var a=t.fields[i];a&&a.ref&&"reportValidity"in a.ref?r(a.ref,i,e):a&&a.refs&&a.refs.forEach(function(t){return r(t,i,e)})};for(var a in t.fields)i(a)},i=function(e,r){var t=a(r).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(function(e){return a(e).match("^"+t+"\\.\\d+")})};function a(e){return e.replace(/[\[\]]/g,"")}exports.toNestErrors=function(r,a){a.shouldUseNativeValidation&&t(r,a);var n={};for(var s in r){var o=e.get(a.fields,s),f=Object.assign(r[s]||{},{ref:o&&o.refs?o.refs[0]:o&&o.ref});if(i(a.names||Object.keys(r),s)){var c=Object.assign({},e.get(n,s));e.set(c,"root",f),e.set(n,s,c)}else e.set(n,s,f)}return n},exports.validateFieldsNatively=t; +//# sourceMappingURL=resolvers.js.map diff --git a/node_modules/@hookform/resolvers/dist/resolvers.js.map b/node_modules/@hookform/resolvers/dist/resolvers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..87b73a00fbb5f48fe9f86f328c40c496a91bd7fd --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/resolvers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolvers.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = (\n errors: FieldErrors,\n options: ResolverOptions,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = (\n errors: FieldErrors,\n options: ResolverOptions,\n): FieldErrors => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n // Radio/checkbox fields keep a placeholder `ref` (`{ name, type }`) and\n // store the actual DOM elements in `refs`, matching react-hook-form's\n // own `validateField` behavior for built-in validation.\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.refs ? field.refs[0] : field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeForRegex(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n// Removes brackets to match react-hook-form's `set` method behavior.\nfunction escapeBrackets(input: string): string {\n return input.replace(/[\\[\\]]/g, '');\n}\n\n// Removes brackets then escapes regex metacharacters so a field name can be\n// safely embedded in a regex pattern without causing a SyntaxError.\nfunction escapeForRegex(input: string): string {\n return escapeBrackets(input).replace(/[.*+?^${}()|\\\\]/g, '\\\\$&');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","isNameInFieldArray","names","name","path","escapeBrackets","replace","some","n","match","input","shouldUseNativeValidation","fieldErrors","Object","assign","keys","fieldArrayErrors","set"],"mappings":"iCASMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,EAAAA,IAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,ECGMa,EAAqB,SACzBC,EACAC,GAEA,IAAMC,EAYCC,EAZqBF,GAYCG,QAAQ,mBAAoB,QAXzD,OAAOJ,EAAMK,KAAK,SAACC,GAAC,OAAKH,EAAeG,GAAGC,MAAUL,IAAAA,EAAa,UAAC,EACrE,EAGA,SAASC,EAAeK,GACtB,OAAOA,EAAMJ,QAAQ,UAAW,GAClC,sBAxC4B,SAC1BjB,EACAM,GAEAA,EAAQgB,2BAA6BjB,EAAuBL,EAAQM,GAEpE,IAAMiB,EAAc,CAA+B,EACnD,IAAK,IAAMR,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAAA,IAAII,EAAQG,OAAQM,GAI5Bd,EAAQuB,OAAOC,OAAOzB,EAAOe,IAAS,CAAA,EAAI,CAC9CjB,IAAKU,GAASA,EAAME,KAAOF,EAAME,KAAK,GAAKF,GAASA,EAAMV,MAG5D,GAAIc,EAAmBN,EAAQO,OAASW,OAAOE,KAAK1B,GAASe,GAAO,CAClE,IAAMY,EAAmBH,OAAOC,OAAO,CAAE,EAAEvB,EAAGA,IAACqB,EAAaR,IAE5Da,MAAID,EAAkB,OAAQ1B,GAC9B2B,EAAGA,IAACL,EAAaR,EAAMY,EACzB,MACEC,EAAAA,IAAIL,EAAaR,EAAMd,EAE3B,CAEA,OAAOsB,CACT"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/dist/resolvers.mjs b/node_modules/@hookform/resolvers/dist/resolvers.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9d65fe306f9aa7b6945a5ee83923e1a27cd83a2c --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/resolvers.mjs @@ -0,0 +1,2 @@ +import{get as e,set as r}from"react-hook-form";const t=(r,t,s)=>{if(r&&"reportValidity"in r){const o=e(s,t);r.setCustomValidity(o&&o.message||""),r.reportValidity()}},s=(e,r)=>{for(const s in r.fields){const o=r.fields[s];o&&o.ref&&"reportValidity"in o.ref?t(o.ref,s,e):o&&o.refs&&o.refs.forEach(r=>t(r,s,e))}},o=(t,o)=>{o.shouldUseNativeValidation&&s(t,o);const n={};for(const s in t){const f=e(o.fields,s),c=Object.assign(t[s]||{},{ref:f&&f.refs?f.refs[0]:f&&f.ref});if(i(o.names||Object.keys(t),s)){const t=Object.assign({},e(n,s));r(t,"root",c),r(n,s,t)}else r(n,s,c)}return n},i=(e,r)=>{const t=n(r).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(e=>n(e).match(`^${t}\\.\\d+`))};function n(e){return e.replace(/[\[\]]/g,"")}export{o as toNestErrors,s as validateFieldsNatively}; +//# sourceMappingURL=resolvers.mjs.map diff --git a/node_modules/@hookform/resolvers/dist/resolvers.mjs.map b/node_modules/@hookform/resolvers/dist/resolvers.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e7876316ab095e0a3d051e940b8fa6d4fcabadf6 --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/resolvers.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolvers.mjs","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = (\n errors: FieldErrors,\n options: ResolverOptions,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = (\n errors: FieldErrors,\n options: ResolverOptions,\n): FieldErrors => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n // Radio/checkbox fields keep a placeholder `ref` (`{ name, type }`) and\n // store the actual DOM elements in `refs`, matching react-hook-form's\n // own `validateField` behavior for built-in validation.\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.refs ? field.refs[0] : field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeForRegex(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n// Removes brackets to match react-hook-form's `set` method behavior.\nfunction escapeBrackets(input: string): string {\n return input.replace(/[\\[\\]]/g, '');\n}\n\n// Removes brackets then escapes regex metacharacters so a field name can be\n// safely embedded in a regex pattern without causing a SyntaxError.\nfunction escapeForRegex(input: string): string {\n return escapeBrackets(input).replace(/[.*+?^${}()|\\\\]/g, '\\\\$&');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","fields","field","refs","forEach","toNestErrors","shouldUseNativeValidation","fieldErrors","path","Object","assign","isNameInFieldArray","names","keys","fieldArrayErrors","set","name","escapeBrackets","replace","some","n","match","input"],"mappings":"+CASA,MAAMA,EAAoBA,CACxBC,EACAC,EACAC,KAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,MAAMG,EAAQC,EAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,GAIWC,EAAyBA,CACpCL,EACAM,KAEA,IAAK,MAAMP,KAAaO,EAAQC,OAAQ,CACtC,MAAMC,EAAQF,EAAQC,OAAOR,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAMC,MACxBD,EAAMC,KAAKC,QAASZ,GAClBD,EAAkBC,EAAKC,EAAWC,GAGxC,GCzBWW,EAAeA,CAC1BX,EACAM,KAEAA,EAAQM,2BAA6BP,EAAuBL,EAAQM,GAEpE,MAAMO,EAAc,CAAA,EACpB,IAAK,MAAMC,KAAQd,EAAQ,CACzB,MAAMQ,EAAQN,EAAII,EAAQC,OAAQO,GAI5Bb,EAAQc,OAAOC,OAAOhB,EAAOc,IAAS,CAAA,EAAI,CAC9ChB,IAAKU,GAASA,EAAMC,KAAOD,EAAMC,KAAK,GAAKD,GAASA,EAAMV,MAG5D,GAAImB,EAAmBX,EAAQY,OAASH,OAAOI,KAAKnB,GAASc,GAAO,CAClE,MAAMM,EAAmBL,OAAOC,OAAO,CAAA,EAAId,EAAIW,EAAaC,IAE5DO,EAAID,EAAkB,OAAQnB,GAC9BoB,EAAIR,EAAaC,EAAMM,EACzB,MACEC,EAAIR,EAAaC,EAAMb,EAE3B,CAEA,OAAOY,CAAW,EAGdI,EAAqBA,CACzBC,EACAI,KAEA,MAAMR,EAYCS,EAZqBD,GAYCE,QAAQ,mBAAoB,QAXzD,OAAON,EAAMO,KAAMC,GAAMH,EAAeG,GAAGC,MAAM,IAAIb,YAAe,EAItE,SAASS,EAAeK,GACtB,OAAOA,EAAMJ,QAAQ,UAAW,GAClC"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/dist/resolvers.module.js b/node_modules/@hookform/resolvers/dist/resolvers.module.js new file mode 100644 index 0000000000000000000000000000000000000000..7ccffc215098fc32a1708579e9e4e9dbc343b13d --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/resolvers.module.js @@ -0,0 +1,2 @@ +import{get as r,set as e}from"react-hook-form";var t=function(e,t,i){if(e&&"reportValidity"in e){var n=r(i,t);e.setCustomValidity(n&&n.message||""),e.reportValidity()}},i=function(r,e){var i=function(i){var n=e.fields[i];n&&n.ref&&"reportValidity"in n.ref?t(n.ref,i,r):n&&n.refs&&n.refs.forEach(function(e){return t(e,i,r)})};for(var n in e.fields)i(n)},n=function(t,n){n.shouldUseNativeValidation&&i(t,n);var a={};for(var o in t){var s=r(n.fields,o),c=Object.assign(t[o]||{},{ref:s&&s.refs?s.refs[0]:s&&s.ref});if(f(n.names||Object.keys(t),o)){var u=Object.assign({},r(a,o));e(u,"root",c),e(a,o,u)}else e(a,o,c)}return a},f=function(r,e){var t=a(e).replace(/[.*+?^${}()|\\]/g,"\\$&");return r.some(function(r){return a(r).match("^"+t+"\\.\\d+")})};function a(r){return r.replace(/[\[\]]/g,"")}export{n as toNestErrors,i as validateFieldsNatively}; +//# sourceMappingURL=resolvers.module.js.map diff --git a/node_modules/@hookform/resolvers/dist/resolvers.module.js.map b/node_modules/@hookform/resolvers/dist/resolvers.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e785d3a5a3f5de93e6d1192c0b0de2bec45b7308 --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/resolvers.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolvers.module.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = (\n errors: FieldErrors,\n options: ResolverOptions,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = (\n errors: FieldErrors,\n options: ResolverOptions,\n): FieldErrors => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n // Radio/checkbox fields keep a placeholder `ref` (`{ name, type }`) and\n // store the actual DOM elements in `refs`, matching react-hook-form's\n // own `validateField` behavior for built-in validation.\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.refs ? field.refs[0] : field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeForRegex(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n// Removes brackets to match react-hook-form's `set` method behavior.\nfunction escapeBrackets(input: string): string {\n return input.replace(/[\\[\\]]/g, '');\n}\n\n// Removes brackets then escapes regex metacharacters so a field name can be\n// safely embedded in a regex pattern without causing a SyntaxError.\nfunction escapeForRegex(input: string): string {\n return escapeBrackets(input).replace(/[.*+?^${}()|\\\\]/g, '\\\\$&');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","toNestErrors","shouldUseNativeValidation","fieldErrors","path","Object","assign","isNameInFieldArray","names","keys","fieldArrayErrors","set","name","escapeBrackets","replace","some","n","match","input"],"mappings":"+CASA,IAAMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,EAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,EC1Baa,EAAe,SAC1BZ,EACAM,GAEAA,EAAQO,2BAA6BR,EAAuBL,EAAQM,GAEpE,IAAMQ,EAAc,CAA+B,EACnD,IAAK,IAAMC,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAII,EAAQG,OAAQM,GAI5Bd,EAAQe,OAAOC,OAAOjB,EAAOe,IAAS,CAAA,EAAI,CAC9CjB,IAAKU,GAASA,EAAME,KAAOF,EAAME,KAAK,GAAKF,GAASA,EAAMV,MAG5D,GAAIoB,EAAmBZ,EAAQa,OAASH,OAAOI,KAAKpB,GAASe,GAAO,CAClE,IAAMM,EAAmBL,OAAOC,OAAO,CAAE,EAAEf,EAAIY,EAAaC,IAE5DO,EAAID,EAAkB,OAAQpB,GAC9BqB,EAAIR,EAAaC,EAAMM,EACzB,MACEC,EAAIR,EAAaC,EAAMd,EAE3B,CAEA,OAAOa,CACT,EAEMI,EAAqB,SACzBC,EACAI,GAEA,IAAMR,EAYCS,EAZqBD,GAYCE,QAAQ,mBAAoB,QAXzD,OAAON,EAAMO,KAAK,SAACC,GAAC,OAAKH,EAAeG,GAAGC,MAAUb,IAAAA,EAAa,UAAC,EACrE,EAGA,SAASS,EAAeK,GACtB,OAAOA,EAAMJ,QAAQ,UAAW,GAClC"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/dist/resolvers.umd.js b/node_modules/@hookform/resolvers/dist/resolvers.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..5a14758402615d92a7bf621952ded1c5cebc632e --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/resolvers.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","react-hook-form"],r):r((e||self).hookformResolvers={},e.ReactHookForm)}(this,function(e,r){var t=function(e,t,o){if(e&&"reportValidity"in e){var i=r.get(o,t);e.setCustomValidity(i&&i.message||""),e.reportValidity()}},o=function(e,r){var o=function(o){var i=r.fields[o];i&&i.ref&&"reportValidity"in i.ref?t(i.ref,o,e):i&&i.refs&&i.refs.forEach(function(r){return t(r,o,e)})};for(var i in r.fields)o(i)},i=function(e,r){var t=n(r).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(function(e){return n(e).match("^"+t+"\\.\\d+")})};function n(e){return e.replace(/[\[\]]/g,"")}e.toNestErrors=function(e,t){t.shouldUseNativeValidation&&o(e,t);var n={};for(var f in e){var s=r.get(t.fields,f),a=Object.assign(e[f]||{},{ref:s&&s.refs?s.refs[0]:s&&s.ref});if(i(t.names||Object.keys(e),f)){var c=Object.assign({},r.get(n,f));r.set(c,"root",a),r.set(n,f,c)}else r.set(n,f,a)}return n},e.validateFieldsNatively=o}); +//# sourceMappingURL=resolvers.umd.js.map diff --git a/node_modules/@hookform/resolvers/dist/resolvers.umd.js.map b/node_modules/@hookform/resolvers/dist/resolvers.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..104ae0abf4a91c96255c7929fbee632e55b8f7d0 --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/resolvers.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolvers.umd.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = (\n errors: FieldErrors,\n options: ResolverOptions,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = (\n errors: FieldErrors,\n options: ResolverOptions,\n): FieldErrors => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n // Radio/checkbox fields keep a placeholder `ref` (`{ name, type }`) and\n // store the actual DOM elements in `refs`, matching react-hook-form's\n // own `validateField` behavior for built-in validation.\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.refs ? field.refs[0] : field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeForRegex(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n// Removes brackets to match react-hook-form's `set` method behavior.\nfunction escapeBrackets(input: string): string {\n return input.replace(/[\\[\\]]/g, '');\n}\n\n// Removes brackets then escapes regex metacharacters so a field name can be\n// safely embedded in a regex pattern without causing a SyntaxError.\nfunction escapeForRegex(input: string): string {\n return escapeBrackets(input).replace(/[.*+?^${}()|\\\\]/g, '\\\\$&');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","isNameInFieldArray","names","name","path","escapeBrackets","replace","some","n","match","input","shouldUseNativeValidation","fieldErrors","Object","assign","keys","fieldArrayErrors","set"],"mappings":"0SASA,IAAMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,EAAAA,IAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,ECGMa,EAAqB,SACzBC,EACAC,GAEA,IAAMC,EAYCC,EAZqBF,GAYCG,QAAQ,mBAAoB,QAXzD,OAAOJ,EAAMK,KAAK,SAACC,GAAC,OAAKH,EAAeG,GAAGC,MAAUL,IAAAA,EAAa,UAAC,EACrE,EAGA,SAASC,EAAeK,GACtB,OAAOA,EAAMJ,QAAQ,UAAW,GAClC,gBAxC4B,SAC1BjB,EACAM,GAEAA,EAAQgB,2BAA6BjB,EAAuBL,EAAQM,GAEpE,IAAMiB,EAAc,CAA+B,EACnD,IAAK,IAAMR,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAAA,IAAII,EAAQG,OAAQM,GAI5Bd,EAAQuB,OAAOC,OAAOzB,EAAOe,IAAS,CAAA,EAAI,CAC9CjB,IAAKU,GAASA,EAAME,KAAOF,EAAME,KAAK,GAAKF,GAASA,EAAMV,MAG5D,GAAIc,EAAmBN,EAAQO,OAASW,OAAOE,KAAK1B,GAASe,GAAO,CAClE,IAAMY,EAAmBH,OAAOC,OAAO,CAAE,EAAEvB,EAAGA,IAACqB,EAAaR,IAE5Da,MAAID,EAAkB,OAAQ1B,GAC9B2B,EAAGA,IAACL,EAAaR,EAAMY,EACzB,MACEC,EAAAA,IAAIL,EAAaR,EAAMd,EAE3B,CAEA,OAAOsB,CACT"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/dist/toNestErrors.d.ts b/node_modules/@hookform/resolvers/dist/toNestErrors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2b22c744d12bf2a1a5509026093799329372337 --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/toNestErrors.d.ts @@ -0,0 +1,2 @@ +import { FieldErrors, FieldValues, ResolverOptions } from 'react-hook-form'; +export declare const toNestErrors: (errors: FieldErrors, options: ResolverOptions) => FieldErrors; diff --git a/node_modules/@hookform/resolvers/dist/validateFieldsNatively.d.ts b/node_modules/@hookform/resolvers/dist/validateFieldsNatively.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..905e44c5aa96d22b9098921573925fc8568b7bfd --- /dev/null +++ b/node_modules/@hookform/resolvers/dist/validateFieldsNatively.d.ts @@ -0,0 +1,2 @@ +import { FieldErrors, FieldValues, ResolverOptions } from 'react-hook-form'; +export declare const validateFieldsNatively: (errors: FieldErrors, options: ResolverOptions) => void; diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.d.ts b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bbf12f456d7c70fff3590c7530d471dfe4ec1b2b --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.d.ts @@ -0,0 +1,11 @@ +import { Schema } from 'effect'; +import { ParseOptions } from 'effect/SchemaAST'; +import { FieldValues, Resolver } from 'react-hook-form'; +export declare function effectTsResolver(schema: Schema.Schema, schemaOptions?: ParseOptions, resolverOptions?: { + mode?: 'async' | 'sync'; + raw?: false; +}): Resolver; +export declare function effectTsResolver(schema: Schema.Schema, schemaOptions: ParseOptions | undefined, resolverOptions: { + mode?: 'async' | 'sync'; + raw: true; +}): Resolver; diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js new file mode 100644 index 0000000000000000000000000000000000000000..458b7c36a008d45af5f8315ed7f00f065a34a30b --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers"),r=require("effect"),t=require("effect/ParseResult"),n=require("react-hook-form");exports.effectTsResolver=function(o,a){return void 0===a&&(a={errors:"all",onExcessProperty:"ignore"}),function(s,c,f){return t.decodeUnknown(o,a)(s).pipe(r.Effect.catchAll(function(e){return r.Effect.flip(t.ArrayFormatter.formatIssue(e))}),r.Effect.mapError(function(r){var t=!f.shouldUseNativeValidation&&"all"===f.criteriaMode,o=r.reduce(function(e,r){var o=r.path.join(".");if(e[o]||(e[o]={message:r.message,type:r._tag}),t){var a=e[o].types,s=a&&a[String(r._tag)];e[o]=n.appendErrors(o,t,e,r._tag,s?[].concat(s,r.message):r.message)}return e},Object.create(null));return e.toNestErrors(o,f)}),r.Effect.tap(function(){return r.Effect.sync(function(){return f.shouldUseNativeValidation&&e.validateFieldsNatively({},f)})}),r.Effect.match({onFailure:function(e){return{errors:e,values:{}}},onSuccess:function(e){return{errors:{},values:e}}}),r.Effect.runPromise)}}; +//# sourceMappingURL=effect-ts.js.map diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js.map b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0482ee68ed9ee3b380c232680974e1d5276f821f --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"effect-ts.js","sources":["../src/effect-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { Effect, Schema } from 'effect';\nimport { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';\nimport { ParseOptions } from 'effect/SchemaAST';\nimport {\n type FieldError,\n FieldValues,\n Resolver,\n appendErrors,\n} from 'react-hook-form';\n\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions?: ParseOptions,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver;\n\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions: ParseOptions | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Effect.ts schema validation\n * @param {Schema.Schema} schema - The Effect.ts schema to validate against\n * @param {ParseOptions} [schemaOptions] - Optional Effect.ts validation options\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema.Struct({\n * name: Schema.String,\n * age: Schema.Number\n * });\n *\n * useForm({\n * resolver: effectTsResolver(schema)\n * });\n */\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions: ParseOptions = { errors: 'all', onExcessProperty: 'ignore' },\n): Resolver {\n return (values, _, options) => {\n return decodeUnknown(\n schema,\n schemaOptions,\n )(values).pipe(\n Effect.catchAll((parseIssue) =>\n Effect.flip(ArrayFormatter.formatIssue(parseIssue)),\n ),\n Effect.mapError((issues) => {\n const validateAllFieldCriteria =\n !options.shouldUseNativeValidation && options.criteriaMode === 'all';\n\n // A null-prototype accumulator avoids false-positive hits from\n // inherited members (e.g. `toString`, `constructor`) when a field\n // is named after one of them — a plain `{}` would make `!acc[key]`\n // truthy-skip those paths and silently drop their errors.\n const errors = issues.reduce(\n (acc, error) => {\n const key = error.path.join('.');\n\n if (!acc[key]) {\n acc[key] = { message: error.message, type: error._tag };\n }\n\n if (validateAllFieldCriteria) {\n const types = acc[key].types;\n const messages = types && types[String(error._tag)];\n\n acc[key] = appendErrors(\n key,\n validateAllFieldCriteria,\n acc,\n error._tag,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return acc;\n },\n Object.create(null) as Record,\n );\n\n return toNestErrors(errors, options);\n }),\n Effect.tap(() =>\n Effect.sync(\n () =>\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options),\n ),\n ),\n Effect.match({\n onFailure: (errors) => ({ errors, values: {} }),\n onSuccess: (result) => ({ errors: {}, values: result }),\n }),\n Effect.runPromise,\n );\n };\n}\n"],"names":["schema","schemaOptions","errors","onExcessProperty","values","_","options","decodeUnknown","pipe","Effect","catchAll","parseIssue","flip","ArrayFormatter","formatIssue","mapError","issues","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","reduce","acc","error","key","path","join","message","type","_tag","types","messages","String","appendErrors","concat","Object","create","toNestErrors","tap","sync","validateFieldsNatively","match","onFailure","onSuccess","result","runPromise"],"mappings":"wJA6CEA,EACAC,GAEA,YAF8B,IAA9BA,IAAAA,EAA8B,CAAEC,OAAQ,MAAOC,iBAAkB,oBAEzDC,EAAQC,EAAGC,GACjB,OAAOC,EAAaA,cAClBP,EACAC,EAFKM,CAGLH,GAAQI,KACRC,EAAMA,OAACC,SAAS,SAACC,GACf,OAAAF,EAAAA,OAAOG,KAAKC,EAAcA,eAACC,YAAYH,GAAY,GAErDF,EAAMA,OAACM,SAAS,SAACC,GACf,IAAMC,GACHX,EAAQY,2BAAsD,QAAzBZ,EAAQa,aAM1CjB,EAASc,EAAOI,OACpB,SAACC,EAAKC,GACJ,IAAMC,EAAMD,EAAME,KAAKC,KAAK,KAM5B,GAJKJ,EAAIE,KACPF,EAAIE,GAAO,CAAEG,QAASJ,EAAMI,QAASC,KAAML,EAAMM,OAG/CX,EAA0B,CAC5B,IAAMY,EAAQR,EAAIE,GAAKM,MACjBC,EAAWD,GAASA,EAAME,OAAOT,EAAMM,OAE7CP,EAAIE,GAAOS,eACTT,EACAN,EACAI,EACAC,EAAMM,KACNE,EACK,GAAgBG,OAAOH,EAAsBR,EAAMI,SACpDJ,EAAMI,QAEd,CAEA,OAAOL,CACT,EACAa,OAAOC,OAAO,OAGhB,OAAOC,eAAalC,EAAQI,EAC9B,GACAG,SAAO4B,IAAI,WACT,OAAA5B,EAAAA,OAAO6B,KACL,WACE,OAAAhC,EAAQY,2BACRqB,EAAsBA,uBAAC,GAAIjC,EAAQ,EACtC,GAEHG,EAAAA,OAAO+B,MAAM,CACXC,UAAW,SAACvC,GAAM,MAAM,CAAEA,OAAAA,EAAQE,OAAQ,GAAI,EAC9CsC,UAAW,SAACC,GAAM,MAAM,CAAEzC,OAAQ,CAAE,EAAEE,OAAQuC,EAAQ,IAExDlC,EAAMA,OAACmC,WAEX,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.mjs b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3fb518555c5f45cb2ecc6c155df15d3b70eb49f1 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{Effect as t}from"effect";import{decodeUnknown as o,ArrayFormatter as n}from"effect/ParseResult";import{appendErrors as a}from"react-hook-form";function i(i,s){return void 0===s&&(s={errors:"all",onExcessProperty:"ignore"}),function(u,c,f){return o(i,s)(u).pipe(t.catchAll(function(r){return t.flip(n.formatIssue(r))}),t.mapError(function(e){var t=!f.shouldUseNativeValidation&&"all"===f.criteriaMode,o=e.reduce(function(r,e){var o=e.path.join(".");if(r[o]||(r[o]={message:e.message,type:e._tag}),t){var n=r[o].types,i=n&&n[String(e._tag)];r[o]=a(o,t,r,e._tag,i?[].concat(i,e.message):e.message)}return r},Object.create(null));return r(o,f)}),t.tap(function(){return t.sync(function(){return f.shouldUseNativeValidation&&e({},f)})}),t.match({onFailure:function(r){return{errors:r,values:{}}},onSuccess:function(r){return{errors:{},values:r}}}),t.runPromise)}}export{i as effectTsResolver}; +//# sourceMappingURL=effect-ts.module.js.map diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c60ee9c22ffced47cd8948029535e1704a1257b6 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";import{Effect as o}from"effect";import{decodeUnknown as t,ArrayFormatter as s}from"effect/ParseResult";import{appendErrors as a}from"react-hook-form";function i(i,c={errors:"all",onExcessProperty:"ignore"}){return(n,l,m)=>t(i,c)(n).pipe(o.catchAll(e=>o.flip(s.formatIssue(e))),o.mapError(r=>{const o=!m.shouldUseNativeValidation&&"all"===m.criteriaMode,t=r.reduce((e,r)=>{const t=r.path.join(".");if(e[t]||(e[t]={message:r.message,type:r._tag}),o){const s=e[t].types,i=s&&s[String(r._tag)];e[t]=a(t,o,e,r._tag,i?[].concat(i,r.message):r.message)}return e},Object.create(null));return e(t,m)}),o.tap(()=>o.sync(()=>m.shouldUseNativeValidation&&r({},m))),o.match({onFailure:e=>({errors:e,values:{}}),onSuccess:e=>({errors:{},values:e})}),o.runPromise)}export{i as effectTsResolver}; +//# sourceMappingURL=effect-ts.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs.map b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6b3328deebd9e0cad0067ca3321be70c599455f6 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"effect-ts.modern.mjs","sources":["../src/effect-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { Effect, Schema } from 'effect';\nimport { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';\nimport { ParseOptions } from 'effect/SchemaAST';\nimport {\n type FieldError,\n FieldValues,\n Resolver,\n appendErrors,\n} from 'react-hook-form';\n\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions?: ParseOptions,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver;\n\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions: ParseOptions | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Effect.ts schema validation\n * @param {Schema.Schema} schema - The Effect.ts schema to validate against\n * @param {ParseOptions} [schemaOptions] - Optional Effect.ts validation options\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema.Struct({\n * name: Schema.String,\n * age: Schema.Number\n * });\n *\n * useForm({\n * resolver: effectTsResolver(schema)\n * });\n */\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions: ParseOptions = { errors: 'all', onExcessProperty: 'ignore' },\n): Resolver {\n return (values, _, options) => {\n return decodeUnknown(\n schema,\n schemaOptions,\n )(values).pipe(\n Effect.catchAll((parseIssue) =>\n Effect.flip(ArrayFormatter.formatIssue(parseIssue)),\n ),\n Effect.mapError((issues) => {\n const validateAllFieldCriteria =\n !options.shouldUseNativeValidation && options.criteriaMode === 'all';\n\n // A null-prototype accumulator avoids false-positive hits from\n // inherited members (e.g. `toString`, `constructor`) when a field\n // is named after one of them — a plain `{}` would make `!acc[key]`\n // truthy-skip those paths and silently drop their errors.\n const errors = issues.reduce(\n (acc, error) => {\n const key = error.path.join('.');\n\n if (!acc[key]) {\n acc[key] = { message: error.message, type: error._tag };\n }\n\n if (validateAllFieldCriteria) {\n const types = acc[key].types;\n const messages = types && types[String(error._tag)];\n\n acc[key] = appendErrors(\n key,\n validateAllFieldCriteria,\n acc,\n error._tag,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return acc;\n },\n Object.create(null) as Record,\n );\n\n return toNestErrors(errors, options);\n }),\n Effect.tap(() =>\n Effect.sync(\n () =>\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options),\n ),\n ),\n Effect.match({\n onFailure: (errors) => ({ errors, values: {} }),\n onSuccess: (result) => ({ errors: {}, values: result }),\n }),\n Effect.runPromise,\n );\n };\n}\n"],"names":["effectTsResolver","schema","schemaOptions","errors","onExcessProperty","values","_","options","decodeUnknown","pipe","Effect","catchAll","parseIssue","flip","ArrayFormatter","formatIssue","mapError","issues","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","reduce","acc","error","key","path","join","message","type","_tag","types","messages","String","appendErrors","concat","Object","create","toNestErrors","tap","sync","validateFieldsNatively","match","onFailure","onSuccess","result","runPromise"],"mappings":"qOA4CgB,SAAAA,EACdC,EACAC,EAA8B,CAAEC,OAAQ,MAAOC,iBAAkB,WAEjE,MAAO,CAACC,EAAQC,EAAGC,IACVC,EACLP,EACAC,EAFKM,CAGLH,GAAQI,KACRC,EAAOC,SAAUC,GACfF,EAAOG,KAAKC,EAAeC,YAAYH,KAEzCF,EAAOM,SAAUC,IACf,MAAMC,GACHX,EAAQY,2BAAsD,QAAzBZ,EAAQa,aAM1CjB,EAASc,EAAOI,OACpB,CAACC,EAAKC,KACJ,MAAMC,EAAMD,EAAME,KAAKC,KAAK,KAM5B,GAJKJ,EAAIE,KACPF,EAAIE,GAAO,CAAEG,QAASJ,EAAMI,QAASC,KAAML,EAAMM,OAG/CX,EAA0B,CAC5B,MAAMY,EAAQR,EAAIE,GAAKM,MACjBC,EAAWD,GAASA,EAAME,OAAOT,EAAMM,OAE7CP,EAAIE,GAAOS,EACTT,EACAN,EACAI,EACAC,EAAMM,KACNE,EACK,GAAgBG,OAAOH,EAAsBR,EAAMI,SACpDJ,EAAMI,QAEd,CAEA,OAAOL,CAAG,EAEZa,OAAOC,OAAO,OAGhB,OAAOC,EAAalC,EAAQI,EAAQ,GAEtCG,EAAO4B,IAAI,IACT5B,EAAO6B,KACL,IACEhC,EAAQY,2BACRqB,EAAuB,CAAA,EAAIjC,KAGjCG,EAAO+B,MAAM,CACXC,UAAYvC,IAAY,CAAEA,SAAQE,OAAQ,CAAA,IAC1CsC,UAAYC,KAAczC,OAAQ,CAAA,EAAIE,OAAQuC,MAEhDlC,EAAOmC,WAGb"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.module.js b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.module.js new file mode 100644 index 0000000000000000000000000000000000000000..3fb518555c5f45cb2ecc6c155df15d3b70eb49f1 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.module.js @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{Effect as t}from"effect";import{decodeUnknown as o,ArrayFormatter as n}from"effect/ParseResult";import{appendErrors as a}from"react-hook-form";function i(i,s){return void 0===s&&(s={errors:"all",onExcessProperty:"ignore"}),function(u,c,f){return o(i,s)(u).pipe(t.catchAll(function(r){return t.flip(n.formatIssue(r))}),t.mapError(function(e){var t=!f.shouldUseNativeValidation&&"all"===f.criteriaMode,o=e.reduce(function(r,e){var o=e.path.join(".");if(r[o]||(r[o]={message:e.message,type:e._tag}),t){var n=r[o].types,i=n&&n[String(e._tag)];r[o]=a(o,t,r,e._tag,i?[].concat(i,e.message):e.message)}return r},Object.create(null));return r(o,f)}),t.tap(function(){return t.sync(function(){return f.shouldUseNativeValidation&&e({},f)})}),t.match({onFailure:function(r){return{errors:r,values:{}}},onSuccess:function(r){return{errors:{},values:r}}}),t.runPromise)}}export{i as effectTsResolver}; +//# sourceMappingURL=effect-ts.module.js.map diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.module.js.map b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2257c52001cd8d7bb7d610e032d0fa57ccf36ce3 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"effect-ts.module.js","sources":["../src/effect-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { Effect, Schema } from 'effect';\nimport { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';\nimport { ParseOptions } from 'effect/SchemaAST';\nimport {\n type FieldError,\n FieldValues,\n Resolver,\n appendErrors,\n} from 'react-hook-form';\n\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions?: ParseOptions,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver;\n\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions: ParseOptions | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Effect.ts schema validation\n * @param {Schema.Schema} schema - The Effect.ts schema to validate against\n * @param {ParseOptions} [schemaOptions] - Optional Effect.ts validation options\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema.Struct({\n * name: Schema.String,\n * age: Schema.Number\n * });\n *\n * useForm({\n * resolver: effectTsResolver(schema)\n * });\n */\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions: ParseOptions = { errors: 'all', onExcessProperty: 'ignore' },\n): Resolver {\n return (values, _, options) => {\n return decodeUnknown(\n schema,\n schemaOptions,\n )(values).pipe(\n Effect.catchAll((parseIssue) =>\n Effect.flip(ArrayFormatter.formatIssue(parseIssue)),\n ),\n Effect.mapError((issues) => {\n const validateAllFieldCriteria =\n !options.shouldUseNativeValidation && options.criteriaMode === 'all';\n\n // A null-prototype accumulator avoids false-positive hits from\n // inherited members (e.g. `toString`, `constructor`) when a field\n // is named after one of them — a plain `{}` would make `!acc[key]`\n // truthy-skip those paths and silently drop their errors.\n const errors = issues.reduce(\n (acc, error) => {\n const key = error.path.join('.');\n\n if (!acc[key]) {\n acc[key] = { message: error.message, type: error._tag };\n }\n\n if (validateAllFieldCriteria) {\n const types = acc[key].types;\n const messages = types && types[String(error._tag)];\n\n acc[key] = appendErrors(\n key,\n validateAllFieldCriteria,\n acc,\n error._tag,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return acc;\n },\n Object.create(null) as Record,\n );\n\n return toNestErrors(errors, options);\n }),\n Effect.tap(() =>\n Effect.sync(\n () =>\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options),\n ),\n ),\n Effect.match({\n onFailure: (errors) => ({ errors, values: {} }),\n onSuccess: (result) => ({ errors: {}, values: result }),\n }),\n Effect.runPromise,\n );\n };\n}\n"],"names":["effectTsResolver","schema","schemaOptions","errors","onExcessProperty","values","_","options","decodeUnknown","pipe","Effect","catchAll","parseIssue","flip","ArrayFormatter","formatIssue","mapError","issues","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","reduce","acc","error","key","path","join","message","type","_tag","types","messages","String","appendErrors","concat","Object","create","toNestErrors","tap","sync","validateFieldsNatively","match","onFailure","onSuccess","result","runPromise"],"mappings":"8OA4CgBA,EACdC,EACAC,GAEA,YAF8B,IAA9BA,IAAAA,EAA8B,CAAEC,OAAQ,MAAOC,iBAAkB,oBAEzDC,EAAQC,EAAGC,GACjB,OAAOC,EACLP,EACAC,EAFKM,CAGLH,GAAQI,KACRC,EAAOC,SAAS,SAACC,GACf,OAAAF,EAAOG,KAAKC,EAAeC,YAAYH,GAAY,GAErDF,EAAOM,SAAS,SAACC,GACf,IAAMC,GACHX,EAAQY,2BAAsD,QAAzBZ,EAAQa,aAM1CjB,EAASc,EAAOI,OACpB,SAACC,EAAKC,GACJ,IAAMC,EAAMD,EAAME,KAAKC,KAAK,KAM5B,GAJKJ,EAAIE,KACPF,EAAIE,GAAO,CAAEG,QAASJ,EAAMI,QAASC,KAAML,EAAMM,OAG/CX,EAA0B,CAC5B,IAAMY,EAAQR,EAAIE,GAAKM,MACjBC,EAAWD,GAASA,EAAME,OAAOT,EAAMM,OAE7CP,EAAIE,GAAOS,EACTT,EACAN,EACAI,EACAC,EAAMM,KACNE,EACK,GAAgBG,OAAOH,EAAsBR,EAAMI,SACpDJ,EAAMI,QAEd,CAEA,OAAOL,CACT,EACAa,OAAOC,OAAO,OAGhB,OAAOC,EAAalC,EAAQI,EAC9B,GACAG,EAAO4B,IAAI,WACT,OAAA5B,EAAO6B,KACL,WACE,OAAAhC,EAAQY,2BACRqB,EAAuB,GAAIjC,EAAQ,EACtC,GAEHG,EAAO+B,MAAM,CACXC,UAAW,SAACvC,GAAM,MAAM,CAAEA,OAAAA,EAAQE,OAAQ,GAAI,EAC9CsC,UAAW,SAACC,GAAM,MAAM,CAAEzC,OAAQ,CAAE,EAAEE,OAAQuC,EAAQ,IAExDlC,EAAOmC,WAEX,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.umd.js b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..41745c72a7efac8c66ff6342a2c36afccd000e4f --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("effect"),require("effect/ParseResult"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","effect","effect/ParseResult","react-hook-form"],r):r((e||self).hookformResolversEffectTs={},e.hookformResolvers,e.Effect,e.EffectParseResult,e.ReactHookForm)}(this,function(e,r,t,o,f){e.effectTsResolver=function(e,n){return void 0===n&&(n={errors:"all",onExcessProperty:"ignore"}),function(s,a,c){return o.decodeUnknown(e,n)(s).pipe(t.Effect.catchAll(function(e){return t.Effect.flip(o.ArrayFormatter.formatIssue(e))}),t.Effect.mapError(function(e){var t=!c.shouldUseNativeValidation&&"all"===c.criteriaMode,o=e.reduce(function(e,r){var o=r.path.join(".");if(e[o]||(e[o]={message:r.message,type:r._tag}),t){var n=e[o].types,s=n&&n[String(r._tag)];e[o]=f.appendErrors(o,t,e,r._tag,s?[].concat(s,r.message):r.message)}return e},Object.create(null));return r.toNestErrors(o,c)}),t.Effect.tap(function(){return t.Effect.sync(function(){return c.shouldUseNativeValidation&&r.validateFieldsNatively({},c)})}),t.Effect.match({onFailure:function(e){return{errors:e,values:{}}},onSuccess:function(e){return{errors:{},values:e}}}),t.Effect.runPromise)}}}); +//# sourceMappingURL=effect-ts.umd.js.map diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.umd.js.map b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..eb2cafb295c3efb258bd9e352df1eb944cc6bf25 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"effect-ts.umd.js","sources":["../src/effect-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { Effect, Schema } from 'effect';\nimport { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';\nimport { ParseOptions } from 'effect/SchemaAST';\nimport {\n type FieldError,\n FieldValues,\n Resolver,\n appendErrors,\n} from 'react-hook-form';\n\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions?: ParseOptions,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver;\n\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions: ParseOptions | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Effect.ts schema validation\n * @param {Schema.Schema} schema - The Effect.ts schema to validate against\n * @param {ParseOptions} [schemaOptions] - Optional Effect.ts validation options\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema.Struct({\n * name: Schema.String,\n * age: Schema.Number\n * });\n *\n * useForm({\n * resolver: effectTsResolver(schema)\n * });\n */\nexport function effectTsResolver(\n schema: Schema.Schema,\n schemaOptions: ParseOptions = { errors: 'all', onExcessProperty: 'ignore' },\n): Resolver {\n return (values, _, options) => {\n return decodeUnknown(\n schema,\n schemaOptions,\n )(values).pipe(\n Effect.catchAll((parseIssue) =>\n Effect.flip(ArrayFormatter.formatIssue(parseIssue)),\n ),\n Effect.mapError((issues) => {\n const validateAllFieldCriteria =\n !options.shouldUseNativeValidation && options.criteriaMode === 'all';\n\n // A null-prototype accumulator avoids false-positive hits from\n // inherited members (e.g. `toString`, `constructor`) when a field\n // is named after one of them — a plain `{}` would make `!acc[key]`\n // truthy-skip those paths and silently drop their errors.\n const errors = issues.reduce(\n (acc, error) => {\n const key = error.path.join('.');\n\n if (!acc[key]) {\n acc[key] = { message: error.message, type: error._tag };\n }\n\n if (validateAllFieldCriteria) {\n const types = acc[key].types;\n const messages = types && types[String(error._tag)];\n\n acc[key] = appendErrors(\n key,\n validateAllFieldCriteria,\n acc,\n error._tag,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return acc;\n },\n Object.create(null) as Record,\n );\n\n return toNestErrors(errors, options);\n }),\n Effect.tap(() =>\n Effect.sync(\n () =>\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options),\n ),\n ),\n Effect.match({\n onFailure: (errors) => ({ errors, values: {} }),\n onSuccess: (result) => ({ errors: {}, values: result }),\n }),\n Effect.runPromise,\n );\n };\n}\n"],"names":["schema","schemaOptions","errors","onExcessProperty","values","_","options","decodeUnknown","pipe","Effect","catchAll","parseIssue","flip","ArrayFormatter","formatIssue","mapError","issues","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","reduce","acc","error","key","path","join","message","type","_tag","types","messages","String","appendErrors","concat","Object","create","toNestErrors","tap","sync","validateFieldsNatively","match","onFailure","onSuccess","result","runPromise"],"mappings":"wgBA6CEA,EACAC,GAEA,YAF8B,IAA9BA,IAAAA,EAA8B,CAAEC,OAAQ,MAAOC,iBAAkB,oBAEzDC,EAAQC,EAAGC,GACjB,OAAOC,EAAaA,cAClBP,EACAC,EAFKM,CAGLH,GAAQI,KACRC,EAAMA,OAACC,SAAS,SAACC,GACf,OAAAF,EAAAA,OAAOG,KAAKC,EAAcA,eAACC,YAAYH,GAAY,GAErDF,EAAMA,OAACM,SAAS,SAACC,GACf,IAAMC,GACHX,EAAQY,2BAAsD,QAAzBZ,EAAQa,aAM1CjB,EAASc,EAAOI,OACpB,SAACC,EAAKC,GACJ,IAAMC,EAAMD,EAAME,KAAKC,KAAK,KAM5B,GAJKJ,EAAIE,KACPF,EAAIE,GAAO,CAAEG,QAASJ,EAAMI,QAASC,KAAML,EAAMM,OAG/CX,EAA0B,CAC5B,IAAMY,EAAQR,EAAIE,GAAKM,MACjBC,EAAWD,GAASA,EAAME,OAAOT,EAAMM,OAE7CP,EAAIE,GAAOS,eACTT,EACAN,EACAI,EACAC,EAAMM,KACNE,EACK,GAAgBG,OAAOH,EAAsBR,EAAMI,SACpDJ,EAAMI,QAEd,CAEA,OAAOL,CACT,EACAa,OAAOC,OAAO,OAGhB,OAAOC,eAAalC,EAAQI,EAC9B,GACAG,SAAO4B,IAAI,WACT,OAAA5B,EAAAA,OAAO6B,KACL,WACE,OAAAhC,EAAQY,2BACRqB,EAAsBA,uBAAC,GAAIjC,EAAQ,EACtC,GAEHG,EAAAA,OAAO+B,MAAM,CACXC,UAAW,SAACvC,GAAM,MAAM,CAAEA,OAAAA,EAAQE,OAAQ,GAAI,EAC9CsC,UAAW,SAACC,GAAM,MAAM,CAAEzC,OAAQ,CAAE,EAAEE,OAAQuC,EAAQ,IAExDlC,EAAMA,OAACmC,WAEX,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/effect-ts/dist/index.d.ts b/node_modules/@hookform/resolvers/effect-ts/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd178c75b860301529085e2ab61cdc151cb872ce --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/dist/index.d.ts @@ -0,0 +1 @@ +export * from './effect-ts'; diff --git a/node_modules/@hookform/resolvers/effect-ts/package.json b/node_modules/@hookform/resolvers/effect-ts/package.json new file mode 100644 index 0000000000000000000000000000000000000000..62774181c615ce23f637bacdf8dad897a911f8e9 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/package.json @@ -0,0 +1,18 @@ +{ + "name": "@hookform/resolvers/effect-ts", + "amdName": "hookformResolversEffectTs", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: effect-ts", + "main": "dist/effect-ts.js", + "module": "dist/effect-ts.module.js", + "umd:main": "dist/effect-ts.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "@hookform/resolvers": "^2.0.0", + "effect": "^3.10.3", + "react-hook-form": "^7.55.0" + } +} diff --git a/node_modules/@hookform/resolvers/effect-ts/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4ea73afc0b94b9bea8e0351434a38c8744ba99fe --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,88 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { Schema } from 'effect'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { effectTsResolver } from '..'; + +const USERNAME_REQUIRED_MESSAGE = 'username field is required'; +const PASSWORD_REQUIRED_MESSAGE = 'password field is required'; + +const schema = Schema.Struct({ + username: Schema.String.pipe( + Schema.nonEmptyString({ message: () => USERNAME_REQUIRED_MESSAGE }), + ), + password: Schema.String.pipe( + Schema.nonEmptyString({ message: () => PASSWORD_REQUIRED_MESSAGE }), + ), +}); + +interface FormData { + username: string; + password: string; +} + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: effectTsResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with effect-ts", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/effect-ts/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6e5a4163119308a6771d42c559c31e8b25f57a6a --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/Form.tsx @@ -0,0 +1,85 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { Schema } from 'effect'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { effectTsResolver } from '..'; + +const USERNAME_REQUIRED_MESSAGE = 'username field is required'; +const PASSWORD_REQUIRED_MESSAGE = 'password field is required'; + +const schema = Schema.Struct({ + username: Schema.String.pipe( + Schema.nonEmptyString({ message: () => USERNAME_REQUIRED_MESSAGE }), + ), + password: Schema.String.pipe( + Schema.nonEmptyString({ message: () => PASSWORD_REQUIRED_MESSAGE }), + ), +}); + +type FormData = Schema.Schema.Type; + +function TestComponent({ + onSubmit, +}: { + onSubmit: (data: FormData) => void; +}) { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: effectTsResolver(schema), + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with Zod and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect(screen.getByText(/username field is required/i)).toBeInTheDocument(); + expect(screen.getByText(/password field is required/i)).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); + +export function TestComponentManualType({ + onSubmit, +}: { + onSubmit: (data: FormData) => void; +}) { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm, undefined, FormData>({ + resolver: effectTsResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} diff --git a/node_modules/@hookform/resolvers/effect-ts/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf6286e2d1e9257efc2ffb8f06cb406ae16c7262 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,124 @@ +import { Schema } from 'effect'; +import { Field, InternalFieldName } from 'react-hook-form'; + +export const schema = Schema.Struct({ + username: Schema.String.pipe( + Schema.nonEmptyString({ message: () => 'A username is required' }), + ), + password: Schema.String.pipe( + Schema.pattern(new RegExp('.*[A-Z].*'), { + message: () => 'At least 1 uppercase letter.', + }), + Schema.pattern(new RegExp('.*[a-z].*'), { + message: () => 'At least 1 lowercase letter.', + }), + Schema.pattern(new RegExp('.*\\d.*'), { + message: () => 'At least 1 number.', + }), + Schema.pattern( + new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'), + { + message: () => 'At least 1 special character.', + }, + ), + Schema.minLength(8, { message: () => 'Must be at least 8 characters.' }), + ), + accessToken: Schema.Union(Schema.String, Schema.Number), + birthYear: Schema.Number.pipe( + Schema.greaterThan(1900, { + message: () => 'Must be greater than the year 1900', + }), + Schema.filter((value) => value < new Date().getFullYear(), { + message: () => 'Must be before the current year.', + }), + ), + email: Schema.String.pipe( + Schema.pattern( + new RegExp( + /^(?!\.)(?!.*\.\.)([A-Z0-9_+-.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i, + ), + { + message: () => 'A valid email address is required.', + }, + ), + ), + tags: Schema.Array( + Schema.Struct({ + name: Schema.String, + }), + ), + luckyNumbers: Schema.Array(Schema.Number), + enabled: Schema.Boolean, + animal: Schema.Union(Schema.String, Schema.Literal('bird', 'snake')), + vehicles: Schema.Array( + Schema.Union( + Schema.Struct({ + type: Schema.Literal('car'), + brand: Schema.String, + horsepower: Schema.Number, + }), + Schema.Struct({ + type: Schema.Literal('bike'), + speed: Schema.Number, + }), + ), + ), +}); + +export const validData: Schema.Schema.Type = { + accessToken: 'abcd1234', + animal: 'dog', + birthYear: 2000, + email: 'johnDoe@here.there', + enabled: true, + luckyNumbers: [1, 2, 3, 4, 5], + password: 'Super#Secret123', + tags: [{ name: 'move' }, { name: 'over' }, { name: 'zod' }, { name: ';)' }], + username: 'johnDoe', + vehicles: [ + { type: 'bike', speed: 5 }, + { type: 'car', brand: 'BMW', horsepower: 150 }, + ], +}; + +export const invalidData = { + username: 'test', + password: 'Password123', + repeatPassword: 'Password123', + birthYear: 2000, + accessToken: '1015d809-e99d-41ec-b161-981a3c243df8', + email: 'john@doe.com', + tags: [{ name: 'test' }], + enabled: true, + animal: ['dog'], + luckyNumbers: [1, 2, '3'], + like: [ + { + id: '1', + name: 'name', + }, + ], + vehicles: [ + { type: 'car', brand: 'BMW', horsepower: 150 }, + { type: 'car', brand: 'Mercedes' }, + ], +} as any as Schema.Schema.Type; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/effect-ts/src/__tests__/__snapshots__/effect-ts.ts.snap b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/__snapshots__/effect-ts.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..0e9e0cc654394190cfbf890de5452f742fcfa752 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/__snapshots__/effect-ts.ts.snap @@ -0,0 +1,74 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`effectTsResolver > should return a single error from effectTsResolver when validation fails 1`] = ` +{ + "errors": { + "animal": { + "message": "Expected string, actual ["dog"]", + "ref": undefined, + "type": "Type", + }, + "luckyNumbers": [ + , + , + { + "message": "Expected number, actual "3"", + "ref": undefined, + "type": "Type", + }, + ], + "password": { + "message": "At least 1 special character.", + "ref": { + "name": "password", + }, + "type": "Refinement", + }, + "vehicles": [ + , + { + "horsepower": { + "message": "is missing", + "ref": undefined, + "type": "Missing", + }, + }, + ], + }, + "values": {}, +} +`; + +exports[`effectTsResolver > should return all the errors from effectTsResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = ` +{ + "errors": { + "phoneNumber": { + "message": "Please enter a valid phone number in international format.", + "ref": { + "name": "phoneNumber", + }, + "type": "Refinement", + "types": { + "Refinement": "Please enter a valid phone number in international format.", + "Type": "Expected undefined, actual "123"", + }, + }, + }, + "values": {}, +} +`; + +exports[`effectTsResolver > should return the first error from effectTsResolver when validation fails with \`validateAllFieldCriteria\` set to firstError 1`] = ` +{ + "errors": { + "phoneNumber": { + "message": "Please enter a valid phone number in international format.", + "ref": { + "name": "phoneNumber", + }, + "type": "Refinement", + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/effect-ts/src/__tests__/effect-ts.ts b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/effect-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..c43e57310a7ae5bc49c88635f64007389c75ce0e --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/effect-ts.ts @@ -0,0 +1,155 @@ +import { renderHook } from '@testing-library/react'; +import { Schema } from 'effect'; +import { Resolver, useForm } from 'react-hook-form'; +import { SubmitHandler } from 'react-hook-form'; +import { effectTsResolver } from '..'; +import { fields, invalidData, schema, validData } from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('effectTsResolver', () => { + it('should return values from effectTsResolver when validation pass', async () => { + const result = await effectTsResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return a single error from effectTsResolver when validation fails', async () => { + const result = await effectTsResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should return the first error from effectTsResolver when validation fails with `validateAllFieldCriteria` set to firstError', async () => { + const SignupSchema = Schema.Struct({ + phoneNumber: Schema.optional( + Schema.String.pipe( + Schema.pattern(/^\+\d{7,15}$/, { + message: () => + 'Please enter a valid phone number in international format.', + }), + ), + ), + }); + + const result = await effectTsResolver(SignupSchema)( + { phoneNumber: '123' }, + undefined, + { + fields: { + phoneNumber: { + ref: { name: 'phoneNumber' }, + name: 'phoneNumber', + }, + }, + criteriaMode: 'firstError', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from effectTsResolver when validation fails with `validateAllFieldCriteria` set to true', async () => { + const SignupSchema = Schema.Struct({ + phoneNumber: Schema.optional( + Schema.String.pipe( + Schema.pattern(/^\+\d{7,15}$/, { + message: () => + 'Please enter a valid phone number in international format.', + }), + ), + ), + }); + + const result = await effectTsResolver(SignupSchema)( + { phoneNumber: '123' }, + undefined, + { + fields: { + phoneNumber: { + ref: { name: 'phoneNumber' }, + name: 'phoneNumber', + }, + }, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + /** + * Type inference tests + */ + it('should correctly infer the output type from a effectTs schema', () => { + const resolver = effectTsResolver(Schema.Struct({ id: Schema.Number })); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver, unknown, Readonly<{ id: number }>> + >(); + }); + + it('should correctly infer the output type from a effectTs schema using a transform', () => { + const resolver = effectTsResolver( + Schema.Struct({ + id: Schema.transform(Schema.Number, Schema.String, { + decode: (val) => String(val), + encode: (val) => Number(val), + }), + }), + ); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver, unknown, Readonly<{ id: string }>> + >(); + }); + + it('should correctly infer the output type from a effectTs schema for the handleSubmit function in useForm', () => { + const schema = Schema.Struct({ id: Schema.Number }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: effectTsResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit) + .parameter(0) + .toEqualTypeOf>>(); + }); + + it('should correctly infer the output type from a effectTs schema with a transform for the handleSubmit function in useForm', () => { + const schema = Schema.Struct({ + id: Schema.transform(Schema.Number, Schema.String, { + decode: (val) => String(val), + encode: (val) => Number(val), + }), + }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: effectTsResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit) + .parameter(0) + .toEqualTypeOf>>(); + }); +}); diff --git a/node_modules/@hookform/resolvers/effect-ts/src/__tests__/special-path-names.ts b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/special-path-names.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c8860c66dc06ee79cbd761599fcffe6f23485a8 --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/src/__tests__/special-path-names.ts @@ -0,0 +1,23 @@ +import { Schema } from 'effect'; +import { effectTsResolver } from '..'; + +const shouldUseNativeValidation = false; + +describe('effectTsResolver special path names', () => { + it.each(['hasOwnProperty', 'toString'])( + 'reports a validation error for a field named "%s"', + async (name) => { + const schema = Schema.Struct({ + [name]: Schema.String.pipe(Schema.minLength(1)), + }); + + const result = await effectTsResolver(schema as any)( + { [name]: '' } as any, + undefined, + { fields: {}, shouldUseNativeValidation } as any, + ); + + expect(result.errors[name]).toBeDefined(); + }, + ); +}); diff --git a/node_modules/@hookform/resolvers/effect-ts/src/effect-ts.ts b/node_modules/@hookform/resolvers/effect-ts/src/effect-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..f89a894e20a8b05034327aa15b8b8964c6eb023b --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/src/effect-ts.ts @@ -0,0 +1,109 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import { Effect, Schema } from 'effect'; +import { ArrayFormatter, decodeUnknown } from 'effect/ParseResult'; +import { ParseOptions } from 'effect/SchemaAST'; +import { + type FieldError, + FieldValues, + Resolver, + appendErrors, +} from 'react-hook-form'; + +export function effectTsResolver( + schema: Schema.Schema, + schemaOptions?: ParseOptions, + resolverOptions?: { + mode?: 'async' | 'sync'; + raw?: false; + }, +): Resolver; + +export function effectTsResolver( + schema: Schema.Schema, + schemaOptions: ParseOptions | undefined, + resolverOptions: { + mode?: 'async' | 'sync'; + raw: true; + }, +): Resolver; + +/** + * Creates a resolver for react-hook-form using Effect.ts schema validation + * @param {Schema.Schema} schema - The Effect.ts schema to validate against + * @param {ParseOptions} [schemaOptions] - Optional Effect.ts validation options + * @returns {Resolver>} A resolver function compatible with react-hook-form + * @example + * const schema = Schema.Struct({ + * name: Schema.String, + * age: Schema.Number + * }); + * + * useForm({ + * resolver: effectTsResolver(schema) + * }); + */ +export function effectTsResolver( + schema: Schema.Schema, + schemaOptions: ParseOptions = { errors: 'all', onExcessProperty: 'ignore' }, +): Resolver { + return (values, _, options) => { + return decodeUnknown( + schema, + schemaOptions, + )(values).pipe( + Effect.catchAll((parseIssue) => + Effect.flip(ArrayFormatter.formatIssue(parseIssue)), + ), + Effect.mapError((issues) => { + const validateAllFieldCriteria = + !options.shouldUseNativeValidation && options.criteriaMode === 'all'; + + // A null-prototype accumulator avoids false-positive hits from + // inherited members (e.g. `toString`, `constructor`) when a field + // is named after one of them — a plain `{}` would make `!acc[key]` + // truthy-skip those paths and silently drop their errors. + const errors = issues.reduce( + (acc, error) => { + const key = error.path.join('.'); + + if (!acc[key]) { + acc[key] = { message: error.message, type: error._tag }; + } + + if (validateAllFieldCriteria) { + const types = acc[key].types; + const messages = types && types[String(error._tag)]; + + acc[key] = appendErrors( + key, + validateAllFieldCriteria, + acc, + error._tag, + messages + ? ([] as string[]).concat(messages as string[], error.message) + : error.message, + ) as FieldError; + } + + return acc; + }, + Object.create(null) as Record, + ); + + return toNestErrors(errors, options); + }), + Effect.tap(() => + Effect.sync( + () => + options.shouldUseNativeValidation && + validateFieldsNatively({}, options), + ), + ), + Effect.match({ + onFailure: (errors) => ({ errors, values: {} }), + onSuccess: (result) => ({ errors: {}, values: result }), + }), + Effect.runPromise, + ); + }; +} diff --git a/node_modules/@hookform/resolvers/effect-ts/src/index.ts b/node_modules/@hookform/resolvers/effect-ts/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd178c75b860301529085e2ab61cdc151cb872ce --- /dev/null +++ b/node_modules/@hookform/resolvers/effect-ts/src/index.ts @@ -0,0 +1 @@ +export * from './effect-ts'; diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.d.ts b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f5b750e8c9c62191a99e06f2591a4947feba320 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.d.ts @@ -0,0 +1,25 @@ +import { AsyncValidator, Validator } from 'fluentvalidation-ts'; +import { FieldValues, Resolver } from 'react-hook-form'; +/** + * Creates a resolver for react-hook-form using FluentValidation schema validation + * @param {Validator} validator - The FluentValidation validator to use + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * import { Validator } from 'fluentvalidation-ts'; + * + * class SchemaValidator extends Validator { + * constructor() { + * super(); + * this.ruleFor('username').notEmpty(); + * this.ruleFor('password').notEmpty(); + * } + * } + * + * const validator = new SchemaValidator(); + * + * useForm({ + * resolver: fluentValidationResolver(validator) + * }); + */ +export declare function fluentValidationResolver(validator: Validator): Resolver; +export declare function fluentAsyncValidationResolver>(validator: TValidator): Resolver; diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.js b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.js new file mode 100644 index 0000000000000000000000000000000000000000..0807114a2338e1ccf6c21b71d21a291e5aae5320 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers");function r(e,t,o){void 0===o&&(o=[]);var n=function(){var n=[].concat(o,[a]),i=e[a];Array.isArray(i)?i.forEach(function(e,o){r(e,t,[].concat(n,[o]))}):"object"==typeof i&&null!==i?r(i,t,n):"string"==typeof i&&(t[n.join(".")]={type:"validation",message:i})};for(var a in e)n()}function t(e,t){var o={};return r(e,o),o}exports.fluentAsyncValidationResolver=function(r){return function(o,n,a){try{return Promise.resolve(r.validateAsync(o)).then(function(r){var n=0===Object.keys(r).length;return a.shouldUseNativeValidation&&e.validateFieldsNatively({},a),n?{values:o,errors:{}}:{values:{},errors:e.toNestErrors(t(r),a)}})}catch(e){return Promise.reject(e)}}},exports.fluentValidationResolver=function(r){return function(o,n,a){try{var i=r.validate(o),s=0===Object.keys(i).length;return a.shouldUseNativeValidation&&e.validateFieldsNatively({},a),Promise.resolve(s?{values:o,errors:{}}:{values:{},errors:e.toNestErrors(t(i),a)})}catch(e){return Promise.reject(e)}}}; +//# sourceMappingURL=fluentvalidation-ts.js.map diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.js.map b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.js.map new file mode 100644 index 0000000000000000000000000000000000000000..26ed0d1d53e10c4ce04c30ee990d78eb1037549c --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fluentvalidation-ts.js","sources":["../src/fluentvalidation-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n AsyncValidator,\n ValidationErrors,\n Validator,\n} from 'fluentvalidation-ts';\nimport { FieldError, FieldValues, Resolver } from 'react-hook-form';\n\nfunction traverseObject(\n object: ValidationErrors,\n errors: Record,\n parentIndices: (string | number)[] = [],\n) {\n for (const key in object) {\n const currentIndex = [...parentIndices, key];\n const currentValue = object[key];\n\n if (Array.isArray(currentValue)) {\n currentValue.forEach((item: any, index: number) => {\n traverseObject(item, errors, [...currentIndex, index]);\n });\n } else if (typeof currentValue === 'object' && currentValue !== null) {\n traverseObject(currentValue, errors, currentIndex);\n } else if (typeof currentValue === 'string') {\n errors[currentIndex.join('.')] = {\n type: 'validation',\n message: currentValue,\n };\n }\n }\n}\n\nfunction parseErrorSchema(\n validationErrors: ValidationErrors,\n validateAllFieldCriteria: boolean,\n) {\n if (validateAllFieldCriteria) {\n // TODO: check this but i think its always one validation error\n }\n\n const errors: Record = {};\n traverseObject(validationErrors, errors);\n\n return errors;\n}\n\n/**\n * Creates a resolver for react-hook-form using FluentValidation schema validation\n * @param {Validator} validator - The FluentValidation validator to use\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * import { Validator } from 'fluentvalidation-ts';\n *\n * class SchemaValidator extends Validator {\n * constructor() {\n * super();\n * this.ruleFor('username').notEmpty();\n * this.ruleFor('password').notEmpty();\n * }\n * }\n *\n * const validator = new SchemaValidator();\n *\n * useForm({\n * resolver: fluentValidationResolver(validator)\n * });\n */\nexport function fluentValidationResolver(\n validator: Validator,\n): Resolver {\n return async (values, _context, options) => {\n const validationResult = validator.validate(values);\n const isValid = Object.keys(validationResult).length === 0;\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return isValid\n ? {\n values: values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validationResult,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n\nexport function fluentAsyncValidationResolver<\n TFieldValues extends FieldValues,\n TValidator extends AsyncValidator,\n>(validator: TValidator): Resolver {\n return async (values, _context, options) => {\n const validationResult = await validator.validateAsync(values);\n const isValid = Object.keys(validationResult).length === 0;\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return isValid\n ? {\n values: values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validationResult,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n"],"names":["traverseObject","object","errors","parentIndices","_loop","currentIndex","concat","key","currentValue","Array","isArray","forEach","item","index","join","type","message","parseErrorSchema","validationErrors","validateAllFieldCriteria","validator","values","_context","options","Promise","resolve","validateAsync","then","validationResult","isValid","Object","keys","length","shouldUseNativeValidation","validateFieldsNatively","toNestErrors","e","reject","validate"],"mappings":"qCAQA,SAASA,EACPC,EACAC,EACAC,YAAAA,IAAAA,EAAqC,IAAE,IAAAC,EAAAA,WAGrC,IAAMC,EAAY,GAAAC,OAAOH,EAAa,CAAEI,IAClCC,EAAeP,EAAOM,GAExBE,MAAMC,QAAQF,GAChBA,EAAaG,QAAQ,SAACC,EAAWC,GAC/Bb,EAAeY,EAAMV,EAAM,GAAAI,OAAMD,EAAcQ,CAAAA,IACjD,GACiC,iBAAjBL,GAA8C,OAAjBA,EAC7CR,EAAeQ,EAAcN,EAAQG,GACJ,iBAAjBG,IAChBN,EAAOG,EAAaS,KAAK,MAAQ,CAC/BC,KAAM,aACNC,QAASR,GAGf,EAhBA,IAAK,IAAMD,KAAON,EAAMG,GAiB1B,CAEA,SAASa,EACPC,EACAC,GAMA,IAAMjB,EAAqC,CAAE,EAG7C,OAFAF,EAAekB,EAAkBhB,GAE1BA,CACT,gDAsDEkB,GACA,OAAA,SAAcC,EAAQC,EAAUC,OAAWC,OAAAA,QAAAC,QACVL,EAAUM,cAAcL,IAAOM,KAAxDC,SAAAA,GACN,IAAMC,EAAmD,IAAzCC,OAAOC,KAAKH,GAAkBI,OAI9C,OAFAT,EAAQU,2BAA6BC,EAAsBA,uBAAC,GAAIX,GAEzDM,EACH,CACER,OAAQA,EACRnB,OAAQ,CAAA,GAEV,CACEmB,OAAQ,CAAA,EACRnB,OAAQiC,EAAAA,aACNlB,EACEW,GAIFL,GAEF,EACR,CAAC,MAAAa,GAAA,OAAAZ,QAAAa,OAAAD,EACH,CAAA,CAAA,4CAtDEhB,GAEA,gBAAcC,EAAQC,EAAUC,OAC9B,IAAMK,EAAmBR,EAAUkB,SAASjB,GACtCQ,EAAmD,IAAzCC,OAAOC,KAAKH,GAAkBI,OAI9C,OAFAT,EAAQU,2BAA6BC,EAAsBA,uBAAC,GAAIX,GAEhEC,QAAAC,QAAOI,EACH,CACER,OAAQA,EACRnB,OAAQ,CAAA,GAEV,CACEmB,OAAQ,CAAA,EACRnB,OAAQiC,EAAYA,aAClBlB,EACEW,GAIFL,IAGV,CAAC,MAAAa,GAAAZ,OAAAA,QAAAa,OAAAD,IACH"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.mjs b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.mjs new file mode 100644 index 0000000000000000000000000000000000000000..07d82ebc8d490bd10bd57227f139c8aec3efd316 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(r,e,o){void 0===o&&(o=[]);var n=function(){var n=[].concat(o,[a]),i=r[a];Array.isArray(i)?i.forEach(function(r,o){t(r,e,[].concat(n,[o]))}):"object"==typeof i&&null!==i?t(i,e,n):"string"==typeof i&&(e[n.join(".")]={type:"validation",message:i})};for(var a in r)n()}function o(r,e){var o={};return t(r,o),o}function n(t){return function(n,a,i){try{var s=t.validate(n),c=0===Object.keys(s).length;return i.shouldUseNativeValidation&&r({},i),Promise.resolve(c?{values:n,errors:{}}:{values:{},errors:e(o(s),i)})}catch(r){return Promise.reject(r)}}}function a(t){return function(n,a,i){try{return Promise.resolve(t.validateAsync(n)).then(function(t){var a=0===Object.keys(t).length;return i.shouldUseNativeValidation&&r({},i),a?{values:n,errors:{}}:{values:{},errors:e(o(t),i)}})}catch(r){return Promise.reject(r)}}}export{a as fluentAsyncValidationResolver,n as fluentValidationResolver}; +//# sourceMappingURL=fluentvalidation-ts.module.js.map diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.modern.mjs b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5c77823968b113dd71cd2693375b820266e9bda4 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.modern.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(r,e,o=[]){for(const n in r){const s=[...o,n],a=r[n];Array.isArray(a)?a.forEach((r,o)=>{t(r,e,[...s,o])}):"object"==typeof a&&null!==a?t(a,e,s):"string"==typeof a&&(e[s.join(".")]={type:"validation",message:a})}}function o(r,e){const o={};return t(r,o),o}function n(t){return async(n,s,a)=>{const i=t.validate(n),c=0===Object.keys(i).length;return a.shouldUseNativeValidation&&r({},a),c?{values:n,errors:{}}:{values:{},errors:e(o(i),a)}}}function s(t){return async(n,s,a)=>{const i=await t.validateAsync(n),c=0===Object.keys(i).length;return a.shouldUseNativeValidation&&r({},a),c?{values:n,errors:{}}:{values:{},errors:e(o(i),a)}}}export{s as fluentAsyncValidationResolver,n as fluentValidationResolver}; +//# sourceMappingURL=fluentvalidation-ts.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.modern.mjs.map b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f1d6819878af3139f83b121ff507b187ee2d9c54 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"fluentvalidation-ts.modern.mjs","sources":["../src/fluentvalidation-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n AsyncValidator,\n ValidationErrors,\n Validator,\n} from 'fluentvalidation-ts';\nimport { FieldError, FieldValues, Resolver } from 'react-hook-form';\n\nfunction traverseObject(\n object: ValidationErrors,\n errors: Record,\n parentIndices: (string | number)[] = [],\n) {\n for (const key in object) {\n const currentIndex = [...parentIndices, key];\n const currentValue = object[key];\n\n if (Array.isArray(currentValue)) {\n currentValue.forEach((item: any, index: number) => {\n traverseObject(item, errors, [...currentIndex, index]);\n });\n } else if (typeof currentValue === 'object' && currentValue !== null) {\n traverseObject(currentValue, errors, currentIndex);\n } else if (typeof currentValue === 'string') {\n errors[currentIndex.join('.')] = {\n type: 'validation',\n message: currentValue,\n };\n }\n }\n}\n\nfunction parseErrorSchema(\n validationErrors: ValidationErrors,\n validateAllFieldCriteria: boolean,\n) {\n if (validateAllFieldCriteria) {\n // TODO: check this but i think its always one validation error\n }\n\n const errors: Record = {};\n traverseObject(validationErrors, errors);\n\n return errors;\n}\n\n/**\n * Creates a resolver for react-hook-form using FluentValidation schema validation\n * @param {Validator} validator - The FluentValidation validator to use\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * import { Validator } from 'fluentvalidation-ts';\n *\n * class SchemaValidator extends Validator {\n * constructor() {\n * super();\n * this.ruleFor('username').notEmpty();\n * this.ruleFor('password').notEmpty();\n * }\n * }\n *\n * const validator = new SchemaValidator();\n *\n * useForm({\n * resolver: fluentValidationResolver(validator)\n * });\n */\nexport function fluentValidationResolver(\n validator: Validator,\n): Resolver {\n return async (values, _context, options) => {\n const validationResult = validator.validate(values);\n const isValid = Object.keys(validationResult).length === 0;\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return isValid\n ? {\n values: values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validationResult,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n\nexport function fluentAsyncValidationResolver<\n TFieldValues extends FieldValues,\n TValidator extends AsyncValidator,\n>(validator: TValidator): Resolver {\n return async (values, _context, options) => {\n const validationResult = await validator.validateAsync(values);\n const isValid = Object.keys(validationResult).length === 0;\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return isValid\n ? {\n values: values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validationResult,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n"],"names":["traverseObject","object","errors","parentIndices","key","currentIndex","currentValue","Array","isArray","forEach","item","index","join","type","message","parseErrorSchema","validationErrors","validateAllFieldCriteria","fluentValidationResolver","validator","async","values","_context","options","validationResult","validate","isValid","Object","keys","length","shouldUseNativeValidation","validateFieldsNatively","toNestErrors","fluentAsyncValidationResolver","validateAsync"],"mappings":"+EAQA,SAASA,EACPC,EACAC,EACAC,EAAqC,IAErC,IAAK,MAAMC,KAAOH,EAAQ,CACxB,MAAMI,EAAe,IAAIF,EAAeC,GAClCE,EAAeL,EAAOG,GAExBG,MAAMC,QAAQF,GAChBA,EAAaG,QAAQ,CAACC,EAAWC,KAC/BX,EAAeU,EAAMR,EAAQ,IAAIG,EAAcM,GAAO,GAEvB,iBAAjBL,GAA8C,OAAjBA,EAC7CN,EAAeM,EAAcJ,EAAQG,GACJ,iBAAjBC,IAChBJ,EAAOG,EAAaO,KAAK,MAAQ,CAC/BC,KAAM,aACNC,QAASR,GAGf,CACF,CAEA,SAASS,EACPC,EACAC,GAMA,MAAMf,EAAqC,CAAA,EAG3C,OAFAF,EAAegB,EAAkBd,GAE1BA,CACT,UAuBgBgB,EACdC,GAEA,OAAOC,MAAOC,EAAQC,EAAUC,KAC9B,MAAMC,EAAmBL,EAAUM,SAASJ,GACtCK,EAAmD,IAAzCC,OAAOC,KAAKJ,GAAkBK,OAI9C,OAFAN,EAAQO,2BAA6BC,EAAuB,GAAIR,GAEzDG,EACH,CACEL,OAAQA,EACRnB,OAAQ,IAEV,CACEmB,OAAQ,CAAE,EACVnB,OAAQ8B,EACNjB,EACES,GAIFD,GAEH,CAET,CAEgB,SAAAU,EAGdd,GACA,aAAcE,EAAQC,EAAUC,KAC9B,MAAMC,QAAyBL,EAAUe,cAAcb,GACjDK,EAAmD,IAAzCC,OAAOC,KAAKJ,GAAkBK,OAI9C,OAFAN,EAAQO,2BAA6BC,EAAuB,GAAIR,GAEzDG,EACH,CACEL,OAAQA,EACRnB,OAAQ,IAEV,CACEmB,OAAQ,CAAE,EACVnB,OAAQ8B,EACNjB,EACES,GAIFD,GAEH,CAET"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.module.js b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.module.js new file mode 100644 index 0000000000000000000000000000000000000000..07d82ebc8d490bd10bd57227f139c8aec3efd316 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.module.js @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(r,e,o){void 0===o&&(o=[]);var n=function(){var n=[].concat(o,[a]),i=r[a];Array.isArray(i)?i.forEach(function(r,o){t(r,e,[].concat(n,[o]))}):"object"==typeof i&&null!==i?t(i,e,n):"string"==typeof i&&(e[n.join(".")]={type:"validation",message:i})};for(var a in r)n()}function o(r,e){var o={};return t(r,o),o}function n(t){return function(n,a,i){try{var s=t.validate(n),c=0===Object.keys(s).length;return i.shouldUseNativeValidation&&r({},i),Promise.resolve(c?{values:n,errors:{}}:{values:{},errors:e(o(s),i)})}catch(r){return Promise.reject(r)}}}function a(t){return function(n,a,i){try{return Promise.resolve(t.validateAsync(n)).then(function(t){var a=0===Object.keys(t).length;return i.shouldUseNativeValidation&&r({},i),a?{values:n,errors:{}}:{values:{},errors:e(o(t),i)}})}catch(r){return Promise.reject(r)}}}export{a as fluentAsyncValidationResolver,n as fluentValidationResolver}; +//# sourceMappingURL=fluentvalidation-ts.module.js.map diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.module.js.map b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dc99d919542f9666cbc88f37782e7fd70e30eb85 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fluentvalidation-ts.module.js","sources":["../src/fluentvalidation-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n AsyncValidator,\n ValidationErrors,\n Validator,\n} from 'fluentvalidation-ts';\nimport { FieldError, FieldValues, Resolver } from 'react-hook-form';\n\nfunction traverseObject(\n object: ValidationErrors,\n errors: Record,\n parentIndices: (string | number)[] = [],\n) {\n for (const key in object) {\n const currentIndex = [...parentIndices, key];\n const currentValue = object[key];\n\n if (Array.isArray(currentValue)) {\n currentValue.forEach((item: any, index: number) => {\n traverseObject(item, errors, [...currentIndex, index]);\n });\n } else if (typeof currentValue === 'object' && currentValue !== null) {\n traverseObject(currentValue, errors, currentIndex);\n } else if (typeof currentValue === 'string') {\n errors[currentIndex.join('.')] = {\n type: 'validation',\n message: currentValue,\n };\n }\n }\n}\n\nfunction parseErrorSchema(\n validationErrors: ValidationErrors,\n validateAllFieldCriteria: boolean,\n) {\n if (validateAllFieldCriteria) {\n // TODO: check this but i think its always one validation error\n }\n\n const errors: Record = {};\n traverseObject(validationErrors, errors);\n\n return errors;\n}\n\n/**\n * Creates a resolver for react-hook-form using FluentValidation schema validation\n * @param {Validator} validator - The FluentValidation validator to use\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * import { Validator } from 'fluentvalidation-ts';\n *\n * class SchemaValidator extends Validator {\n * constructor() {\n * super();\n * this.ruleFor('username').notEmpty();\n * this.ruleFor('password').notEmpty();\n * }\n * }\n *\n * const validator = new SchemaValidator();\n *\n * useForm({\n * resolver: fluentValidationResolver(validator)\n * });\n */\nexport function fluentValidationResolver(\n validator: Validator,\n): Resolver {\n return async (values, _context, options) => {\n const validationResult = validator.validate(values);\n const isValid = Object.keys(validationResult).length === 0;\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return isValid\n ? {\n values: values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validationResult,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n\nexport function fluentAsyncValidationResolver<\n TFieldValues extends FieldValues,\n TValidator extends AsyncValidator,\n>(validator: TValidator): Resolver {\n return async (values, _context, options) => {\n const validationResult = await validator.validateAsync(values);\n const isValid = Object.keys(validationResult).length === 0;\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return isValid\n ? {\n values: values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validationResult,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n"],"names":["traverseObject","object","errors","parentIndices","_loop","currentIndex","concat","key","currentValue","Array","isArray","forEach","item","index","join","type","message","parseErrorSchema","validationErrors","validateAllFieldCriteria","fluentValidationResolver","validator","values","_context","options","validationResult","validate","isValid","Object","keys","length","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","toNestErrors","e","reject","fluentAsyncValidationResolver","validateAsync","then"],"mappings":"+EAQA,SAASA,EACPC,EACAC,EACAC,YAAAA,IAAAA,EAAqC,IAAE,IAAAC,EAAAA,WAGrC,IAAMC,EAAY,GAAAC,OAAOH,EAAa,CAAEI,IAClCC,EAAeP,EAAOM,GAExBE,MAAMC,QAAQF,GAChBA,EAAaG,QAAQ,SAACC,EAAWC,GAC/Bb,EAAeY,EAAMV,EAAM,GAAAI,OAAMD,EAAcQ,CAAAA,IACjD,GACiC,iBAAjBL,GAA8C,OAAjBA,EAC7CR,EAAeQ,EAAcN,EAAQG,GACJ,iBAAjBG,IAChBN,EAAOG,EAAaS,KAAK,MAAQ,CAC/BC,KAAM,aACNC,QAASR,GAGf,EAhBA,IAAK,IAAMD,KAAON,EAAMG,GAiB1B,CAEA,SAASa,EACPC,EACAC,GAMA,IAAMjB,EAAqC,CAAE,EAG7C,OAFAF,EAAekB,EAAkBhB,GAE1BA,CACT,UAuBgBkB,EACdC,GAEA,gBAAcC,EAAQC,EAAUC,OAC9B,IAAMC,EAAmBJ,EAAUK,SAASJ,GACtCK,EAAmD,IAAzCC,OAAOC,KAAKJ,GAAkBK,OAI9C,OAFAN,EAAQO,2BAA6BC,EAAuB,GAAIR,GAEhES,QAAAC,QAAOP,EACH,CACEL,OAAQA,EACRpB,OAAQ,CAAA,GAEV,CACEoB,OAAQ,CAAA,EACRpB,OAAQiC,EACNlB,EACEQ,GAIFD,IAGV,CAAC,MAAAY,GAAAH,OAAAA,QAAAI,OAAAD,IACH,UAEgBE,EAGdjB,GACA,OAAA,SAAcC,EAAQC,EAAUC,OAAWS,OAAAA,QAAAC,QACVb,EAAUkB,cAAcjB,IAAOkB,KAAxDf,SAAAA,GACN,IAAME,EAAmD,IAAzCC,OAAOC,KAAKJ,GAAkBK,OAI9C,OAFAN,EAAQO,2BAA6BC,EAAuB,GAAIR,GAEzDG,EACH,CACEL,OAAQA,EACRpB,OAAQ,CAAA,GAEV,CACEoB,OAAQ,CAAA,EACRpB,OAAQiC,EACNlB,EACEQ,GAIFD,GAEF,EACR,CAAC,MAAAY,GAAA,OAAAH,QAAAI,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.umd.js b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..1f102e6a7799ff73d13b0fed0eb728c9f59ac238 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],r):r((e||self)["hookformResolversfluentvalidation-ts"]={},e.hookformResolvers)}(this,function(e,r){function o(e,r,t){void 0===t&&(t=[]);var n=function(){var n=[].concat(t,[i]),s=e[i];Array.isArray(s)?s.forEach(function(e,t){o(e,r,[].concat(n,[t]))}):"object"==typeof s&&null!==s?o(s,r,n):"string"==typeof s&&(r[n.join(".")]={type:"validation",message:s})};for(var i in e)n()}function t(e,r){var t={};return o(e,t),t}e.fluentAsyncValidationResolver=function(e){return function(o,n,i){try{return Promise.resolve(e.validateAsync(o)).then(function(e){var n=0===Object.keys(e).length;return i.shouldUseNativeValidation&&r.validateFieldsNatively({},i),n?{values:o,errors:{}}:{values:{},errors:r.toNestErrors(t(e),i)}})}catch(e){return Promise.reject(e)}}},e.fluentValidationResolver=function(e){return function(o,n,i){try{var s=e.validate(o),a=0===Object.keys(s).length;return i.shouldUseNativeValidation&&r.validateFieldsNatively({},i),Promise.resolve(a?{values:o,errors:{}}:{values:{},errors:r.toNestErrors(t(s),i)})}catch(e){return Promise.reject(e)}}}}); +//# sourceMappingURL=fluentvalidation-ts.umd.js.map diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.umd.js.map b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..eba2be4380db6772d7e6277aed1f850a718a87e4 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/fluentvalidation-ts.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fluentvalidation-ts.umd.js","sources":["../src/fluentvalidation-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n AsyncValidator,\n ValidationErrors,\n Validator,\n} from 'fluentvalidation-ts';\nimport { FieldError, FieldValues, Resolver } from 'react-hook-form';\n\nfunction traverseObject(\n object: ValidationErrors,\n errors: Record,\n parentIndices: (string | number)[] = [],\n) {\n for (const key in object) {\n const currentIndex = [...parentIndices, key];\n const currentValue = object[key];\n\n if (Array.isArray(currentValue)) {\n currentValue.forEach((item: any, index: number) => {\n traverseObject(item, errors, [...currentIndex, index]);\n });\n } else if (typeof currentValue === 'object' && currentValue !== null) {\n traverseObject(currentValue, errors, currentIndex);\n } else if (typeof currentValue === 'string') {\n errors[currentIndex.join('.')] = {\n type: 'validation',\n message: currentValue,\n };\n }\n }\n}\n\nfunction parseErrorSchema(\n validationErrors: ValidationErrors,\n validateAllFieldCriteria: boolean,\n) {\n if (validateAllFieldCriteria) {\n // TODO: check this but i think its always one validation error\n }\n\n const errors: Record = {};\n traverseObject(validationErrors, errors);\n\n return errors;\n}\n\n/**\n * Creates a resolver for react-hook-form using FluentValidation schema validation\n * @param {Validator} validator - The FluentValidation validator to use\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * import { Validator } from 'fluentvalidation-ts';\n *\n * class SchemaValidator extends Validator {\n * constructor() {\n * super();\n * this.ruleFor('username').notEmpty();\n * this.ruleFor('password').notEmpty();\n * }\n * }\n *\n * const validator = new SchemaValidator();\n *\n * useForm({\n * resolver: fluentValidationResolver(validator)\n * });\n */\nexport function fluentValidationResolver(\n validator: Validator,\n): Resolver {\n return async (values, _context, options) => {\n const validationResult = validator.validate(values);\n const isValid = Object.keys(validationResult).length === 0;\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return isValid\n ? {\n values: values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validationResult,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n\nexport function fluentAsyncValidationResolver<\n TFieldValues extends FieldValues,\n TValidator extends AsyncValidator,\n>(validator: TValidator): Resolver {\n return async (values, _context, options) => {\n const validationResult = await validator.validateAsync(values);\n const isValid = Object.keys(validationResult).length === 0;\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return isValid\n ? {\n values: values,\n errors: {},\n }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validationResult,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n"],"names":["traverseObject","object","errors","parentIndices","_loop","currentIndex","concat","key","currentValue","Array","isArray","forEach","item","index","join","type","message","parseErrorSchema","validationErrors","validateAllFieldCriteria","validator","values","_context","options","Promise","resolve","validateAsync","then","validationResult","isValid","Object","keys","length","shouldUseNativeValidation","validateFieldsNatively","toNestErrors","e","reject","validate"],"mappings":"4UAQA,SAASA,EACPC,EACAC,EACAC,YAAAA,IAAAA,EAAqC,IAAE,IAAAC,EAAAA,WAGrC,IAAMC,EAAY,GAAAC,OAAOH,EAAa,CAAEI,IAClCC,EAAeP,EAAOM,GAExBE,MAAMC,QAAQF,GAChBA,EAAaG,QAAQ,SAACC,EAAWC,GAC/Bb,EAAeY,EAAMV,EAAM,GAAAI,OAAMD,EAAcQ,CAAAA,IACjD,GACiC,iBAAjBL,GAA8C,OAAjBA,EAC7CR,EAAeQ,EAAcN,EAAQG,GACJ,iBAAjBG,IAChBN,EAAOG,EAAaS,KAAK,MAAQ,CAC/BC,KAAM,aACNC,QAASR,GAGf,EAhBA,IAAK,IAAMD,KAAON,EAAMG,GAiB1B,CAEA,SAASa,EACPC,EACAC,GAMA,IAAMjB,EAAqC,CAAE,EAG7C,OAFAF,EAAekB,EAAkBhB,GAE1BA,CACT,0CAsDEkB,GACA,OAAA,SAAcC,EAAQC,EAAUC,OAAWC,OAAAA,QAAAC,QACVL,EAAUM,cAAcL,IAAOM,KAAxDC,SAAAA,GACN,IAAMC,EAAmD,IAAzCC,OAAOC,KAAKH,GAAkBI,OAI9C,OAFAT,EAAQU,2BAA6BC,EAAsBA,uBAAC,GAAIX,GAEzDM,EACH,CACER,OAAQA,EACRnB,OAAQ,CAAA,GAEV,CACEmB,OAAQ,CAAA,EACRnB,OAAQiC,EAAAA,aACNlB,EACEW,GAIFL,GAEF,EACR,CAAC,MAAAa,GAAA,OAAAZ,QAAAa,OAAAD,EACH,CAAA,CAAA,sCAtDEhB,GAEA,gBAAcC,EAAQC,EAAUC,OAC9B,IAAMK,EAAmBR,EAAUkB,SAASjB,GACtCQ,EAAmD,IAAzCC,OAAOC,KAAKH,GAAkBI,OAI9C,OAFAT,EAAQU,2BAA6BC,EAAsBA,uBAAC,GAAIX,GAEhEC,QAAAC,QAAOI,EACH,CACER,OAAQA,EACRnB,OAAQ,CAAA,GAEV,CACEmB,OAAQ,CAAA,EACRnB,OAAQiC,EAAYA,aAClBlB,EACEW,GAIFL,IAGV,CAAC,MAAAa,GAAAZ,OAAAA,QAAAa,OAAAD,IACH"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/index.d.ts b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f27a0c3fdd40f45e2f99a4ccdd16d382a323469 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/dist/index.d.ts @@ -0,0 +1 @@ +export * from './fluentvalidation-ts'; diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/package.json b/node_modules/@hookform/resolvers/fluentvalidation-ts/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6acab914e9813df6e68f3b4a3633ebd4d5fb2d99 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/package.json @@ -0,0 +1,18 @@ +{ + "name": "@hookform/resolvers/fluentvalidation-ts", + "amdName": "hookformResolversfluentvalidation-ts", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: fluentvalidation-ts", + "main": "dist/fluentvalidation-ts.js", + "module": "dist/fluentvalidation-ts.module.js", + "umd:main": "dist/fluentvalidation-ts.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0", + "fluentvalidation-ts": "^3.0.0" + } +} diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5b9ed768298805a75e9207874a9a3a846890174f --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,88 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { Validator } from 'fluentvalidation-ts'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { fluentValidationResolver } from '../fluentvalidation-ts'; + +const USERNAME_REQUIRED_MESSAGE = 'username field is required'; +const PASSWORD_REQUIRED_MESSAGE = 'password field is required'; + +type FormData = { + username: string; + password: string; +}; + +class FormDataValidator extends Validator { + constructor() { + super(); + + this.ruleFor('username').notEmpty().withMessage(USERNAME_REQUIRED_MESSAGE); + this.ruleFor('password').notEmpty().withMessage(PASSWORD_REQUIRED_MESSAGE); + } +} + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: fluentValidationResolver(new FormDataValidator()), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with fluentvalidation-ts", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..48dbf356ed0409df5b15fd097d13aaf95810880c --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/Form.tsx @@ -0,0 +1,63 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { Validator } from 'fluentvalidation-ts'; +import React from 'react'; +import { SubmitHandler, useForm } from 'react-hook-form'; +import { fluentValidationResolver } from '../fluentvalidation-ts'; + +type FormData = { + username: string; + password: string; +}; + +class FormDataValidator extends Validator { + constructor() { + super(); + + this.ruleFor('username') + .notEmpty() + .withMessage('username is a required field'); + this.ruleFor('password') + .notEmpty() + .withMessage('password is a required field'); + } +} + +interface Props { + onSubmit: SubmitHandler; +} + +function TestComponent({ onSubmit }: Props) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: fluentValidationResolver(new FormDataValidator()), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with Yup and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect(screen.getByText(/username is a required field/i)).toBeInTheDocument(); + expect(screen.getByText(/password is a required field/i)).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..03953e23c5e58083507a10d81ccb0fab6ddbf7e2 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,121 @@ +import { Validator } from 'fluentvalidation-ts'; +import { Field, InternalFieldName } from 'react-hook-form'; + +const beNumeric = (value: string | number | undefined) => !isNaN(Number(value)); + +export type Schema = { + username: string; + password: string; + repeatPassword: string; + accessToken?: string; + birthYear?: number; + email?: string; + tags?: string[]; + enabled?: boolean; + like?: { + id: number; + name: string; + }[]; +}; + +export type SchemaWithWhen = { + name: string; + value: string; +}; + +export class SchemaValidator extends Validator { + constructor() { + super(); + + this.ruleFor('username') + .notEmpty() + .matches(/^\w+$/) + .minLength(3) + .maxLength(30); + + this.ruleFor('password') + .notEmpty() + .matches(/.*[A-Z].*/) + .withMessage('One uppercase character') + .matches(/.*[a-z].*/) + .withMessage('One lowercase character') + .matches(/.*\d.*/) + .withMessage('One number') + .matches(new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*')) + .withMessage('One special character') + .minLength(8) + .withMessage('Must be at least 8 characters in length'); + + this.ruleFor('repeatPassword') + .notEmpty() + .must((repeatPassword, data) => repeatPassword === data.password); + + this.ruleFor('accessToken'); + this.ruleFor('birthYear') + .must(beNumeric) + .inclusiveBetween(1900, 2013) + .when((birthYear) => birthYear != undefined); + + this.ruleFor('email').emailAddress(); + this.ruleFor('tags'); + this.ruleFor('enabled'); + + this.ruleForEach('like').setValidator(() => new LikeValidator()); + } +} + +export class LikeValidator extends Validator<{ + id: number; + name: string; +}> { + constructor() { + super(); + + this.ruleFor('id').notNull(); + this.ruleFor('name').notEmpty().length(4, 4); + } +} + +export const validData = { + username: 'Doe', + password: 'Password123_', + repeatPassword: 'Password123_', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + accesstoken: 'accesstoken', + like: [ + { + id: 1, + name: 'name', + }, + ], +} as Schema; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: [{ id: 'z' }], + // Must be set to "unknown", otherwise typescript knows that it is invalid +} as unknown as Required; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/__snapshots__/fluentvalidation-ts.ts.snap b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/__snapshots__/fluentvalidation-ts.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..f2ef0e42bcdfd44935a7283b4cb21ed80f72e1fc --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/__snapshots__/fluentvalidation-ts.ts.snap @@ -0,0 +1,129 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`fluentValidationResolver > should return a single error from fluentValidationResolver when validation fails 1`] = ` +{ + "errors": { + "birthYear": { + "message": "Value is not valid", + "ref": undefined, + "type": "validation", + }, + "email": { + "message": "Not a valid email address", + "ref": { + "name": "email", + }, + "type": "validation", + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "validation", + }, + "repeatPassword": { + "message": "Value is not valid", + "ref": undefined, + "type": "validation", + }, + }, + "values": {}, +} +`; + +exports[`fluentValidationResolver > should return a single error from fluentValidationResolver with \`mode: sync\` when validation fails 1`] = ` +{ + "errors": { + "birthYear": { + "message": "Value is not valid", + "ref": undefined, + "type": "validation", + }, + "email": { + "message": "Not a valid email address", + "ref": { + "name": "email", + }, + "type": "validation", + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "validation", + }, + "repeatPassword": { + "message": "Value is not valid", + "ref": undefined, + "type": "validation", + }, + }, + "values": {}, +} +`; + +exports[`fluentValidationResolver > should return all the errors from fluentValidationResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = ` +{ + "errors": { + "birthYear": { + "message": "Value is not valid", + "ref": undefined, + "type": "validation", + }, + "email": { + "message": "Not a valid email address", + "ref": { + "name": "email", + }, + "type": "validation", + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "validation", + }, + "repeatPassword": { + "message": "Value is not valid", + "ref": undefined, + "type": "validation", + }, + }, + "values": {}, +} +`; + +exports[`fluentValidationResolver > should return all the errors from fluentValidationResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = ` +{ + "errors": { + "birthYear": { + "message": "Value is not valid", + "ref": undefined, + "type": "validation", + }, + "email": { + "message": "Not a valid email address", + "ref": { + "name": "email", + }, + "type": "validation", + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "validation", + }, + "repeatPassword": { + "message": "Value is not valid", + "ref": undefined, + "type": "validation", + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/fluentvalidation-ts.ts b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/fluentvalidation-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..52f611d18d1276f24fd251dc79339f8255d0d387 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/__tests__/fluentvalidation-ts.ts @@ -0,0 +1,113 @@ +/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */ +import { fluentValidationResolver } from '..'; +import { + SchemaValidator, + fields, + invalidData, + validData, +} from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +const validator = new SchemaValidator(); + +describe('fluentValidationResolver', () => { + it('should return values from fluentValidationResolver when validation pass', async () => { + const validatorSpy = vi.spyOn(validator, 'validate'); + + const result = await fluentValidationResolver(validator)( + validData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(validatorSpy).toHaveBeenCalledTimes(1); + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return values from fluentValidationResolver with `mode: sync` when validation pass', async () => { + const validatorSpy = vi.spyOn(validator, 'validate'); + + const result = await fluentValidationResolver(validator)( + validData, + undefined, + { fields, shouldUseNativeValidation }, + ); + + expect(validatorSpy).toHaveBeenCalledTimes(1); + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return a single error from fluentValidationResolver when validation fails', async () => { + const result = await fluentValidationResolver(validator)( + invalidData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return a single error from fluentValidationResolver with `mode: sync` when validation fails', async () => { + const validateSpy = vi.spyOn(validator, 'validate'); + + const result = await fluentValidationResolver(validator)( + invalidData, + undefined, + { fields, shouldUseNativeValidation }, + ); + + expect(validateSpy).toHaveBeenCalledTimes(1); + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from fluentValidationResolver when validation fails with `validateAllFieldCriteria` set to true', async () => { + const result = await fluentValidationResolver(validator)( + invalidData, + undefined, + { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from fluentValidationResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => { + const result = await fluentValidationResolver(validator)( + invalidData, + undefined, + { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return values from fluentValidationResolver when validation pass & raw=true', async () => { + const schemaSpy = vi.spyOn(validator, 'validate'); + + const result = await fluentValidationResolver(validator)( + validData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(schemaSpy).toHaveBeenCalledTimes(1); + expect(result).toEqual({ errors: {}, values: validData }); + }); +}); diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/src/fluentvalidation-ts.ts b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/fluentvalidation-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcb1d18ca9bd3c55feff7b33ee4ad403ab835f69 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/fluentvalidation-ts.ts @@ -0,0 +1,123 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import { + AsyncValidator, + ValidationErrors, + Validator, +} from 'fluentvalidation-ts'; +import { FieldError, FieldValues, Resolver } from 'react-hook-form'; + +function traverseObject( + object: ValidationErrors, + errors: Record, + parentIndices: (string | number)[] = [], +) { + for (const key in object) { + const currentIndex = [...parentIndices, key]; + const currentValue = object[key]; + + if (Array.isArray(currentValue)) { + currentValue.forEach((item: any, index: number) => { + traverseObject(item, errors, [...currentIndex, index]); + }); + } else if (typeof currentValue === 'object' && currentValue !== null) { + traverseObject(currentValue, errors, currentIndex); + } else if (typeof currentValue === 'string') { + errors[currentIndex.join('.')] = { + type: 'validation', + message: currentValue, + }; + } + } +} + +function parseErrorSchema( + validationErrors: ValidationErrors, + validateAllFieldCriteria: boolean, +) { + if (validateAllFieldCriteria) { + // TODO: check this but i think its always one validation error + } + + const errors: Record = {}; + traverseObject(validationErrors, errors); + + return errors; +} + +/** + * Creates a resolver for react-hook-form using FluentValidation schema validation + * @param {Validator} validator - The FluentValidation validator to use + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * import { Validator } from 'fluentvalidation-ts'; + * + * class SchemaValidator extends Validator { + * constructor() { + * super(); + * this.ruleFor('username').notEmpty(); + * this.ruleFor('password').notEmpty(); + * } + * } + * + * const validator = new SchemaValidator(); + * + * useForm({ + * resolver: fluentValidationResolver(validator) + * }); + */ +export function fluentValidationResolver( + validator: Validator, +): Resolver { + return async (values, _context, options) => { + const validationResult = validator.validate(values); + const isValid = Object.keys(validationResult).length === 0; + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return isValid + ? { + values: values, + errors: {}, + } + : { + values: {}, + errors: toNestErrors( + parseErrorSchema( + validationResult, + !options.shouldUseNativeValidation && + options.criteriaMode === 'all', + ), + options, + ), + }; + }; +} + +export function fluentAsyncValidationResolver< + TFieldValues extends FieldValues, + TValidator extends AsyncValidator, +>(validator: TValidator): Resolver { + return async (values, _context, options) => { + const validationResult = await validator.validateAsync(values); + const isValid = Object.keys(validationResult).length === 0; + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return isValid + ? { + values: values, + errors: {}, + } + : { + values: {}, + errors: toNestErrors( + parseErrorSchema( + validationResult, + !options.shouldUseNativeValidation && + options.criteriaMode === 'all', + ), + options, + ), + }; + }; +} diff --git a/node_modules/@hookform/resolvers/fluentvalidation-ts/src/index.ts b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f27a0c3fdd40f45e2f99a4ccdd16d382a323469 --- /dev/null +++ b/node_modules/@hookform/resolvers/fluentvalidation-ts/src/index.ts @@ -0,0 +1 @@ +export * from './fluentvalidation-ts'; diff --git a/node_modules/@hookform/resolvers/io-ts/dist/arrayToPath.d.ts b/node_modules/@hookform/resolvers/io-ts/dist/arrayToPath.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af8aae9269434b199de68f36a207fe3514aea1a8 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/arrayToPath.d.ts @@ -0,0 +1,3 @@ +import * as Either from 'fp-ts/Either'; +declare const arrayToPath: (paths: Either.Either[]) => string; +export default arrayToPath; diff --git a/node_modules/@hookform/resolvers/io-ts/dist/errorsToRecord.d.ts b/node_modules/@hookform/resolvers/io-ts/dist/errorsToRecord.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..86fcae668360677507c3923a230760e1ad91e54f --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/errorsToRecord.d.ts @@ -0,0 +1,8 @@ +import { ValidationError } from 'io-ts'; +import { FieldError } from 'react-hook-form'; +export type ErrorObject = Record; +export type FieldErrorWithPath = FieldError & { + path: string; +}; +declare const errorsToRecord: (validateAllFieldCriteria: boolean) => (validationErrors: ReadonlyArray) => ErrorObject; +export default errorsToRecord; diff --git a/node_modules/@hookform/resolvers/io-ts/dist/index.d.ts b/node_modules/@hookform/resolvers/io-ts/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7069193a6597de1fe962a50de11f5096ddee8f5f --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/index.d.ts @@ -0,0 +1 @@ +export * from './io-ts'; diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.d.ts b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfebee31773c2d72e31b3d6d0d379917ee5cfca5 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.d.ts @@ -0,0 +1,10 @@ +import * as t from 'io-ts'; +import { FieldValues, Resolver } from 'react-hook-form'; +export declare function ioTsResolver(schema: t.Type, resolverOptions?: { + mode?: 'async' | 'sync'; + raw?: false; +}): Resolver; +export declare function ioTsResolver(schema: t.Type, resolverOptions: { + mode?: 'async' | 'sync'; + raw: true; +}): Resolver; diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.js b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.js new file mode 100644 index 0000000000000000000000000000000000000000..1e67e4719cccc239f864ed047cacfe9ebc9a0563 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers"),n=require("fp-ts/Either"),t=require("fp-ts/function"),r=require("fp-ts/Option"),i=require("fp-ts/ReadonlyArray"),u=require("fp-ts/ReadonlyRecord"),o=require("fp-ts/Semigroup"),a=require("io-ts");function f(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}}),n.default=e,n}var c=/*#__PURE__*/f(n),p=/*#__PURE__*/f(r),s=/*#__PURE__*/f(i),l=/*#__PURE__*/f(u),d=/*#__PURE__*/f(o);function m(){return m=Object.assign?Object.assign.bind():function(e){for(var n=1;n0?".":"")+e},function(e){return"["+e+"]"}),function(n){return""+e+n})},"")},v=["path"],g=[a.TaggedUnionType,a.UnionType,a.IntersectionType,a.ExactType,a.RefinementType],O=function(e){var n,r=t.pipe(n=e.context,s.filterMapWithIndex(function(e,t){var r=e-1,i=-1===r?void 0:n[r];return void 0===i||g.some(function(e){return i.type instanceof e})?p.none:p.some(t)}),s.map(function(e){return e.key}),s.map(function(e){return t.pipe(e,function(e){return parseInt(e,10)},c.fromPredicate(t.not(Number.isNaN),function(){return e}))}),s.toArray,y);return{message:t.pipe(e.message,c.fromNullable(e.context),c.mapLeft(t.flow(s.last,p.map(function(e){return"expected "+e.type.name+" but got "+JSON.stringify(e.actual)}),p.getOrElseW(function(){return t.absurd("Error context is missing name")}))),c.getOrElseW(t.identity)),type:t.pipe(e.context,s.last,p.map(function(e){return e.type.name}),p.getOrElse(function(){return"unknown"})),path:r}},b=function(e){return t.pipe(e,s.map(function(e){var n;return(n={})[e.path]={type:e.type,message:e.message},n}),function(e){return d.fold({concat:function(e,n){return Object.assign({},n,e)}})({},e)})},h={concat:function(e,n){var t;return m({},n,{types:m({},e.types,(t={},t[e.type]=e.message,t[n.type]=n.message,t))})}},x=function(e){return t.pipe(l.fromFoldableMap(h,s.Foldable)(e,function(e){return[e.path,e]}),l.map(function(e){return function(e,n){if(null==e)return{};var t={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==n.indexOf(r))continue;t[r]=e[r]}return t}(e,v)}))};exports.ioTsResolver=function(n){return function(r,i,u){return t.pipe(r,n.decode,c.mapLeft((o=!u.shouldUseNativeValidation&&"all"===u.criteriaMode,function(e){var n=o?x:b;return t.pipe(e,s.map(O),n)})),c.mapLeft(function(n){return e.toNestErrors(n,u)}),c.fold(function(e){return{values:{},errors:e}},function(n){return u.shouldUseNativeValidation&&e.validateFieldsNatively({},u),{values:n,errors:{}}}));var o}}; +//# sourceMappingURL=io-ts.js.map diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.js.map b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9e234a617b638c4a59dff8098092c61fc80e0dd1 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"io-ts.js","sources":["../src/arrayToPath.ts","../src/errorsToRecord.ts","../src/io-ts.ts"],"sourcesContent":["import * as Either from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\n\nconst arrayToPath = (paths: Either.Either[]): string =>\n paths.reduce(\n (previous, path, index) =>\n pipe(\n path,\n Either.fold(\n (key) => `${index > 0 ? '.' : ''}${key}`,\n (key) => `[${key}]`,\n ),\n (path) => `${previous}${path}`,\n ),\n '',\n );\n\nexport default arrayToPath;\n","import * as Either from 'fp-ts/Either';\nimport * as Option from 'fp-ts/Option';\nimport * as ReadonlyArray from 'fp-ts/ReadonlyArray';\nimport * as ReadonlyRecord from 'fp-ts/ReadonlyRecord';\nimport * as SemiGroup from 'fp-ts/Semigroup';\nimport { absurd, flow, identity, not, pipe } from 'fp-ts/function';\nimport * as t from 'io-ts';\nimport {\n ExactType,\n IntersectionType,\n RefinementType,\n TaggedUnionType,\n UnionType,\n ValidationError,\n} from 'io-ts';\nimport { FieldError } from 'react-hook-form';\nimport arrayToPath from './arrayToPath';\n\nexport type ErrorObject = Record;\nexport type FieldErrorWithPath = FieldError & { path: string };\n\nconst INSTANCE_TYPES_TO_FILTER = [\n TaggedUnionType,\n UnionType,\n IntersectionType,\n ExactType,\n RefinementType,\n];\nconst formatErrorPath = (context: t.Context): string =>\n pipe(\n context,\n ReadonlyArray.filterMapWithIndex((index, contextEntry) => {\n const previousIndex = index - 1;\n const previousContextEntry =\n previousIndex === -1 ? undefined : context[previousIndex];\n const shouldBeFiltered =\n previousContextEntry === undefined ||\n INSTANCE_TYPES_TO_FILTER.some(\n (type) => previousContextEntry.type instanceof type,\n );\n\n return shouldBeFiltered ? Option.none : Option.some(contextEntry);\n }),\n ReadonlyArray.map(({ key }) => key),\n ReadonlyArray.map((key) =>\n pipe(\n key,\n (k) => parseInt(k, 10),\n Either.fromPredicate(not(Number.isNaN), () => key),\n ),\n ),\n ReadonlyArray.toArray,\n arrayToPath,\n );\n\nconst formatError = (e: t.ValidationError): FieldErrorWithPath => {\n const path = formatErrorPath(e.context);\n\n const message = pipe(\n e.message,\n Either.fromNullable(e.context),\n Either.mapLeft(\n flow(\n ReadonlyArray.last,\n Option.map(\n (contextEntry) =>\n `expected ${contextEntry.type.name} but got ${JSON.stringify(\n contextEntry.actual,\n )}`,\n ),\n Option.getOrElseW(() =>\n absurd('Error context is missing name' as never),\n ),\n ),\n ),\n Either.getOrElseW(identity),\n );\n\n const type = pipe(\n e.context,\n ReadonlyArray.last,\n Option.map((contextEntry) => contextEntry.type.name),\n Option.getOrElse(() => 'unknown'),\n );\n\n return { message, type, path };\n};\n\n// this is almost the same function like Semigroup.getObjectSemigroup but reversed\n// in order to get the first error\nconst getObjectSemigroup = <\n A extends Record = never,\n>(): SemiGroup.Semigroup => ({\n concat: (first, second) => Object.assign({}, second, first),\n});\n\nconst concatToSingleError = (\n errors: ReadonlyArray,\n): ErrorObject =>\n pipe(\n errors,\n ReadonlyArray.map((error) => ({\n [error.path]: {\n type: error.type,\n message: error.message,\n },\n })),\n (errors) => SemiGroup.fold(getObjectSemigroup())({}, errors),\n );\n\nconst appendSeveralErrors: SemiGroup.Semigroup = {\n concat: (a, b) => ({\n ...b,\n types: { ...a.types, [a.type]: a.message, [b.type]: b.message },\n }),\n};\n\nconst concatToMultipleErrors = (\n errors: ReadonlyArray,\n): ErrorObject =>\n pipe(\n ReadonlyRecord.fromFoldableMap(appendSeveralErrors, ReadonlyArray.Foldable)(\n errors,\n (error) => [error.path, error],\n ),\n ReadonlyRecord.map((errorWithPath) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { path, ...error } = errorWithPath;\n\n return error;\n }),\n );\n\nconst errorsToRecord =\n (validateAllFieldCriteria: boolean) =>\n (validationErrors: ReadonlyArray): ErrorObject => {\n const concat = validateAllFieldCriteria\n ? concatToMultipleErrors\n : concatToSingleError;\n\n return pipe(validationErrors, ReadonlyArray.map(formatError), concat);\n };\n\nexport default errorsToRecord;\n","import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport * as Either from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\nimport * as t from 'io-ts';\nimport {\n FieldErrors,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n} from 'react-hook-form';\nimport errorsToRecord, { ErrorObject } from './errorsToRecord';\n\nexport function ioTsResolver(\n schema: t.Type,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver;\n\nexport function ioTsResolver(\n schema: t.Type,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using io-ts schema validation\n * @param {t.Type} schema - The io-ts schema to validate against\n * @param {Object} options - Additional resolver configuration\n * @param {string} [options.mode='async'] - Validation mode\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = t.type({\n * name: t.string,\n * age: t.number\n * });\n *\n * useForm({\n * resolver: ioTsResolver(schema)\n * });\n */\nexport function ioTsResolver(\n schema: t.Type,\n): Resolver {\n return (values, _context, options) =>\n pipe(\n values,\n schema.decode,\n Either.mapLeft(\n errorsToRecord(\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n ),\n ),\n Either.mapLeft((errors: ErrorObject) =>\n toNestErrors(errors, options),\n ),\n Either.fold<\n FieldErrors,\n Output,\n ResolverError | ResolverSuccess\n >(\n (errors) => ({\n values: {},\n errors,\n }),\n (values) => {\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n values,\n errors: {},\n };\n },\n ),\n );\n}\n"],"names":["arrayToPath","paths","reduce","previous","path","index","pipe","Either","fold","key","_excluded","INSTANCE_TYPES_TO_FILTER","TaggedUnionType","UnionType","IntersectionType","ExactType","RefinementType","formatError","e","context","ReadonlyArray","filterMapWithIndex","contextEntry","previousIndex","previousContextEntry","undefined","some","type","Option","none","map","_ref","k","parseInt","fromPredicate","not","Number","isNaN","toArray","message","fromNullable","mapLeft","flow","last","name","JSON","stringify","actual","getOrElseW","absurd","identity","getOrElse","concatToSingleError","errors","error","_ref2","SemiGroup","concat","first","second","Object","assign","appendSeveralErrors","a","b","_extends2","_extends","types","concatToMultipleErrors","ReadonlyRecord","fromFoldableMap","Foldable","errorWithPath","_objectWithoutPropertiesLoose","schema","values","_context","options","decode","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","validationErrors","toNestErrors","validateFieldsNatively"],"mappings":"szBAGA,IAAMA,EAAc,SAACC,UACnBA,EAAMC,OACJ,SAACC,EAAUC,EAAMC,GAAK,OACpBC,EAAAA,KACEF,EACAG,EAAOC,KACL,SAACC,GAAG,OAAQJ,EAAQ,EAAI,IAAM,IAAKI,CAAG,EACtC,SAACA,GAAYA,MAAAA,IAAAA,QAEf,SAACL,YAAYD,EAAWC,CAAI,EAC7B,EACH,GACD,ECfHM,EAAA,CAAA,QAqBMC,EAA2B,CAC/BC,EAAeA,gBACfC,EAASA,UACTC,mBACAC,EAAAA,UACAC,EAAAA,gBA6BIC,EAAc,SAACC,GACnB,IA5BuBC,EA4BjBf,EA3BNE,EAAAA,KADuBa,EA4BMD,EAAEC,QAzB7BC,EAAcC,mBAAmB,SAAChB,EAAOiB,GACvC,IAAMC,EAAgBlB,EAAQ,EACxBmB,GACe,IAAnBD,OAAuBE,EAAYN,EAAQI,GAO7C,YAL2BE,IAAzBD,GACAb,EAAyBe,KACvB,SAACC,GAAI,OAAKH,EAAqBG,gBAAgBA,CAAI,GAG7BC,EAAOC,KAAOD,EAAOF,KAAKJ,EACtD,GACAF,EAAcU,IAAI,SAAAC,GAAa,OAAPA,EAAHtB,GAAa,GAClCW,EAAcU,IAAI,SAACrB,GAAG,OACpBH,OACEG,EACA,SAACuB,GAAM,OAAAC,SAASD,EAAG,GAAG,EACtBzB,EAAO2B,cAAcC,EAAAA,IAAYC,OAAOC,OAAQ,kBAAM5B,CAAG,GAC1D,GAEHW,EAAckB,QACdtC,GAiCF,MAAO,CAAEuC,QA3BOjC,OACdY,EAAEqB,QACFhC,EAAOiC,aAAatB,EAAEC,SACtBZ,EAAOkC,QACLC,EAAAA,KACEtB,EAAcuB,KACdf,EAAOE,IACL,SAACR,GACaA,MAAAA,YAAAA,EAAaK,KAAKiB,KAAI,YAAYC,KAAKC,UACjDxB,EAAayB,OACd,GAELnB,EAAOoB,WAAW,WAAA,OAChBC,EAAMA,OAAS,gCAAyC,KAI9D1C,EAAOyC,WAAWE,EAAQA,WAUVvB,KAPLrB,EAAIA,KACfY,EAAEC,QACFC,EAAcuB,KACdf,EAAOE,IAAI,SAACR,UAAiBA,EAAaK,KAAKiB,IAAI,GACnDhB,EAAOuB,UAAU,iBAAM,SAAS,IAGV/C,KAAAA,EAC1B,EAUMgD,EAAsB,SAC1BC,GAEA,OAAA/C,OACE+C,EACAjC,EAAcU,IAAI,SAACwB,GAAKC,IAAAA,SAAAA,EAAA,CAAA,GACrBD,EAAMlD,MAAO,CACZuB,KAAM2B,EAAM3B,KACZY,QAASe,EAAMf,SAChBgB,CAAA,GAEH,SAACF,GAAM,OAAKG,EAAUhD,KAfM,CAC9BiD,OAAQ,SAACC,EAAOC,GAAM,OAAKC,OAAOC,OAAO,GAAIF,EAAQD,EAAM,GAc7CF,CAAkD,CAAA,EAAIH,EAAO,EAC1E,EAEGS,EAA+D,CACnEL,OAAQ,SAACM,EAAGC,GAACC,IAAAA,SAAAC,EAAA,CAAA,EACRF,EACHG,CAAAA,MAAKD,EAAA,CAAA,EAAOH,EAAEI,OAAKF,EAAAA,GAAAA,EAAGF,EAAEpC,MAAOoC,EAAExB,QAAO0B,EAAGD,EAAErC,MAAOqC,EAAEzB,QAAO0B,QAI3DG,EAAyB,SAC7Bf,GAEA,OAAA/C,EAAIA,KACF+D,EAAeC,gBAAgBR,EAAqB1C,EAAcmD,SAAlEF,CACEhB,EACA,SAACC,GAAK,MAAK,CAACA,EAAMlD,KAAMkD,EAAM,GAEhCe,EAAevC,IAAI,SAAC0C,GAIlB,kJAFsBC,CAAKD,EAAa9D,EAG1C,GACD,uBCtFa,SACdgE,GAEA,OAAO,SAACC,EAAQC,EAAUC,GAAO,OAC/BvE,EAAIA,KACFqE,EACAD,EAAOI,OACPvE,EAAOkC,SDkFVsC,GChFQF,EAAQG,2BAAsD,QAAzBH,EAAQI,aDiFtD,SAACC,GACC,IAAMzB,EAASsB,EACXX,EACAhB,EAEJ,OAAO9C,EAAIA,KAAC4E,EAAkB9D,EAAcU,IAAIb,GAAcwC,EAChE,ICpFIlD,EAAOkC,QAAQ,SAACY,GAAmB,OACjC8B,EAAYA,aAAQ9B,EAAQwB,EAAQ,GAEtCtE,EAAOC,KAKL,SAAC6C,GAAY,MAAA,CACXsB,OAAQ,CAAE,EACVtB,OAAAA,EACD,EACD,SAACsB,GAIC,OAHAE,EAAQG,2BACNI,EAAsBA,uBAAC,GAAIP,GAEtB,CACLF,OAAAA,EACAtB,OAAQ,CAAA,EAEZ,IDyDN,IAAC0B,CCvDE,CACL"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.mjs b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c6873f5393fb95e767b94a4f33fa09c561f14ad5 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as n,validateFieldsNatively as t}from"@hookform/resolvers";import*as r from"fp-ts/Either";import{pipe as e,flow as o,absurd as u,identity as a,not as i}from"fp-ts/function";import*as f from"fp-ts/Option";import*as s from"fp-ts/ReadonlyArray";import*as c from"fp-ts/ReadonlyRecord";import*as p from"fp-ts/Semigroup";import{TaggedUnionType as m,UnionType as l,IntersectionType as d,ExactType as v,RefinementType as y}from"io-ts";function g(){return g=Object.assign?Object.assign.bind():function(n){for(var t=1;t0?".":"")+n},function(n){return"["+n+"]"}),function(t){return""+n+t})},"")},O=["path"],b=[m,l,d,v,y],x=function(n){var t,c=e(t=n.context,s.filterMapWithIndex(function(n,r){var e=n-1,o=-1===e?void 0:t[e];return void 0===o||b.some(function(n){return o.type instanceof n})?f.none:f.some(r)}),s.map(function(n){return n.key}),s.map(function(n){return e(n,function(n){return parseInt(n,10)},r.fromPredicate(i(Number.isNaN),function(){return n}))}),s.toArray,h);return{message:e(n.message,r.fromNullable(n.context),r.mapLeft(o(s.last,f.map(function(n){return"expected "+n.type.name+" but got "+JSON.stringify(n.actual)}),f.getOrElseW(function(){return u("Error context is missing name")}))),r.getOrElseW(a)),type:e(n.context,s.last,f.map(function(n){return n.type.name}),f.getOrElse(function(){return"unknown"})),path:c}},N=function(n){return e(n,s.map(function(n){var t;return(t={})[n.path]={type:n.type,message:n.message},t}),function(n){return p.fold({concat:function(n,t){return Object.assign({},t,n)}})({},n)})},E={concat:function(n,t){var r;return g({},t,{types:g({},n.types,(r={},r[n.type]=n.message,r[t.type]=t.message,r))})}},j=function(n){return e(c.fromFoldableMap(E,s.Foldable)(n,function(n){return[n.path,n]}),c.map(function(n){return function(n,t){if(null==n)return{};var r={};for(var e in n)if({}.hasOwnProperty.call(n,e)){if(-1!==t.indexOf(e))continue;r[e]=n[e]}return r}(n,O)}))};function k(o){return function(u,a,i){return e(u,o.decode,r.mapLeft((f=!i.shouldUseNativeValidation&&"all"===i.criteriaMode,function(n){var t=f?j:N;return e(n,s.map(x),t)})),r.mapLeft(function(t){return n(t,i)}),r.fold(function(n){return{values:{},errors:n}},function(n){return i.shouldUseNativeValidation&&t({},i),{values:n,errors:{}}}));var f}}export{k as ioTsResolver}; +//# sourceMappingURL=io-ts.module.js.map diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.modern.mjs b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c6d3fb05451775770edb014747aaa7039d40e39f --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.modern.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as t}from"@hookform/resolvers";import*as r from"fp-ts/Either";import{pipe as o,flow as a,absurd as n,identity as s,not as p}from"fp-ts/function";import*as i from"fp-ts/Option";import*as m from"fp-ts/ReadonlyArray";import*as f from"fp-ts/ReadonlyRecord";import*as l from"fp-ts/Semigroup";import{TaggedUnionType as c,UnionType as u,IntersectionType as d,ExactType as y,RefinementType as g}from"io-ts";function v(){return v=Object.assign?Object.assign.bind():function(e){for(var t=1;te.reduce((e,t,a)=>o(t,r.fold(e=>`${a>0?".":""}${e}`,e=>`[${e}]`),t=>`${e}${t}`),""),O=["path"],b=[c,u,d,y,g],x=e=>{const t=o(f=e.context,m.filterMapWithIndex((e,t)=>{const r=e-1,o=-1===r?void 0:f[r];return void 0===o||b.some(e=>o.type instanceof e)?i.none:i.some(t)}),m.map(({key:e})=>e),m.map(e=>o(e,e=>parseInt(e,10),r.fromPredicate(p(Number.isNaN),()=>e))),m.toArray,h);var f;return{message:o(e.message,r.fromNullable(e.context),r.mapLeft(a(m.last,i.map(e=>`expected ${e.type.name} but got ${JSON.stringify(e.actual)}`),i.getOrElseW(()=>n("Error context is missing name")))),r.getOrElseW(s)),type:o(e.context,m.last,i.map(e=>e.type.name),i.getOrElse(()=>"unknown")),path:t}},N=e=>o(e,m.map(e=>({[e.path]:{type:e.type,message:e.message}})),e=>l.fold({concat:(e,t)=>Object.assign({},t,e)})({},e)),$={concat:(e,t)=>v({},t,{types:v({},e.types,{[e.type]:e.message,[t.type]:t.message})})},E=e=>o(f.fromFoldableMap($,m.Foldable)(e,e=>[e.path,e]),f.map(e=>function(e,t){if(null==e)return{};var r={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;r[o]=e[o]}return r}(e,O)));function j(a){return(n,s,p)=>{return o(n,a.decode,r.mapLeft((i=!p.shouldUseNativeValidation&&"all"===p.criteriaMode,e=>{const t=i?E:N;return o(e,m.map(x),t)})),r.mapLeft(t=>e(t,p)),r.fold(e=>({values:{},errors:e}),e=>(p.shouldUseNativeValidation&&t({},p),{values:e,errors:{}})));var i}}export{j as ioTsResolver}; +//# sourceMappingURL=io-ts.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.modern.mjs.map b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..aafb49f59f0804934554a3a9e0cc0227a780d27e --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"io-ts.modern.mjs","sources":["../src/arrayToPath.ts","../src/errorsToRecord.ts","../src/io-ts.ts"],"sourcesContent":["import * as Either from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\n\nconst arrayToPath = (paths: Either.Either[]): string =>\n paths.reduce(\n (previous, path, index) =>\n pipe(\n path,\n Either.fold(\n (key) => `${index > 0 ? '.' : ''}${key}`,\n (key) => `[${key}]`,\n ),\n (path) => `${previous}${path}`,\n ),\n '',\n );\n\nexport default arrayToPath;\n","import * as Either from 'fp-ts/Either';\nimport * as Option from 'fp-ts/Option';\nimport * as ReadonlyArray from 'fp-ts/ReadonlyArray';\nimport * as ReadonlyRecord from 'fp-ts/ReadonlyRecord';\nimport * as SemiGroup from 'fp-ts/Semigroup';\nimport { absurd, flow, identity, not, pipe } from 'fp-ts/function';\nimport * as t from 'io-ts';\nimport {\n ExactType,\n IntersectionType,\n RefinementType,\n TaggedUnionType,\n UnionType,\n ValidationError,\n} from 'io-ts';\nimport { FieldError } from 'react-hook-form';\nimport arrayToPath from './arrayToPath';\n\nexport type ErrorObject = Record;\nexport type FieldErrorWithPath = FieldError & { path: string };\n\nconst INSTANCE_TYPES_TO_FILTER = [\n TaggedUnionType,\n UnionType,\n IntersectionType,\n ExactType,\n RefinementType,\n];\nconst formatErrorPath = (context: t.Context): string =>\n pipe(\n context,\n ReadonlyArray.filterMapWithIndex((index, contextEntry) => {\n const previousIndex = index - 1;\n const previousContextEntry =\n previousIndex === -1 ? undefined : context[previousIndex];\n const shouldBeFiltered =\n previousContextEntry === undefined ||\n INSTANCE_TYPES_TO_FILTER.some(\n (type) => previousContextEntry.type instanceof type,\n );\n\n return shouldBeFiltered ? Option.none : Option.some(contextEntry);\n }),\n ReadonlyArray.map(({ key }) => key),\n ReadonlyArray.map((key) =>\n pipe(\n key,\n (k) => parseInt(k, 10),\n Either.fromPredicate(not(Number.isNaN), () => key),\n ),\n ),\n ReadonlyArray.toArray,\n arrayToPath,\n );\n\nconst formatError = (e: t.ValidationError): FieldErrorWithPath => {\n const path = formatErrorPath(e.context);\n\n const message = pipe(\n e.message,\n Either.fromNullable(e.context),\n Either.mapLeft(\n flow(\n ReadonlyArray.last,\n Option.map(\n (contextEntry) =>\n `expected ${contextEntry.type.name} but got ${JSON.stringify(\n contextEntry.actual,\n )}`,\n ),\n Option.getOrElseW(() =>\n absurd('Error context is missing name' as never),\n ),\n ),\n ),\n Either.getOrElseW(identity),\n );\n\n const type = pipe(\n e.context,\n ReadonlyArray.last,\n Option.map((contextEntry) => contextEntry.type.name),\n Option.getOrElse(() => 'unknown'),\n );\n\n return { message, type, path };\n};\n\n// this is almost the same function like Semigroup.getObjectSemigroup but reversed\n// in order to get the first error\nconst getObjectSemigroup = <\n A extends Record = never,\n>(): SemiGroup.Semigroup => ({\n concat: (first, second) => Object.assign({}, second, first),\n});\n\nconst concatToSingleError = (\n errors: ReadonlyArray,\n): ErrorObject =>\n pipe(\n errors,\n ReadonlyArray.map((error) => ({\n [error.path]: {\n type: error.type,\n message: error.message,\n },\n })),\n (errors) => SemiGroup.fold(getObjectSemigroup())({}, errors),\n );\n\nconst appendSeveralErrors: SemiGroup.Semigroup = {\n concat: (a, b) => ({\n ...b,\n types: { ...a.types, [a.type]: a.message, [b.type]: b.message },\n }),\n};\n\nconst concatToMultipleErrors = (\n errors: ReadonlyArray,\n): ErrorObject =>\n pipe(\n ReadonlyRecord.fromFoldableMap(appendSeveralErrors, ReadonlyArray.Foldable)(\n errors,\n (error) => [error.path, error],\n ),\n ReadonlyRecord.map((errorWithPath) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { path, ...error } = errorWithPath;\n\n return error;\n }),\n );\n\nconst errorsToRecord =\n (validateAllFieldCriteria: boolean) =>\n (validationErrors: ReadonlyArray): ErrorObject => {\n const concat = validateAllFieldCriteria\n ? concatToMultipleErrors\n : concatToSingleError;\n\n return pipe(validationErrors, ReadonlyArray.map(formatError), concat);\n };\n\nexport default errorsToRecord;\n","import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport * as Either from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\nimport * as t from 'io-ts';\nimport {\n FieldErrors,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n} from 'react-hook-form';\nimport errorsToRecord, { ErrorObject } from './errorsToRecord';\n\nexport function ioTsResolver(\n schema: t.Type,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver;\n\nexport function ioTsResolver(\n schema: t.Type,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using io-ts schema validation\n * @param {t.Type} schema - The io-ts schema to validate against\n * @param {Object} options - Additional resolver configuration\n * @param {string} [options.mode='async'] - Validation mode\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = t.type({\n * name: t.string,\n * age: t.number\n * });\n *\n * useForm({\n * resolver: ioTsResolver(schema)\n * });\n */\nexport function ioTsResolver(\n schema: t.Type,\n): Resolver {\n return (values, _context, options) =>\n pipe(\n values,\n schema.decode,\n Either.mapLeft(\n errorsToRecord(\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n ),\n ),\n Either.mapLeft((errors: ErrorObject) =>\n toNestErrors(errors, options),\n ),\n Either.fold<\n FieldErrors,\n Output,\n ResolverError | ResolverSuccess\n >(\n (errors) => ({\n values: {},\n errors,\n }),\n (values) => {\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n values,\n errors: {},\n };\n },\n ),\n );\n}\n"],"names":["arrayToPath","paths","reduce","previous","path","index","pipe","Either","fold","key","_excluded","INSTANCE_TYPES_TO_FILTER","TaggedUnionType","UnionType","IntersectionType","ExactType","RefinementType","formatError","e","context","ReadonlyArray","filterMapWithIndex","contextEntry","previousIndex","previousContextEntry","undefined","some","type","Option","none","map","k","parseInt","fromPredicate","not","Number","isNaN","toArray","message","fromNullable","mapLeft","flow","last","name","JSON","stringify","actual","getOrElseW","absurd","identity","getOrElse","concatToSingleError","errors","error","SemiGroup","getObjectSemigroup","concat","first","second","Object","assign","appendSeveralErrors","a","b","_extends","types","concatToMultipleErrors","ReadonlyRecord","fromFoldableMap","Foldable","errorWithPath","_objectWithoutPropertiesLoose","ioTsResolver","schema","values","_context","options","decode","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","validationErrors","toNestErrors","validateFieldsNatively"],"mappings":"upBAGA,MAAMA,EAAeC,GACnBA,EAAMC,OACJ,CAACC,EAAUC,EAAMC,IACfC,EACEF,EACAG,EAAOC,KACJC,GAAQ,GAAGJ,EAAQ,EAAI,IAAM,KAAKI,IAClCA,GAAQ,IAAIA,MAEdL,GAAS,GAAGD,IAAWC,KAE5B,ICdJM,EAAA,CAAA,QAqBMC,EAA2B,CAC/BC,EACAC,EACAC,EACAC,EACAC,GA6BIC,EAAeC,IACnB,MAAMd,EA3BNE,EADuBa,EA4BMD,EAAEC,QAzB7BC,EAAcC,mBAAmB,CAAChB,EAAOiB,KACvC,MAAMC,EAAgBlB,EAAQ,EACxBmB,GACe,IAAnBD,OAAuBE,EAAYN,EAAQI,GAO7C,YAL2BE,IAAzBD,GACAb,EAAyBe,KACtBC,GAASH,EAAqBG,gBAAgBA,GAGzBC,EAAOC,KAAOD,EAAOF,KAAKJ,EAAa,GAEnEF,EAAcU,IAAI,EAAGrB,SAAUA,GAC/BW,EAAcU,IAAKrB,GACjBH,EACEG,EACCsB,GAAMC,SAASD,EAAG,IACnBxB,EAAO0B,cAAcC,EAAYC,OAAOC,OAAQ,IAAM3B,KAG1DW,EAAciB,QACdrC,GAxBqBmB,MAyDvB,MAAO,CAAEmB,QA3BOhC,EACdY,EAAEoB,QACF/B,EAAOgC,aAAarB,EAAEC,SACtBZ,EAAOiC,QACLC,EACErB,EAAcsB,KACdd,EAAOE,IACJR,GACC,YAAYA,EAAaK,KAAKgB,gBAAgBC,KAAKC,UACjDvB,EAAawB,WAGnBlB,EAAOmB,WAAW,IAChBC,EAAe,oCAIrBzC,EAAOwC,WAAWE,IAUFtB,KAPLrB,EACXY,EAAEC,QACFC,EAAcsB,KACdd,EAAOE,IAAKR,GAAiBA,EAAaK,KAAKgB,MAC/Cf,EAAOsB,UAAU,IAAM,YAGD9C,OAAM,EAW1B+C,EACJC,GAEA9C,EACE8C,EACAhC,EAAcU,IAAKuB,IAAK,CACtB,CAACA,EAAMjD,MAAO,CACZuB,KAAM0B,EAAM1B,KACZW,QAASe,EAAMf,YAGlBc,GAAWE,EAAU9C,KAjBC+C,CAGzBC,OAAQA,CAACC,EAAOC,IAAWC,OAAOC,OAAO,CAAE,EAAEF,EAAQD,IAcvCH,CAAkD,CAAA,EAAIF,IAGhES,EAA+D,CACnEL,OAAQA,CAACM,EAAGC,IAACC,EACRD,CAAAA,EAAAA,EACHE,CAAAA,MAAKD,KAAOF,EAAEG,MAAK,CAAE,CAACH,EAAEnC,MAAOmC,EAAExB,QAAS,CAACyB,EAAEpC,MAAOoC,EAAEzB,aAIpD4B,EACJd,GAEA9C,EACE6D,EAAeC,gBAAgBP,EAAqBzC,EAAciD,SAAlEF,CACEf,EACCC,GAAU,CAACA,EAAMjD,KAAMiD,IAE1Bc,EAAerC,IAAKwC,8IAEIC,CAAKD,EAAa5D,KClFxC,SAAU8D,EACdC,GAEA,MAAO,CAACC,EAAQC,EAAUC,KACxBtE,SACEoE,EACAD,EAAOI,OACPtE,EAAOiC,SDkFVsC,GChFQF,EAAQG,2BAAsD,QAAzBH,EAAQI,aDiFrDC,IACC,MAAMzB,EAASsB,EACXZ,EACAf,EAEJ,OAAO7C,EAAK2E,EAAkB7D,EAAcU,IAAIb,GAAcuC,EAAO,ICnFnEjD,EAAOiC,QAASY,GACd8B,EAAoB9B,EAAQwB,IAE9BrE,EAAOC,KAKJ4C,KACCsB,OAAQ,CAAE,EACVtB,WAEDsB,IACCE,EAAQG,2BACNI,EAAuB,GAAIP,GAEtB,CACLF,SACAtB,OAAQ,CAAA,MD2DjB0B,KCvDE,CACL"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.module.js b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.module.js new file mode 100644 index 0000000000000000000000000000000000000000..c6873f5393fb95e767b94a4f33fa09c561f14ad5 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.module.js @@ -0,0 +1,2 @@ +import{toNestErrors as n,validateFieldsNatively as t}from"@hookform/resolvers";import*as r from"fp-ts/Either";import{pipe as e,flow as o,absurd as u,identity as a,not as i}from"fp-ts/function";import*as f from"fp-ts/Option";import*as s from"fp-ts/ReadonlyArray";import*as c from"fp-ts/ReadonlyRecord";import*as p from"fp-ts/Semigroup";import{TaggedUnionType as m,UnionType as l,IntersectionType as d,ExactType as v,RefinementType as y}from"io-ts";function g(){return g=Object.assign?Object.assign.bind():function(n){for(var t=1;t0?".":"")+n},function(n){return"["+n+"]"}),function(t){return""+n+t})},"")},O=["path"],b=[m,l,d,v,y],x=function(n){var t,c=e(t=n.context,s.filterMapWithIndex(function(n,r){var e=n-1,o=-1===e?void 0:t[e];return void 0===o||b.some(function(n){return o.type instanceof n})?f.none:f.some(r)}),s.map(function(n){return n.key}),s.map(function(n){return e(n,function(n){return parseInt(n,10)},r.fromPredicate(i(Number.isNaN),function(){return n}))}),s.toArray,h);return{message:e(n.message,r.fromNullable(n.context),r.mapLeft(o(s.last,f.map(function(n){return"expected "+n.type.name+" but got "+JSON.stringify(n.actual)}),f.getOrElseW(function(){return u("Error context is missing name")}))),r.getOrElseW(a)),type:e(n.context,s.last,f.map(function(n){return n.type.name}),f.getOrElse(function(){return"unknown"})),path:c}},N=function(n){return e(n,s.map(function(n){var t;return(t={})[n.path]={type:n.type,message:n.message},t}),function(n){return p.fold({concat:function(n,t){return Object.assign({},t,n)}})({},n)})},E={concat:function(n,t){var r;return g({},t,{types:g({},n.types,(r={},r[n.type]=n.message,r[t.type]=t.message,r))})}},j=function(n){return e(c.fromFoldableMap(E,s.Foldable)(n,function(n){return[n.path,n]}),c.map(function(n){return function(n,t){if(null==n)return{};var r={};for(var e in n)if({}.hasOwnProperty.call(n,e)){if(-1!==t.indexOf(e))continue;r[e]=n[e]}return r}(n,O)}))};function k(o){return function(u,a,i){return e(u,o.decode,r.mapLeft((f=!i.shouldUseNativeValidation&&"all"===i.criteriaMode,function(n){var t=f?j:N;return e(n,s.map(x),t)})),r.mapLeft(function(t){return n(t,i)}),r.fold(function(n){return{values:{},errors:n}},function(n){return i.shouldUseNativeValidation&&t({},i),{values:n,errors:{}}}));var f}}export{k as ioTsResolver}; +//# sourceMappingURL=io-ts.module.js.map diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.module.js.map b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5cf041e38f8911798576e6f583147a3b972999fe --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"io-ts.module.js","sources":["../src/arrayToPath.ts","../src/errorsToRecord.ts","../src/io-ts.ts"],"sourcesContent":["import * as Either from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\n\nconst arrayToPath = (paths: Either.Either[]): string =>\n paths.reduce(\n (previous, path, index) =>\n pipe(\n path,\n Either.fold(\n (key) => `${index > 0 ? '.' : ''}${key}`,\n (key) => `[${key}]`,\n ),\n (path) => `${previous}${path}`,\n ),\n '',\n );\n\nexport default arrayToPath;\n","import * as Either from 'fp-ts/Either';\nimport * as Option from 'fp-ts/Option';\nimport * as ReadonlyArray from 'fp-ts/ReadonlyArray';\nimport * as ReadonlyRecord from 'fp-ts/ReadonlyRecord';\nimport * as SemiGroup from 'fp-ts/Semigroup';\nimport { absurd, flow, identity, not, pipe } from 'fp-ts/function';\nimport * as t from 'io-ts';\nimport {\n ExactType,\n IntersectionType,\n RefinementType,\n TaggedUnionType,\n UnionType,\n ValidationError,\n} from 'io-ts';\nimport { FieldError } from 'react-hook-form';\nimport arrayToPath from './arrayToPath';\n\nexport type ErrorObject = Record;\nexport type FieldErrorWithPath = FieldError & { path: string };\n\nconst INSTANCE_TYPES_TO_FILTER = [\n TaggedUnionType,\n UnionType,\n IntersectionType,\n ExactType,\n RefinementType,\n];\nconst formatErrorPath = (context: t.Context): string =>\n pipe(\n context,\n ReadonlyArray.filterMapWithIndex((index, contextEntry) => {\n const previousIndex = index - 1;\n const previousContextEntry =\n previousIndex === -1 ? undefined : context[previousIndex];\n const shouldBeFiltered =\n previousContextEntry === undefined ||\n INSTANCE_TYPES_TO_FILTER.some(\n (type) => previousContextEntry.type instanceof type,\n );\n\n return shouldBeFiltered ? Option.none : Option.some(contextEntry);\n }),\n ReadonlyArray.map(({ key }) => key),\n ReadonlyArray.map((key) =>\n pipe(\n key,\n (k) => parseInt(k, 10),\n Either.fromPredicate(not(Number.isNaN), () => key),\n ),\n ),\n ReadonlyArray.toArray,\n arrayToPath,\n );\n\nconst formatError = (e: t.ValidationError): FieldErrorWithPath => {\n const path = formatErrorPath(e.context);\n\n const message = pipe(\n e.message,\n Either.fromNullable(e.context),\n Either.mapLeft(\n flow(\n ReadonlyArray.last,\n Option.map(\n (contextEntry) =>\n `expected ${contextEntry.type.name} but got ${JSON.stringify(\n contextEntry.actual,\n )}`,\n ),\n Option.getOrElseW(() =>\n absurd('Error context is missing name' as never),\n ),\n ),\n ),\n Either.getOrElseW(identity),\n );\n\n const type = pipe(\n e.context,\n ReadonlyArray.last,\n Option.map((contextEntry) => contextEntry.type.name),\n Option.getOrElse(() => 'unknown'),\n );\n\n return { message, type, path };\n};\n\n// this is almost the same function like Semigroup.getObjectSemigroup but reversed\n// in order to get the first error\nconst getObjectSemigroup = <\n A extends Record = never,\n>(): SemiGroup.Semigroup => ({\n concat: (first, second) => Object.assign({}, second, first),\n});\n\nconst concatToSingleError = (\n errors: ReadonlyArray,\n): ErrorObject =>\n pipe(\n errors,\n ReadonlyArray.map((error) => ({\n [error.path]: {\n type: error.type,\n message: error.message,\n },\n })),\n (errors) => SemiGroup.fold(getObjectSemigroup())({}, errors),\n );\n\nconst appendSeveralErrors: SemiGroup.Semigroup = {\n concat: (a, b) => ({\n ...b,\n types: { ...a.types, [a.type]: a.message, [b.type]: b.message },\n }),\n};\n\nconst concatToMultipleErrors = (\n errors: ReadonlyArray,\n): ErrorObject =>\n pipe(\n ReadonlyRecord.fromFoldableMap(appendSeveralErrors, ReadonlyArray.Foldable)(\n errors,\n (error) => [error.path, error],\n ),\n ReadonlyRecord.map((errorWithPath) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { path, ...error } = errorWithPath;\n\n return error;\n }),\n );\n\nconst errorsToRecord =\n (validateAllFieldCriteria: boolean) =>\n (validationErrors: ReadonlyArray): ErrorObject => {\n const concat = validateAllFieldCriteria\n ? concatToMultipleErrors\n : concatToSingleError;\n\n return pipe(validationErrors, ReadonlyArray.map(formatError), concat);\n };\n\nexport default errorsToRecord;\n","import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport * as Either from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\nimport * as t from 'io-ts';\nimport {\n FieldErrors,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n} from 'react-hook-form';\nimport errorsToRecord, { ErrorObject } from './errorsToRecord';\n\nexport function ioTsResolver(\n schema: t.Type,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver;\n\nexport function ioTsResolver(\n schema: t.Type,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using io-ts schema validation\n * @param {t.Type} schema - The io-ts schema to validate against\n * @param {Object} options - Additional resolver configuration\n * @param {string} [options.mode='async'] - Validation mode\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = t.type({\n * name: t.string,\n * age: t.number\n * });\n *\n * useForm({\n * resolver: ioTsResolver(schema)\n * });\n */\nexport function ioTsResolver(\n schema: t.Type,\n): Resolver {\n return (values, _context, options) =>\n pipe(\n values,\n schema.decode,\n Either.mapLeft(\n errorsToRecord(\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n ),\n ),\n Either.mapLeft((errors: ErrorObject) =>\n toNestErrors(errors, options),\n ),\n Either.fold<\n FieldErrors,\n Output,\n ResolverError | ResolverSuccess\n >(\n (errors) => ({\n values: {},\n errors,\n }),\n (values) => {\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n values,\n errors: {},\n };\n },\n ),\n );\n}\n"],"names":["arrayToPath","paths","reduce","previous","path","index","pipe","Either","fold","key","_excluded","INSTANCE_TYPES_TO_FILTER","TaggedUnionType","UnionType","IntersectionType","ExactType","RefinementType","formatError","e","context","ReadonlyArray","filterMapWithIndex","contextEntry","previousIndex","previousContextEntry","undefined","some","type","Option","none","map","_ref","k","parseInt","fromPredicate","not","Number","isNaN","toArray","message","fromNullable","mapLeft","flow","last","name","JSON","stringify","actual","getOrElseW","absurd","identity","getOrElse","concatToSingleError","errors","error","_ref2","SemiGroup","concat","first","second","Object","assign","appendSeveralErrors","a","b","_extends2","_extends","types","concatToMultipleErrors","ReadonlyRecord","fromFoldableMap","Foldable","errorWithPath","_objectWithoutPropertiesLoose","ioTsResolver","schema","values","_context","options","decode","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","validationErrors","toNestErrors","validateFieldsNatively"],"mappings":"upBAGA,IAAMA,EAAc,SAACC,UACnBA,EAAMC,OACJ,SAACC,EAAUC,EAAMC,GAAK,OACpBC,EACEF,EACAG,EAAOC,KACL,SAACC,GAAG,OAAQJ,EAAQ,EAAI,IAAM,IAAKI,CAAG,EACtC,SAACA,GAAYA,MAAAA,IAAAA,QAEf,SAACL,YAAYD,EAAWC,CAAI,EAC7B,EACH,GACD,ECfHM,EAAA,CAAA,QAqBMC,EAA2B,CAC/BC,EACAC,EACAC,EACAC,EACAC,GA6BIC,EAAc,SAACC,GACnB,IA5BuBC,EA4BjBf,EA3BNE,EADuBa,EA4BMD,EAAEC,QAzB7BC,EAAcC,mBAAmB,SAAChB,EAAOiB,GACvC,IAAMC,EAAgBlB,EAAQ,EACxBmB,GACe,IAAnBD,OAAuBE,EAAYN,EAAQI,GAO7C,YAL2BE,IAAzBD,GACAb,EAAyBe,KACvB,SAACC,GAAI,OAAKH,EAAqBG,gBAAgBA,CAAI,GAG7BC,EAAOC,KAAOD,EAAOF,KAAKJ,EACtD,GACAF,EAAcU,IAAI,SAAAC,GAAa,OAAPA,EAAHtB,GAAa,GAClCW,EAAcU,IAAI,SAACrB,GAAG,OACpBH,EACEG,EACA,SAACuB,GAAM,OAAAC,SAASD,EAAG,GAAG,EACtBzB,EAAO2B,cAAcC,EAAYC,OAAOC,OAAQ,kBAAM5B,CAAG,GAC1D,GAEHW,EAAckB,QACdtC,GAiCF,MAAO,CAAEuC,QA3BOjC,EACdY,EAAEqB,QACFhC,EAAOiC,aAAatB,EAAEC,SACtBZ,EAAOkC,QACLC,EACEtB,EAAcuB,KACdf,EAAOE,IACL,SAACR,GACaA,MAAAA,YAAAA,EAAaK,KAAKiB,KAAI,YAAYC,KAAKC,UACjDxB,EAAayB,OACd,GAELnB,EAAOoB,WAAW,WAAA,OAChBC,EAAe,gCAAyC,KAI9D1C,EAAOyC,WAAWE,IAUFvB,KAPLrB,EACXY,EAAEC,QACFC,EAAcuB,KACdf,EAAOE,IAAI,SAACR,UAAiBA,EAAaK,KAAKiB,IAAI,GACnDhB,EAAOuB,UAAU,iBAAM,SAAS,IAGV/C,KAAAA,EAC1B,EAUMgD,EAAsB,SAC1BC,GAEA,OAAA/C,EACE+C,EACAjC,EAAcU,IAAI,SAACwB,GAAKC,IAAAA,SAAAA,EAAA,CAAA,GACrBD,EAAMlD,MAAO,CACZuB,KAAM2B,EAAM3B,KACZY,QAASe,EAAMf,SAChBgB,CAAA,GAEH,SAACF,GAAM,OAAKG,EAAUhD,KAfM,CAC9BiD,OAAQ,SAACC,EAAOC,GAAM,OAAKC,OAAOC,OAAO,GAAIF,EAAQD,EAAM,GAc7CF,CAAkD,CAAA,EAAIH,EAAO,EAC1E,EAEGS,EAA+D,CACnEL,OAAQ,SAACM,EAAGC,GAACC,IAAAA,SAAAC,EAAA,CAAA,EACRF,EACHG,CAAAA,MAAKD,EAAA,CAAA,EAAOH,EAAEI,OAAKF,EAAAA,GAAAA,EAAGF,EAAEpC,MAAOoC,EAAExB,QAAO0B,EAAGD,EAAErC,MAAOqC,EAAEzB,QAAO0B,QAI3DG,EAAyB,SAC7Bf,GAEA,OAAA/C,EACE+D,EAAeC,gBAAgBR,EAAqB1C,EAAcmD,SAAlEF,CACEhB,EACA,SAACC,GAAK,MAAK,CAACA,EAAMlD,KAAMkD,EAAM,GAEhCe,EAAevC,IAAI,SAAC0C,GAIlB,kJAFsBC,CAAKD,EAAa9D,EAG1C,GACD,ECtFa,SAAAgE,EACdC,GAEA,OAAO,SAACC,EAAQC,EAAUC,GAAO,OAC/BxE,EACEsE,EACAD,EAAOI,OACPxE,EAAOkC,SDkFVuC,GChFQF,EAAQG,2BAAsD,QAAzBH,EAAQI,aDiFtD,SAACC,GACC,IAAM1B,EAASuB,EACXZ,EACAhB,EAEJ,OAAO9C,EAAK6E,EAAkB/D,EAAcU,IAAIb,GAAcwC,EAChE,ICpFIlD,EAAOkC,QAAQ,SAACY,GAAmB,OACjC+B,EAAoB/B,EAAQyB,EAAQ,GAEtCvE,EAAOC,KAKL,SAAC6C,GAAY,MAAA,CACXuB,OAAQ,CAAE,EACVvB,OAAAA,EACD,EACD,SAACuB,GAIC,OAHAE,EAAQG,2BACNI,EAAuB,GAAIP,GAEtB,CACLF,OAAAA,EACAvB,OAAQ,CAAA,EAEZ,IDyDN,IAAC2B,CCvDE,CACL"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.umd.js b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..cc4ea8d562a846a4bdccfb49e7f7c111c68940b1 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.umd.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("@hookform/resolvers"),require("fp-ts/Either"),require("fp-ts/function"),require("fp-ts/Option"),require("fp-ts/ReadonlyArray"),require("fp-ts/ReadonlyRecord"),require("fp-ts/Semigroup"),require("io-ts")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","fp-ts/Either","fp-ts/function","fp-ts/Option","fp-ts/ReadonlyArray","fp-ts/ReadonlyRecord","fp-ts/Semigroup","io-ts"],n):n((e||self).hookformResolversIoTs={},e.hookformResolvers,e.Either,e._function,e.Option,e.ReadonlyArray,e.ReadonlyRecord,e.Semigroup,e.ioTs)}(this,function(e,n,t,r,o,i,u,a,f){function s(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}}),n.default=e,n}var p=/*#__PURE__*/s(t),c=/*#__PURE__*/s(o),l=/*#__PURE__*/s(i),d=/*#__PURE__*/s(u),y=/*#__PURE__*/s(a);function m(){return m=Object.assign?Object.assign.bind():function(e){for(var n=1;n0?".":"")+e},function(e){return"["+e+"]"}),function(n){return""+e+n})},"")},g=["path"],h=[f.TaggedUnionType,f.UnionType,f.IntersectionType,f.ExactType,f.RefinementType],b=function(e){var n,t=r.pipe(n=e.context,l.filterMapWithIndex(function(e,t){var r=e-1,o=-1===r?void 0:n[r];return void 0===o||h.some(function(e){return o.type instanceof e})?c.none:c.some(t)}),l.map(function(e){return e.key}),l.map(function(e){return r.pipe(e,function(e){return parseInt(e,10)},p.fromPredicate(r.not(Number.isNaN),function(){return e}))}),l.toArray,v);return{message:r.pipe(e.message,p.fromNullable(e.context),p.mapLeft(r.flow(l.last,c.map(function(e){return"expected "+e.type.name+" but got "+JSON.stringify(e.actual)}),c.getOrElseW(function(){return r.absurd("Error context is missing name")}))),p.getOrElseW(r.identity)),type:r.pipe(e.context,l.last,c.map(function(e){return e.type.name}),c.getOrElse(function(){return"unknown"})),path:t}},O=function(e){return r.pipe(e,l.map(function(e){var n;return(n={})[e.path]={type:e.type,message:e.message},n}),function(e){return y.fold({concat:function(e,n){return Object.assign({},n,e)}})({},e)})},R={concat:function(e,n){var t;return m({},n,{types:m({},e.types,(t={},t[e.type]=e.message,t[n.type]=n.message,t))})}},x=function(e){return r.pipe(d.fromFoldableMap(R,l.Foldable)(e,function(e){return[e.path,e]}),d.map(function(e){return function(e,n){if(null==e)return{};var t={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==n.indexOf(r))continue;t[r]=e[r]}return t}(e,g)}))};e.ioTsResolver=function(e){return function(t,o,i){return r.pipe(t,e.decode,p.mapLeft((u=!i.shouldUseNativeValidation&&"all"===i.criteriaMode,function(e){var n=u?x:O;return r.pipe(e,l.map(b),n)})),p.mapLeft(function(e){return n.toNestErrors(e,i)}),p.fold(function(e){return{values:{},errors:e}},function(e){return i.shouldUseNativeValidation&&n.validateFieldsNatively({},i),{values:e,errors:{}}}));var u}}}); +//# sourceMappingURL=io-ts.umd.js.map diff --git a/node_modules/@hookform/resolvers/io-ts/dist/io-ts.umd.js.map b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a4d42feb7aa9fb88cdd47ff0da973ab585424ebc --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/dist/io-ts.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"io-ts.umd.js","sources":["../src/arrayToPath.ts","../src/errorsToRecord.ts","../src/io-ts.ts"],"sourcesContent":["import * as Either from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\n\nconst arrayToPath = (paths: Either.Either[]): string =>\n paths.reduce(\n (previous, path, index) =>\n pipe(\n path,\n Either.fold(\n (key) => `${index > 0 ? '.' : ''}${key}`,\n (key) => `[${key}]`,\n ),\n (path) => `${previous}${path}`,\n ),\n '',\n );\n\nexport default arrayToPath;\n","import * as Either from 'fp-ts/Either';\nimport * as Option from 'fp-ts/Option';\nimport * as ReadonlyArray from 'fp-ts/ReadonlyArray';\nimport * as ReadonlyRecord from 'fp-ts/ReadonlyRecord';\nimport * as SemiGroup from 'fp-ts/Semigroup';\nimport { absurd, flow, identity, not, pipe } from 'fp-ts/function';\nimport * as t from 'io-ts';\nimport {\n ExactType,\n IntersectionType,\n RefinementType,\n TaggedUnionType,\n UnionType,\n ValidationError,\n} from 'io-ts';\nimport { FieldError } from 'react-hook-form';\nimport arrayToPath from './arrayToPath';\n\nexport type ErrorObject = Record;\nexport type FieldErrorWithPath = FieldError & { path: string };\n\nconst INSTANCE_TYPES_TO_FILTER = [\n TaggedUnionType,\n UnionType,\n IntersectionType,\n ExactType,\n RefinementType,\n];\nconst formatErrorPath = (context: t.Context): string =>\n pipe(\n context,\n ReadonlyArray.filterMapWithIndex((index, contextEntry) => {\n const previousIndex = index - 1;\n const previousContextEntry =\n previousIndex === -1 ? undefined : context[previousIndex];\n const shouldBeFiltered =\n previousContextEntry === undefined ||\n INSTANCE_TYPES_TO_FILTER.some(\n (type) => previousContextEntry.type instanceof type,\n );\n\n return shouldBeFiltered ? Option.none : Option.some(contextEntry);\n }),\n ReadonlyArray.map(({ key }) => key),\n ReadonlyArray.map((key) =>\n pipe(\n key,\n (k) => parseInt(k, 10),\n Either.fromPredicate(not(Number.isNaN), () => key),\n ),\n ),\n ReadonlyArray.toArray,\n arrayToPath,\n );\n\nconst formatError = (e: t.ValidationError): FieldErrorWithPath => {\n const path = formatErrorPath(e.context);\n\n const message = pipe(\n e.message,\n Either.fromNullable(e.context),\n Either.mapLeft(\n flow(\n ReadonlyArray.last,\n Option.map(\n (contextEntry) =>\n `expected ${contextEntry.type.name} but got ${JSON.stringify(\n contextEntry.actual,\n )}`,\n ),\n Option.getOrElseW(() =>\n absurd('Error context is missing name' as never),\n ),\n ),\n ),\n Either.getOrElseW(identity),\n );\n\n const type = pipe(\n e.context,\n ReadonlyArray.last,\n Option.map((contextEntry) => contextEntry.type.name),\n Option.getOrElse(() => 'unknown'),\n );\n\n return { message, type, path };\n};\n\n// this is almost the same function like Semigroup.getObjectSemigroup but reversed\n// in order to get the first error\nconst getObjectSemigroup = <\n A extends Record = never,\n>(): SemiGroup.Semigroup => ({\n concat: (first, second) => Object.assign({}, second, first),\n});\n\nconst concatToSingleError = (\n errors: ReadonlyArray,\n): ErrorObject =>\n pipe(\n errors,\n ReadonlyArray.map((error) => ({\n [error.path]: {\n type: error.type,\n message: error.message,\n },\n })),\n (errors) => SemiGroup.fold(getObjectSemigroup())({}, errors),\n );\n\nconst appendSeveralErrors: SemiGroup.Semigroup = {\n concat: (a, b) => ({\n ...b,\n types: { ...a.types, [a.type]: a.message, [b.type]: b.message },\n }),\n};\n\nconst concatToMultipleErrors = (\n errors: ReadonlyArray,\n): ErrorObject =>\n pipe(\n ReadonlyRecord.fromFoldableMap(appendSeveralErrors, ReadonlyArray.Foldable)(\n errors,\n (error) => [error.path, error],\n ),\n ReadonlyRecord.map((errorWithPath) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { path, ...error } = errorWithPath;\n\n return error;\n }),\n );\n\nconst errorsToRecord =\n (validateAllFieldCriteria: boolean) =>\n (validationErrors: ReadonlyArray): ErrorObject => {\n const concat = validateAllFieldCriteria\n ? concatToMultipleErrors\n : concatToSingleError;\n\n return pipe(validationErrors, ReadonlyArray.map(formatError), concat);\n };\n\nexport default errorsToRecord;\n","import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport * as Either from 'fp-ts/Either';\nimport { pipe } from 'fp-ts/function';\nimport * as t from 'io-ts';\nimport {\n FieldErrors,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n} from 'react-hook-form';\nimport errorsToRecord, { ErrorObject } from './errorsToRecord';\n\nexport function ioTsResolver(\n schema: t.Type,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver;\n\nexport function ioTsResolver(\n schema: t.Type,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using io-ts schema validation\n * @param {t.Type} schema - The io-ts schema to validate against\n * @param {Object} options - Additional resolver configuration\n * @param {string} [options.mode='async'] - Validation mode\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = t.type({\n * name: t.string,\n * age: t.number\n * });\n *\n * useForm({\n * resolver: ioTsResolver(schema)\n * });\n */\nexport function ioTsResolver(\n schema: t.Type,\n): Resolver {\n return (values, _context, options) =>\n pipe(\n values,\n schema.decode,\n Either.mapLeft(\n errorsToRecord(\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n ),\n ),\n Either.mapLeft((errors: ErrorObject) =>\n toNestErrors(errors, options),\n ),\n Either.fold<\n FieldErrors,\n Output,\n ResolverError | ResolverSuccess\n >(\n (errors) => ({\n values: {},\n errors,\n }),\n (values) => {\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n values,\n errors: {},\n };\n },\n ),\n );\n}\n"],"names":["arrayToPath","paths","reduce","previous","path","index","pipe","Either","fold","key","_excluded","INSTANCE_TYPES_TO_FILTER","TaggedUnionType","UnionType","IntersectionType","ExactType","RefinementType","formatError","e","context","ReadonlyArray","filterMapWithIndex","contextEntry","previousIndex","previousContextEntry","undefined","some","type","Option","none","map","_ref","k","parseInt","fromPredicate","not","Number","isNaN","toArray","message","fromNullable","mapLeft","flow","last","name","JSON","stringify","actual","getOrElseW","absurd","identity","getOrElse","concatToSingleError","errors","error","_ref2","SemiGroup","concat","first","second","Object","assign","appendSeveralErrors","a","b","_extends2","_extends","types","concatToMultipleErrors","ReadonlyRecord","fromFoldableMap","Foldable","errorWithPath","_objectWithoutPropertiesLoose","schema","values","_context","options","decode","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","validationErrors","toNestErrors","validateFieldsNatively"],"mappings":"mxCAGA,IAAMA,EAAc,SAACC,UACnBA,EAAMC,OACJ,SAACC,EAAUC,EAAMC,GAAK,OACpBC,EAAAA,KACEF,EACAG,EAAOC,KACL,SAACC,GAAG,OAAQJ,EAAQ,EAAI,IAAM,IAAKI,CAAG,EACtC,SAACA,GAAYA,MAAAA,IAAAA,QAEf,SAACL,YAAYD,EAAWC,CAAI,EAC7B,EACH,GACD,ECfHM,EAAA,CAAA,QAqBMC,EAA2B,CAC/BC,EAAeA,gBACfC,EAASA,UACTC,mBACAC,EAAAA,UACAC,EAAAA,gBA6BIC,EAAc,SAACC,GACnB,IA5BuBC,EA4BjBf,EA3BNE,EAAAA,KADuBa,EA4BMD,EAAEC,QAzB7BC,EAAcC,mBAAmB,SAAChB,EAAOiB,GACvC,IAAMC,EAAgBlB,EAAQ,EACxBmB,GACe,IAAnBD,OAAuBE,EAAYN,EAAQI,GAO7C,YAL2BE,IAAzBD,GACAb,EAAyBe,KACvB,SAACC,GAAI,OAAKH,EAAqBG,gBAAgBA,CAAI,GAG7BC,EAAOC,KAAOD,EAAOF,KAAKJ,EACtD,GACAF,EAAcU,IAAI,SAAAC,GAAa,OAAPA,EAAHtB,GAAa,GAClCW,EAAcU,IAAI,SAACrB,GAAG,OACpBH,OACEG,EACA,SAACuB,GAAM,OAAAC,SAASD,EAAG,GAAG,EACtBzB,EAAO2B,cAAcC,EAAAA,IAAYC,OAAOC,OAAQ,kBAAM5B,CAAG,GAC1D,GAEHW,EAAckB,QACdtC,GAiCF,MAAO,CAAEuC,QA3BOjC,OACdY,EAAEqB,QACFhC,EAAOiC,aAAatB,EAAEC,SACtBZ,EAAOkC,QACLC,EAAAA,KACEtB,EAAcuB,KACdf,EAAOE,IACL,SAACR,GACaA,MAAAA,YAAAA,EAAaK,KAAKiB,KAAI,YAAYC,KAAKC,UACjDxB,EAAayB,OACd,GAELnB,EAAOoB,WAAW,WAAA,OAChBC,EAAMA,OAAS,gCAAyC,KAI9D1C,EAAOyC,WAAWE,EAAQA,WAUVvB,KAPLrB,EAAIA,KACfY,EAAEC,QACFC,EAAcuB,KACdf,EAAOE,IAAI,SAACR,UAAiBA,EAAaK,KAAKiB,IAAI,GACnDhB,EAAOuB,UAAU,iBAAM,SAAS,IAGV/C,KAAAA,EAC1B,EAUMgD,EAAsB,SAC1BC,GAEA,OAAA/C,OACE+C,EACAjC,EAAcU,IAAI,SAACwB,GAAKC,IAAAA,SAAAA,EAAA,CAAA,GACrBD,EAAMlD,MAAO,CACZuB,KAAM2B,EAAM3B,KACZY,QAASe,EAAMf,SAChBgB,CAAA,GAEH,SAACF,GAAM,OAAKG,EAAUhD,KAfM,CAC9BiD,OAAQ,SAACC,EAAOC,GAAM,OAAKC,OAAOC,OAAO,GAAIF,EAAQD,EAAM,GAc7CF,CAAkD,CAAA,EAAIH,EAAO,EAC1E,EAEGS,EAA+D,CACnEL,OAAQ,SAACM,EAAGC,GAACC,IAAAA,SAAAC,EAAA,CAAA,EACRF,EACHG,CAAAA,MAAKD,EAAA,CAAA,EAAOH,EAAEI,OAAKF,EAAAA,GAAAA,EAAGF,EAAEpC,MAAOoC,EAAExB,QAAO0B,EAAGD,EAAErC,MAAOqC,EAAEzB,QAAO0B,QAI3DG,EAAyB,SAC7Bf,GAEA,OAAA/C,EAAIA,KACF+D,EAAeC,gBAAgBR,EAAqB1C,EAAcmD,SAAlEF,CACEhB,EACA,SAACC,GAAK,MAAK,CAACA,EAAMlD,KAAMkD,EAAM,GAEhCe,EAAevC,IAAI,SAAC0C,GAIlB,kJAFsBC,CAAKD,EAAa9D,EAG1C,GACD,iBCtFa,SACdgE,GAEA,OAAO,SAACC,EAAQC,EAAUC,GAAO,OAC/BvE,EAAIA,KACFqE,EACAD,EAAOI,OACPvE,EAAOkC,SDkFVsC,GChFQF,EAAQG,2BAAsD,QAAzBH,EAAQI,aDiFtD,SAACC,GACC,IAAMzB,EAASsB,EACXX,EACAhB,EAEJ,OAAO9C,EAAIA,KAAC4E,EAAkB9D,EAAcU,IAAIb,GAAcwC,EAChE,ICpFIlD,EAAOkC,QAAQ,SAACY,GAAmB,OACjC8B,EAAYA,aAAQ9B,EAAQwB,EAAQ,GAEtCtE,EAAOC,KAKL,SAAC6C,GAAY,MAAA,CACXsB,OAAQ,CAAE,EACVtB,OAAAA,EACD,EACD,SAACsB,GAIC,OAHAE,EAAQG,2BACNI,EAAsBA,uBAAC,GAAIP,GAEtB,CACLF,OAAAA,EACAtB,OAAQ,CAAA,EAEZ,IDyDN,IAAC0B,CCvDE,CACL"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/io-ts/package.json b/node_modules/@hookform/resolvers/io-ts/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7a4e0b6d87acea58e11c63a30f3e46395e5bebff --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/package.json @@ -0,0 +1,19 @@ +{ + "name": "@hookform/resolvers/io-ts", + "amdName": "hookformResolversIoTs", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: io-ts", + "main": "dist/io-ts.js", + "module": "dist/io-ts.module.js", + "umd:main": "dist/io-ts.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0", + "io-ts": "^2.0.0", + "fp-ts": "^2.7.0" + } +} diff --git a/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5aa7865cf2e2be845fb1db2da7c3c74c19a0532a --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,78 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import * as t from 'io-ts'; +import * as tt from 'io-ts-types'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { ioTsResolver } from '..'; + +const USERNAME_REQUIRED_MESSAGE = 'username field is required'; +const PASSWORD_REQUIRED_MESSAGE = 'password field is required'; + +const schema = t.type({ + username: tt.withMessage(tt.NonEmptyString, () => USERNAME_REQUIRED_MESSAGE), + password: tt.withMessage(tt.NonEmptyString, () => PASSWORD_REQUIRED_MESSAGE), +}); + +function TestComponent({ + onSubmit, +}: { onSubmit: (data: t.OutputOf) => void }) { + const { register, handleSubmit } = useForm({ + resolver: ioTsResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with io-ts", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..bb70f60d771b36d3e2dcfcbee1c0afb8fc838366 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form.tsx @@ -0,0 +1,87 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import * as t from 'io-ts'; +import * as tt from 'io-ts-types'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { ioTsResolver } from '..'; + +const schema = t.type({ + username: tt.withMessage( + tt.NonEmptyString, + () => 'username is a required field', + ), + password: tt.withMessage( + tt.NonEmptyString, + () => 'password is a required field', + ), +}); + +interface FormData { + username: string; + password: string; +} + +function TestComponent({ + onSubmit, +}: { onSubmit: (data: t.OutputOf) => void }) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: ioTsResolver(schema), + criteriaMode: 'all', + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with io-ts and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect(screen.getByText(/username is a required field/i)).toBeInTheDocument(); + expect(screen.getByText(/password is a required field/i)).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); + +export function TestComponentManualType({ + onSubmit, +}: { + onSubmit: (data: FormData) => void; +}) { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm, undefined, FormData>({ + resolver: ioTsResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} diff --git a/node_modules/@hookform/resolvers/io-ts/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/io-ts/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..388b2dd0074f9b54ada570a45ab48492a612ad70 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,112 @@ +import * as t from 'io-ts'; +import * as tt from 'io-ts-types'; + +import { Field, InternalFieldName } from 'react-hook-form'; + +export const schema = t.intersection([ + t.type({ + username: tt.NonEmptyString, + password: tt.NonEmptyString, + accessToken: tt.UUID, + birthYear: t.number, + email: t.string, + tags: t.array( + t.type({ + name: t.string, + }), + ), + luckyNumbers: t.array(t.number), + enabled: t.boolean, + animal: t.union([ + t.string, + t.number, + t.literal('bird'), + t.literal('snake'), + ]), + vehicles: t.array( + t.union([ + t.type({ + type: t.literal('car'), + brand: t.string, + horsepower: t.number, + }), + t.type({ + type: t.literal('bike'), + speed: t.number, + }), + ]), + ), + }), + t.partial({ + like: t.array( + t.type({ + id: tt.withMessage( + t.number, + (i) => `this id is very important but you passed: ${typeof i}(${i})`, + ), + name: t.string, + }), + ), + }), +]); + +export const validData = { + username: 'Doe', + password: 'Password123', + accessToken: 'c2883927-5178-4ad1-bbee-07ba33a5de19', + birthYear: 2000, + email: 'john@doe.com', + tags: [{ name: 'test' }], + enabled: true, + luckyNumbers: [17, 5], + animal: 'cat', + like: [ + { + id: 1, + name: 'name', + }, + ], + vehicles: [{ type: 'car', brand: 'BMW', horsepower: 150 }], +} satisfies t.OutputOf; + +export const invalidData = { + username: 'test', + password: 'Password123', + repeatPassword: 'Password123', + birthYear: 2000, + accessToken: '1015d809-e99d-41ec-b161-981a3c243df8', + email: 'john@doe.com', + tags: [{ name: 'test' }], + enabled: true, + animal: ['dog'], + luckyNumbers: [1, 2, '3'], + like: [ + { + id: '1', + name: 'name', + }, + ], + vehicles: [ + { type: 'car', brand: 'BMW', horsepower: 150 }, + { type: 'car', brand: 'Mercedes' }, + ], +} as unknown as t.OutputOf; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/io-ts/src/__tests__/__snapshots__/io-ts.ts.snap b/node_modules/@hookform/resolvers/io-ts/src/__tests__/__snapshots__/io-ts.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..badecbd461308a261b3ab113e350dc0ff2d00d26 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/__tests__/__snapshots__/io-ts.ts.snap @@ -0,0 +1,89 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`ioTsResolver > should return a single error from ioTsResolver when validation fails 1`] = ` +{ + "errors": { + "animal": { + "message": "expected string but got ["dog"]", + "ref": undefined, + "type": "string", + }, + "like": [ + { + "id": { + "message": "this id is very important but you passed: string(1)", + "ref": undefined, + "type": "number", + }, + }, + ], + "luckyNumbers": [ + , + , + { + "message": "expected number but got "3"", + "ref": undefined, + "type": "number", + }, + ], + "vehicles": [ + , + { + "horsepower": { + "message": "expected number but got undefined", + "ref": undefined, + "type": "number", + }, + }, + ], + }, + "values": {}, +} +`; + +exports[`ioTsResolver > should return all the errors from ioTsResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = ` +{ + "errors": { + "animal": { + "message": "expected "snake" but got ["dog"]", + "ref": undefined, + "type": ""snake"", + "types": { + ""bird"": "expected "bird" but got ["dog"]", + ""snake"": "expected "snake" but got ["dog"]", + "number": "expected number but got ["dog"]", + "string": "expected string but got ["dog"]", + }, + }, + "like": [ + { + "id": { + "message": "this id is very important but you passed: string(1)", + "ref": undefined, + "type": "number", + }, + }, + ], + "luckyNumbers": [ + , + , + { + "message": "expected number but got "3"", + "ref": undefined, + "type": "number", + }, + ], + "vehicles": [ + , + { + "horsepower": { + "message": "expected number but got undefined", + "ref": undefined, + "type": "number", + }, + }, + ], + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/io-ts/src/__tests__/errorsToRecord.ts b/node_modules/@hookform/resolvers/io-ts/src/__tests__/errorsToRecord.ts new file mode 100644 index 0000000000000000000000000000000000000000..9174a9525a1271047c0100425eb2961daebb89e8 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/__tests__/errorsToRecord.ts @@ -0,0 +1,57 @@ +import { isLeft } from 'fp-ts/Either'; +import * as t from 'io-ts'; +import errorsToRecord from '../errorsToRecord'; + +const assertLeft = (result: t.Validation) => { + expect(isLeft(result)).toBe(true); + if (!isLeft(result)) { + throw new Error( + 'panic! error is not of the "left" type, should be unreachable', + ); + } + return result.left; +}; + +const FIRST_NAME_FIELD_PATH = 'firstName' as const; +const FIRST_NAME_ERROR_SHAPE = { + message: 'expected string but got undefined', + type: 'string', +}; +describe('errorsToRecord', () => { + it('should return a correct error for an exact intersection type error object', () => { + // a recommended pattern from https://github.com/gcanti/io-ts/blob/master/index.md#mixing-required-and-optional-props + const schema = t.exact( + t.intersection([ + t.type({ + [FIRST_NAME_FIELD_PATH]: t.string, + }), + t.partial({ + lastName: t.string, + }), + ]), + ); + const error = assertLeft(schema.decode({})); + const record = errorsToRecord(false)(error); + expect(record[FIRST_NAME_FIELD_PATH]).toMatchObject(FIRST_NAME_ERROR_SHAPE); + }); + it('should return a correct error for a branded intersection', () => { + interface Brand { + readonly Brand: unique symbol; + } + const schema = t.brand( + t.intersection([ + t.type({ + [FIRST_NAME_FIELD_PATH]: t.string, + }), + t.type({ + lastName: t.string, + }), + ]), + (_x): _x is t.Branded => true, + 'Brand', + ); + const error = assertLeft(schema.decode({})); + const record = errorsToRecord(false)(error); + expect(record[FIRST_NAME_FIELD_PATH]).toMatchObject(FIRST_NAME_ERROR_SHAPE); + }); +}); diff --git a/node_modules/@hookform/resolvers/io-ts/src/__tests__/io-ts.ts b/node_modules/@hookform/resolvers/io-ts/src/__tests__/io-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2b240fab132f42db636a1faa25cca3d4a5d1325 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/__tests__/io-ts.ts @@ -0,0 +1,100 @@ +import { renderHook } from '@testing-library/react'; +import * as t from 'io-ts'; +import * as tt from 'io-ts-types'; +import { Resolver, SubmitHandler, useForm } from 'react-hook-form'; +import { ioTsResolver } from '..'; +import { fields, invalidData, schema, validData } from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('ioTsResolver', () => { + it('should return values from ioTsResolver when validation pass', async () => { + const validateSpy = vi.spyOn(schema, 'decode'); + + const result = ioTsResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(validateSpy).toHaveBeenCalled(); + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return a single error from ioTsResolver when validation fails', () => { + const result = ioTsResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from ioTsResolver when validation fails with `validateAllFieldCriteria` set to true', () => { + const result = ioTsResolver(schema)(invalidData, undefined, { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + /** + * Type inference tests + */ + it('should correctly infer the output type from a io-ts schema', () => { + const resolver = ioTsResolver(t.type({ id: t.number })); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: number }, unknown, { id: number }> + >(); + }); + + it('should correctly infer the output type from a io-ts schema using a transform', () => { + const resolver = ioTsResolver(t.type({ id: tt.NumberFromString })); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: string }, unknown, { id: number }> + >(); + }); + + it('should correctly infer the output type from a io-ts schema for the handleSubmit function in useForm', () => { + const schema = t.type({ id: t.number }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: ioTsResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: number; + }> + >(); + }); + + it('should correctly infer the output type from a io-ts schema with a transform for the handleSubmit function in useForm', () => { + const schema = t.type({ id: tt.NumberFromString }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: ioTsResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: number; + }> + >(); + }); +}); diff --git a/node_modules/@hookform/resolvers/io-ts/src/arrayToPath.ts b/node_modules/@hookform/resolvers/io-ts/src/arrayToPath.ts new file mode 100644 index 0000000000000000000000000000000000000000..b75d6c6bcae78e61e7f78ca080c3331dd2be579f --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/arrayToPath.ts @@ -0,0 +1,18 @@ +import * as Either from 'fp-ts/Either'; +import { pipe } from 'fp-ts/function'; + +const arrayToPath = (paths: Either.Either[]): string => + paths.reduce( + (previous, path, index) => + pipe( + path, + Either.fold( + (key) => `${index > 0 ? '.' : ''}${key}`, + (key) => `[${key}]`, + ), + (path) => `${previous}${path}`, + ), + '', + ); + +export default arrayToPath; diff --git a/node_modules/@hookform/resolvers/io-ts/src/errorsToRecord.ts b/node_modules/@hookform/resolvers/io-ts/src/errorsToRecord.ts new file mode 100644 index 0000000000000000000000000000000000000000..d01f7c34543a5dda643fa39222520e8792233f20 --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/errorsToRecord.ts @@ -0,0 +1,144 @@ +import * as Either from 'fp-ts/Either'; +import * as Option from 'fp-ts/Option'; +import * as ReadonlyArray from 'fp-ts/ReadonlyArray'; +import * as ReadonlyRecord from 'fp-ts/ReadonlyRecord'; +import * as SemiGroup from 'fp-ts/Semigroup'; +import { absurd, flow, identity, not, pipe } from 'fp-ts/function'; +import * as t from 'io-ts'; +import { + ExactType, + IntersectionType, + RefinementType, + TaggedUnionType, + UnionType, + ValidationError, +} from 'io-ts'; +import { FieldError } from 'react-hook-form'; +import arrayToPath from './arrayToPath'; + +export type ErrorObject = Record; +export type FieldErrorWithPath = FieldError & { path: string }; + +const INSTANCE_TYPES_TO_FILTER = [ + TaggedUnionType, + UnionType, + IntersectionType, + ExactType, + RefinementType, +]; +const formatErrorPath = (context: t.Context): string => + pipe( + context, + ReadonlyArray.filterMapWithIndex((index, contextEntry) => { + const previousIndex = index - 1; + const previousContextEntry = + previousIndex === -1 ? undefined : context[previousIndex]; + const shouldBeFiltered = + previousContextEntry === undefined || + INSTANCE_TYPES_TO_FILTER.some( + (type) => previousContextEntry.type instanceof type, + ); + + return shouldBeFiltered ? Option.none : Option.some(contextEntry); + }), + ReadonlyArray.map(({ key }) => key), + ReadonlyArray.map((key) => + pipe( + key, + (k) => parseInt(k, 10), + Either.fromPredicate(not(Number.isNaN), () => key), + ), + ), + ReadonlyArray.toArray, + arrayToPath, + ); + +const formatError = (e: t.ValidationError): FieldErrorWithPath => { + const path = formatErrorPath(e.context); + + const message = pipe( + e.message, + Either.fromNullable(e.context), + Either.mapLeft( + flow( + ReadonlyArray.last, + Option.map( + (contextEntry) => + `expected ${contextEntry.type.name} but got ${JSON.stringify( + contextEntry.actual, + )}`, + ), + Option.getOrElseW(() => + absurd('Error context is missing name' as never), + ), + ), + ), + Either.getOrElseW(identity), + ); + + const type = pipe( + e.context, + ReadonlyArray.last, + Option.map((contextEntry) => contextEntry.type.name), + Option.getOrElse(() => 'unknown'), + ); + + return { message, type, path }; +}; + +// this is almost the same function like Semigroup.getObjectSemigroup but reversed +// in order to get the first error +const getObjectSemigroup = < + A extends Record = never, +>(): SemiGroup.Semigroup
=> ({ + concat: (first, second) => Object.assign({}, second, first), +}); + +const concatToSingleError = ( + errors: ReadonlyArray, +): ErrorObject => + pipe( + errors, + ReadonlyArray.map((error) => ({ + [error.path]: { + type: error.type, + message: error.message, + }, + })), + (errors) => SemiGroup.fold(getObjectSemigroup())({}, errors), + ); + +const appendSeveralErrors: SemiGroup.Semigroup = { + concat: (a, b) => ({ + ...b, + types: { ...a.types, [a.type]: a.message, [b.type]: b.message }, + }), +}; + +const concatToMultipleErrors = ( + errors: ReadonlyArray, +): ErrorObject => + pipe( + ReadonlyRecord.fromFoldableMap(appendSeveralErrors, ReadonlyArray.Foldable)( + errors, + (error) => [error.path, error], + ), + ReadonlyRecord.map((errorWithPath) => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { path, ...error } = errorWithPath; + + return error; + }), + ); + +const errorsToRecord = + (validateAllFieldCriteria: boolean) => + (validationErrors: ReadonlyArray): ErrorObject => { + const concat = validateAllFieldCriteria + ? concatToMultipleErrors + : concatToSingleError; + + return pipe(validationErrors, ReadonlyArray.map(formatError), concat); + }; + +export default errorsToRecord; diff --git a/node_modules/@hookform/resolvers/io-ts/src/index.ts b/node_modules/@hookform/resolvers/io-ts/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..7069193a6597de1fe962a50de11f5096ddee8f5f --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/index.ts @@ -0,0 +1 @@ +export * from './io-ts'; diff --git a/node_modules/@hookform/resolvers/io-ts/src/io-ts.ts b/node_modules/@hookform/resolvers/io-ts/src/io-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..0361fc1e94955cf12f39ba67673c5a3df6be797f --- /dev/null +++ b/node_modules/@hookform/resolvers/io-ts/src/io-ts.ts @@ -0,0 +1,81 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import * as Either from 'fp-ts/Either'; +import { pipe } from 'fp-ts/function'; +import * as t from 'io-ts'; +import { + FieldErrors, + FieldValues, + Resolver, + ResolverError, + ResolverSuccess, +} from 'react-hook-form'; +import errorsToRecord, { ErrorObject } from './errorsToRecord'; + +export function ioTsResolver( + schema: t.Type, + resolverOptions?: { + mode?: 'async' | 'sync'; + raw?: false; + }, +): Resolver; + +export function ioTsResolver( + schema: t.Type, + resolverOptions: { + mode?: 'async' | 'sync'; + raw: true; + }, +): Resolver; + +/** + * Creates a resolver for react-hook-form using io-ts schema validation + * @param {t.Type} schema - The io-ts schema to validate against + * @param {Object} options - Additional resolver configuration + * @param {string} [options.mode='async'] - Validation mode + * @returns {Resolver>} A resolver function compatible with react-hook-form + * @example + * const schema = t.type({ + * name: t.string, + * age: t.number + * }); + * + * useForm({ + * resolver: ioTsResolver(schema) + * }); + */ +export function ioTsResolver( + schema: t.Type, +): Resolver { + return (values, _context, options) => + pipe( + values, + schema.decode, + Either.mapLeft( + errorsToRecord( + !options.shouldUseNativeValidation && options.criteriaMode === 'all', + ), + ), + Either.mapLeft((errors: ErrorObject) => + toNestErrors(errors, options), + ), + Either.fold< + FieldErrors, + Output, + ResolverError | ResolverSuccess + >( + (errors) => ({ + values: {}, + errors, + }), + (values) => { + options.shouldUseNativeValidation && + validateFieldsNatively({}, options); + + return { + values, + errors: {}, + }; + }, + ), + ); +} diff --git a/node_modules/@hookform/resolvers/joi/dist/index.d.ts b/node_modules/@hookform/resolvers/joi/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e9d42aba06d014deccc5465d5109b9bff07d4d6 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/index.d.ts @@ -0,0 +1,2 @@ +export * from './joi'; +export * from './types'; diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.d.ts b/node_modules/@hookform/resolvers/joi/dist/joi.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a26256affab6ee5ff95786fb5e3b8831b4307cf --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.d.ts @@ -0,0 +1,19 @@ +import { Resolver } from './types'; +/** + * Creates a resolver for react-hook-form using Joi schema validation + * @param {Joi.ObjectSchema} schema - The Joi schema to validate against + * @param {Joi.ValidationOptions} [schemaOptions] - Optional Joi validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='async'] - Validation mode + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * const schema = Joi.object({ + * name: Joi.string().required(), + * age: Joi.number().required() + * }); + * + * useForm({ + * resolver: joiResolver(schema) + * }); + */ +export declare const joiResolver: Resolver; diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.js b/node_modules/@hookform/resolvers/joi/dist/joi.js new file mode 100644 index 0000000000000000000000000000000000000000..43d75f848f188c87588b34214c6319b3c0e71af3 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers"),r=require("react-hook-form");exports.joiResolver=function(t,n,o){return void 0===n&&(n={abortEarly:!1}),void 0===o&&(o={}),function(a,i,s){try{var u=function(){return l.error?{values:{},errors:e.toNestErrors((t=l.error,n=!s.shouldUseNativeValidation&&"all"===s.criteriaMode,t.details.length?t.details.reduce(function(e,t){var o=t.path.join(".");if(e[o]||(e[o]={message:t.message,type:t.type}),n){var a=e[o].types,i=a&&a[t.type];e[o]=r.appendErrors(o,n,e,t.type,i?[].concat(i,t.message):t.message)}return e},Object.create(null)):{}),s)}:(s.shouldUseNativeValidation&&e.validateFieldsNatively({},s),{errors:{},values:l.value});var t,n},c=Object.assign({},n,{context:i}),l={},v=function(){if("sync"===o.mode)l=t.validate(a,c);else{var e=function(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(function(){return Promise.resolve(t.validateAsync(a,c)).then(function(e){l.value=e})},function(e){l.error=e});if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(v&&v.then?v.then(u):u())}catch(e){return Promise.reject(e)}}}; +//# sourceMappingURL=joi.js.map diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.js.map b/node_modules/@hookform/resolvers/joi/dist/joi.js.map new file mode 100644 index 0000000000000000000000000000000000000000..00e22e15a6dcf9005eaadb35490a3b8235f7698e --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"joi.js","sources":["../src/joi.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { ValidationError } from 'joi';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n error: ValidationError,\n validateAllFieldCriteria: boolean,\n) =>\n error.details.length\n ? // A null-prototype accumulator avoids false-positive hits from\n // inherited members (e.g. `toString`, `constructor`) when a field is\n // named after one of them — a plain `{}` would make `!previous[_path]`\n // truthy-skip those paths and silently drop their errors.\n error.details.reduce>((previous, error) => {\n const _path = error.path.join('.');\n\n if (!previous[_path]) {\n previous[_path] = { message: error.message, type: error.type };\n }\n\n if (validateAllFieldCriteria) {\n const types = previous[_path].types;\n const messages = types && types[error.type!];\n\n previous[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n previous,\n error.type,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return previous;\n }, Object.create(null))\n : {};\n\n/**\n * Creates a resolver for react-hook-form using Joi schema validation\n * @param {Joi.ObjectSchema} schema - The Joi schema to validate against\n * @param {Joi.ValidationOptions} [schemaOptions] - Optional Joi validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = Joi.object({\n * name: Joi.string().required(),\n * age: Joi.number().required()\n * });\n *\n * useForm({\n * resolver: joiResolver(schema)\n * });\n */\nexport const joiResolver: Resolver =\n (\n schema,\n schemaOptions = {\n abortEarly: false,\n },\n resolverOptions = {},\n ) =>\n async (values, context, options) => {\n const _schemaOptions = Object.assign({}, schemaOptions, {\n context,\n });\n\n let result: Record = {};\n if (resolverOptions.mode === 'sync') {\n result = schema.validate(values, _schemaOptions);\n } else {\n try {\n result.value = await schema.validateAsync(values, _schemaOptions);\n } catch (e) {\n result.error = e;\n }\n }\n\n if (result.error) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n result.error,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: result.value,\n };\n };\n"],"names":["schema","schemaOptions","resolverOptions","values","abortEarly","context","options","_temp3","result","error","errors","toNestErrors","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","details","length","reduce","previous","_path","path","join","message","type","types","messages","appendErrors","concat","Object","create","validateFieldsNatively","value","_schemaOptions","assign","_temp2","mode","validate","_temp","_catch","Promise","resolve","validateAsync","then","_schema$validateAsync","e","reject"],"mappings":"sFA0DE,SACEA,EACAC,EAGAC,GAEKC,YALLF,IAAAA,IAAAA,EAAgB,CACdG,YAAY,SAEC,IAAfF,IAAAA,EAAkB,CAAE,GAEfC,SAAAA,EAAQE,EAASC,OAAWC,IAAAA,EAAAA,WAgBjC,OAAIC,EAAOC,MACF,CACLN,OAAQ,CAAE,EACVO,OAAQC,EAAAA,cA9EdF,EAgFUD,EAAOC,MA/EjBG,GAgFWN,EAAQO,2BACkB,QAAzBP,EAAQQ,aA/EpBL,EAAMM,QAAQC,OAKVP,EAAMM,QAAQE,OAAmC,SAACC,EAAUT,GAC1D,IAAMU,EAAQV,EAAMW,KAAKC,KAAK,KAM9B,GAJKH,EAASC,KACZD,EAASC,GAAS,CAAEG,QAASb,EAAMa,QAASC,KAAMd,EAAMc,OAGtDX,EAA0B,CAC5B,IAAMY,EAAQN,EAASC,GAAOK,MACxBC,EAAWD,GAASA,EAAMf,EAAMc,MAEtCL,EAASC,GAASO,EAAAA,aAChBP,EACAP,EACAM,EACAT,EAAMc,KACNE,EACK,GAAgBE,OAAOF,EAAsBhB,EAAMa,SACpDb,EAAMa,QAEd,CAEA,OAAOJ,CACT,EAAGU,OAAOC,OAAO,OACjB,CAAE,GAoDEvB,KAKNA,EAAQO,2BAA6BiB,EAAsBA,uBAAC,CAAE,EAAExB,GAEzD,CACLI,OAAQ,CAAA,EACRP,OAAQK,EAAOuB,QA9FI,IACvBtB,EACAG,CA6FI,EAlCIoB,EAAiBJ,OAAOK,OAAO,GAAIhC,EAAe,CACtDI,QAAAA,IAGEG,EAA8B,CAAA,EAAG0B,EACjChC,WAAAA,GAAyB,SAAzBA,EAAgBiC,KAClB3B,EAASR,EAAOoC,SAASjC,EAAQ6B,OAAgB,CAAA,IAAAK,uFAAAC,CAE7C,WAAA,OAAAC,QAAAC,QACmBxC,EAAOyC,cAActC,EAAQ6B,IAAeU,KAAA,SAAAC,GAAjEnC,EAAOuB,MAAKY,CAAsD,EACpE,EAAC,SAAQC,GACPpC,EAAOC,MAAQmC,CACjB,GAACP,GAAAA,GAAAA,EAAAK,KAAAL,OAAAA,EAAAK,KAAAH,WAAAA,EAAAA,CAAAA,CAPCrC,GAODqC,OAAAA,QAAAC,QAAAN,GAAAA,EAAAQ,KAAAR,EAAAQ,KAAAnC,GAAAA,IAuBL,CAAC,MAAAqC,GAAA,OAAAL,QAAAM,OAAAD,EAAA,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.mjs b/node_modules/@hookform/resolvers/joi/dist/joi.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f46a9b5c9657ad668ac46c337cfba16d53d11475 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";import{appendErrors as t}from"react-hook-form";var n=function(n,o,a){return void 0===o&&(o={abortEarly:!1}),void 0===a&&(a={}),function(i,s,u){try{var c=function(){return v.error?{values:{},errors:e((n=v.error,o=!u.shouldUseNativeValidation&&"all"===u.criteriaMode,n.details.length?n.details.reduce(function(e,r){var n=r.path.join(".");if(e[n]||(e[n]={message:r.message,type:r.type}),o){var a=e[n].types,i=a&&a[r.type];e[n]=t(n,o,e,r.type,i?[].concat(i,r.message):r.message)}return e},Object.create(null)):{}),u)}:(u.shouldUseNativeValidation&&r({},u),{errors:{},values:v.value});var n,o},l=Object.assign({},o,{context:s}),v={},f=function(){if("sync"===a.mode)v=n.validate(i,l);else{var e=function(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(function(){return Promise.resolve(n.validateAsync(i,l)).then(function(e){v.value=e})},function(e){v.error=e});if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(c):c())}catch(e){return Promise.reject(e)}}};export{n as joiResolver}; +//# sourceMappingURL=joi.module.js.map diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.modern.mjs b/node_modules/@hookform/resolvers/joi/dist/joi.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1fabbc2223fe6610530676ea891eed3b8bb88525 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.modern.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";import{appendErrors as t}from"react-hook-form";const a=(a,o={abortEarly:!1},s={})=>async(l,i,c)=>{const n=Object.assign({},o,{context:i});let d={};if("sync"===s.mode)d=a.validate(l,n);else try{d.value=await a.validateAsync(l,n)}catch(e){d.error=e}return d.error?{values:{},errors:e((m=d.error,u=!c.shouldUseNativeValidation&&"all"===c.criteriaMode,m.details.length?m.details.reduce((e,r)=>{const a=r.path.join(".");if(e[a]||(e[a]={message:r.message,type:r.type}),u){const o=e[a].types,s=o&&o[r.type];e[a]=t(a,u,e,r.type,s?[].concat(s,r.message):r.message)}return e},Object.create(null)):{}),c)}:(c.shouldUseNativeValidation&&r({},c),{errors:{},values:d.value});var m,u};export{a as joiResolver}; +//# sourceMappingURL=joi.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.modern.mjs.map b/node_modules/@hookform/resolvers/joi/dist/joi.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1599c94f696769982762aa8a0784c9a4f8555be6 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"joi.modern.mjs","sources":["../src/joi.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { ValidationError } from 'joi';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n error: ValidationError,\n validateAllFieldCriteria: boolean,\n) =>\n error.details.length\n ? // A null-prototype accumulator avoids false-positive hits from\n // inherited members (e.g. `toString`, `constructor`) when a field is\n // named after one of them — a plain `{}` would make `!previous[_path]`\n // truthy-skip those paths and silently drop their errors.\n error.details.reduce>((previous, error) => {\n const _path = error.path.join('.');\n\n if (!previous[_path]) {\n previous[_path] = { message: error.message, type: error.type };\n }\n\n if (validateAllFieldCriteria) {\n const types = previous[_path].types;\n const messages = types && types[error.type!];\n\n previous[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n previous,\n error.type,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return previous;\n }, Object.create(null))\n : {};\n\n/**\n * Creates a resolver for react-hook-form using Joi schema validation\n * @param {Joi.ObjectSchema} schema - The Joi schema to validate against\n * @param {Joi.ValidationOptions} [schemaOptions] - Optional Joi validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = Joi.object({\n * name: Joi.string().required(),\n * age: Joi.number().required()\n * });\n *\n * useForm({\n * resolver: joiResolver(schema)\n * });\n */\nexport const joiResolver: Resolver =\n (\n schema,\n schemaOptions = {\n abortEarly: false,\n },\n resolverOptions = {},\n ) =>\n async (values, context, options) => {\n const _schemaOptions = Object.assign({}, schemaOptions, {\n context,\n });\n\n let result: Record = {};\n if (resolverOptions.mode === 'sync') {\n result = schema.validate(values, _schemaOptions);\n } else {\n try {\n result.value = await schema.validateAsync(values, _schemaOptions);\n } catch (e) {\n result.error = e;\n }\n }\n\n if (result.error) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n result.error,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: result.value,\n };\n };\n"],"names":["joiResolver","schema","schemaOptions","abortEarly","resolverOptions","async","values","context","options","_schemaOptions","Object","assign","result","mode","validate","value","validateAsync","e","error","errors","toNestErrors","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","details","length","reduce","previous","_path","path","join","message","type","types","messages","appendErrors","concat","create","validateFieldsNatively","parseErrorSchema"],"mappings":"8HAKA,MAoDaA,EACXA,CACEC,EACAC,EAAgB,CACdC,YAAY,GAEdC,EAAkB,CAAE,IAEtBC,MAAOC,EAAQC,EAASC,KACtB,MAAMC,EAAiBC,OAAOC,OAAO,CAAA,EAAIT,EAAe,CACtDK,YAGF,IAAIK,EAA8B,CAAE,EACpC,GAA6B,SAAzBR,EAAgBS,KAClBD,EAASX,EAAOa,SAASR,EAAQG,QAEjC,IACEG,EAAOG,YAAcd,EAAOe,cAAcV,EAAQG,EACpD,CAAE,MAAOQ,GACPL,EAAOM,MAAQD,CACjB,CAGF,OAAIL,EAAOM,MACF,CACLZ,OAAQ,CAAE,EACVa,OAAQC,GA9EdF,EAgFUN,EAAOM,MA/EjBG,GAgFWb,EAAQc,2BACkB,QAAzBd,EAAQe,aA/EpBL,EAAMM,QAAQC,OAKVP,EAAMM,QAAQE,OAAmC,CAACC,EAAUT,KAC1D,MAAMU,EAAQV,EAAMW,KAAKC,KAAK,KAM9B,GAJKH,EAASC,KACZD,EAASC,GAAS,CAAEG,QAASb,EAAMa,QAASC,KAAMd,EAAMc,OAGtDX,EAA0B,CAC5B,MAAMY,EAAQN,EAASC,GAAOK,MACxBC,EAAWD,GAASA,EAAMf,EAAMc,MAEtCL,EAASC,GAASO,EAChBP,EACAP,EACAM,EACAT,EAAMc,KACNE,EACK,GAAgBE,OAAOF,EAAsBhB,EAAMa,SACpDb,EAAMa,QAEd,CAEA,OAAOJ,CAAQ,EACdjB,OAAO2B,OAAO,OACjB,CAAA,GAoDI7B,KAKNA,EAAQc,2BAA6BgB,EAAuB,CAAA,EAAI9B,GAEzD,CACLW,OAAQ,CAAE,EACVb,OAAQM,EAAOG,QA9FIwB,IACvBrB,EACAG,CA6FG"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.module.js b/node_modules/@hookform/resolvers/joi/dist/joi.module.js new file mode 100644 index 0000000000000000000000000000000000000000..f46a9b5c9657ad668ac46c337cfba16d53d11475 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.module.js @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";import{appendErrors as t}from"react-hook-form";var n=function(n,o,a){return void 0===o&&(o={abortEarly:!1}),void 0===a&&(a={}),function(i,s,u){try{var c=function(){return v.error?{values:{},errors:e((n=v.error,o=!u.shouldUseNativeValidation&&"all"===u.criteriaMode,n.details.length?n.details.reduce(function(e,r){var n=r.path.join(".");if(e[n]||(e[n]={message:r.message,type:r.type}),o){var a=e[n].types,i=a&&a[r.type];e[n]=t(n,o,e,r.type,i?[].concat(i,r.message):r.message)}return e},Object.create(null)):{}),u)}:(u.shouldUseNativeValidation&&r({},u),{errors:{},values:v.value});var n,o},l=Object.assign({},o,{context:s}),v={},f=function(){if("sync"===a.mode)v=n.validate(i,l);else{var e=function(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(function(){return Promise.resolve(n.validateAsync(i,l)).then(function(e){v.value=e})},function(e){v.error=e});if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(c):c())}catch(e){return Promise.reject(e)}}};export{n as joiResolver}; +//# sourceMappingURL=joi.module.js.map diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.module.js.map b/node_modules/@hookform/resolvers/joi/dist/joi.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..75a1b7afd6e3813a4fac03ac4f774e99b1ef26ff --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"joi.module.js","sources":["../src/joi.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { ValidationError } from 'joi';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n error: ValidationError,\n validateAllFieldCriteria: boolean,\n) =>\n error.details.length\n ? // A null-prototype accumulator avoids false-positive hits from\n // inherited members (e.g. `toString`, `constructor`) when a field is\n // named after one of them — a plain `{}` would make `!previous[_path]`\n // truthy-skip those paths and silently drop their errors.\n error.details.reduce>((previous, error) => {\n const _path = error.path.join('.');\n\n if (!previous[_path]) {\n previous[_path] = { message: error.message, type: error.type };\n }\n\n if (validateAllFieldCriteria) {\n const types = previous[_path].types;\n const messages = types && types[error.type!];\n\n previous[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n previous,\n error.type,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return previous;\n }, Object.create(null))\n : {};\n\n/**\n * Creates a resolver for react-hook-form using Joi schema validation\n * @param {Joi.ObjectSchema} schema - The Joi schema to validate against\n * @param {Joi.ValidationOptions} [schemaOptions] - Optional Joi validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = Joi.object({\n * name: Joi.string().required(),\n * age: Joi.number().required()\n * });\n *\n * useForm({\n * resolver: joiResolver(schema)\n * });\n */\nexport const joiResolver: Resolver =\n (\n schema,\n schemaOptions = {\n abortEarly: false,\n },\n resolverOptions = {},\n ) =>\n async (values, context, options) => {\n const _schemaOptions = Object.assign({}, schemaOptions, {\n context,\n });\n\n let result: Record = {};\n if (resolverOptions.mode === 'sync') {\n result = schema.validate(values, _schemaOptions);\n } else {\n try {\n result.value = await schema.validateAsync(values, _schemaOptions);\n } catch (e) {\n result.error = e;\n }\n }\n\n if (result.error) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n result.error,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: result.value,\n };\n };\n"],"names":["joiResolver","schema","schemaOptions","resolverOptions","values","abortEarly","context","options","_temp3","result","error","errors","toNestErrors","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","details","length","reduce","previous","_path","path","join","message","type","types","messages","appendErrors","concat","Object","create","validateFieldsNatively","value","_schemaOptions","assign","_temp2","mode","validate","_temp","_catch","Promise","resolve","validateAsync","then","_schema$validateAsync","e","reject"],"mappings":"8HAKA,IAoDaA,EACX,SACEC,EACAC,EAGAC,GAEKC,YALLF,IAAAA,IAAAA,EAAgB,CACdG,YAAY,SAEC,IAAfF,IAAAA,EAAkB,CAAE,GAEfC,SAAAA,EAAQE,EAASC,OAAWC,IAAAA,EAAAA,WAgBjC,OAAIC,EAAOC,MACF,CACLN,OAAQ,CAAE,EACVO,OAAQC,GA9EdF,EAgFUD,EAAOC,MA/EjBG,GAgFWN,EAAQO,2BACkB,QAAzBP,EAAQQ,aA/EpBL,EAAMM,QAAQC,OAKVP,EAAMM,QAAQE,OAAmC,SAACC,EAAUT,GAC1D,IAAMU,EAAQV,EAAMW,KAAKC,KAAK,KAM9B,GAJKH,EAASC,KACZD,EAASC,GAAS,CAAEG,QAASb,EAAMa,QAASC,KAAMd,EAAMc,OAGtDX,EAA0B,CAC5B,IAAMY,EAAQN,EAASC,GAAOK,MACxBC,EAAWD,GAASA,EAAMf,EAAMc,MAEtCL,EAASC,GAASO,EAChBP,EACAP,EACAM,EACAT,EAAMc,KACNE,EACK,GAAgBE,OAAOF,EAAsBhB,EAAMa,SACpDb,EAAMa,QAEd,CAEA,OAAOJ,CACT,EAAGU,OAAOC,OAAO,OACjB,CAAE,GAoDEvB,KAKNA,EAAQO,2BAA6BiB,EAAuB,CAAE,EAAExB,GAEzD,CACLI,OAAQ,CAAA,EACRP,OAAQK,EAAOuB,QA9FI,IACvBtB,EACAG,CA6FI,EAlCIoB,EAAiBJ,OAAOK,OAAO,GAAIhC,EAAe,CACtDI,QAAAA,IAGEG,EAA8B,CAAA,EAAG0B,EACjChC,WAAAA,GAAyB,SAAzBA,EAAgBiC,KAClB3B,EAASR,EAAOoC,SAASjC,EAAQ6B,OAAgB,CAAA,IAAAK,uFAAAC,CAE7C,WAAA,OAAAC,QAAAC,QACmBxC,EAAOyC,cAActC,EAAQ6B,IAAeU,KAAA,SAAAC,GAAjEnC,EAAOuB,MAAKY,CAAsD,EACpE,EAAC,SAAQC,GACPpC,EAAOC,MAAQmC,CACjB,GAACP,GAAAA,GAAAA,EAAAK,KAAAL,OAAAA,EAAAK,KAAAH,WAAAA,EAAAA,CAAAA,CAPCrC,GAODqC,OAAAA,QAAAC,QAAAN,GAAAA,EAAAQ,KAAAR,EAAAQ,KAAAnC,GAAAA,IAuBL,CAAC,MAAAqC,GAAA,OAAAL,QAAAM,OAAAD,EAAA,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.umd.js b/node_modules/@hookform/resolvers/joi/dist/joi.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..cbcec5ec7da8390deeb2ad51bb5ea30236fe5888 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","react-hook-form"],r):r((e||self).hookformResolversJoi={},e.hookformResolvers,e.ReactHookForm)}(this,function(e,r,o){e.joiResolver=function(e,t,n){return void 0===t&&(t={abortEarly:!1}),void 0===n&&(n={}),function(i,s,a){try{var l=function(){return c.error?{values:{},errors:r.toNestErrors((e=c.error,t=!a.shouldUseNativeValidation&&"all"===a.criteriaMode,e.details.length?e.details.reduce(function(e,r){var n=r.path.join(".");if(e[n]||(e[n]={message:r.message,type:r.type}),t){var i=e[n].types,s=i&&i[r.type];e[n]=o.appendErrors(n,t,e,r.type,s?[].concat(s,r.message):r.message)}return e},Object.create(null)):{}),a)}:(a.shouldUseNativeValidation&&r.validateFieldsNatively({},a),{errors:{},values:c.value});var e,t},u=Object.assign({},t,{context:s}),c={},f=function(){if("sync"===n.mode)c=e.validate(i,u);else{var r=function(e,r){try{var o=e()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(function(){return Promise.resolve(e.validateAsync(i,u)).then(function(e){c.value=e})},function(e){c.error=e});if(r&&r.then)return r.then(function(){})}}();return Promise.resolve(f&&f.then?f.then(l):l())}catch(e){return Promise.reject(e)}}}}); +//# sourceMappingURL=joi.umd.js.map diff --git a/node_modules/@hookform/resolvers/joi/dist/joi.umd.js.map b/node_modules/@hookform/resolvers/joi/dist/joi.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8843f4f98ed789500e3156afcfb0258fcd58fdda --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/joi.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"joi.umd.js","sources":["../src/joi.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { ValidationError } from 'joi';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n error: ValidationError,\n validateAllFieldCriteria: boolean,\n) =>\n error.details.length\n ? // A null-prototype accumulator avoids false-positive hits from\n // inherited members (e.g. `toString`, `constructor`) when a field is\n // named after one of them — a plain `{}` would make `!previous[_path]`\n // truthy-skip those paths and silently drop their errors.\n error.details.reduce>((previous, error) => {\n const _path = error.path.join('.');\n\n if (!previous[_path]) {\n previous[_path] = { message: error.message, type: error.type };\n }\n\n if (validateAllFieldCriteria) {\n const types = previous[_path].types;\n const messages = types && types[error.type!];\n\n previous[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n previous,\n error.type,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return previous;\n }, Object.create(null))\n : {};\n\n/**\n * Creates a resolver for react-hook-form using Joi schema validation\n * @param {Joi.ObjectSchema} schema - The Joi schema to validate against\n * @param {Joi.ValidationOptions} [schemaOptions] - Optional Joi validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = Joi.object({\n * name: Joi.string().required(),\n * age: Joi.number().required()\n * });\n *\n * useForm({\n * resolver: joiResolver(schema)\n * });\n */\nexport const joiResolver: Resolver =\n (\n schema,\n schemaOptions = {\n abortEarly: false,\n },\n resolverOptions = {},\n ) =>\n async (values, context, options) => {\n const _schemaOptions = Object.assign({}, schemaOptions, {\n context,\n });\n\n let result: Record = {};\n if (resolverOptions.mode === 'sync') {\n result = schema.validate(values, _schemaOptions);\n } else {\n try {\n result.value = await schema.validateAsync(values, _schemaOptions);\n } catch (e) {\n result.error = e;\n }\n }\n\n if (result.error) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n result.error,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: result.value,\n };\n };\n"],"names":["schema","schemaOptions","resolverOptions","values","abortEarly","context","options","_temp3","result","error","errors","toNestErrors","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","details","length","reduce","previous","_path","path","join","message","type","types","messages","appendErrors","concat","Object","create","validateFieldsNatively","value","_schemaOptions","assign","_temp2","mode","validate","_temp","_catch","Promise","resolve","validateAsync","then","_schema$validateAsync","e","reject"],"mappings":"sYA0DE,SACEA,EACAC,EAGAC,GAEKC,YALLF,IAAAA,IAAAA,EAAgB,CACdG,YAAY,SAEC,IAAfF,IAAAA,EAAkB,CAAE,GAEfC,SAAAA,EAAQE,EAASC,OAAWC,IAAAA,EAAAA,WAgBjC,OAAIC,EAAOC,MACF,CACLN,OAAQ,CAAE,EACVO,OAAQC,EAAAA,cA9EdF,EAgFUD,EAAOC,MA/EjBG,GAgFWN,EAAQO,2BACkB,QAAzBP,EAAQQ,aA/EpBL,EAAMM,QAAQC,OAKVP,EAAMM,QAAQE,OAAmC,SAACC,EAAUT,GAC1D,IAAMU,EAAQV,EAAMW,KAAKC,KAAK,KAM9B,GAJKH,EAASC,KACZD,EAASC,GAAS,CAAEG,QAASb,EAAMa,QAASC,KAAMd,EAAMc,OAGtDX,EAA0B,CAC5B,IAAMY,EAAQN,EAASC,GAAOK,MACxBC,EAAWD,GAASA,EAAMf,EAAMc,MAEtCL,EAASC,GAASO,EAAAA,aAChBP,EACAP,EACAM,EACAT,EAAMc,KACNE,EACK,GAAgBE,OAAOF,EAAsBhB,EAAMa,SACpDb,EAAMa,QAEd,CAEA,OAAOJ,CACT,EAAGU,OAAOC,OAAO,OACjB,CAAE,GAoDEvB,KAKNA,EAAQO,2BAA6BiB,EAAsBA,uBAAC,CAAE,EAAExB,GAEzD,CACLI,OAAQ,CAAA,EACRP,OAAQK,EAAOuB,QA9FI,IACvBtB,EACAG,CA6FI,EAlCIoB,EAAiBJ,OAAOK,OAAO,GAAIhC,EAAe,CACtDI,QAAAA,IAGEG,EAA8B,CAAA,EAAG0B,EACjChC,WAAAA,GAAyB,SAAzBA,EAAgBiC,KAClB3B,EAASR,EAAOoC,SAASjC,EAAQ6B,OAAgB,CAAA,IAAAK,uFAAAC,CAE7C,WAAA,OAAAC,QAAAC,QACmBxC,EAAOyC,cAActC,EAAQ6B,IAAeU,KAAA,SAAAC,GAAjEnC,EAAOuB,MAAKY,CAAsD,EACpE,EAAC,SAAQC,GACPpC,EAAOC,MAAQmC,CACjB,GAACP,GAAAA,GAAAA,EAAAK,KAAAL,OAAAA,EAAAK,KAAAH,WAAAA,EAAAA,CAAAA,CAPCrC,GAODqC,OAAAA,QAAAC,QAAAN,GAAAA,EAAAQ,KAAAR,EAAAQ,KAAAnC,GAAAA,IAuBL,CAAC,MAAAqC,GAAA,OAAAL,QAAAM,OAAAD,EAAA,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/joi/dist/types.d.ts b/node_modules/@hookform/resolvers/joi/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..067cbc17b8e3b45ba105a89e21d587c50e8bd9d2 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/dist/types.d.ts @@ -0,0 +1,5 @@ +import type { AsyncValidationOptions, Schema } from 'joi'; +import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form'; +export type Resolver = (schema: T, schemaOptions?: AsyncValidationOptions, factoryOptions?: { + mode?: 'async' | 'sync'; +}) => (values: TFieldValues, context: TContext | undefined, options: ResolverOptions) => Promise>; diff --git a/node_modules/@hookform/resolvers/joi/package.json b/node_modules/@hookform/resolvers/joi/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4cccb2c08428ac61ee2e9a940c38f4dc43fdde1d --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/package.json @@ -0,0 +1,17 @@ +{ + "name": "@hookform/resolvers/joi", + "amdName": "hookformResolversJoi", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: joi", + "main": "dist/joi.js", + "module": "dist/joi.module.js", + "umd:main": "dist/joi.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0" + } +} diff --git a/node_modules/@hookform/resolvers/joi/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/joi/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f4a2e83ce8df6e99e84d5a062c27d34cfdf68a16 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,85 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import * as Joi from 'joi'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { joiResolver } from '..'; + +const schema = Joi.object({ + username: Joi.string().required(), + password: Joi.string().required(), +}); + +interface FormData { + username: string; + password: string; +} + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: joiResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with Joi", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe( + '"username" is not allowed to be empty', + ); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe( + '"password" is not allowed to be empty', + ); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/joi/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/joi/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..038fe9d2f93d011dbb46265111d61de122bfcf0c --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/__tests__/Form.tsx @@ -0,0 +1,59 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import * as Joi from 'joi'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { joiResolver } from '..'; + +const schema = Joi.object({ + username: Joi.string().required(), + password: Joi.string().required(), +}); + +interface FormData { + username: string; + password: string; +} + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: joiResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with Joi and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect( + screen.getByText(/"username" is not allowed to be empty/i), + ).toBeInTheDocument(); + expect( + screen.getByText(/"password" is not allowed to be empty/i), + ).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/joi/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/joi/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..87a6b9b77ae089a531c67d48ca8474c61bec2aef --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,85 @@ +import * as Joi from 'joi'; + +import { Field, InternalFieldName } from 'react-hook-form'; + +export const schema = Joi.object({ + username: Joi.string().alphanum().min(3).max(30).required(), + password: Joi.string() + .pattern(new RegExp('.*[A-Z].*'), 'One uppercase character') + .pattern(new RegExp('.*[a-z].*'), 'One lowercase character') + .pattern(new RegExp('.*\\d.*'), 'One number') + .pattern( + new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'), + 'One special character', + ) + .min(8) + .required(), + repeatPassword: Joi.ref('password'), + accessToken: [Joi.string(), Joi.number()], + birthYear: Joi.number().integer().min(1900).max(2013), + email: Joi.string().email({ + minDomainSegments: 2, + tlds: { allow: ['com', 'net'] }, + }), + tags: Joi.array().items(Joi.string()).required(), + enabled: Joi.boolean().required(), + like: Joi.array() + .items( + Joi.object({ id: Joi.number(), name: Joi.string().length(4).regex(/a/) }), + ) + .optional(), +}); + +interface Data { + username: string; + password: string; + repeatPassword: string; + accessToken?: number | string; + birthYear?: number; + email?: string; + tags: string[]; + enabled: boolean; + like: { id: number; name: string }[]; +} + +export const validData: Data = { + username: 'Doe', + password: 'Password123_', + repeatPassword: 'Password123_', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + like: [ + { + id: 1, + name: 'name', + }, + ], +}; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: [{ id: 'z', name: 'r' }], +}; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/joi/src/__tests__/__snapshots__/joi.ts.snap b/node_modules/@hookform/resolvers/joi/src/__tests__/__snapshots__/joi.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..06dee50be489d82766cca9122d29dda7d333deaa --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/__tests__/__snapshots__/joi.ts.snap @@ -0,0 +1,293 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`joiResolver > should return a single error from joiResolver when validation fails 1`] = ` +{ + "errors": { + "birthYear": { + "message": ""birthYear" must be a number", + "ref": undefined, + "type": "number.base", + }, + "email": { + "message": ""email" is not allowed to be empty", + "ref": { + "name": "email", + }, + "type": "string.empty", + }, + "enabled": { + "message": ""enabled" is required", + "ref": undefined, + "type": "any.required", + }, + "like": [ + { + "id": { + "message": ""like[0].id" must be a number", + "ref": undefined, + "type": "number.base", + }, + "name": { + "message": ""like[0].name" length must be 4 characters long", + "ref": undefined, + "type": "string.length", + }, + }, + ], + "password": { + "message": ""password" with value "___" fails to match the One uppercase character pattern", + "ref": { + "name": "password", + }, + "type": "string.pattern.name", + }, + "tags": { + "message": ""tags" is required", + "ref": undefined, + "type": "any.required", + }, + "username": { + "message": ""username" is required", + "ref": { + "name": "username", + }, + "type": "any.required", + }, + }, + "values": {}, +} +`; + +exports[`joiResolver > should return a single error from joiResolver with \`mode: sync\` when validation fails 1`] = ` +{ + "errors": { + "birthYear": { + "message": ""birthYear" must be a number", + "ref": undefined, + "type": "number.base", + }, + "email": { + "message": ""email" is not allowed to be empty", + "ref": { + "name": "email", + }, + "type": "string.empty", + }, + "enabled": { + "message": ""enabled" is required", + "ref": undefined, + "type": "any.required", + }, + "like": [ + { + "id": { + "message": ""like[0].id" must be a number", + "ref": undefined, + "type": "number.base", + }, + "name": { + "message": ""like[0].name" length must be 4 characters long", + "ref": undefined, + "type": "string.length", + }, + }, + ], + "password": { + "message": ""password" with value "___" fails to match the One uppercase character pattern", + "ref": { + "name": "password", + }, + "type": "string.pattern.name", + }, + "tags": { + "message": ""tags" is required", + "ref": undefined, + "type": "any.required", + }, + "username": { + "message": ""username" is required", + "ref": { + "name": "username", + }, + "type": "any.required", + }, + }, + "values": {}, +} +`; + +exports[`joiResolver > should return all the errors from joiResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = ` +{ + "errors": { + "birthYear": { + "message": ""birthYear" must be a number", + "ref": undefined, + "type": "number.base", + "types": { + "number.base": ""birthYear" must be a number", + }, + }, + "email": { + "message": ""email" is not allowed to be empty", + "ref": { + "name": "email", + }, + "type": "string.empty", + "types": { + "string.empty": ""email" is not allowed to be empty", + }, + }, + "enabled": { + "message": ""enabled" is required", + "ref": undefined, + "type": "any.required", + "types": { + "any.required": ""enabled" is required", + }, + }, + "like": [ + { + "id": { + "message": ""like[0].id" must be a number", + "ref": undefined, + "type": "number.base", + "types": { + "number.base": ""like[0].id" must be a number", + }, + }, + "name": { + "message": ""like[0].name" length must be 4 characters long", + "ref": undefined, + "type": "string.length", + "types": { + "string.length": ""like[0].name" length must be 4 characters long", + "string.pattern.base": ""like[0].name" with value "r" fails to match the required pattern: /a/", + }, + }, + }, + ], + "password": { + "message": ""password" with value "___" fails to match the One uppercase character pattern", + "ref": { + "name": "password", + }, + "type": "string.pattern.name", + "types": { + "string.min": ""password" length must be at least 8 characters long", + "string.pattern.name": [ + ""password" with value "___" fails to match the One uppercase character pattern", + ""password" with value "___" fails to match the One lowercase character pattern", + ""password" with value "___" fails to match the One number pattern", + ], + }, + }, + "tags": { + "message": ""tags" is required", + "ref": undefined, + "type": "any.required", + "types": { + "any.required": ""tags" is required", + }, + }, + "username": { + "message": ""username" is required", + "ref": { + "name": "username", + }, + "type": "any.required", + "types": { + "any.required": ""username" is required", + }, + }, + }, + "values": {}, +} +`; + +exports[`joiResolver > should return all the errors from joiResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = ` +{ + "errors": { + "birthYear": { + "message": ""birthYear" must be a number", + "ref": undefined, + "type": "number.base", + "types": { + "number.base": ""birthYear" must be a number", + }, + }, + "email": { + "message": ""email" is not allowed to be empty", + "ref": { + "name": "email", + }, + "type": "string.empty", + "types": { + "string.empty": ""email" is not allowed to be empty", + }, + }, + "enabled": { + "message": ""enabled" is required", + "ref": undefined, + "type": "any.required", + "types": { + "any.required": ""enabled" is required", + }, + }, + "like": [ + { + "id": { + "message": ""like[0].id" must be a number", + "ref": undefined, + "type": "number.base", + "types": { + "number.base": ""like[0].id" must be a number", + }, + }, + "name": { + "message": ""like[0].name" length must be 4 characters long", + "ref": undefined, + "type": "string.length", + "types": { + "string.length": ""like[0].name" length must be 4 characters long", + "string.pattern.base": ""like[0].name" with value "r" fails to match the required pattern: /a/", + }, + }, + }, + ], + "password": { + "message": ""password" with value "___" fails to match the One uppercase character pattern", + "ref": { + "name": "password", + }, + "type": "string.pattern.name", + "types": { + "string.min": ""password" length must be at least 8 characters long", + "string.pattern.name": [ + ""password" with value "___" fails to match the One uppercase character pattern", + ""password" with value "___" fails to match the One lowercase character pattern", + ""password" with value "___" fails to match the One number pattern", + ], + }, + }, + "tags": { + "message": ""tags" is required", + "ref": undefined, + "type": "any.required", + "types": { + "any.required": ""tags" is required", + }, + }, + "username": { + "message": ""username" is required", + "ref": { + "name": "username", + }, + "type": "any.required", + "types": { + "any.required": ""username" is required", + }, + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/joi/src/__tests__/joi.ts b/node_modules/@hookform/resolvers/joi/src/__tests__/joi.ts new file mode 100644 index 0000000000000000000000000000000000000000..36dc28b9058e70a21a8c9f868252cc24e3e4d6ff --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/__tests__/joi.ts @@ -0,0 +1,98 @@ +import { joiResolver } from '..'; +import { fields, invalidData, schema, validData } from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('joiResolver', () => { + it('should return values from joiResolver when validation pass', async () => { + const validateAsyncSpy = vi.spyOn(schema, 'validateAsync'); + const validateSpy = vi.spyOn(schema, 'validate'); + + const result = await joiResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(validateSpy).not.toHaveBeenCalled(); + expect(validateAsyncSpy).toHaveBeenCalledTimes(1); + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return values from joiResolver with `mode: sync` when validation pass', async () => { + const validateAsyncSpy = vi.spyOn(schema, 'validateAsync'); + const validateSpy = vi.spyOn(schema, 'validate'); + + const result = await joiResolver(schema, undefined, { + mode: 'sync', + })(validData, undefined, { fields, shouldUseNativeValidation }); + + expect(validateAsyncSpy).not.toHaveBeenCalled(); + expect(validateSpy).toHaveBeenCalledTimes(1); + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return a single error from joiResolver when validation fails', async () => { + const result = await joiResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should return a single error from joiResolver with `mode: sync` when validation fails', async () => { + const validateAsyncSpy = vi.spyOn(schema, 'validateAsync'); + const validateSpy = vi.spyOn(schema, 'validate'); + + const result = await joiResolver(schema, undefined, { + mode: 'sync', + })(invalidData, undefined, { fields, shouldUseNativeValidation }); + + expect(validateAsyncSpy).not.toHaveBeenCalled(); + expect(validateSpy).toHaveBeenCalledTimes(1); + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from joiResolver when validation fails with `validateAllFieldCriteria` set to true', async () => { + const result = await joiResolver(schema)(invalidData, undefined, { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from joiResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => { + const result = await joiResolver(schema, undefined, { mode: 'sync' })( + invalidData, + undefined, + { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return values from joiResolver when validation pass and pass down the Joi context', async () => { + const context = { value: 'context' }; + const validateAsyncSpy = vi.spyOn(schema, 'validateAsync'); + const validateSpy = vi.spyOn(schema, 'validate'); + + const result = await joiResolver(schema)(validData, context, { + fields, + shouldUseNativeValidation, + }); + + expect(validateSpy).not.toHaveBeenCalled(); + expect(validateAsyncSpy).toHaveBeenCalledTimes(1); + expect(validateAsyncSpy).toHaveBeenCalledWith(validData, { + abortEarly: false, + context, + }); + expect(result).toEqual({ errors: {}, values: validData }); + }); +}); diff --git a/node_modules/@hookform/resolvers/joi/src/__tests__/special-path-names.ts b/node_modules/@hookform/resolvers/joi/src/__tests__/special-path-names.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b0d5ab57863d6c2b00ec61da03d3b70ff13087a --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/__tests__/special-path-names.ts @@ -0,0 +1,24 @@ +import * as Joi from 'joi'; +import { joiResolver } from '..'; + +const shouldUseNativeValidation = false; + +describe('joiResolver special path names', () => { + it.each(['hasOwnProperty', 'toString'])( + 'reports a validation error for a field named "%s"', + async (name) => { + const schema = Joi.object({ [name]: Joi.string().min(1).required() }); + + const result = await joiResolver(schema)( + { [name]: '' } as any, + undefined, + { + fields: {}, + shouldUseNativeValidation, + } as any, + ); + + expect(result.errors[name]).toBeDefined(); + }, + ); +}); diff --git a/node_modules/@hookform/resolvers/joi/src/index.ts b/node_modules/@hookform/resolvers/joi/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e9d42aba06d014deccc5465d5109b9bff07d4d6 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/index.ts @@ -0,0 +1,2 @@ +export * from './joi'; +export * from './types'; diff --git a/node_modules/@hookform/resolvers/joi/src/joi.ts b/node_modules/@hookform/resolvers/joi/src/joi.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7d537b507bd95d37ec2ba24236769b3f00fa3c9 --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/joi.ts @@ -0,0 +1,102 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import type { ValidationError } from 'joi'; +import { FieldError, appendErrors } from 'react-hook-form'; +import { Resolver } from './types'; + +const parseErrorSchema = ( + error: ValidationError, + validateAllFieldCriteria: boolean, +) => + error.details.length + ? // A null-prototype accumulator avoids false-positive hits from + // inherited members (e.g. `toString`, `constructor`) when a field is + // named after one of them — a plain `{}` would make `!previous[_path]` + // truthy-skip those paths and silently drop their errors. + error.details.reduce>((previous, error) => { + const _path = error.path.join('.'); + + if (!previous[_path]) { + previous[_path] = { message: error.message, type: error.type }; + } + + if (validateAllFieldCriteria) { + const types = previous[_path].types; + const messages = types && types[error.type!]; + + previous[_path] = appendErrors( + _path, + validateAllFieldCriteria, + previous, + error.type, + messages + ? ([] as string[]).concat(messages as string[], error.message) + : error.message, + ) as FieldError; + } + + return previous; + }, Object.create(null)) + : {}; + +/** + * Creates a resolver for react-hook-form using Joi schema validation + * @param {Joi.ObjectSchema} schema - The Joi schema to validate against + * @param {Joi.ValidationOptions} [schemaOptions] - Optional Joi validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='async'] - Validation mode + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * const schema = Joi.object({ + * name: Joi.string().required(), + * age: Joi.number().required() + * }); + * + * useForm({ + * resolver: joiResolver(schema) + * }); + */ +export const joiResolver: Resolver = + ( + schema, + schemaOptions = { + abortEarly: false, + }, + resolverOptions = {}, + ) => + async (values, context, options) => { + const _schemaOptions = Object.assign({}, schemaOptions, { + context, + }); + + let result: Record = {}; + if (resolverOptions.mode === 'sync') { + result = schema.validate(values, _schemaOptions); + } else { + try { + result.value = await schema.validateAsync(values, _schemaOptions); + } catch (e) { + result.error = e; + } + } + + if (result.error) { + return { + values: {}, + errors: toNestErrors( + parseErrorSchema( + result.error, + !options.shouldUseNativeValidation && + options.criteriaMode === 'all', + ), + options, + ), + }; + } + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return { + errors: {}, + values: result.value, + }; + }; diff --git a/node_modules/@hookform/resolvers/joi/src/types.ts b/node_modules/@hookform/resolvers/joi/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..262c5cf4dff97eaba6d94bcecb167b70bd5a511d --- /dev/null +++ b/node_modules/@hookform/resolvers/joi/src/types.ts @@ -0,0 +1,12 @@ +import type { AsyncValidationOptions, Schema } from 'joi'; +import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form'; + +export type Resolver = ( + schema: T, + schemaOptions?: AsyncValidationOptions, + factoryOptions?: { mode?: 'async' | 'sync' }, +) => ( + values: TFieldValues, + context: TContext | undefined, + options: ResolverOptions, +) => Promise>; diff --git a/node_modules/@hookform/resolvers/nope/dist/index.d.ts b/node_modules/@hookform/resolvers/nope/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..70d2e237299d0ebfd856eb4c8016838df67c5a99 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/index.d.ts @@ -0,0 +1,2 @@ +export * from './nope'; +export * from './types'; diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.d.ts b/node_modules/@hookform/resolvers/nope/dist/nope.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b5341d62b4069849bb2941e2886b9d2ac564dfc --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.d.ts @@ -0,0 +1,19 @@ +import type { Resolver } from './types'; +/** + * Creates a resolver for react-hook-form using Nope schema validation + * @param {NopeSchema} schema - The Nope schema to validate against + * @param {NopeSchemaOptions} [schemaOptions] - Optional Nope validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='async'] - Validation mode + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * const schema = nope.object({ + * name: nope.string().required(), + * age: nope.number().required() + * }); + * + * useForm({ + * resolver: nopeResolver(schema) + * }); + */ +export declare const nopeResolver: Resolver; diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.js b/node_modules/@hookform/resolvers/nope/dist/nope.js new file mode 100644 index 0000000000000000000000000000000000000000..ede85db202bda7cde9a94240148cdb4f38e4c4d9 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.js @@ -0,0 +1,2 @@ +var r=require("@hookform/resolvers"),e=function(r,o,t){return void 0===o&&(o={}),void 0===t&&(t=""),Object.keys(r).reduce(function(o,s){var a=t?t+"."+s:s,i=r[s];return"string"==typeof i?o[a]={message:i}:e(i,o,a),o},o)};exports.nopeResolver=function(o,t){return void 0===t&&(t={abortEarly:!1}),function(s,a,i){var n=o.validate(s,a,t);return n?{values:{},errors:r.toNestErrors(e(n),i)}:(i.shouldUseNativeValidation&&r.validateFieldsNatively({},i),{values:s,errors:{}})}}; +//# sourceMappingURL=nope.js.map diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.js.map b/node_modules/@hookform/resolvers/nope/dist/nope.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9dc3e202451cf25d1cf95bf846d58cbcebca6945 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nope.js","sources":["../src/nope.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { FieldError, FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\n// nope-validator doesn't publicly export this shape (and its internal file\n// layout has changed across major versions), so it's redeclared here to\n// avoid depending on an unstable, non-exported module path.\ntype ShapeErrors = {\n [key: string]: string | ShapeErrors;\n};\n\nconst parseErrors = (\n errors: ShapeErrors,\n parsedErrors: FieldErrors = {},\n path = '',\n) => {\n return Object.keys(errors).reduce((acc, key) => {\n const _path = path ? `${path}.${key}` : key;\n const error = errors[key];\n\n if (typeof error === 'string') {\n acc[_path] = {\n message: error,\n } as FieldError;\n } else {\n parseErrors(error, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n};\n\n/**\n * Creates a resolver for react-hook-form using Nope schema validation\n * @param {NopeSchema} schema - The Nope schema to validate against\n * @param {NopeSchemaOptions} [schemaOptions] - Optional Nope validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = nope.object({\n * name: nope.string().required(),\n * age: nope.number().required()\n * });\n *\n * useForm({\n * resolver: nopeResolver(schema)\n * });\n */\nexport const nopeResolver: Resolver =\n (\n schema,\n schemaOptions = {\n abortEarly: false,\n },\n ) =>\n (values, context, options) => {\n const result = schema.validate(values, context, schemaOptions) as\n | ShapeErrors\n | undefined;\n\n if (result) {\n return { values: {}, errors: toNestErrors(parseErrors(result), options) };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return { values, errors: {} };\n };\n"],"names":["parseErrors","errors","parsedErrors","path","Object","keys","reduce","acc","key","_path","error","message","schema","schemaOptions","abortEarly","values","context","options","result","validate","toNestErrors","shouldUseNativeValidation","validateFieldsNatively"],"mappings":"qCAWMA,EAAc,SAClBC,EACAC,EACAC,GAEA,YAHAD,IAAAA,IAAAA,EAA4B,CAAA,QACxB,IAAJC,IAAAA,EAAO,IAEAC,OAAOC,KAAKJ,GAAQK,OAAO,SAACC,EAAKC,GACtC,IAAMC,EAAQN,EAAUA,EAAQK,IAAAA,EAAQA,EAClCE,EAAQT,EAAOO,GAUrB,MARqB,iBAAVE,EACTH,EAAIE,GAAS,CACXE,QAASD,GAGXV,EAAYU,EAAOH,EAAKE,GAGnBF,CACT,EAAGL,EACL,uBAoBE,SACEU,EACAC,eAAAA,IAAAA,IAAAA,EAAgB,CACdC,YAAY,IAGfC,SAAAA,EAAQC,EAASC,GAChB,IAAMC,EAASN,EAAOO,SAASJ,EAAQC,EAASH,GAIhD,OAAIK,EACK,CAAEH,OAAQ,GAAId,OAAQmB,EAAYA,aAACpB,EAAYkB,GAASD,KAGjEA,EAAQI,2BAA6BC,EAAsBA,uBAAC,CAAE,EAAEL,GAEzD,CAAEF,OAAAA,EAAQd,OAAQ,CAAA,GAC3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.mjs b/node_modules/@hookform/resolvers/nope/dist/nope.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d9782e679079280f0f9207fb40bdda7041064829 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";var o=function(r,e,t){return void 0===e&&(e={}),void 0===t&&(t=""),Object.keys(r).reduce(function(e,n){var a=t?t+"."+n:n,i=r[n];return"string"==typeof i?e[a]={message:i}:o(i,e,a),e},e)},t=function(t,n){return void 0===n&&(n={abortEarly:!1}),function(a,i,s){var u=t.validate(a,i,n);return u?{values:{},errors:r(o(u),s)}:(s.shouldUseNativeValidation&&e({},s),{values:a,errors:{}})}};export{t as nopeResolver}; +//# sourceMappingURL=nope.module.js.map diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.modern.mjs b/node_modules/@hookform/resolvers/nope/dist/nope.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c515864c2dd17ac7e4a4550b59da8178a91e8c49 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.modern.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";const o=(r,e={},s="")=>Object.keys(r).reduce((e,t)=>{const a=s?`${s}.${t}`:t,l=r[t];return"string"==typeof l?e[a]={message:l}:o(l,e,a),e},e),s=(s,t={abortEarly:!1})=>(a,l,n)=>{const i=s.validate(a,l,t);return i?{values:{},errors:r(o(i),n)}:(n.shouldUseNativeValidation&&e({},n),{values:a,errors:{}})};export{s as nopeResolver}; +//# sourceMappingURL=nope.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.modern.mjs.map b/node_modules/@hookform/resolvers/nope/dist/nope.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..2f08c0c74249a099b136c0151aca4fa2043ad8ee --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"nope.modern.mjs","sources":["../src/nope.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { FieldError, FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\n// nope-validator doesn't publicly export this shape (and its internal file\n// layout has changed across major versions), so it's redeclared here to\n// avoid depending on an unstable, non-exported module path.\ntype ShapeErrors = {\n [key: string]: string | ShapeErrors;\n};\n\nconst parseErrors = (\n errors: ShapeErrors,\n parsedErrors: FieldErrors = {},\n path = '',\n) => {\n return Object.keys(errors).reduce((acc, key) => {\n const _path = path ? `${path}.${key}` : key;\n const error = errors[key];\n\n if (typeof error === 'string') {\n acc[_path] = {\n message: error,\n } as FieldError;\n } else {\n parseErrors(error, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n};\n\n/**\n * Creates a resolver for react-hook-form using Nope schema validation\n * @param {NopeSchema} schema - The Nope schema to validate against\n * @param {NopeSchemaOptions} [schemaOptions] - Optional Nope validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = nope.object({\n * name: nope.string().required(),\n * age: nope.number().required()\n * });\n *\n * useForm({\n * resolver: nopeResolver(schema)\n * });\n */\nexport const nopeResolver: Resolver =\n (\n schema,\n schemaOptions = {\n abortEarly: false,\n },\n ) =>\n (values, context, options) => {\n const result = schema.validate(values, context, schemaOptions) as\n | ShapeErrors\n | undefined;\n\n if (result) {\n return { values: {}, errors: toNestErrors(parseErrors(result), options) };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return { values, errors: {} };\n };\n"],"names":["parseErrors","errors","parsedErrors","path","Object","keys","reduce","acc","key","_path","error","message","nopeResolver","schema","schemaOptions","abortEarly","values","context","options","result","validate","toNestErrors","shouldUseNativeValidation","validateFieldsNatively"],"mappings":"+EAWA,MAAMA,EAAcA,CAClBC,EACAC,EAA4B,CAAE,EAC9BC,EAAO,KAEAC,OAAOC,KAAKJ,GAAQK,OAAO,CAACC,EAAKC,KACtC,MAAMC,EAAQN,EAAO,GAAGA,KAAQK,IAAQA,EAClCE,EAAQT,EAAOO,GAUrB,MARqB,iBAAVE,EACTH,EAAIE,GAAS,CACXE,QAASD,GAGXV,EAAYU,EAAOH,EAAKE,GAGnBF,CAAG,EACTL,GAoBQU,EACXA,CACEC,EACAC,EAAgB,CACdC,YAAY,KAGhB,CAACC,EAAQC,EAASC,KAChB,MAAMC,EAASN,EAAOO,SAASJ,EAAQC,EAASH,GAIhD,OAAIK,EACK,CAAEH,OAAQ,GAAIf,OAAQoB,EAAarB,EAAYmB,GAASD,KAGjEA,EAAQI,2BAA6BC,EAAuB,GAAIL,GAEzD,CAAEF,SAAQf,OAAQ,CAAA,GAAI"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.module.js b/node_modules/@hookform/resolvers/nope/dist/nope.module.js new file mode 100644 index 0000000000000000000000000000000000000000..d9782e679079280f0f9207fb40bdda7041064829 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.module.js @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";var o=function(r,e,t){return void 0===e&&(e={}),void 0===t&&(t=""),Object.keys(r).reduce(function(e,n){var a=t?t+"."+n:n,i=r[n];return"string"==typeof i?e[a]={message:i}:o(i,e,a),e},e)},t=function(t,n){return void 0===n&&(n={abortEarly:!1}),function(a,i,s){var u=t.validate(a,i,n);return u?{values:{},errors:r(o(u),s)}:(s.shouldUseNativeValidation&&e({},s),{values:a,errors:{}})}};export{t as nopeResolver}; +//# sourceMappingURL=nope.module.js.map diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.module.js.map b/node_modules/@hookform/resolvers/nope/dist/nope.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..799433819383be3045bced2bb22308ddc9981598 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nope.module.js","sources":["../src/nope.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { FieldError, FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\n// nope-validator doesn't publicly export this shape (and its internal file\n// layout has changed across major versions), so it's redeclared here to\n// avoid depending on an unstable, non-exported module path.\ntype ShapeErrors = {\n [key: string]: string | ShapeErrors;\n};\n\nconst parseErrors = (\n errors: ShapeErrors,\n parsedErrors: FieldErrors = {},\n path = '',\n) => {\n return Object.keys(errors).reduce((acc, key) => {\n const _path = path ? `${path}.${key}` : key;\n const error = errors[key];\n\n if (typeof error === 'string') {\n acc[_path] = {\n message: error,\n } as FieldError;\n } else {\n parseErrors(error, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n};\n\n/**\n * Creates a resolver for react-hook-form using Nope schema validation\n * @param {NopeSchema} schema - The Nope schema to validate against\n * @param {NopeSchemaOptions} [schemaOptions] - Optional Nope validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = nope.object({\n * name: nope.string().required(),\n * age: nope.number().required()\n * });\n *\n * useForm({\n * resolver: nopeResolver(schema)\n * });\n */\nexport const nopeResolver: Resolver =\n (\n schema,\n schemaOptions = {\n abortEarly: false,\n },\n ) =>\n (values, context, options) => {\n const result = schema.validate(values, context, schemaOptions) as\n | ShapeErrors\n | undefined;\n\n if (result) {\n return { values: {}, errors: toNestErrors(parseErrors(result), options) };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return { values, errors: {} };\n };\n"],"names":["parseErrors","errors","parsedErrors","path","Object","keys","reduce","acc","key","_path","error","message","nopeResolver","schema","schemaOptions","abortEarly","values","context","options","result","validate","toNestErrors","shouldUseNativeValidation","validateFieldsNatively"],"mappings":"+EAWA,IAAMA,EAAc,SAClBC,EACAC,EACAC,GAEA,YAHAD,IAAAA,IAAAA,EAA4B,CAAA,QACxB,IAAJC,IAAAA,EAAO,IAEAC,OAAOC,KAAKJ,GAAQK,OAAO,SAACC,EAAKC,GACtC,IAAMC,EAAQN,EAAUA,EAAQK,IAAAA,EAAQA,EAClCE,EAAQT,EAAOO,GAUrB,MARqB,iBAAVE,EACTH,EAAIE,GAAS,CACXE,QAASD,GAGXV,EAAYU,EAAOH,EAAKE,GAGnBF,CACT,EAAGL,EACL,EAmBaU,EACX,SACEC,EACAC,eAAAA,IAAAA,IAAAA,EAAgB,CACdC,YAAY,IAGfC,SAAAA,EAAQC,EAASC,GAChB,IAAMC,EAASN,EAAOO,SAASJ,EAAQC,EAASH,GAIhD,OAAIK,EACK,CAAEH,OAAQ,GAAIf,OAAQoB,EAAarB,EAAYmB,GAASD,KAGjEA,EAAQI,2BAA6BC,EAAuB,CAAE,EAAEL,GAEzD,CAAEF,OAAAA,EAAQf,OAAQ,CAAA,GAC3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.umd.js b/node_modules/@hookform/resolvers/nope/dist/nope.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..182922dd1d7c0ef751c1f5469bf4cb8a3561a6e2 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.umd.js @@ -0,0 +1,2 @@ +!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],o):o((e||self).hookformResolversNope={},e.hookformResolvers)}(this,function(e,o){var r=function(e,o,t){return void 0===o&&(o={}),void 0===t&&(t=""),Object.keys(e).reduce(function(o,s){var n=t?t+"."+s:s,i=e[s];return"string"==typeof i?o[n]={message:i}:r(i,o,n),o},o)};e.nopeResolver=function(e,t){return void 0===t&&(t={abortEarly:!1}),function(s,n,i){var f=e.validate(s,n,t);return f?{values:{},errors:o.toNestErrors(r(f),i)}:(i.shouldUseNativeValidation&&o.validateFieldsNatively({},i),{values:s,errors:{}})}}}); +//# sourceMappingURL=nope.umd.js.map diff --git a/node_modules/@hookform/resolvers/nope/dist/nope.umd.js.map b/node_modules/@hookform/resolvers/nope/dist/nope.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f467ebd1fcbf7b40823810c26f780a3f06cb8b83 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/nope.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nope.umd.js","sources":["../src/nope.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { FieldError, FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\n// nope-validator doesn't publicly export this shape (and its internal file\n// layout has changed across major versions), so it's redeclared here to\n// avoid depending on an unstable, non-exported module path.\ntype ShapeErrors = {\n [key: string]: string | ShapeErrors;\n};\n\nconst parseErrors = (\n errors: ShapeErrors,\n parsedErrors: FieldErrors = {},\n path = '',\n) => {\n return Object.keys(errors).reduce((acc, key) => {\n const _path = path ? `${path}.${key}` : key;\n const error = errors[key];\n\n if (typeof error === 'string') {\n acc[_path] = {\n message: error,\n } as FieldError;\n } else {\n parseErrors(error, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n};\n\n/**\n * Creates a resolver for react-hook-form using Nope schema validation\n * @param {NopeSchema} schema - The Nope schema to validate against\n * @param {NopeSchemaOptions} [schemaOptions] - Optional Nope validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver} A resolver function compatible with react-hook-form\n * @example\n * const schema = nope.object({\n * name: nope.string().required(),\n * age: nope.number().required()\n * });\n *\n * useForm({\n * resolver: nopeResolver(schema)\n * });\n */\nexport const nopeResolver: Resolver =\n (\n schema,\n schemaOptions = {\n abortEarly: false,\n },\n ) =>\n (values, context, options) => {\n const result = schema.validate(values, context, schemaOptions) as\n | ShapeErrors\n | undefined;\n\n if (result) {\n return { values: {}, errors: toNestErrors(parseErrors(result), options) };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return { values, errors: {} };\n };\n"],"names":["parseErrors","errors","parsedErrors","path","Object","keys","reduce","acc","key","_path","error","message","schema","schemaOptions","abortEarly","values","context","options","result","validate","toNestErrors","shouldUseNativeValidation","validateFieldsNatively"],"mappings":"0TAWA,IAAMA,EAAc,SAClBC,EACAC,EACAC,GAEA,YAHAD,IAAAA,IAAAA,EAA4B,CAAA,QACxB,IAAJC,IAAAA,EAAO,IAEAC,OAAOC,KAAKJ,GAAQK,OAAO,SAACC,EAAKC,GACtC,IAAMC,EAAQN,EAAUA,EAAQK,IAAAA,EAAQA,EAClCE,EAAQT,EAAOO,GAUrB,MARqB,iBAAVE,EACTH,EAAIE,GAAS,CACXE,QAASD,GAGXV,EAAYU,EAAOH,EAAKE,GAGnBF,CACT,EAAGL,EACL,iBAoBE,SACEU,EACAC,eAAAA,IAAAA,IAAAA,EAAgB,CACdC,YAAY,IAGfC,SAAAA,EAAQC,EAASC,GAChB,IAAMC,EAASN,EAAOO,SAASJ,EAAQC,EAASH,GAIhD,OAAIK,EACK,CAAEH,OAAQ,GAAId,OAAQmB,EAAYA,aAACpB,EAAYkB,GAASD,KAGjEA,EAAQI,2BAA6BC,EAAsBA,uBAAC,CAAE,EAAEL,GAEzD,CAAEF,OAAAA,EAAQd,OAAQ,CAAA,GAC3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/nope/dist/types.d.ts b/node_modules/@hookform/resolvers/nope/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..903c5a644b4957aad0343bdb8b089afac67b9e1b --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/dist/types.d.ts @@ -0,0 +1,10 @@ +import type { object as nopeObject } from 'nope-validator'; +import type { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form'; +type NopeObject = ReturnType; +type ValidateOptions = Parameters[2]; +type Context = Parameters[1]; +export type Resolver = (schema: T, schemaOptions?: ValidateOptions, resolverOptions?: { + mode?: 'async' | 'sync'; + rawValues?: boolean; +}) => (values: TFieldValues, context: TContext | undefined, options: ResolverOptions) => ResolverResult; +export {}; diff --git a/node_modules/@hookform/resolvers/nope/package.json b/node_modules/@hookform/resolvers/nope/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f62c045d3ac546f0019175a716ac65f7a471b71a --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/package.json @@ -0,0 +1,18 @@ +{ + "name": "@hookform/resolvers/nope", + "amdName": "hookformResolversNope", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: nope", + "main": "dist/nope.js", + "module": "dist/nope.module.js", + "umd:main": "dist/nope.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0", + "nope-validator": "^0.12.0" + } +} diff --git a/node_modules/@hookform/resolvers/nope/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/nope/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e0635b30cb9278986bcd3293e269af7cb2a89906 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,85 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import Nope from 'nope-validator'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { nopeResolver } from '..'; + +const USERNAME_REQUIRED_MESSAGE = 'username field is required'; +const PASSWORD_REQUIRED_MESSAGE = 'password field is required'; + +const schema = Nope.object().shape({ + username: Nope.string().required(USERNAME_REQUIRED_MESSAGE), + password: Nope.string().required(PASSWORD_REQUIRED_MESSAGE), +}); + +interface FormData { + unusedProperty: string; + username: string; + password: string; +} + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: nopeResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with Nope", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/nope/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/nope/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..08194a539075e3ed5ad307b82a2848592a175996 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/src/__tests__/Form.tsx @@ -0,0 +1,55 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import Nope from 'nope-validator'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { nopeResolver } from '..'; + +const schema = Nope.object().shape({ + username: Nope.string().required(), + password: Nope.string().required(), +}); + +interface FormData { + unusedProperty: string; + username: string; + password: string; +} + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: nopeResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with Yup and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect(screen.getAllByText(/This field is required/i)).toHaveLength(2); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/nope/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/nope/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..7068b5781c1ed5bd5c21e2a3c0ec8c66b23c6fb7 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,70 @@ +import Nope from 'nope-validator'; +import { Field, InternalFieldName } from 'react-hook-form'; + +export const schema = Nope.object().shape({ + username: Nope.string().regex(/^\w+$/).min(2).max(30).required(), + password: Nope.string() + .regex(new RegExp('.*[A-Z].*'), 'One uppercase character') + .regex(new RegExp('.*[a-z].*'), 'One lowercase character') + .regex(new RegExp('.*\\d.*'), 'One number') + .regex( + new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'), + 'One special character', + ) + .min(8, 'Must be at least 8 characters in length') + .required('New Password is required'), + repeatPassword: Nope.string() + .oneOf([Nope.ref('password')], "Passwords don't match") + .required(), + accessToken: Nope.string(), + birthYear: Nope.number().min(1900).max(2013), + email: Nope.string().email(), + tags: Nope.array().of(Nope.string()).required(), + enabled: Nope.boolean(), + like: Nope.object().shape({ + id: Nope.number().required(), + name: Nope.string().atLeast(4).required(), + }), +}); + +export const validData = { + username: 'Doe', + password: 'Password123_', + repeatPassword: 'Password123_', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + accessToken: 'accessToken', + like: { + id: 1, + name: 'name', + }, +}; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: { id: 'z' }, + tags: [1, 2, 3], +}; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/nope/src/__tests__/__snapshots__/nope.ts.snap b/node_modules/@hookform/resolvers/nope/src/__tests__/__snapshots__/nope.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..094cd1788b58192407eb05ec732d7d14180c7a28 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/src/__tests__/__snapshots__/nope.ts.snap @@ -0,0 +1,43 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`nopeResolver > should return a single error from nopeResolver when validation fails 1`] = ` +{ + "errors": { + "birthYear": { + "message": "The field is not a valid number", + "ref": undefined, + }, + "like": { + "id": { + "message": "The field is not a valid number", + "ref": undefined, + }, + "name": { + "message": "This field is required", + "ref": undefined, + }, + }, + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + }, + "repeatPassword": { + "message": "This field is required", + "ref": undefined, + }, + "tags": { + "message": "One or more elements are of invalid type", + "ref": undefined, + }, + "username": { + "message": "This field is required", + "ref": { + "name": "username", + }, + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/nope/src/__tests__/nope.ts b/node_modules/@hookform/resolvers/nope/src/__tests__/nope.ts new file mode 100644 index 0000000000000000000000000000000000000000..0aee74935c2faee2f406ccbc5d8ba8d2fb7c4bfa --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/src/__tests__/nope.ts @@ -0,0 +1,28 @@ +/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */ +import { nopeResolver } from '..'; +import { fields, invalidData, schema, validData } from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('nopeResolver', () => { + it('should return values from nopeResolver when validation pass', async () => { + const schemaSpy = vi.spyOn(schema, 'validate'); + + const result = await nopeResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(schemaSpy).toHaveBeenCalledTimes(1); + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return a single error from nopeResolver when validation fails', async () => { + const result = await nopeResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); +}); diff --git a/node_modules/@hookform/resolvers/nope/src/index.ts b/node_modules/@hookform/resolvers/nope/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..70d2e237299d0ebfd856eb4c8016838df67c5a99 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/src/index.ts @@ -0,0 +1,2 @@ +export * from './nope'; +export * from './types'; diff --git a/node_modules/@hookform/resolvers/nope/src/nope.ts b/node_modules/@hookform/resolvers/nope/src/nope.ts new file mode 100644 index 0000000000000000000000000000000000000000..65f18e49e5191a9465b156950d19dcf94157e86c --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/src/nope.ts @@ -0,0 +1,69 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import type { FieldError, FieldErrors } from 'react-hook-form'; +import type { Resolver } from './types'; + +// nope-validator doesn't publicly export this shape (and its internal file +// layout has changed across major versions), so it's redeclared here to +// avoid depending on an unstable, non-exported module path. +type ShapeErrors = { + [key: string]: string | ShapeErrors; +}; + +const parseErrors = ( + errors: ShapeErrors, + parsedErrors: FieldErrors = {}, + path = '', +) => { + return Object.keys(errors).reduce((acc, key) => { + const _path = path ? `${path}.${key}` : key; + const error = errors[key]; + + if (typeof error === 'string') { + acc[_path] = { + message: error, + } as FieldError; + } else { + parseErrors(error, acc, _path); + } + + return acc; + }, parsedErrors); +}; + +/** + * Creates a resolver for react-hook-form using Nope schema validation + * @param {NopeSchema} schema - The Nope schema to validate against + * @param {NopeSchemaOptions} [schemaOptions] - Optional Nope validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {string} [resolverOptions.mode='async'] - Validation mode + * @returns {Resolver} A resolver function compatible with react-hook-form + * @example + * const schema = nope.object({ + * name: nope.string().required(), + * age: nope.number().required() + * }); + * + * useForm({ + * resolver: nopeResolver(schema) + * }); + */ +export const nopeResolver: Resolver = + ( + schema, + schemaOptions = { + abortEarly: false, + }, + ) => + (values, context, options) => { + const result = schema.validate(values, context, schemaOptions) as + | ShapeErrors + | undefined; + + if (result) { + return { values: {}, errors: toNestErrors(parseErrors(result), options) }; + } + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return { values, errors: {} }; + }; diff --git a/node_modules/@hookform/resolvers/nope/src/types.ts b/node_modules/@hookform/resolvers/nope/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..556a356df2ecdc8b29676d0837886e95a6c1d5f9 --- /dev/null +++ b/node_modules/@hookform/resolvers/nope/src/types.ts @@ -0,0 +1,25 @@ +import type { object as nopeObject } from 'nope-validator'; +import type { + FieldValues, + ResolverOptions, + ResolverResult, +} from 'react-hook-form'; + +// nope-validator doesn't publicly export the `NopeObject` class itself (and +// its internal file layout has changed across major versions), so it's +// derived here from the return type of its exported `object()` factory +// instead of depending on an unstable, non-exported module path. +type NopeObject = ReturnType; + +type ValidateOptions = Parameters[2]; +type Context = Parameters[1]; + +export type Resolver = ( + schema: T, + schemaOptions?: ValidateOptions, + resolverOptions?: { mode?: 'async' | 'sync'; rawValues?: boolean }, +) => ( + values: TFieldValues, + context: TContext | undefined, + options: ResolverOptions, +) => ResolverResult; diff --git a/node_modules/@hookform/resolvers/package.json b/node_modules/@hookform/resolvers/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ee64d8d4b17c6ff16e298cbacaa31553a5a86549 --- /dev/null +++ b/node_modules/@hookform/resolvers/package.json @@ -0,0 +1,438 @@ +{ + "name": "@hookform/resolvers", + "amdName": "hookformResolvers", + "version": "5.9.0", + "description": "React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope, computed-types, TypeBox, arktype, Typanion, Effect-TS and VineJS", + "main": "dist/resolvers.js", + "module": "dist/resolvers.module.js", + "umd:main": "dist/resolvers.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "umd": "./dist/resolvers.umd.js", + "import": "./dist/resolvers.mjs", + "require": "./dist/resolvers.js" + }, + "./zod": { + "types": "./zod/dist/index.d.ts", + "umd": "./zod/dist/zod.umd.js", + "import": "./zod/dist/zod.mjs", + "require": "./zod/dist/zod.js" + }, + "./typebox": { + "types": "./typebox/dist/index.d.ts", + "umd": "./typebox/dist/typebox.umd.js", + "import": "./typebox/dist/typebox.mjs", + "require": "./typebox/dist/typebox.js" + }, + "./yup": { + "types": "./yup/dist/index.d.ts", + "umd": "./yup/dist/yup.umd.js", + "import": "./yup/dist/yup.mjs", + "require": "./yup/dist/yup.js" + }, + "./joi": { + "types": "./joi/dist/index.d.ts", + "umd": "./joi/dist/joi.umd.js", + "import": "./joi/dist/joi.mjs", + "require": "./joi/dist/joi.js" + }, + "./vest": { + "types": "./vest/dist/index.d.ts", + "umd": "./vest/dist/vest.umd.js", + "import": "./vest/dist/vest.mjs", + "require": "./vest/dist/vest.js" + }, + "./superstruct": { + "types": "./superstruct/dist/index.d.ts", + "umd": "./superstruct/dist/superstruct.umd.js", + "import": "./superstruct/dist/superstruct.mjs", + "require": "./superstruct/dist/superstruct.js" + }, + "./class-validator": { + "types": "./class-validator/dist/index.d.ts", + "umd": "./class-validator/dist/class-validator.umd.js", + "import": "./class-validator/dist/class-validator.mjs", + "require": "./class-validator/dist/class-validator.js" + }, + "./io-ts": { + "types": "./io-ts/dist/index.d.ts", + "umd": "./io-ts/dist/io-ts.umd.js", + "import": "./io-ts/dist/io-ts.mjs", + "require": "./io-ts/dist/io-ts.js" + }, + "./nope": { + "types": "./nope/dist/index.d.ts", + "umd": "./nope/dist/nope.umd.js", + "import": "./nope/dist/nope.mjs", + "require": "./nope/dist/nope.js" + }, + "./computed-types": { + "types": "./computed-types/dist/index.d.ts", + "umd": "./computed-types/dist/computed-types.umd.js", + "import": "./computed-types/dist/computed-types.mjs", + "require": "./computed-types/dist/computed-types.js" + }, + "./typanion": { + "types": "./typanion/dist/index.d.ts", + "umd": "./typanion/dist/typanion.umd.js", + "import": "./typanion/dist/typanion.mjs", + "require": "./typanion/dist/typanion.js" + }, + "./ajv": { + "types": "./ajv/dist/index.d.ts", + "umd": "./ajv/dist/ajv.umd.js", + "import": "./ajv/dist/ajv.mjs", + "require": "./ajv/dist/ajv.js" + }, + "./arktype": { + "types": "./arktype/dist/index.d.ts", + "umd": "./arktype/dist/arktype.umd.js", + "import": "./arktype/dist/arktype.mjs", + "require": "./arktype/dist/arktype.js" + }, + "./valibot": { + "types": "./valibot/dist/index.d.ts", + "umd": "./valibot/dist/valibot.umd.js", + "import": "./valibot/dist/valibot.mjs", + "require": "./valibot/dist/valibot.js" + }, + "./typeschema": { + "types": "./typeschema/dist/index.d.ts", + "umd": "./typeschema/dist/typeschema.umd.js", + "import": "./typeschema/dist/typeschema.mjs", + "require": "./typeschema/dist/typeschema.js" + }, + "./effect-ts": { + "types": "./effect-ts/dist/index.d.ts", + "umd": "./effect-ts/dist/effect-ts.umd.js", + "import": "./effect-ts/dist/effect-ts.mjs", + "require": "./effect-ts/dist/effect-ts.js" + }, + "./vine": { + "types": "./vine/dist/index.d.ts", + "umd": "./vine/dist/vine.umd.js", + "import": "./vine/dist/vine.mjs", + "require": "./vine/dist/vine.js" + }, + "./fluentvalidation-ts": { + "types": "./fluentvalidation-ts/dist/index.d.ts", + "umd": "./fluentvalidation-ts/dist/fluentvalidation-ts.umd.js", + "import": "./fluentvalidation-ts/dist/fluentvalidation-ts.mjs", + "require": "./fluentvalidation-ts/dist/fluentvalidation-ts.js" + }, + "./standard-schema": { + "types": "./standard-schema/dist/index.d.ts", + "umd": "./standard-schema/dist/standard-schema.umd.js", + "import": "./standard-schema/dist/standard-schema.mjs", + "require": "./standard-schema/dist/standard-schema.js" + }, + "./ata-validator": { + "types": "./ata-validator/dist/index.d.ts", + "umd": "./ata-validator/dist/ata-validator.umd.js", + "import": "./ata-validator/dist/ata-validator.mjs", + "require": "./ata-validator/dist/ata-validator.js" + }, + "./package.json": "./package.json", + "./*": "./*" + }, + "files": [ + "dist", + "yup/package.json", + "yup/src", + "yup/dist", + "zod/package.json", + "zod/src", + "zod/dist", + "vest/package.json", + "vest/src", + "vest/dist", + "joi/package.json", + "joi/src", + "joi/dist", + "superstruct/package.json", + "superstruct/src", + "superstruct/dist", + "class-validator/package.json", + "class-validator/src", + "class-validator/dist", + "io-ts/package.json", + "io-ts/src", + "io-ts/dist", + "nope/package.json", + "nope/src", + "nope/dist", + "computed-types/package.json", + "computed-types/src", + "computed-types/dist", + "typanion/package.json", + "typanion/src", + "typanion/dist", + "ajv/package.json", + "ajv/src", + "ajv/dist", + "typebox/package.json", + "typebox/src", + "typebox/dist", + "arktype/package.json", + "arktype/src", + "arktype/dist", + "valibot/package.json", + "valibot/src", + "valibot/dist", + "typeschema/package.json", + "typeschema/src", + "typeschema/dist", + "effect-ts/package.json", + "effect-ts/src", + "effect-ts/dist", + "effect-ts/package.json", + "effect-ts/src", + "effect-ts/dist", + "vine/package.json", + "vine/src", + "vine/dist", + "fluentvalidation-ts/package.json", + "fluentvalidation-ts/src", + "fluentvalidation-ts/dist", + "standard-schema/package.json", + "standard-schema/src", + "standard-schema/dist", + "ata-validator/package.json", + "ata-validator/src", + "ata-validator/dist" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "prepare": "run-s build:src", + "build": "cross-env npm-run-all --parallel 'build:*'", + "build:src": "microbundle build --tsconfig tsconfig.build.json --globals react-hook-form=ReactHookForm", + "build:zod": "microbundle --cwd zod --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:yup": "microbundle --cwd yup --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:joi": "microbundle --cwd joi --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:superstruct": "microbundle --cwd superstruct --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:io-ts": "microbundle --cwd io-ts --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,fp-ts/Either=Either,fp-ts/function=_function,fp-ts/Option=Option,fp-ts/ReadonlyArray=ReadonlyArray,fp-ts/Semigroup=Semigroup,fp-ts/ReadonlyRecord=ReadonlyRecord", + "build:vest": "microbundle --cwd vest --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:class-validator": "microbundle --cwd class-validator --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:nope": "microbundle --cwd nope --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:computed-types": "microbundle --cwd computed-types --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:typanion": "microbundle --cwd typanion --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:ajv": "microbundle --cwd ajv --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:typebox": "microbundle --cwd typebox --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@sinclair/typebox/value=value,@sinclair/typebox/compiler=compiler", + "build:arktype": "microbundle --cwd arktype --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:valibot": "microbundle --cwd valibot --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:typeschema": "microbundle --cwd typeschema --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@typeschema/main=main", + "build:effect-ts": "microbundle --cwd effect-ts --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,effect=Effect,effect/SchemaAST=EffectSchemaAST,effect/ParseResult=EffectParseResult", + "build:vine": "microbundle --cwd vine --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@vinejs/vine=vine", + "build:fluentvalidation-ts": "microbundle --cwd fluentvalidation-ts --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm", + "build:standard-schema": "microbundle --cwd standard-schema --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@standard-schema/spec=standardSchema", + "build:ata-validator": "microbundle --cwd ata-validator --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,ata-validator=ataValidator", + "postbuild": "node ./config/node-13-exports.js && check-export-map && node ./config/check-peer-deps.js", + "lint": "biome check --write --vcs-use-ignore-file=true .", + "lint:types": "tsc", + "test": "vitest run", + "test:watch": "vitest watch", + "check:all": "npm-run-all --parallel lint:* test" + }, + "keywords": [ + "scheme", + "validation", + "scheme-validation", + "hookform", + "react-hook-form", + "yup", + "joi", + "superstruct", + "typescript", + "zod", + "vest", + "class-validator", + "io-ts", + "effect-ts", + "nope", + "computed-types", + "typanion", + "ajv", + "TypeBox", + "arktype", + "typeschema", + "vine", + "fluentvalidation-ts", + "standard-schema", + "ata-validator" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/react-hook-form/resolvers.git" + }, + "author": "bluebill1049 ", + "license": "MIT", + "bugs": { + "url": "https://github.com/react-hook-form/resolvers/issues" + }, + "homepage": "https://react-hook-form.com", + "devDependencies": { + "@biomejs/biome": "^1.9.4", + "@sinclair/typebox": "^0.34.52", + "@standard-schema/spec": "^1.1.0", + "@testing-library/dom": "^10.4.1", + "@testing-library/jest-dom": "^6.10.0", + "@testing-library/react": "^16.3.2", + "@testing-library/user-event": "^14.6.1", + "@types/node": "^22.20.1", + "@types/react": "^19.2.17", + "@typeschema/core": "^0.14.0", + "@typeschema/main": "^0.14.1", + "@typeschema/zod": "^0.14.0", + "@vinejs/vine": "^4.4.0", + "@vitejs/plugin-react": "^4.7.0", + "ajv": "^8.20.0", + "ata-validator": "^1.2.0", + "ajv-errors": "^3.0.0", + "ajv-formats": "^2.1.1", + "arktype": "2.0.4", + "check-export-map": "^1.3.1", + "class-transformer": "^0.5.1", + "class-validator": "^0.14.4", + "computed-types": "^1.11.2", + "cross-env": "^7.0.3", + "effect": "^3.22.0", + "fluentvalidation-ts": "^3.3.0", + "fp-ts": "^2.16.11", + "io-ts": "^2.2.22", + "io-ts-types": "^0.5.19", + "joi": "^18.2.3", + "jsdom": "^26.1.0", + "lefthook": "^1.13.6", + "microbundle": "^0.15.1", + "monocle-ts": "^2.3.13", + "newtype-ts": "^0.3.5", + "nope-validator": "^1.2.2", + "npm-run-all": "^4.1.5", + "react": "^19.2.8", + "react-dom": "^19.2.8", + "react-hook-form": "^7.83.0", + "reflect-metadata": "^0.2.2", + "superstruct": "^2.0.2", + "typanion": "^3.14.0", + "typescript": "^6.0.3", + "valibot": "1.0.0-beta.12", + "vest": "^6.3.2", + "vite": "^6.4.3", + "vite-tsconfig-paths": "^5.1.4", + "vitest": "^3.2.7", + "yup": "^1.7.1", + "zod": "^3.25.76" + }, + "peerDependencies": { + "@sinclair/typebox": ">=0.25.24", + "@standard-schema/spec": "^1.0.0", + "@typeschema/main": ">=0.13.7", + "@vinejs/vine": "^2.0.0 || ^3.0.0 || ^4.0.0", + "ajv": "^8.12.0", + "ajv-errors": "^3.0.0", + "ajv-formats": "^2.1.1", + "arktype": "^2.0.0", + "ata-validator": "^1.2.0", + "class-transformer": ">=0.4.0", + "class-validator": ">=0.12.0", + "computed-types": "^1.0.0", + "effect": "^3.10.3", + "fluentvalidation-ts": "^3.0.0", + "fp-ts": "^2.7.0", + "io-ts": "^2.0.0", + "joi": "^17.0.0 || ^18.0.0", + "nope-validator": ">=0.12.0", + "react-hook-form": "^7.55.0", + "superstruct": ">=0.12.0", + "typanion": "^3.3.2", + "valibot": ">=0.31.0 || ^1.0.0-beta.4 || ^1.0.0-rc", + "vest": ">=6.0.0", + "yup": "^1.0.0", + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "@sinclair/typebox": { + "optional": true + }, + "@standard-schema/spec": { + "optional": true + }, + "@typeschema/main": { + "optional": true + }, + "@vinejs/vine": { + "optional": true + }, + "ajv": { + "optional": true + }, + "ajv-errors": { + "optional": true + }, + "ajv-formats": { + "optional": true + }, + "arktype": { + "optional": true + }, + "ata-validator": { + "optional": true + }, + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + }, + "computed-types": { + "optional": true + }, + "effect": { + "optional": true + }, + "fluentvalidation-ts": { + "optional": true + }, + "fp-ts": { + "optional": true + }, + "io-ts": { + "optional": true + }, + "joi": { + "optional": true + }, + "nope-validator": { + "optional": true + }, + "superstruct": { + "optional": true + }, + "typanion": { + "optional": true + }, + "valibot": { + "optional": true + }, + "vest": { + "optional": true + }, + "yup": { + "optional": true + }, + "zod": { + "optional": true + } + }, + "dependencies": { + "@standard-schema/utils": "^0.3.0" + }, + "overrides": { + "ajv": "^8.20.0" + } +} diff --git a/node_modules/@hookform/resolvers/standard-schema/dist/index.d.ts b/node_modules/@hookform/resolvers/standard-schema/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef117ca633c3e0a476ab384cc12c0cdb50ab37b7 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/dist/index.d.ts @@ -0,0 +1 @@ +export * from './standard-schema'; diff --git a/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.d.ts b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a222de2d91d0d96d20ccb4154c7b9c0a6f090374 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.d.ts @@ -0,0 +1,8 @@ +import { StandardSchemaV1 } from '@standard-schema/spec'; +import { FieldValues, Resolver } from 'react-hook-form'; +export declare function standardSchemaResolver(schema: StandardSchemaV1, _schemaOptions?: never, resolverOptions?: { + raw?: false; +}): Resolver; +export declare function standardSchemaResolver(schema: StandardSchemaV1, _schemaOptions: never | undefined, resolverOptions: { + raw: true; +}): Resolver; diff --git a/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.js b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..915e91b61b9ed03ff11aa697644e56eff7c228e8 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers"),r=require("@standard-schema/utils");function t(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=Array(r);t=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(i);!(g=h()).done;){var b=g.value,p=b[0];p!==a&&(y[p]=b[1])}var j=i.get(a);return j&&(y.root?(o(y.root,j.message),function(e,r){if(r){for(var t=e.types||{},n=0,a=Object.values(r);n();\n\n for (let i = 0; i < issues.length; i++) {\n const error = issues[i];\n const path = getDotPath(error) || schemaRootKey;\n const fieldError = errors.get(path);\n\n if (!fieldError) {\n errors.set(path, { message: error.message, type: '' });\n } else if (path === schemaRootKey) {\n // Root-level issues aren't tied to a single field, so there's no\n // natural \"first\" message to prefer the way there is for a field —\n // keep every one of them regardless of criteriaMode.\n appendErrorMessage(fieldError, error.message);\n }\n\n if (validateAllFieldCriteria) {\n const currentError = errors.get(path)!;\n const types = currentError.types || {};\n\n currentError.types = {\n ...types,\n [Object.keys(types).length]: error.message,\n };\n }\n }\n\n const fieldErrors: Record = {};\n\n for (const [path, error] of errors) {\n if (path !== schemaRootKey) {\n fieldErrors[path] = error;\n }\n }\n\n const rootError = errors.get(schemaRootKey);\n\n if (rootError) {\n if (fieldErrors.root) {\n appendErrorMessage(fieldErrors.root, rootError.message);\n appendErrorTypes(fieldErrors.root, rootError.types);\n } else {\n fieldErrors.root = rootError;\n }\n }\n\n return fieldErrors;\n}\n\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions?: {\n raw?: false;\n },\n): Resolver;\n\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions: never | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form that validates data using a Standard Schema.\n *\n * @param {Schema} schema - The Standard Schema to validate against\n * @param {Object} resolverOptions - Options for the resolver\n * @param {boolean} [resolverOptions.raw=false] - Whether to return raw input values instead of parsed values\n * @returns {Resolver} A resolver function compatible with react-hook-form\n *\n * @example\n * ```ts\n * const schema = z.object({\n * name: z.string().min(2),\n * age: z.number().min(18)\n * });\n *\n * useForm({\n * resolver: standardSchemaResolver(schema)\n * });\n * ```\n */\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return async (values, _, options) => {\n let result = schema['~standard'].validate(values);\n if (result instanceof Promise) {\n result = await result;\n }\n\n if (result.issues) {\n const errors = parseErrorSchema(\n result.issues,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n );\n\n return {\n values: {},\n errors: toNestErrors(errors, options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result.value,\n errors: {},\n };\n };\n}\n"],"names":["schemaRootKey","Symbol","appendErrorMessage","error","message","schema","_schemaOptions","resolverOptions","values","_","options","_temp2","result","issues","errors","validateAllFieldCriteria","Map","i","length","path","getDotPath","fieldError","get","set","type","_extends2","currentError","types","_extends","Object","keys","_step","fieldErrors","_iterator","_createForOfIteratorHelperLoose","done","_step$value","value","rootError","root","nextTypes","_i","_Object$values","appendErrorTypes","parseErrorSchema","shouldUseNativeValidation","criteriaMode","toNestErrors","validateFieldsNatively","raw","assign","validate","_temp","Promise","resolve","then","_result","e","reject"],"mappings":"uYAKA,IAAMA,EAAgBC,OAAO,eAE7B,SAASC,EAAmBC,EAAmBC,GACxCA,IAILD,EAAMC,QAAUD,EAAMC,QAAaD,EAAMC,QAAO,KAAKA,EAAYA,EACnE,gCAiHgB,SAKdC,EACAC,EACAC,GAIA,YAJAA,IAAAA,IAAAA,EAEI,CAAE,GAEN,SAAcC,EAAQC,EAAGC,GAAW,IAAA,IAAAC,EAAA,WAMlC,GAAIC,EAAOC,OAAQ,CACjB,IAAMC,EAnHZ,SACED,EACAE,GAIA,IAFA,IAAMD,EAAS,IAAIE,IAEVC,EAAI,EAAGA,EAAIJ,EAAOK,OAAQD,IAAK,CACtC,IAAMd,EAAQU,EAAOI,GACfE,EAAOC,aAAWjB,IAAUH,EAC5BqB,EAAaP,EAAOQ,IAAIH,GAW9B,GATKE,EAEMF,IAASnB,GAIlBE,EAAmBmB,EAAYlB,EAAMC,SALrCU,EAAOS,IAAIJ,EAAM,CAAEf,QAASD,EAAMC,QAASoB,KAAM,KAQ/CT,EAA0B,CAAA,IAAAU,EACtBC,EAAeZ,EAAOQ,IAAIH,GAC1BQ,EAAQD,EAAaC,OAAS,CAAA,EAEpCD,EAAaC,MAAKC,EACbD,CAAAA,EAAAA,IAAKF,EAAA,CAAA,GACPI,OAAOC,KAAKH,GAAOT,QAASf,EAAMC,QAAOqB,GAE9C,CACF,CAIA,IAFA,IAEkCM,EAF5BC,EAA0C,CAAA,EAEhDC,2pBAAAC,CAA4BpB,KAAMiB,EAAAE,KAAAE,MAAE,CAAA,IAAAC,EAAAL,EAAAM,MAAxBlB,EAAIiB,EAAA,GACVjB,IAASnB,IACXgC,EAAYb,GAFOiB,EACrB,GAGF,CAEA,IAAME,EAAYxB,EAAOQ,IAAItB,GAW7B,OATIsC,IACEN,EAAYO,MACdrC,EAAmB8B,EAAYO,KAAMD,EAAUlC,SAzDrD,SAA0BD,EAAmBwB,GAC3C,GAAKA,EAAL,CAMA,IAFA,IAAMa,EAAYrC,EAAMwB,OAAS,CAAA,EAEjCc,EAAA,EAAAC,EAAsBb,OAAOrB,OAAOmB,GAAMc,EAAAC,EAAAxB,OAAAuB,IAAE,CAAvC,IAAMrC,EAAOsC,EAAAD,GAChBD,EAAUX,OAAOC,KAAKU,GAAWtB,QAAUd,CAC7C,CAEAD,EAAMwB,MAAQa,CARd,CASF,CA8CMG,CAAiBX,EAAYO,KAAMD,EAAUX,QAE7CK,EAAYO,KAAOD,GAIhBN,CACT,CAgEqBY,CACbhC,EAAOC,QACNH,EAAQmC,2BAAsD,QAAzBnC,EAAQoC,cAGhD,MAAO,CACLtC,OAAQ,CAAE,EACVM,OAAQiC,EAAAA,aAAajC,EAAQJ,GAEjC,CAIA,OAFAA,EAAQmC,2BAA6BG,EAAsBA,uBAAC,CAAE,EAAEtC,GAEzD,CACLF,OAAQD,EAAgB0C,IAAMpB,OAAOqB,OAAO,CAAE,EAAE1C,GAAUI,EAAOyB,MACjEvB,OAAQ,GACR,EAtBEF,EAASP,EAAO,aAAa8C,SAAS3C,GAAQ4C,EAAA,WAAA,GAC9CxC,aAAkByC,QAAO,OAAAA,QAAAC,QACZ1C,GAAM2C,KAAA,SAAAC,GAArB5C,EAAM4C,CAAgB,GAF0B,UAE1BH,QAAAC,QAAAF,GAAAA,EAAAG,KAAAH,EAAAG,KAAA5C,GAAAA,IAqB1B,CAAC,MAAA8C,UAAAJ,QAAAK,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.mjs b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e1b6a69e22a3469dfe96cff160d0193e73905683 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";import{getDotPath as t}from"@standard-schema/utils";function n(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=Array(r);t=e.length?{done:!0}:{done:!1,value:e[t++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(i);!(y=h()).done;){var p=y.value,b=p[0];b!==a&&(d[b]=p[1])}var j=i.get(a);return j&&(d.root?(s(d.root,j.message),function(e,r){if(r){for(var t=e.types||{},n=0,o=Object.values(r);n{let f=a["~standard"].validate(i);if(f instanceof Promise&&(f=await f),f.issues){const s=function(e,s){const a=new Map;for(let i=0;i();\n\n for (let i = 0; i < issues.length; i++) {\n const error = issues[i];\n const path = getDotPath(error) || schemaRootKey;\n const fieldError = errors.get(path);\n\n if (!fieldError) {\n errors.set(path, { message: error.message, type: '' });\n } else if (path === schemaRootKey) {\n // Root-level issues aren't tied to a single field, so there's no\n // natural \"first\" message to prefer the way there is for a field —\n // keep every one of them regardless of criteriaMode.\n appendErrorMessage(fieldError, error.message);\n }\n\n if (validateAllFieldCriteria) {\n const currentError = errors.get(path)!;\n const types = currentError.types || {};\n\n currentError.types = {\n ...types,\n [Object.keys(types).length]: error.message,\n };\n }\n }\n\n const fieldErrors: Record = {};\n\n for (const [path, error] of errors) {\n if (path !== schemaRootKey) {\n fieldErrors[path] = error;\n }\n }\n\n const rootError = errors.get(schemaRootKey);\n\n if (rootError) {\n if (fieldErrors.root) {\n appendErrorMessage(fieldErrors.root, rootError.message);\n appendErrorTypes(fieldErrors.root, rootError.types);\n } else {\n fieldErrors.root = rootError;\n }\n }\n\n return fieldErrors;\n}\n\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions?: {\n raw?: false;\n },\n): Resolver;\n\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions: never | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form that validates data using a Standard Schema.\n *\n * @param {Schema} schema - The Standard Schema to validate against\n * @param {Object} resolverOptions - Options for the resolver\n * @param {boolean} [resolverOptions.raw=false] - Whether to return raw input values instead of parsed values\n * @returns {Resolver} A resolver function compatible with react-hook-form\n *\n * @example\n * ```ts\n * const schema = z.object({\n * name: z.string().min(2),\n * age: z.number().min(18)\n * });\n *\n * useForm({\n * resolver: standardSchemaResolver(schema)\n * });\n * ```\n */\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return async (values, _, options) => {\n let result = schema['~standard'].validate(values);\n if (result instanceof Promise) {\n result = await result;\n }\n\n if (result.issues) {\n const errors = parseErrorSchema(\n result.issues,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n );\n\n return {\n values: {},\n errors: toNestErrors(errors, options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result.value,\n errors: {},\n };\n };\n}\n"],"names":["schemaRootKey","Symbol","appendErrorMessage","error","message","standardSchemaResolver","schema","_schemaOptions","resolverOptions","async","values","_","options","result","validate","Promise","issues","errors","validateAllFieldCriteria","Map","i","length","path","getDotPath","fieldError","get","set","type","currentError","types","_extends","Object","keys","fieldErrors","rootError","root","nextTypes","appendErrorTypes","parseErrorSchema","shouldUseNativeValidation","criteriaMode","toNestErrors","validateFieldsNatively","raw","assign","value"],"mappings":"2VAKA,MAAMA,EAAgBC,OAAO,eAE7B,SAASC,EAAmBC,EAAmBC,GACxCA,IAILD,EAAMC,QAAUD,EAAMC,QAAU,GAAGD,EAAMC,YAAYA,IAAYA,EACnE,CAiHgB,SAAAC,EAKdC,EACAC,EACAC,EAEI,CAAE,GAEN,OAAOC,MAAOC,EAAQC,EAAGC,KACvB,IAAIC,EAASP,EAAO,aAAaQ,SAASJ,GAK1C,GAJIG,aAAkBE,UACpBF,QAAeA,GAGbA,EAAOG,OAAQ,CACjB,MAAMC,EAnHZ,SACED,EACAE,GAEA,MAAMD,EAAS,IAAIE,IAEnB,IAAK,IAAIC,EAAI,EAAGA,EAAIJ,EAAOK,OAAQD,IAAK,CACtC,MAAMjB,EAAQa,EAAOI,GACfE,EAAOC,EAAWpB,IAAUH,EAC5BwB,EAAaP,EAAOQ,IAAIH,GAW9B,GATKE,EAEMF,IAAStB,GAIlBE,EAAmBsB,EAAYrB,EAAMC,SALrCa,EAAOS,IAAIJ,EAAM,CAAElB,QAASD,EAAMC,QAASuB,KAAM,KAQ/CT,EAA0B,CAC5B,MAAMU,EAAeX,EAAOQ,IAAIH,GAC1BO,EAAQD,EAAaC,OAAS,CAAA,EAEpCD,EAAaC,MAAKC,EACbD,CAAAA,EAAAA,EACH,CAAA,CAACE,OAAOC,KAAKH,GAAOR,QAASlB,EAAMC,SAEvC,CACF,CAEA,MAAM6B,EAA0C,CAAE,EAElD,IAAK,MAAOX,EAAMnB,KAAUc,EACtBK,IAAStB,IACXiC,EAAYX,GAAQnB,GAIxB,MAAM+B,EAAYjB,EAAOQ,IAAIzB,GAW7B,OATIkC,IACED,EAAYE,MACdjC,EAAmB+B,EAAYE,KAAMD,EAAU9B,SAzDrD,SAA0BD,EAAmB0B,GAC3C,IAAKA,EACH,OAGF,MAAMO,EAAYjC,EAAM0B,OAAS,CAAE,EAEnC,IAAK,MAAMzB,KAAW2B,OAAOrB,OAAOmB,GAClCO,EAAUL,OAAOC,KAAKI,GAAWf,QAAUjB,EAG7CD,EAAM0B,MAAQO,CAChB,CA8CMC,CAAiBJ,EAAYE,KAAMD,EAAUL,QAE7CI,EAAYE,KAAOD,GAIhBD,CACT,CAgEqBK,CACbzB,EAAOG,QACNJ,EAAQ2B,2BAAsD,QAAzB3B,EAAQ4B,cAGhD,MAAO,CACL9B,OAAQ,CAAE,EACVO,OAAQwB,EAAaxB,EAAQL,GAEjC,CAIA,OAFAA,EAAQ2B,2BAA6BG,EAAuB,CAAE,EAAE9B,GAEzD,CACLF,OAAQF,EAAgBmC,IAAMZ,OAAOa,OAAO,CAAE,EAAElC,GAAUG,EAAOgC,MACjE5B,OAAQ,GACT,CAEL"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.module.js b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.module.js new file mode 100644 index 0000000000000000000000000000000000000000..e1b6a69e22a3469dfe96cff160d0193e73905683 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.module.js @@ -0,0 +1,2 @@ +import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";import{getDotPath as t}from"@standard-schema/utils";function n(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=Array(r);t=e.length?{done:!0}:{done:!1,value:e[t++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(i);!(y=h()).done;){var p=y.value,b=p[0];b!==a&&(d[b]=p[1])}var j=i.get(a);return j&&(d.root?(s(d.root,j.message),function(e,r){if(r){for(var t=e.types||{},n=0,o=Object.values(r);n();\n\n for (let i = 0; i < issues.length; i++) {\n const error = issues[i];\n const path = getDotPath(error) || schemaRootKey;\n const fieldError = errors.get(path);\n\n if (!fieldError) {\n errors.set(path, { message: error.message, type: '' });\n } else if (path === schemaRootKey) {\n // Root-level issues aren't tied to a single field, so there's no\n // natural \"first\" message to prefer the way there is for a field —\n // keep every one of them regardless of criteriaMode.\n appendErrorMessage(fieldError, error.message);\n }\n\n if (validateAllFieldCriteria) {\n const currentError = errors.get(path)!;\n const types = currentError.types || {};\n\n currentError.types = {\n ...types,\n [Object.keys(types).length]: error.message,\n };\n }\n }\n\n const fieldErrors: Record = {};\n\n for (const [path, error] of errors) {\n if (path !== schemaRootKey) {\n fieldErrors[path] = error;\n }\n }\n\n const rootError = errors.get(schemaRootKey);\n\n if (rootError) {\n if (fieldErrors.root) {\n appendErrorMessage(fieldErrors.root, rootError.message);\n appendErrorTypes(fieldErrors.root, rootError.types);\n } else {\n fieldErrors.root = rootError;\n }\n }\n\n return fieldErrors;\n}\n\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions?: {\n raw?: false;\n },\n): Resolver;\n\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions: never | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form that validates data using a Standard Schema.\n *\n * @param {Schema} schema - The Standard Schema to validate against\n * @param {Object} resolverOptions - Options for the resolver\n * @param {boolean} [resolverOptions.raw=false] - Whether to return raw input values instead of parsed values\n * @returns {Resolver} A resolver function compatible with react-hook-form\n *\n * @example\n * ```ts\n * const schema = z.object({\n * name: z.string().min(2),\n * age: z.number().min(18)\n * });\n *\n * useForm({\n * resolver: standardSchemaResolver(schema)\n * });\n * ```\n */\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return async (values, _, options) => {\n let result = schema['~standard'].validate(values);\n if (result instanceof Promise) {\n result = await result;\n }\n\n if (result.issues) {\n const errors = parseErrorSchema(\n result.issues,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n );\n\n return {\n values: {},\n errors: toNestErrors(errors, options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result.value,\n errors: {},\n };\n };\n}\n"],"names":["schemaRootKey","Symbol","appendErrorMessage","error","message","standardSchemaResolver","schema","_schemaOptions","resolverOptions","values","_","options","_temp2","result","issues","errors","validateAllFieldCriteria","Map","i","length","path","getDotPath","fieldError","get","set","type","_extends2","currentError","types","_extends","Object","keys","_step","fieldErrors","_iterator","_createForOfIteratorHelperLoose","done","_step$value","value","rootError","root","nextTypes","_i","_Object$values","appendErrorTypes","parseErrorSchema","shouldUseNativeValidation","criteriaMode","toNestErrors","validateFieldsNatively","raw","assign","validate","_temp","Promise","resolve","then","_result","e","reject"],"mappings":"icAKA,IAAMA,EAAgBC,OAAO,eAE7B,SAASC,EAAmBC,EAAmBC,GACxCA,IAILD,EAAMC,QAAUD,EAAMC,QAAaD,EAAMC,QAAO,KAAKA,EAAYA,EACnE,CAiHgB,SAAAC,EAKdC,EACAC,EACAC,GAIA,YAJAA,IAAAA,IAAAA,EAEI,CAAE,GAEN,SAAcC,EAAQC,EAAGC,GAAW,IAAA,IAAAC,EAAA,WAMlC,GAAIC,EAAOC,OAAQ,CACjB,IAAMC,EAnHZ,SACED,EACAE,GAIA,IAFA,IAAMD,EAAS,IAAIE,IAEVC,EAAI,EAAGA,EAAIJ,EAAOK,OAAQD,IAAK,CACtC,IAAMf,EAAQW,EAAOI,GACfE,EAAOC,EAAWlB,IAAUH,EAC5BsB,EAAaP,EAAOQ,IAAIH,GAW9B,GATKE,EAEMF,IAASpB,GAIlBE,EAAmBoB,EAAYnB,EAAMC,SALrCW,EAAOS,IAAIJ,EAAM,CAAEhB,QAASD,EAAMC,QAASqB,KAAM,KAQ/CT,EAA0B,CAAA,IAAAU,EACtBC,EAAeZ,EAAOQ,IAAIH,GAC1BQ,EAAQD,EAAaC,OAAS,CAAA,EAEpCD,EAAaC,MAAKC,EACbD,CAAAA,EAAAA,IAAKF,EAAA,CAAA,GACPI,OAAOC,KAAKH,GAAOT,QAAShB,EAAMC,QAAOsB,GAE9C,CACF,CAIA,IAFA,IAEkCM,EAF5BC,EAA0C,CAAA,EAEhDC,2pBAAAC,CAA4BpB,KAAMiB,EAAAE,KAAAE,MAAE,CAAA,IAAAC,EAAAL,EAAAM,MAAxBlB,EAAIiB,EAAA,GACVjB,IAASpB,IACXiC,EAAYb,GAFOiB,EACrB,GAGF,CAEA,IAAME,EAAYxB,EAAOQ,IAAIvB,GAW7B,OATIuC,IACEN,EAAYO,MACdtC,EAAmB+B,EAAYO,KAAMD,EAAUnC,SAzDrD,SAA0BD,EAAmByB,GAC3C,GAAKA,EAAL,CAMA,IAFA,IAAMa,EAAYtC,EAAMyB,OAAS,CAAA,EAEjCc,EAAA,EAAAC,EAAsBb,OAAOrB,OAAOmB,GAAMc,EAAAC,EAAAxB,OAAAuB,IAAE,CAAvC,IAAMtC,EAAOuC,EAAAD,GAChBD,EAAUX,OAAOC,KAAKU,GAAWtB,QAAUf,CAC7C,CAEAD,EAAMyB,MAAQa,CARd,CASF,CA8CMG,CAAiBX,EAAYO,KAAMD,EAAUX,QAE7CK,EAAYO,KAAOD,GAIhBN,CACT,CAgEqBY,CACbhC,EAAOC,QACNH,EAAQmC,2BAAsD,QAAzBnC,EAAQoC,cAGhD,MAAO,CACLtC,OAAQ,CAAE,EACVM,OAAQiC,EAAajC,EAAQJ,GAEjC,CAIA,OAFAA,EAAQmC,2BAA6BG,EAAuB,CAAE,EAAEtC,GAEzD,CACLF,OAAQD,EAAgB0C,IAAMpB,OAAOqB,OAAO,CAAE,EAAE1C,GAAUI,EAAOyB,MACjEvB,OAAQ,GACR,EAtBEF,EAASP,EAAO,aAAa8C,SAAS3C,GAAQ4C,EAAA,WAAA,GAC9CxC,aAAkByC,QAAO,OAAAA,QAAAC,QACZ1C,GAAM2C,KAAA,SAAAC,GAArB5C,EAAM4C,CAAgB,GAF0B,UAE1BH,QAAAC,QAAAF,GAAAA,EAAAG,KAAAH,EAAAG,KAAA5C,GAAAA,IAqB1B,CAAC,MAAA8C,UAAAJ,QAAAK,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.umd.js b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..23cd59d109d0805095b2793cc3736cec196efb06 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/dist/standard-schema.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("@standard-schema/utils")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","@standard-schema/utils"],r):r((e||self).hookformResolversStandardSchema={},e.hookformResolvers,e.utils)}(this,function(e,r,t){function n(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=Array(r);t=e.length?{done:!0}:{done:!1,value:e[t++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(i);!(h=g()).done;){var p=h.value,b=p[0];b!==a&&(y[b]=p[1])}var j=i.get(a);return j&&(y.root?(s(y.root,j.message),function(e,r){if(r){for(var t=e.types||{},n=0,o=Object.values(r);n();\n\n for (let i = 0; i < issues.length; i++) {\n const error = issues[i];\n const path = getDotPath(error) || schemaRootKey;\n const fieldError = errors.get(path);\n\n if (!fieldError) {\n errors.set(path, { message: error.message, type: '' });\n } else if (path === schemaRootKey) {\n // Root-level issues aren't tied to a single field, so there's no\n // natural \"first\" message to prefer the way there is for a field —\n // keep every one of them regardless of criteriaMode.\n appendErrorMessage(fieldError, error.message);\n }\n\n if (validateAllFieldCriteria) {\n const currentError = errors.get(path)!;\n const types = currentError.types || {};\n\n currentError.types = {\n ...types,\n [Object.keys(types).length]: error.message,\n };\n }\n }\n\n const fieldErrors: Record = {};\n\n for (const [path, error] of errors) {\n if (path !== schemaRootKey) {\n fieldErrors[path] = error;\n }\n }\n\n const rootError = errors.get(schemaRootKey);\n\n if (rootError) {\n if (fieldErrors.root) {\n appendErrorMessage(fieldErrors.root, rootError.message);\n appendErrorTypes(fieldErrors.root, rootError.types);\n } else {\n fieldErrors.root = rootError;\n }\n }\n\n return fieldErrors;\n}\n\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions?: {\n raw?: false;\n },\n): Resolver;\n\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions: never | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form that validates data using a Standard Schema.\n *\n * @param {Schema} schema - The Standard Schema to validate against\n * @param {Object} resolverOptions - Options for the resolver\n * @param {boolean} [resolverOptions.raw=false] - Whether to return raw input values instead of parsed values\n * @returns {Resolver} A resolver function compatible with react-hook-form\n *\n * @example\n * ```ts\n * const schema = z.object({\n * name: z.string().min(2),\n * age: z.number().min(18)\n * });\n *\n * useForm({\n * resolver: standardSchemaResolver(schema)\n * });\n * ```\n */\nexport function standardSchemaResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(\n schema: StandardSchemaV1,\n _schemaOptions?: never,\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return async (values, _, options) => {\n let result = schema['~standard'].validate(values);\n if (result instanceof Promise) {\n result = await result;\n }\n\n if (result.issues) {\n const errors = parseErrorSchema(\n result.issues,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n );\n\n return {\n values: {},\n errors: toNestErrors(errors, options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result.value,\n errors: {},\n };\n };\n}\n"],"names":["schemaRootKey","Symbol","appendErrorMessage","error","message","schema","_schemaOptions","resolverOptions","values","_","options","_temp2","result","issues","errors","validateAllFieldCriteria","Map","i","length","path","getDotPath","fieldError","get","set","type","_extends2","currentError","types","_extends","Object","keys","_step","fieldErrors","_iterator","_createForOfIteratorHelperLoose","done","_step$value","value","rootError","root","nextTypes","_i","_Object$values","appendErrorTypes","parseErrorSchema","shouldUseNativeValidation","criteriaMode","toNestErrors","validateFieldsNatively","raw","assign","validate","_temp","Promise","resolve","then","_result","e","reject"],"mappings":"usBAKA,IAAMA,EAAgBC,OAAO,eAE7B,SAASC,EAAmBC,EAAmBC,GACxCA,IAILD,EAAMC,QAAUD,EAAMC,QAAaD,EAAMC,QAAO,KAAKA,EAAYA,EACnE,0BAiHgB,SAKdC,EACAC,EACAC,GAIA,YAJAA,IAAAA,IAAAA,EAEI,CAAE,GAEN,SAAcC,EAAQC,EAAGC,GAAW,IAAA,IAAAC,EAAA,WAMlC,GAAIC,EAAOC,OAAQ,CACjB,IAAMC,EAnHZ,SACED,EACAE,GAIA,IAFA,IAAMD,EAAS,IAAIE,IAEVC,EAAI,EAAGA,EAAIJ,EAAOK,OAAQD,IAAK,CACtC,IAAMd,EAAQU,EAAOI,GACfE,EAAOC,aAAWjB,IAAUH,EAC5BqB,EAAaP,EAAOQ,IAAIH,GAW9B,GATKE,EAEMF,IAASnB,GAIlBE,EAAmBmB,EAAYlB,EAAMC,SALrCU,EAAOS,IAAIJ,EAAM,CAAEf,QAASD,EAAMC,QAASoB,KAAM,KAQ/CT,EAA0B,CAAA,IAAAU,EACtBC,EAAeZ,EAAOQ,IAAIH,GAC1BQ,EAAQD,EAAaC,OAAS,CAAA,EAEpCD,EAAaC,MAAKC,EACbD,CAAAA,EAAAA,IAAKF,EAAA,CAAA,GACPI,OAAOC,KAAKH,GAAOT,QAASf,EAAMC,QAAOqB,GAE9C,CACF,CAIA,IAFA,IAEkCM,EAF5BC,EAA0C,CAAA,EAEhDC,2pBAAAC,CAA4BpB,KAAMiB,EAAAE,KAAAE,MAAE,CAAA,IAAAC,EAAAL,EAAAM,MAAxBlB,EAAIiB,EAAA,GACVjB,IAASnB,IACXgC,EAAYb,GAFOiB,EACrB,GAGF,CAEA,IAAME,EAAYxB,EAAOQ,IAAItB,GAW7B,OATIsC,IACEN,EAAYO,MACdrC,EAAmB8B,EAAYO,KAAMD,EAAUlC,SAzDrD,SAA0BD,EAAmBwB,GAC3C,GAAKA,EAAL,CAMA,IAFA,IAAMa,EAAYrC,EAAMwB,OAAS,CAAA,EAEjCc,EAAA,EAAAC,EAAsBb,OAAOrB,OAAOmB,GAAMc,EAAAC,EAAAxB,OAAAuB,IAAE,CAAvC,IAAMrC,EAAOsC,EAAAD,GAChBD,EAAUX,OAAOC,KAAKU,GAAWtB,QAAUd,CAC7C,CAEAD,EAAMwB,MAAQa,CARd,CASF,CA8CMG,CAAiBX,EAAYO,KAAMD,EAAUX,QAE7CK,EAAYO,KAAOD,GAIhBN,CACT,CAgEqBY,CACbhC,EAAOC,QACNH,EAAQmC,2BAAsD,QAAzBnC,EAAQoC,cAGhD,MAAO,CACLtC,OAAQ,CAAE,EACVM,OAAQiC,EAAAA,aAAajC,EAAQJ,GAEjC,CAIA,OAFAA,EAAQmC,2BAA6BG,EAAsBA,uBAAC,CAAE,EAAEtC,GAEzD,CACLF,OAAQD,EAAgB0C,IAAMpB,OAAOqB,OAAO,CAAE,EAAE1C,GAAUI,EAAOyB,MACjEvB,OAAQ,GACR,EAtBEF,EAASP,EAAO,aAAa8C,SAAS3C,GAAQ4C,EAAA,WAAA,GAC9CxC,aAAkByC,QAAO,OAAAA,QAAAC,QACZ1C,GAAM2C,KAAA,SAAAC,GAArB5C,EAAM4C,CAAgB,GAF0B,UAE1BH,QAAAC,QAAAF,GAAAA,EAAAG,KAAAH,EAAAG,KAAA5C,GAAAA,IAqB1B,CAAC,MAAA8C,UAAAJ,QAAAK,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/standard-schema/package.json b/node_modules/@hookform/resolvers/standard-schema/package.json new file mode 100644 index 0000000000000000000000000000000000000000..da4bb90292083dcede2de6c745f9477d2b30b6f8 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/package.json @@ -0,0 +1,19 @@ +{ + "name": "@hookform/resolvers/standard-schema", + "amdName": "hookformResolversStandardSchema", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: standard-schema", + "main": "dist/standard-schema.js", + "module": "dist/standard-schema.module.js", + "umd:main": "dist/standard-schema.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@standard-schema/spec": "^1.0.0", + "@standard-schema/utils": "^0.3.0", + "@hookform/resolvers": "^2.0.0" + } +} diff --git a/node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2f965099507a7ea21ffddf3a355d9c9ab9a2218b --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,82 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { type } from 'arktype'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { standardSchemaResolver } from '..'; + +const schema = type({ + username: 'string>1', + password: 'string>1', +}); + +type FormData = typeof schema.infer; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: standardSchemaResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with arkType", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe( + 'username must be at least length 2', + ); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe( + 'password must be at least length 2', + ); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..db01bb677dc2f9a6f4c7fc11af1bfa3eba95cd64 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form.tsx @@ -0,0 +1,54 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import { type } from 'arktype'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { standardSchemaResolver } from '..'; + +const schema = type({ + username: 'string>1', + password: 'string>1', +}); + +function TestComponent({ + onSubmit, +}: { + onSubmit: (data: typeof schema.infer) => void; +}) { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: standardSchemaResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with arkType and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect( + screen.getByText('username must be at least length 2'), + ).toBeInTheDocument(); + expect( + screen.getByText('password must be at least length 2'), + ).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/standard-schema/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..7236799fe970b61dd70e28157997523f9efe27eb --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,111 @@ +import { StandardSchemaV1 } from '@standard-schema/spec'; +import { Field, InternalFieldName } from 'react-hook-form'; +import { z } from 'zod/v3'; + +export const schema = z + .object({ + username: z.string().regex(/^\w+$/).min(3).max(30), + password: z + .string() + .regex(new RegExp('.*[A-Z].*'), 'One uppercase character') + .regex(new RegExp('.*[a-z].*'), 'One lowercase character') + .regex(new RegExp('.*\\d.*'), 'One number') + .regex( + new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'), + 'One special character', + ) + .min(8, 'Must be at least 8 characters in length'), + repeatPassword: z.string(), + accessToken: z.union([z.string(), z.number()]), + birthYear: z.number().min(1900).max(2013).optional(), + email: z.string().email().optional(), + tags: z.array(z.string()), + enabled: z.boolean(), + url: z.string().url('Custom error url').or(z.literal('')), + like: z + .array( + z.object({ + id: z.number(), + name: z.string().length(4), + }), + ) + .optional(), + dateStr: z + .string() + .transform((value) => new Date(value)) + .refine((value) => !isNaN(value.getTime()), { + message: 'Invalid date', + }), + }) + .refine((obj) => obj.password === obj.repeatPassword, { + message: 'Passwords do not match', + path: ['confirm'], + }); + +export const validData = { + username: 'Doe', + password: 'Password123_', + repeatPassword: 'Password123_', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + accessToken: 'accessToken', + url: 'https://react-hook-form.com/', + like: [ + { + id: 1, + name: 'name', + }, + ], + dateStr: '2020-01-01T00:00:00.000Z', +} satisfies z.input; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: [{ id: 'z' }], + url: 'abc', +} as unknown as z.input; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; + +export const customSchema: StandardSchemaV1< + StandardSchemaV1.InferInput, + StandardSchemaV1.InferOutput +> = { + '~standard': { + version: 1, + vendor: 'custom', + validate: () => ({ + issues: [ + { + path: [{ key: 'username' }], + message: 'Custom error', + }, + { + path: [{ key: 'like' }, { key: 0 }, { key: 'id' }], + message: 'Custom error', + }, + ], + }), + }, +}; diff --git a/node_modules/@hookform/resolvers/standard-schema/src/__tests__/__snapshots__/standard-schema.ts.snap b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/__snapshots__/standard-schema.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..db6bec7891545657555e77631df20321b3235f80 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/__snapshots__/standard-schema.ts.snap @@ -0,0 +1,305 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`standardSchemaResolver > should collect all root errors when validateAllFieldCriteria is true 1`] = ` +{ + "errors": { + "root": { + "message": "Invalid union +Missing discriminator", + "ref": undefined, + "type": "", + "types": { + "0": "Invalid union", + "1": "Missing discriminator", + }, + }, + }, + "values": {}, +} +`; + +exports[`standardSchemaResolver > should correctly handle path segments that are objects 1`] = ` +{ + "errors": { + "like": [ + { + "id": { + "message": "Custom error", + "ref": undefined, + "type": "", + }, + }, + ], + "username": { + "message": "Custom error", + "ref": { + "name": "username", + }, + "type": "", + }, + }, + "values": {}, +} +`; + +exports[`standardSchemaResolver > should return a root error when a standard schema issue has no path 1`] = ` +{ + "errors": { + "root": { + "message": "Invalid input", + "ref": undefined, + "type": "", + }, + }, + "values": {}, +} +`; + +exports[`standardSchemaResolver > should return a single error from standardSchemaResolver when validation fails 1`] = ` +{ + "errors": { + "accessToken": { + "message": "Invalid input", + "ref": undefined, + "type": "", + }, + "birthYear": { + "message": "Expected number, received string", + "ref": undefined, + "type": "", + }, + "dateStr": { + "message": "Required", + "ref": undefined, + "type": "", + }, + "email": { + "message": "Invalid email", + "ref": { + "name": "email", + }, + "type": "", + }, + "enabled": { + "message": "Required", + "ref": undefined, + "type": "", + }, + "like": [ + { + "id": { + "message": "Expected number, received string", + "ref": undefined, + "type": "", + }, + "name": { + "message": "Required", + "ref": undefined, + "type": "", + }, + }, + ], + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "", + }, + "repeatPassword": { + "message": "Required", + "ref": undefined, + "type": "", + }, + "tags": { + "message": "Required", + "ref": undefined, + "type": "", + }, + "url": { + "message": "Custom error url", + "ref": undefined, + "type": "", + }, + "username": { + "message": "Required", + "ref": { + "name": "username", + }, + "type": "", + }, + }, + "values": {}, +} +`; + +exports[`standardSchemaResolver > should return all the errors from standardSchemaResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = ` +{ + "errors": { + "accessToken": { + "message": "Invalid input", + "ref": undefined, + "type": "", + "types": { + "0": "Invalid input", + }, + }, + "birthYear": { + "message": "Expected number, received string", + "ref": undefined, + "type": "", + "types": { + "0": "Expected number, received string", + }, + }, + "dateStr": { + "message": "Required", + "ref": undefined, + "type": "", + "types": { + "0": "Required", + }, + }, + "email": { + "message": "Invalid email", + "ref": { + "name": "email", + }, + "type": "", + "types": { + "0": "Invalid email", + }, + }, + "enabled": { + "message": "Required", + "ref": undefined, + "type": "", + "types": { + "0": "Required", + }, + }, + "like": [ + { + "id": { + "message": "Expected number, received string", + "ref": undefined, + "type": "", + "types": { + "0": "Expected number, received string", + }, + }, + "name": { + "message": "Required", + "ref": undefined, + "type": "", + "types": { + "0": "Required", + }, + }, + }, + ], + "password": { + "message": "One uppercase character", + "ref": { + "name": "password", + }, + "type": "", + "types": { + "0": "One uppercase character", + "1": "One lowercase character", + "2": "One number", + "3": "Must be at least 8 characters in length", + }, + }, + "repeatPassword": { + "message": "Required", + "ref": undefined, + "type": "", + "types": { + "0": "Required", + }, + }, + "tags": { + "message": "Required", + "ref": undefined, + "type": "", + "types": { + "0": "Required", + }, + }, + "url": { + "message": "Custom error url", + "ref": undefined, + "type": "", + "types": { + "0": "Custom error url", + }, + }, + "username": { + "message": "Required", + "ref": { + "name": "username", + }, + "type": "", + "types": { + "0": "Required", + }, + }, + }, + "values": {}, +} +`; + +exports[`standardSchemaResolver > should return values from standardSchemaResolver when validation pass & raw=true 1`] = ` +{ + "errors": {}, + "values": { + "accessToken": "accessToken", + "birthYear": 2000, + "dateStr": "2020-01-01T00:00:00.000Z", + "email": "john@doe.com", + "enabled": true, + "like": [ + { + "id": 1, + "name": "name", + }, + ], + "password": "Password123_", + "repeatPassword": "Password123_", + "tags": [ + "tag1", + "tag2", + ], + "url": "https://react-hook-form.com/", + "username": "Doe", + }, +} +`; + +exports[`standardSchemaResolver > should return values from standardSchemaResolver when validation pass 1`] = ` +{ + "errors": {}, + "values": { + "accessToken": "accessToken", + "birthYear": 2000, + "dateStr": 2020-01-01T00:00:00.000Z, + "email": "john@doe.com", + "enabled": true, + "like": [ + { + "id": 1, + "name": "name", + }, + ], + "password": "Password123_", + "repeatPassword": "Password123_", + "tags": [ + "tag1", + "tag2", + ], + "url": "https://react-hook-form.com/", + "username": "Doe", + }, +} +`; diff --git a/node_modules/@hookform/resolvers/standard-schema/src/__tests__/standard-schema.ts b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/standard-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3e5c8093d443b4877bacb51b36ec8d0d60c30eb --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/src/__tests__/standard-schema.ts @@ -0,0 +1,264 @@ +import { renderHook } from '@testing-library/react'; +import { Resolver, SubmitHandler, useForm } from 'react-hook-form'; +import { z } from 'zod/v3'; +import { standardSchemaResolver } from '..'; +import { + customSchema, + fields, + invalidData, + schema, + validData, +} from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('standardSchemaResolver', () => { + it('should return values from standardSchemaResolver when validation pass', async () => { + const result = await standardSchemaResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should return a single error from standardSchemaResolver when validation fails', async () => { + const result = await standardSchemaResolver(schema)( + invalidData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return all the errors from standardSchemaResolver when validation fails with `validateAllFieldCriteria` set to true', async () => { + const result = await standardSchemaResolver(schema)( + invalidData, + undefined, + { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return values from standardSchemaResolver when validation pass & raw=true', async () => { + const validateSpy = vi.spyOn(schema['~standard'], 'validate'); + + const result = await standardSchemaResolver(schema, undefined, { + raw: true, + })(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(validateSpy).toHaveBeenCalledTimes(1); + expect(result).toMatchSnapshot(); + }); + it('should correctly handle path segments that are objects', async () => { + const result = await standardSchemaResolver(customSchema)( + validData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(result).toMatchSnapshot(); + }); + + it('should return a root error when a standard schema issue has no path', async () => { + const result = await standardSchemaResolver({ + '~standard': { + version: 1, + vendor: 'custom', + validate: () => ({ + issues: [ + { + message: 'Invalid input', + }, + ], + }), + }, + })(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should collect all root errors when validateAllFieldCriteria is true', async () => { + const result = await standardSchemaResolver({ + '~standard': { + version: 1, + vendor: 'custom', + validate: () => ({ + issues: [ + { + message: 'Invalid union', + }, + { + message: 'Missing discriminator', + }, + ], + }), + }, + })(validData, undefined, { + fields, + criteriaMode: 'all', + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should preserve a root field error when a schema root error is present', async () => { + const result = await standardSchemaResolver({ + '~standard': { + version: 1, + vendor: 'custom', + validate: () => ({ + issues: [ + { + path: [{ key: 'root' }], + message: 'Root field error', + }, + { + message: 'Schema root error', + }, + ], + }), + }, + })(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result.errors).toMatchObject({ + root: { + message: 'Root field error\nSchema root error', + }, + }); + }); + + it('should only keep the first error message for the same field path in `firstError` mode', async () => { + const result = await standardSchemaResolver({ + '~standard': { + version: 1, + vendor: 'custom', + validate: () => ({ + issues: [ + { + path: [{ key: 'username' }], + message: 'First username error', + }, + { + path: [{ key: 'username' }], + message: 'Second username error', + }, + ], + }), + }, + })(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result.errors).toMatchObject({ + username: { + message: 'First username error', + }, + }); + }); + + /** + * Type inference tests + */ + it('should correctly infer the output type from a standardSchema schema', () => { + const resolver = standardSchemaResolver(z.object({ id: z.number() })); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: number }, unknown, { id: number }> + >(); + }); + + it('should correctly infer the output type from a standardSchema schema using a transform', () => { + const resolver = standardSchemaResolver( + z.object({ id: z.number().transform((val) => String(val)) }), + ); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: number }, unknown, { id: string }> + >(); + }); + + it('should correctly infer the output type from a standardSchema schema when a different input type is specified', () => { + const schema = z.object({ id: z.number() }).transform(({ id }) => { + return { id: String(id) }; + }); + + const resolver = standardSchemaResolver< + { id: number }, + any, + z.output + >(schema); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: number }, any, { id: string }> + >(); + }); + + it('should correctly infer the output type from a standardSchema schema for the handleSubmit function in useForm', () => { + const schema = z.object({ id: z.number() }); + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: standardSchemaResolver(schema), + defaultValues: { + id: 3, + }, + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: number; + }> + >(); + }); + + it('should correctly infer the output type from a standardSchema schema with a transform for the handleSubmit function in useForm', () => { + const schema = z.object({ id: z.number().transform((val) => String(val)) }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: standardSchemaResolver(schema), + defaultValues: { + id: 3, + }, + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: string; + }> + >(); + }); +}); diff --git a/node_modules/@hookform/resolvers/standard-schema/src/index.ts b/node_modules/@hookform/resolvers/standard-schema/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef117ca633c3e0a476ab384cc12c0cdb50ab37b7 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/src/index.ts @@ -0,0 +1 @@ +export * from './standard-schema'; diff --git a/node_modules/@hookform/resolvers/standard-schema/src/standard-schema.ts b/node_modules/@hookform/resolvers/standard-schema/src/standard-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..73e040a21afb9b577cf62a82184de7cb19cf7d69 --- /dev/null +++ b/node_modules/@hookform/resolvers/standard-schema/src/standard-schema.ts @@ -0,0 +1,163 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import { StandardSchemaV1 } from '@standard-schema/spec'; +import { getDotPath } from '@standard-schema/utils'; +import { FieldError, FieldValues, Resolver } from 'react-hook-form'; + +const schemaRootKey = Symbol('Schema root'); + +function appendErrorMessage(error: FieldError, message: string | undefined) { + if (!message) { + return; + } + + error.message = error.message ? `${error.message}\n${message}` : message; +} + +function appendErrorTypes(error: FieldError, types: FieldError['types']) { + if (!types) { + return; + } + + const nextTypes = error.types || {}; + + for (const message of Object.values(types)) { + nextTypes[Object.keys(nextTypes).length] = message; + } + + error.types = nextTypes; +} + +function parseErrorSchema( + issues: readonly StandardSchemaV1.Issue[], + validateAllFieldCriteria: boolean, +) { + const errors = new Map(); + + for (let i = 0; i < issues.length; i++) { + const error = issues[i]; + const path = getDotPath(error) || schemaRootKey; + const fieldError = errors.get(path); + + if (!fieldError) { + errors.set(path, { message: error.message, type: '' }); + } else if (path === schemaRootKey) { + // Root-level issues aren't tied to a single field, so there's no + // natural "first" message to prefer the way there is for a field — + // keep every one of them regardless of criteriaMode. + appendErrorMessage(fieldError, error.message); + } + + if (validateAllFieldCriteria) { + const currentError = errors.get(path)!; + const types = currentError.types || {}; + + currentError.types = { + ...types, + [Object.keys(types).length]: error.message, + }; + } + } + + const fieldErrors: Record = {}; + + for (const [path, error] of errors) { + if (path !== schemaRootKey) { + fieldErrors[path] = error; + } + } + + const rootError = errors.get(schemaRootKey); + + if (rootError) { + if (fieldErrors.root) { + appendErrorMessage(fieldErrors.root, rootError.message); + appendErrorTypes(fieldErrors.root, rootError.types); + } else { + fieldErrors.root = rootError; + } + } + + return fieldErrors; +} + +export function standardSchemaResolver< + Input extends FieldValues, + Context, + Output, +>( + schema: StandardSchemaV1, + _schemaOptions?: never, + resolverOptions?: { + raw?: false; + }, +): Resolver; + +export function standardSchemaResolver< + Input extends FieldValues, + Context, + Output, +>( + schema: StandardSchemaV1, + _schemaOptions: never | undefined, + resolverOptions: { + raw: true; + }, +): Resolver; + +/** + * Creates a resolver for react-hook-form that validates data using a Standard Schema. + * + * @param {Schema} schema - The Standard Schema to validate against + * @param {Object} resolverOptions - Options for the resolver + * @param {boolean} [resolverOptions.raw=false] - Whether to return raw input values instead of parsed values + * @returns {Resolver} A resolver function compatible with react-hook-form + * + * @example + * ```ts + * const schema = z.object({ + * name: z.string().min(2), + * age: z.number().min(18) + * }); + * + * useForm({ + * resolver: standardSchemaResolver(schema) + * }); + * ``` + */ +export function standardSchemaResolver< + Input extends FieldValues, + Context, + Output, +>( + schema: StandardSchemaV1, + _schemaOptions?: never, + resolverOptions: { + raw?: boolean; + } = {}, +): Resolver { + return async (values, _, options) => { + let result = schema['~standard'].validate(values); + if (result instanceof Promise) { + result = await result; + } + + if (result.issues) { + const errors = parseErrorSchema( + result.issues, + !options.shouldUseNativeValidation && options.criteriaMode === 'all', + ); + + return { + values: {}, + errors: toNestErrors(errors, options), + }; + } + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return { + values: resolverOptions.raw ? Object.assign({}, values) : result.value, + errors: {}, + }; + }; +} diff --git a/node_modules/@hookform/resolvers/superstruct/dist/index.d.ts b/node_modules/@hookform/resolvers/superstruct/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2acaa550eae38d3ff33df03d444d9b82461cc3cc --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/index.d.ts @@ -0,0 +1 @@ +export * from './superstruct'; diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.d.ts b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b71c31399bd306176455b7cdc419da6f0716d753 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.d.ts @@ -0,0 +1,13 @@ +import { FieldValues, Resolver } from 'react-hook-form'; +import { Infer, Struct, validate } from 'superstruct'; +export declare function superstructResolver(schema: Struct, schemaOptions: Omit[2], 'coerce'> & { + coerce: true; +}, resolverOptions?: { + raw?: boolean; +}): Resolver; +export declare function superstructResolver(schema: Struct, schemaOptions?: Parameters[2], resolverOptions?: { + raw?: false; +}): Resolver>; +export declare function superstructResolver(schema: Struct, schemaOptions: Parameters[2] | undefined, resolverOptions: { + raw: true; +}): Resolver; diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.js b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.js new file mode 100644 index 0000000000000000000000000000000000000000..45b4ddd3fcbc81310276ce071a2cb5540203fc95 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers"),r=require("superstruct");exports.superstructResolver=function(s,t,a){return void 0===a&&(a={}),function(o,u,i){var n,l=r.validate(o,s,t);return l[0]?{values:{},errors:e.toNestErrors((n=l[0],n.failures().reduce(function(e,r){return(e[r.path.join(".")]={message:r.message,type:r.type})&&e},{})),i)}:(i.shouldUseNativeValidation&&e.validateFieldsNatively({},i),{values:a.raw?Object.assign({},o):l[1],errors:{}})}}; +//# sourceMappingURL=superstruct.js.map diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.js.map b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1be9a66c4a96d5e5549a0a72365f3441b9a85de9 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.js.map @@ -0,0 +1 @@ +{"version":3,"file":"superstruct.js","sources":["../src/superstruct.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { FieldError, FieldValues, Resolver } from 'react-hook-form';\nimport { Infer, Struct, StructError, validate } from 'superstruct';\n\nfunction parseErrorSchema(error: StructError) {\n return error.failures().reduce>(\n (previous, error) =>\n (previous[error.path.join('.')] = {\n message: error.message,\n type: error.type,\n }) && previous,\n {},\n );\n}\n\n// This is required to correctly type the input of the returned function when coerce is true\n// superstruct does not store the input type of a schema alongside it\n// Infer gives the output type of the coercion\nexport function superstructResolver(\n schema: Struct,\n schemaOptions: Omit[2], 'coerce'> & {\n coerce: true;\n },\n resolverOptions?: {\n raw?: boolean;\n },\n): Resolver;\n\nexport function superstructResolver(\n schema: Struct,\n schemaOptions?: Parameters[2],\n resolverOptions?: {\n raw?: false;\n },\n): Resolver>;\n\nexport function superstructResolver(\n schema: Struct,\n schemaOptions: Parameters[2] | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Superstruct schema validation\n * @param {Struct} schema - The Superstruct schema to validate against\n * @param {Parameters[2]} [schemaOptions] - Optional Superstruct validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {boolean} [resolverOptions.raw=false] - If true, returns raw values rather than validated results\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = struct({\n * name: string(),\n * age: number()\n * });\n *\n * useForm({\n * resolver: superstructResolver(schema)\n * });\n */\nexport function superstructResolver(\n schema: Struct,\n schemaOptions?: Parameters[2],\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return (values: Input, _, options) => {\n const result = validate(values, schema, schemaOptions);\n\n if (result[0]) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(result[0]), options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result[1],\n errors: {},\n };\n };\n}\n"],"names":["schema","schemaOptions","resolverOptions","values","_","options","error","result","validate","errors","toNestErrors","failures","reduce","previous","path","join","message","type","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign"],"mappings":"0FA6DM,SACJA,EACAC,EACAC,GAIA,gBAJAA,IAAAA,EAEI,aAEIC,EAAeC,EAAGC,GACxB,IAjEsBC,EAiEhBC,EAASC,EAAQA,SAACL,EAAQH,EAAQC,GAExC,OAAIM,EAAO,GACF,CACLJ,OAAQ,CAAA,EACRM,OAAQC,EAAYA,cAtEFJ,EAsEoBC,EAAO,GArE5CD,EAAMK,WAAWC,OACtB,SAACC,EAAUP,UACRO,EAASP,EAAMQ,KAAKC,KAAK,MAAQ,CAChCC,QAASV,EAAMU,QACfC,KAAMX,EAAMW,QACRJ,CAAQ,EAChB,CAAE,IA+DoDR,KAItDA,EAAQa,2BAA6BC,EAAAA,uBAAuB,CAAE,EAAEd,GAEzD,CACLF,OAAQD,EAAgBkB,IAAMC,OAAOC,OAAO,CAAA,EAAInB,GAAUI,EAAO,GACjEE,OAAQ,IAEZ,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.mjs b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.mjs new file mode 100644 index 0000000000000000000000000000000000000000..785ff2578814995870a22e4504a83504ac09ed98 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{validate as o}from"superstruct";function s(s,t,u){return void 0===u&&(u={}),function(a,i,n){var f,m=o(a,s,t);return m[0]?{values:{},errors:r((f=m[0],f.failures().reduce(function(r,e){return(r[e.path.join(".")]={message:e.message,type:e.type})&&r},{})),n)}:(n.shouldUseNativeValidation&&e({},n),{values:u.raw?Object.assign({},a):m[1],errors:{}})}}export{s as superstructResolver}; +//# sourceMappingURL=superstruct.module.js.map diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.modern.mjs b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..377db187813cabf777ac1984423d8c7f7509039b --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.modern.mjs @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{validate as s}from"superstruct";function o(o,t,a={}){return(u,i,n)=>{const m=s(u,o,t);return m[0]?{values:{},errors:r((p=m[0],p.failures().reduce((r,e)=>(r[e.path.join(".")]={message:e.message,type:e.type})&&r,{})),n)}:(n.shouldUseNativeValidation&&e({},n),{values:a.raw?Object.assign({},u):m[1],errors:{}});var p}}export{o as superstructResolver}; +//# sourceMappingURL=superstruct.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.modern.mjs.map b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..5251052491aefc4f6b148481e1bb44d264452c97 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"superstruct.modern.mjs","sources":["../src/superstruct.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { FieldError, FieldValues, Resolver } from 'react-hook-form';\nimport { Infer, Struct, StructError, validate } from 'superstruct';\n\nfunction parseErrorSchema(error: StructError) {\n return error.failures().reduce>(\n (previous, error) =>\n (previous[error.path.join('.')] = {\n message: error.message,\n type: error.type,\n }) && previous,\n {},\n );\n}\n\n// This is required to correctly type the input of the returned function when coerce is true\n// superstruct does not store the input type of a schema alongside it\n// Infer gives the output type of the coercion\nexport function superstructResolver(\n schema: Struct,\n schemaOptions: Omit[2], 'coerce'> & {\n coerce: true;\n },\n resolverOptions?: {\n raw?: boolean;\n },\n): Resolver;\n\nexport function superstructResolver(\n schema: Struct,\n schemaOptions?: Parameters[2],\n resolverOptions?: {\n raw?: false;\n },\n): Resolver>;\n\nexport function superstructResolver(\n schema: Struct,\n schemaOptions: Parameters[2] | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Superstruct schema validation\n * @param {Struct} schema - The Superstruct schema to validate against\n * @param {Parameters[2]} [schemaOptions] - Optional Superstruct validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {boolean} [resolverOptions.raw=false] - If true, returns raw values rather than validated results\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = struct({\n * name: string(),\n * age: number()\n * });\n *\n * useForm({\n * resolver: superstructResolver(schema)\n * });\n */\nexport function superstructResolver(\n schema: Struct,\n schemaOptions?: Parameters[2],\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return (values: Input, _, options) => {\n const result = validate(values, schema, schemaOptions);\n\n if (result[0]) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(result[0]), options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result[1],\n errors: {},\n };\n };\n}\n"],"names":["superstructResolver","schema","schemaOptions","resolverOptions","values","_","options","result","validate","errors","toNestErrors","error","failures","reduce","previous","path","join","message","type","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign"],"mappings":"sHA6DgB,SAAAA,EACdC,EACAC,EACAC,EAEI,CAAA,GAEJ,MAAO,CAACC,EAAeC,EAAGC,KACxB,MAAMC,EAASC,EAASJ,EAAQH,EAAQC,GAExC,OAAIK,EAAO,GACF,CACLH,OAAQ,CAAE,EACVK,OAAQC,GAtEUC,EAsEoBJ,EAAO,GArE5CI,EAAMC,WAAWC,OACtB,CAACC,EAAUH,KACRG,EAASH,EAAMI,KAAKC,KAAK,MAAQ,CAChCC,QAASN,EAAMM,QACfC,KAAMP,EAAMO,QACRJ,EACR,CAAA,IA+DsDR,KAItDA,EAAQa,2BAA6BC,EAAuB,CAAE,EAAEd,GAEzD,CACLF,OAAQD,EAAgBkB,IAAMC,OAAOC,OAAO,GAAInB,GAAUG,EAAO,GACjEE,OAAQ,CAAA,IA9Ed,IAA0BE,CA+ErB,CAEL"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.module.js b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.module.js new file mode 100644 index 0000000000000000000000000000000000000000..785ff2578814995870a22e4504a83504ac09ed98 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.module.js @@ -0,0 +1,2 @@ +import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{validate as o}from"superstruct";function s(s,t,u){return void 0===u&&(u={}),function(a,i,n){var f,m=o(a,s,t);return m[0]?{values:{},errors:r((f=m[0],f.failures().reduce(function(r,e){return(r[e.path.join(".")]={message:e.message,type:e.type})&&r},{})),n)}:(n.shouldUseNativeValidation&&e({},n),{values:u.raw?Object.assign({},a):m[1],errors:{}})}}export{s as superstructResolver}; +//# sourceMappingURL=superstruct.module.js.map diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.module.js.map b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0657221689a0a1b0594a93cda54c9967bb9b845a --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"superstruct.module.js","sources":["../src/superstruct.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { FieldError, FieldValues, Resolver } from 'react-hook-form';\nimport { Infer, Struct, StructError, validate } from 'superstruct';\n\nfunction parseErrorSchema(error: StructError) {\n return error.failures().reduce>(\n (previous, error) =>\n (previous[error.path.join('.')] = {\n message: error.message,\n type: error.type,\n }) && previous,\n {},\n );\n}\n\n// This is required to correctly type the input of the returned function when coerce is true\n// superstruct does not store the input type of a schema alongside it\n// Infer gives the output type of the coercion\nexport function superstructResolver(\n schema: Struct,\n schemaOptions: Omit[2], 'coerce'> & {\n coerce: true;\n },\n resolverOptions?: {\n raw?: boolean;\n },\n): Resolver;\n\nexport function superstructResolver(\n schema: Struct,\n schemaOptions?: Parameters[2],\n resolverOptions?: {\n raw?: false;\n },\n): Resolver>;\n\nexport function superstructResolver(\n schema: Struct,\n schemaOptions: Parameters[2] | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Superstruct schema validation\n * @param {Struct} schema - The Superstruct schema to validate against\n * @param {Parameters[2]} [schemaOptions] - Optional Superstruct validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {boolean} [resolverOptions.raw=false] - If true, returns raw values rather than validated results\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = struct({\n * name: string(),\n * age: number()\n * });\n *\n * useForm({\n * resolver: superstructResolver(schema)\n * });\n */\nexport function superstructResolver(\n schema: Struct,\n schemaOptions?: Parameters[2],\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return (values: Input, _, options) => {\n const result = validate(values, schema, schemaOptions);\n\n if (result[0]) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(result[0]), options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result[1],\n errors: {},\n };\n };\n}\n"],"names":["superstructResolver","schema","schemaOptions","resolverOptions","values","_","options","error","result","validate","errors","toNestErrors","failures","reduce","previous","path","join","message","type","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign"],"mappings":"sHA6DM,SAAUA,EACdC,EACAC,EACAC,GAIA,gBAJAA,IAAAA,EAEI,aAEIC,EAAeC,EAAGC,GACxB,IAjEsBC,EAiEhBC,EAASC,EAASL,EAAQH,EAAQC,GAExC,OAAIM,EAAO,GACF,CACLJ,OAAQ,CAAA,EACRM,OAAQC,GAtEUJ,EAsEoBC,EAAO,GArE5CD,EAAMK,WAAWC,OACtB,SAACC,EAAUP,UACRO,EAASP,EAAMQ,KAAKC,KAAK,MAAQ,CAChCC,QAASV,EAAMU,QACfC,KAAMX,EAAMW,QACRJ,CAAQ,EAChB,CAAE,IA+DoDR,KAItDA,EAAQa,2BAA6BC,EAAuB,CAAE,EAAEd,GAEzD,CACLF,OAAQD,EAAgBkB,IAAMC,OAAOC,OAAO,CAAA,EAAInB,GAAUI,EAAO,GACjEE,OAAQ,IAEZ,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.umd.js b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..8e318c5645ee70b2d8d196ac80c8662f96f6ea90 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("superstruct")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","superstruct"],r):r((e||self).hookformResolversSuperstruct={},e.hookformResolvers,e.superstruct)}(this,function(e,r,o){e.superstructResolver=function(e,s,t){return void 0===t&&(t={}),function(u,i,n){var f,a=o.validate(u,e,s);return a[0]?{values:{},errors:r.toNestErrors((f=a[0],f.failures().reduce(function(e,r){return(e[r.path.join(".")]={message:r.message,type:r.type})&&e},{})),n)}:(n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{values:t.raw?Object.assign({},u):a[1],errors:{}})}}}); +//# sourceMappingURL=superstruct.umd.js.map diff --git a/node_modules/@hookform/resolvers/superstruct/dist/superstruct.umd.js.map b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ccacb3e41dd8b0fe6596827f08ed3dac0b7c60e0 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/dist/superstruct.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"superstruct.umd.js","sources":["../src/superstruct.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { FieldError, FieldValues, Resolver } from 'react-hook-form';\nimport { Infer, Struct, StructError, validate } from 'superstruct';\n\nfunction parseErrorSchema(error: StructError) {\n return error.failures().reduce>(\n (previous, error) =>\n (previous[error.path.join('.')] = {\n message: error.message,\n type: error.type,\n }) && previous,\n {},\n );\n}\n\n// This is required to correctly type the input of the returned function when coerce is true\n// superstruct does not store the input type of a schema alongside it\n// Infer gives the output type of the coercion\nexport function superstructResolver(\n schema: Struct,\n schemaOptions: Omit[2], 'coerce'> & {\n coerce: true;\n },\n resolverOptions?: {\n raw?: boolean;\n },\n): Resolver;\n\nexport function superstructResolver(\n schema: Struct,\n schemaOptions?: Parameters[2],\n resolverOptions?: {\n raw?: false;\n },\n): Resolver>;\n\nexport function superstructResolver(\n schema: Struct,\n schemaOptions: Parameters[2] | undefined,\n resolverOptions: {\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Superstruct schema validation\n * @param {Struct} schema - The Superstruct schema to validate against\n * @param {Parameters[2]} [schemaOptions] - Optional Superstruct validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {boolean} [resolverOptions.raw=false] - If true, returns raw values rather than validated results\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = struct({\n * name: string(),\n * age: number()\n * });\n *\n * useForm({\n * resolver: superstructResolver(schema)\n * });\n */\nexport function superstructResolver(\n schema: Struct,\n schemaOptions?: Parameters[2],\n resolverOptions: {\n raw?: boolean;\n } = {},\n): Resolver {\n return (values: Input, _, options) => {\n const result = validate(values, schema, schemaOptions);\n\n if (result[0]) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(result[0]), options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : result[1],\n errors: {},\n };\n };\n}\n"],"names":["schema","schemaOptions","resolverOptions","values","_","options","error","result","validate","errors","toNestErrors","failures","reduce","previous","path","join","message","type","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign"],"mappings":"4YA6DM,SACJA,EACAC,EACAC,GAIA,gBAJAA,IAAAA,EAEI,aAEIC,EAAeC,EAAGC,GACxB,IAjEsBC,EAiEhBC,EAASC,EAAQA,SAACL,EAAQH,EAAQC,GAExC,OAAIM,EAAO,GACF,CACLJ,OAAQ,CAAA,EACRM,OAAQC,EAAYA,cAtEFJ,EAsEoBC,EAAO,GArE5CD,EAAMK,WAAWC,OACtB,SAACC,EAAUP,UACRO,EAASP,EAAMQ,KAAKC,KAAK,MAAQ,CAChCC,QAASV,EAAMU,QACfC,KAAMX,EAAMW,QACRJ,CAAQ,EAChB,CAAE,IA+DoDR,KAItDA,EAAQa,2BAA6BC,EAAAA,uBAAuB,CAAE,EAAEd,GAEzD,CACLF,OAAQD,EAAgBkB,IAAMC,OAAOC,OAAO,CAAA,EAAInB,GAAUI,EAAO,GACjEE,OAAQ,IAEZ,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/superstruct/package.json b/node_modules/@hookform/resolvers/superstruct/package.json new file mode 100644 index 0000000000000000000000000000000000000000..818a20e5bc137890d97447cae11536870d50299b --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/package.json @@ -0,0 +1,18 @@ +{ + "name": "@hookform/resolvers/superstruct", + "amdName": "hookformResolversSuperstruct", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: superstruct", + "main": "dist/superstruct.js", + "module": "dist/superstruct.module.js", + "umd:main": "dist/superstruct.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0", + "superstruct": ">=0.12.0" + } +} diff --git a/node_modules/@hookform/resolvers/superstruct/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/superstruct/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b09f9a3c0fb35325507d786012d8d2eacb10bbb1 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,82 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { Infer, object, size, string } from 'superstruct'; +import { superstructResolver } from '..'; + +const schema = object({ + username: size(string(), 2), + password: size(string(), 6), +}); + +type FormData = Infer; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { register, handleSubmit } = useForm({ + resolver: superstructResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with Superstruct", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe( + 'Expected a string with a length of `2` but received one with a length of `0`', + ); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe( + 'Expected a string with a length of `6` but received one with a length of `0`', + ); + + await user.type(screen.getByPlaceholderText(/username/i), 'jo'); + await user.type(screen.getByPlaceholderText(/password/i), 'passwo'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/superstruct/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/superstruct/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9798c69915bdc3e4adbaf1108f111fe6139e2225 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/src/__tests__/Form.tsx @@ -0,0 +1,86 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import { Infer, object, size, string } from 'superstruct'; +import { superstructResolver } from '..'; + +const schema = object({ + username: size(string(), 2), + password: size(string(), 6), +}); + +type FormData = Infer; + +interface Props { + onSubmit: (data: FormData) => void; +} + +function TestComponent({ onSubmit }: Props) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: superstructResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with Superstruct and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect( + screen.getByText( + /Expected a string with a length of `2` but received one with a length of `0`/i, + ), + ).toBeInTheDocument(); + expect( + screen.getByText( + /Expected a string with a length of `6` but received one with a length of `0`/i, + ), + ).toBeInTheDocument(); + expect(handleSubmit).not.toHaveBeenCalled(); +}); + +export function TestComponentManualType({ + onSubmit, +}: { + onSubmit: (data: FormData) => void; +}) { + const { + register, + handleSubmit, + formState: { errors }, + } = useForm, undefined, FormData>({ + resolver: superstructResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} diff --git a/node_modules/@hookform/resolvers/superstruct/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/superstruct/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f30ef919e53de4f8f3e5f327a1e8f640df14b36 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,75 @@ +import { Field, InternalFieldName } from 'react-hook-form'; +import { + Infer, + array, + boolean, + define, + max, + min, + number, + object, + optional, + pattern, + size, + string, + union, +} from 'superstruct'; + +const Password = define( + 'Password', + (value, ctx) => value === ctx.branch[0].password, +); + +export const schema = object({ + username: size(pattern(string(), /^\w+$/), 3, 30), + password: pattern(string(), /^[a-zA-Z0-9]{3,30}/), + repeatPassword: Password, + accessToken: optional(union([string(), number()])), + birthYear: optional(max(min(number(), 1900), 2013)), + email: optional(pattern(string(), /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)), + tags: array(string()), + enabled: boolean(), + like: optional(array(object({ id: number(), name: size(string(), 4) }))), +}); + +export const validData: Infer = { + username: 'Doe', + password: 'Password123', + repeatPassword: 'Password123', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + like: [ + { + id: 1, + name: 'name', + }, + ], +}; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: [{ id: 'z' }], +} as any as Infer; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/superstruct/src/__tests__/__snapshots__/superstruct.ts.snap b/node_modules/@hookform/resolvers/superstruct/src/__tests__/__snapshots__/superstruct.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..55bbc92eea0cc8ed08fadf344a7e0e2cd381baf6 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/src/__tests__/__snapshots__/superstruct.ts.snap @@ -0,0 +1,64 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`superstructResolver > should return a single error from superstructResolver when validation fails 1`] = ` +{ + "errors": { + "birthYear": { + "message": "Expected a number, but received: "birthYear"", + "ref": undefined, + "type": "number", + }, + "email": { + "message": "Expected a string matching \`/^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/\` but received """, + "ref": { + "name": "email", + }, + "type": "string", + }, + "enabled": { + "message": "Expected a value of type \`boolean\`, but received: \`undefined\`", + "ref": undefined, + "type": "boolean", + }, + "like": [ + { + "id": { + "message": "Expected a number, but received: "z"", + "ref": undefined, + "type": "number", + }, + "name": { + "message": "Expected a string, but received: undefined", + "ref": undefined, + "type": "string", + }, + }, + ], + "password": { + "message": "Expected a string matching \`/^[a-zA-Z0-9]{3,30}/\` but received "___"", + "ref": { + "name": "password", + }, + "type": "string", + }, + "repeatPassword": { + "message": "Expected a value of type \`Password\`, but received: \`undefined\`", + "ref": undefined, + "type": "Password", + }, + "tags": { + "message": "Expected an array value, but received: undefined", + "ref": undefined, + "type": "array", + }, + "username": { + "message": "Expected a string, but received: undefined", + "ref": { + "name": "username", + }, + "type": "string", + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/superstruct/src/__tests__/superstruct.ts b/node_modules/@hookform/resolvers/superstruct/src/__tests__/superstruct.ts new file mode 100644 index 0000000000000000000000000000000000000000..66b65c31d0d04bbe77704f2e2ad7d1f1fd60522c --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/src/__tests__/superstruct.ts @@ -0,0 +1,111 @@ +import { renderHook } from '@testing-library/react'; +import { Resolver, SubmitHandler, useForm } from 'react-hook-form'; +import * as s from 'superstruct'; +import { superstructResolver } from '..'; +import { fields, invalidData, schema, validData } from './__fixtures__/data'; + +const shouldUseNativeValidation = false; + +describe('superstructResolver', () => { + it('should return values from superstructResolver when validation pass', async () => { + const result = await superstructResolver(schema)(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return values from superstructResolver with coerced values', async () => { + const result = await superstructResolver( + s.object({ + id: s.coerce(s.string(), s.number(), (val) => String(val)), + }), + { coerce: true }, + )({ id: 1 }, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toEqual({ errors: {}, values: { id: '1' } }); + }); + + it('should return a single error from superstructResolver when validation fails', async () => { + const result = await superstructResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + it('should return values from superstructResolver when validation pass & raw=true', async () => { + const result = await superstructResolver(schema, undefined, { raw: true })( + validData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(result).toEqual({ errors: {}, values: validData }); + }); + + /** + * Type inference tests + */ + it('should correctly infer the output type from a superstruct schema', () => { + const resolver = superstructResolver(s.object({ id: s.number() })); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver<{ id: number }, unknown, { id: number }> + >(); + }); + + it('should correctly infer the output type from a superstruct schema for the handleSubmit function in useForm', () => { + const schema = s.object({ id: s.number() }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: superstructResolver(schema, {}), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: number; + }> + >(); + }); + + it('should correctly infer the output type from a superstruct schema with a transform for the handleSubmit function in useForm', () => { + const schema = s.object({ + id: s.coerce(s.string(), s.number(), (val) => String(val)), + }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + // With coerce, there is no way to infer the input type of the schema + resolver: superstructResolver<{ id: number }, unknown, { id: string }>( + schema, + { coerce: true }, + ), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf< + SubmitHandler<{ + id: string; + }> + >(); + }); +}); diff --git a/node_modules/@hookform/resolvers/superstruct/src/index.ts b/node_modules/@hookform/resolvers/superstruct/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2acaa550eae38d3ff33df03d444d9b82461cc3cc --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/src/index.ts @@ -0,0 +1 @@ +export * from './superstruct'; diff --git a/node_modules/@hookform/resolvers/superstruct/src/superstruct.ts b/node_modules/@hookform/resolvers/superstruct/src/superstruct.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b5df17f8f37bb1197f0f9bf885ef489e941ad56 --- /dev/null +++ b/node_modules/@hookform/resolvers/superstruct/src/superstruct.ts @@ -0,0 +1,86 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import { FieldError, FieldValues, Resolver } from 'react-hook-form'; +import { Infer, Struct, StructError, validate } from 'superstruct'; + +function parseErrorSchema(error: StructError) { + return error.failures().reduce>( + (previous, error) => + (previous[error.path.join('.')] = { + message: error.message, + type: error.type, + }) && previous, + {}, + ); +} + +// This is required to correctly type the input of the returned function when coerce is true +// superstruct does not store the input type of a schema alongside it +// Infer gives the output type of the coercion +export function superstructResolver( + schema: Struct, + schemaOptions: Omit[2], 'coerce'> & { + coerce: true; + }, + resolverOptions?: { + raw?: boolean; + }, +): Resolver; + +export function superstructResolver( + schema: Struct, + schemaOptions?: Parameters[2], + resolverOptions?: { + raw?: false; + }, +): Resolver>; + +export function superstructResolver( + schema: Struct, + schemaOptions: Parameters[2] | undefined, + resolverOptions: { + raw: true; + }, +): Resolver; + +/** + * Creates a resolver for react-hook-form using Superstruct schema validation + * @param {Struct} schema - The Superstruct schema to validate against + * @param {Parameters[2]} [schemaOptions] - Optional Superstruct validation options + * @param {Object} resolverOptions - Additional resolver configuration + * @param {boolean} [resolverOptions.raw=false] - If true, returns raw values rather than validated results + * @returns {Resolver>} A resolver function compatible with react-hook-form + * @example + * const schema = struct({ + * name: string(), + * age: number() + * }); + * + * useForm({ + * resolver: superstructResolver(schema) + * }); + */ +export function superstructResolver( + schema: Struct, + schemaOptions?: Parameters[2], + resolverOptions: { + raw?: boolean; + } = {}, +): Resolver { + return (values: Input, _, options) => { + const result = validate(values, schema, schemaOptions); + + if (result[0]) { + return { + values: {}, + errors: toNestErrors(parseErrorSchema(result[0]), options), + }; + } + + options.shouldUseNativeValidation && validateFieldsNatively({}, options); + + return { + values: resolverOptions.raw ? Object.assign({}, values) : result[1], + errors: {}, + }; + }; +} diff --git a/node_modules/@hookform/resolvers/typanion/dist/index.d.ts b/node_modules/@hookform/resolvers/typanion/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11df6dcb08305cf9f8d4b6374e053b50dbf35416 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/index.d.ts @@ -0,0 +1 @@ +export * from './typanion'; diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.d.ts b/node_modules/@hookform/resolvers/typanion/dist/typanion.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a72881eb444be39f5a82a99c8154f2c2905d174a --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.d.ts @@ -0,0 +1,10 @@ +import type { FieldValues, Resolver } from 'react-hook-form'; +import * as t from 'typanion'; +export declare function typanionResolver(schema: t.StrictValidator, schemaOptions?: Pick, resolverOptions?: { + mode?: 'async' | 'sync'; + raw?: false; +}): Resolver>; +export declare function typanionResolver(schema: t.StrictValidator, schemaOptions: Pick | undefined, resolverOptions: { + mode?: 'async' | 'sync'; + raw: true; +}): Resolver; diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.js b/node_modules/@hookform/resolvers/typanion/dist/typanion.js new file mode 100644 index 0000000000000000000000000000000000000000..059e356b0b7393eebaa051f87152688964a554d0 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.js @@ -0,0 +1,2 @@ +var r=require("@hookform/resolvers");exports.typanionResolver=function(e,o){return void 0===o&&(o={}),function(s,i,t){var n=[],a=e(s,Object.assign({},{errors:n},o)),u=function(r,e){return void 0===e&&(e={}),r.reduce(function(r,e){var o=e.indexOf(":"),s=e.slice(1,o),i=e.slice(o+1).trim();return r[s]={message:i},r},e)}(n);return a?(t.shouldUseNativeValidation&&r.validateFieldsNatively(u,t),{values:s,errors:{}}):{values:{},errors:r.toNestErrors(u,t)}}}; +//# sourceMappingURL=typanion.js.map diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.js.map b/node_modules/@hookform/resolvers/typanion/dist/typanion.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b21cfbe54a4668f18b55ff9f1c1d27b54e9ce394 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typanion.js","sources":["../src/typanion.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n} from 'react-hook-form';\nimport * as t from 'typanion';\n\nfunction parseErrors(errors: string[], parsedErrors: FieldErrors = {}) {\n return errors.reduce((acc, error) => {\n const fieldIndex = error.indexOf(':');\n\n const field = error.slice(1, fieldIndex);\n const message = error.slice(fieldIndex + 1).trim();\n\n acc[field] = {\n message,\n } as FieldError;\n\n return acc;\n }, parsedErrors);\n}\n\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions?: Pick,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver>;\n\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions: Pick | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Typanion schema validation\n * @param {t.StrictValidator} schema - The Typanion schema to validate against\n * @param {Pick} [schemaOptions] - Optional Typanion validation options\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = t.isObject({\n * name: t.isString(),\n * age: t.isInteger()\n * });\n *\n * useForm({\n * resolver: typanionResolver(schema)\n * });\n */\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions: Pick = {},\n): Resolver {\n return (values: Input, _, options) => {\n const rawErrors: string[] = [];\n const isValid = schema(\n values,\n Object.assign(\n {},\n {\n errors: rawErrors,\n },\n schemaOptions,\n ),\n );\n const parsedErrors = parseErrors(rawErrors);\n\n if (isValid) {\n options.shouldUseNativeValidation &&\n validateFieldsNatively(parsedErrors, options);\n\n return { values, errors: {} };\n }\n\n return { values: {}, errors: toNestErrors(parsedErrors, options) };\n };\n}\n"],"names":["schema","schemaOptions","values","_","options","rawErrors","isValid","Object","assign","errors","parsedErrors","reduce","acc","error","fieldIndex","indexOf","field","slice","message","trim","parseErrors","shouldUseNativeValidation","validateFieldsNatively","toNestErrors"],"mappings":"uEA0DEA,EACAC,GAEA,gBAFAA,IAAAA,EAAmE,IAE5D,SAACC,EAAeC,EAAGC,GACxB,IAAMC,EAAsB,GACtBC,EAAUN,EACdE,EACAK,OAAOC,OACL,GACA,CACEC,OAAQJ,GAEVJ,IAGES,EAhEV,SAAqBD,EAAkBC,GACrC,gBADqCA,IAAAA,EAA4B,IAC1DD,EAAOE,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAaD,EAAME,QAAQ,KAE3BC,EAAQH,EAAMI,MAAM,EAAGH,GACvBI,EAAUL,EAAMI,MAAMH,EAAa,GAAGK,OAM5C,OAJAP,EAAII,GAAS,CACXE,QAAAA,GAGKN,CACT,EAAGF,EACL,CAmDyBU,CAAYf,GAEjC,OAAIC,GACFF,EAAQiB,2BACNC,yBAAuBZ,EAAcN,GAEhC,CAAEF,OAAAA,EAAQO,OAAQ,CAAA,IAGpB,CAAEP,OAAQ,CAAE,EAAEO,OAAQc,EAAAA,aAAab,EAAcN,GAC1D,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.mjs b/node_modules/@hookform/resolvers/typanion/dist/typanion.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a0b54499326bf3540e91ab6641249504f2f34abd --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function o(o,i){return void 0===i&&(i={}),function(n,s,t){var u=[],a=o(n,Object.assign({},{errors:u},i)),c=function(r,e){return void 0===e&&(e={}),r.reduce(function(r,e){var o=e.indexOf(":"),i=e.slice(1,o),n=e.slice(o+1).trim();return r[i]={message:n},r},e)}(u);return a?(t.shouldUseNativeValidation&&r(c,t),{values:n,errors:{}}):{values:{},errors:e(c,t)}}}export{o as typanionResolver}; +//# sourceMappingURL=typanion.module.js.map diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.modern.mjs b/node_modules/@hookform/resolvers/typanion/dist/typanion.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c329dae44de3b7c13cea31aa98f3b9f99d3d0e44 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.modern.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function s(s,o={}){return(t,n,i)=>{const u=[],c=s(t,Object.assign({},{errors:u},o)),a=function(r,e={}){return r.reduce((r,e)=>{const s=e.indexOf(":"),o=e.slice(1,s),t=e.slice(s+1).trim();return r[o]={message:t},r},e)}(u);return c?(i.shouldUseNativeValidation&&r(a,i),{values:t,errors:{}}):{values:{},errors:e(a,i)}}}export{s as typanionResolver}; +//# sourceMappingURL=typanion.modern.mjs.map diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.modern.mjs.map b/node_modules/@hookform/resolvers/typanion/dist/typanion.modern.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..2e6a1054651182345d4c689bee224185ac17d957 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.modern.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"typanion.modern.mjs","sources":["../src/typanion.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n} from 'react-hook-form';\nimport * as t from 'typanion';\n\nfunction parseErrors(errors: string[], parsedErrors: FieldErrors = {}) {\n return errors.reduce((acc, error) => {\n const fieldIndex = error.indexOf(':');\n\n const field = error.slice(1, fieldIndex);\n const message = error.slice(fieldIndex + 1).trim();\n\n acc[field] = {\n message,\n } as FieldError;\n\n return acc;\n }, parsedErrors);\n}\n\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions?: Pick,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver>;\n\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions: Pick | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Typanion schema validation\n * @param {t.StrictValidator} schema - The Typanion schema to validate against\n * @param {Pick} [schemaOptions] - Optional Typanion validation options\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = t.isObject({\n * name: t.isString(),\n * age: t.isInteger()\n * });\n *\n * useForm({\n * resolver: typanionResolver(schema)\n * });\n */\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions: Pick = {},\n): Resolver {\n return (values: Input, _, options) => {\n const rawErrors: string[] = [];\n const isValid = schema(\n values,\n Object.assign(\n {},\n {\n errors: rawErrors,\n },\n schemaOptions,\n ),\n );\n const parsedErrors = parseErrors(rawErrors);\n\n if (isValid) {\n options.shouldUseNativeValidation &&\n validateFieldsNatively(parsedErrors, options);\n\n return { values, errors: {} };\n }\n\n return { values: {}, errors: toNestErrors(parsedErrors, options) };\n };\n}\n"],"names":["typanionResolver","schema","schemaOptions","values","_","options","rawErrors","isValid","Object","assign","errors","parsedErrors","reduce","acc","error","fieldIndex","indexOf","field","slice","message","trim","parseErrors","shouldUseNativeValidation","validateFieldsNatively","toNestErrors"],"mappings":"wFAyDgBA,EACdC,EACAC,EAAmE,CAAA,GAEnE,MAAO,CAACC,EAAeC,EAAGC,KACxB,MAAMC,EAAsB,GACtBC,EAAUN,EACdE,EACAK,OAAOC,OACL,GACA,CACEC,OAAQJ,GAEVJ,IAGES,EAhEV,SAAqBD,EAAkBC,EAA4B,IACjE,OAAOD,EAAOE,OAAO,CAACC,EAAKC,KACzB,MAAMC,EAAaD,EAAME,QAAQ,KAE3BC,EAAQH,EAAMI,MAAM,EAAGH,GACvBI,EAAUL,EAAMI,MAAMH,EAAa,GAAGK,OAM5C,OAJAP,EAAII,GAAS,CACXE,WAGKN,CAAG,EACTF,EACL,CAmDyBU,CAAYf,GAEjC,OAAIC,GACFF,EAAQiB,2BACNC,EAAuBZ,EAAcN,GAEhC,CAAEF,SAAQO,OAAQ,CAAA,IAGpB,CAAEP,OAAQ,CAAA,EAAIO,OAAQc,EAAab,EAAcN,GAAU,CAEtE"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.module.js b/node_modules/@hookform/resolvers/typanion/dist/typanion.module.js new file mode 100644 index 0000000000000000000000000000000000000000..a0b54499326bf3540e91ab6641249504f2f34abd --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.module.js @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function o(o,i){return void 0===i&&(i={}),function(n,s,t){var u=[],a=o(n,Object.assign({},{errors:u},i)),c=function(r,e){return void 0===e&&(e={}),r.reduce(function(r,e){var o=e.indexOf(":"),i=e.slice(1,o),n=e.slice(o+1).trim();return r[i]={message:n},r},e)}(u);return a?(t.shouldUseNativeValidation&&r(c,t),{values:n,errors:{}}):{values:{},errors:e(c,t)}}}export{o as typanionResolver}; +//# sourceMappingURL=typanion.module.js.map diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.module.js.map b/node_modules/@hookform/resolvers/typanion/dist/typanion.module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..44ac3bdd678cef7c8f8ca7875c7e25cec3ecc4c8 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typanion.module.js","sources":["../src/typanion.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n} from 'react-hook-form';\nimport * as t from 'typanion';\n\nfunction parseErrors(errors: string[], parsedErrors: FieldErrors = {}) {\n return errors.reduce((acc, error) => {\n const fieldIndex = error.indexOf(':');\n\n const field = error.slice(1, fieldIndex);\n const message = error.slice(fieldIndex + 1).trim();\n\n acc[field] = {\n message,\n } as FieldError;\n\n return acc;\n }, parsedErrors);\n}\n\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions?: Pick,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver>;\n\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions: Pick | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Typanion schema validation\n * @param {t.StrictValidator} schema - The Typanion schema to validate against\n * @param {Pick} [schemaOptions] - Optional Typanion validation options\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = t.isObject({\n * name: t.isString(),\n * age: t.isInteger()\n * });\n *\n * useForm({\n * resolver: typanionResolver(schema)\n * });\n */\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions: Pick = {},\n): Resolver {\n return (values: Input, _, options) => {\n const rawErrors: string[] = [];\n const isValid = schema(\n values,\n Object.assign(\n {},\n {\n errors: rawErrors,\n },\n schemaOptions,\n ),\n );\n const parsedErrors = parseErrors(rawErrors);\n\n if (isValid) {\n options.shouldUseNativeValidation &&\n validateFieldsNatively(parsedErrors, options);\n\n return { values, errors: {} };\n }\n\n return { values: {}, errors: toNestErrors(parsedErrors, options) };\n };\n}\n"],"names":["typanionResolver","schema","schemaOptions","values","_","options","rawErrors","isValid","Object","assign","errors","parsedErrors","reduce","acc","error","fieldIndex","indexOf","field","slice","message","trim","parseErrors","shouldUseNativeValidation","validateFieldsNatively","toNestErrors"],"mappings":"wFAyDgBA,EACdC,EACAC,GAEA,gBAFAA,IAAAA,EAAmE,IAE5D,SAACC,EAAeC,EAAGC,GACxB,IAAMC,EAAsB,GACtBC,EAAUN,EACdE,EACAK,OAAOC,OACL,GACA,CACEC,OAAQJ,GAEVJ,IAGES,EAhEV,SAAqBD,EAAkBC,GACrC,gBADqCA,IAAAA,EAA4B,IAC1DD,EAAOE,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAaD,EAAME,QAAQ,KAE3BC,EAAQH,EAAMI,MAAM,EAAGH,GACvBI,EAAUL,EAAMI,MAAMH,EAAa,GAAGK,OAM5C,OAJAP,EAAII,GAAS,CACXE,QAAAA,GAGKN,CACT,EAAGF,EACL,CAmDyBU,CAAYf,GAEjC,OAAIC,GACFF,EAAQiB,2BACNC,EAAuBZ,EAAcN,GAEhC,CAAEF,OAAAA,EAAQO,OAAQ,CAAA,IAGpB,CAAEP,OAAQ,CAAE,EAAEO,OAAQc,EAAab,EAAcN,GAC1D,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.umd.js b/node_modules/@hookform/resolvers/typanion/dist/typanion.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..0ff388b44fc449fcb967269e962cbd64295d41e9 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.umd.js @@ -0,0 +1,2 @@ +!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],o):o((e||self).hookformResolversTypanion={},e.hookformResolvers)}(this,function(e,o){e.typanionResolver=function(e,r){return void 0===r&&(r={}),function(n,s,i){var t=[],f=e(n,Object.assign({},{errors:t},r)),l=function(e,o){return void 0===o&&(o={}),e.reduce(function(e,o){var r=o.indexOf(":"),n=o.slice(1,r),s=o.slice(r+1).trim();return e[n]={message:s},e},o)}(t);return f?(i.shouldUseNativeValidation&&o.validateFieldsNatively(l,i),{values:n,errors:{}}):{values:{},errors:o.toNestErrors(l,i)}}}}); +//# sourceMappingURL=typanion.umd.js.map diff --git a/node_modules/@hookform/resolvers/typanion/dist/typanion.umd.js.map b/node_modules/@hookform/resolvers/typanion/dist/typanion.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a01f2e089239da0a59ae49f5753d553ce1673342 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/dist/typanion.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typanion.umd.js","sources":["../src/typanion.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n} from 'react-hook-form';\nimport * as t from 'typanion';\n\nfunction parseErrors(errors: string[], parsedErrors: FieldErrors = {}) {\n return errors.reduce((acc, error) => {\n const fieldIndex = error.indexOf(':');\n\n const field = error.slice(1, fieldIndex);\n const message = error.slice(fieldIndex + 1).trim();\n\n acc[field] = {\n message,\n } as FieldError;\n\n return acc;\n }, parsedErrors);\n}\n\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions?: Pick,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver>;\n\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions: Pick | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver;\n\n/**\n * Creates a resolver for react-hook-form using Typanion schema validation\n * @param {t.StrictValidator} schema - The Typanion schema to validate against\n * @param {Pick} [schemaOptions] - Optional Typanion validation options\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = t.isObject({\n * name: t.isString(),\n * age: t.isInteger()\n * });\n *\n * useForm({\n * resolver: typanionResolver(schema)\n * });\n */\nexport function typanionResolver(\n schema: t.StrictValidator,\n schemaOptions: Pick = {},\n): Resolver {\n return (values: Input, _, options) => {\n const rawErrors: string[] = [];\n const isValid = schema(\n values,\n Object.assign(\n {},\n {\n errors: rawErrors,\n },\n schemaOptions,\n ),\n );\n const parsedErrors = parseErrors(rawErrors);\n\n if (isValid) {\n options.shouldUseNativeValidation &&\n validateFieldsNatively(parsedErrors, options);\n\n return { values, errors: {} };\n }\n\n return { values: {}, errors: toNestErrors(parsedErrors, options) };\n };\n}\n"],"names":["schema","schemaOptions","values","_","options","rawErrors","isValid","Object","assign","errors","parsedErrors","reduce","acc","error","fieldIndex","indexOf","field","slice","message","trim","parseErrors","shouldUseNativeValidation","validateFieldsNatively","toNestErrors"],"mappings":"0VA0DEA,EACAC,GAEA,gBAFAA,IAAAA,EAAmE,IAE5D,SAACC,EAAeC,EAAGC,GACxB,IAAMC,EAAsB,GACtBC,EAAUN,EACdE,EACAK,OAAOC,OACL,GACA,CACEC,OAAQJ,GAEVJ,IAGES,EAhEV,SAAqBD,EAAkBC,GACrC,gBADqCA,IAAAA,EAA4B,IAC1DD,EAAOE,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAaD,EAAME,QAAQ,KAE3BC,EAAQH,EAAMI,MAAM,EAAGH,GACvBI,EAAUL,EAAMI,MAAMH,EAAa,GAAGK,OAM5C,OAJAP,EAAII,GAAS,CACXE,QAAAA,GAGKN,CACT,EAAGF,EACL,CAmDyBU,CAAYf,GAEjC,OAAIC,GACFF,EAAQiB,2BACNC,yBAAuBZ,EAAcN,GAEhC,CAAEF,OAAAA,EAAQO,OAAQ,CAAA,IAGpB,CAAEP,OAAQ,CAAE,EAAEO,OAAQc,EAAAA,aAAab,EAAcN,GAC1D,CACF"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/typanion/package.json b/node_modules/@hookform/resolvers/typanion/package.json new file mode 100644 index 0000000000000000000000000000000000000000..da76b2c3438961474eb8a4e153d9c5a6fba43508 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/package.json @@ -0,0 +1,18 @@ +{ + "name": "@hookform/resolvers/typanion", + "amdName": "hookformResolversTypanion", + "version": "1.0.0", + "private": true, + "description": "React Hook Form validation resolver: typanion", + "main": "dist/typanion.js", + "module": "dist/typanion.module.js", + "umd:main": "dist/typanion.umd.js", + "source": "src/index.ts", + "types": "dist/index.d.ts", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.55.0", + "@hookform/resolvers": "^2.0.0", + "typanion": "^3.3.2" + } +} diff --git a/node_modules/@hookform/resolvers/typanion/src/__tests__/Form-native-validation.tsx b/node_modules/@hookform/resolvers/typanion/src/__tests__/Form-native-validation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b0765763371c57894103fff6787ae9361ec68607 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/src/__tests__/Form-native-validation.tsx @@ -0,0 +1,77 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import * as t from 'typanion'; +import { typanionResolver } from '..'; + +const ERROR_MESSAGE = + 'Expected to have a length of at least 1 elements (got 0)'; + +const schema = t.isObject({ + username: t.cascade(t.isString(), [t.hasMinLength(1)]), + password: t.cascade(t.isString(), [t.hasMinLength(1)]), +}); + +function TestComponent({ + onSubmit, +}: { onSubmit: (data: t.InferType) => void }) { + const { register, handleSubmit } = useForm({ + resolver: typanionResolver(schema), + shouldUseNativeValidation: true, + }); + + return ( +
+ + + + + +
+ ); +} + +test("form's native validation with Typanion", async () => { + const handleSubmit = vi.fn(); + render(); + + // username + let usernameField = screen.getByPlaceholderText( + /username/i, + ) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + let passwordField = screen.getByPlaceholderText( + /password/i, + ) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); + + await user.click(screen.getByText(/submit/i)); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(false); + expect(usernameField.validationMessage).toBe(ERROR_MESSAGE); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(false); + expect(passwordField.validationMessage).toBe(ERROR_MESSAGE); + + await user.type(screen.getByPlaceholderText(/username/i), 'joe'); + await user.type(screen.getByPlaceholderText(/password/i), 'password'); + + // username + usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; + expect(usernameField.validity.valid).toBe(true); + expect(usernameField.validationMessage).toBe(''); + + // password + passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; + expect(passwordField.validity.valid).toBe(true); + expect(passwordField.validationMessage).toBe(''); +}); diff --git a/node_modules/@hookform/resolvers/typanion/src/__tests__/Form.tsx b/node_modules/@hookform/resolvers/typanion/src/__tests__/Form.tsx new file mode 100644 index 0000000000000000000000000000000000000000..431114e1da0902e2270503b94a4a00c5e963e09a --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/src/__tests__/Form.tsx @@ -0,0 +1,51 @@ +import { render, screen } from '@testing-library/react'; +import user from '@testing-library/user-event'; +import React from 'react'; +import { useForm } from 'react-hook-form'; +import * as t from 'typanion'; +import { typanionResolver } from '..'; + +const schema = t.isObject({ + username: t.cascade(t.isString(), [t.hasMinLength(1)]), + password: t.cascade(t.isString(), [t.hasMinLength(1)]), +}); + +function TestComponent({ + onSubmit, +}: { onSubmit: (data: t.InferType) => void }) { + const { + register, + formState: { errors }, + handleSubmit, + } = useForm({ + resolver: typanionResolver(schema), // Useful to check TypeScript regressions + }); + + return ( +
+ + {errors.username && {errors.username.message}} + + + {errors.password && {errors.password.message}} + + +
+ ); +} + +test("form's validation with Typanion and TypeScript's integration", async () => { + const handleSubmit = vi.fn(); + render(); + + expect(screen.queryAllByRole('alert')).toHaveLength(0); + + await user.click(screen.getByText(/submit/i)); + + expect( + screen.getAllByText( + 'Expected to have a length of at least 1 elements (got 0)', + ), + ).toHaveLength(2); + expect(handleSubmit).not.toHaveBeenCalled(); +}); diff --git a/node_modules/@hookform/resolvers/typanion/src/__tests__/__fixtures__/data.ts b/node_modules/@hookform/resolvers/typanion/src/__tests__/__fixtures__/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..513c3c7174a5658f6c0219fc5949fad6413697c7 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/src/__tests__/__fixtures__/data.ts @@ -0,0 +1,82 @@ +import { Field, InternalFieldName } from 'react-hook-form'; +import * as t from 'typanion'; + +export const schema = t.isObject({ + username: t.cascade(t.isString(), [ + t.matchesRegExp(/^\w+$/), + t.hasMinLength(2), + t.hasMaxLength(30), + ]), + password: t.cascade(t.isString(), [ + t.matchesRegExp(new RegExp('.*[A-Z].*')), // one uppercase character + t.matchesRegExp(new RegExp('.*[a-z].*')), // one lowercase character + t.matchesRegExp(new RegExp('.*\\d.*')), // one number + t.matchesRegExp( + new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'), + ), // one special character + t.hasMinLength(8), // Must be at least 8 characters in length + ]), + repeatPassword: t.cascade(t.isString(), [ + t.matchesRegExp(new RegExp('.*[A-Z].*')), // one uppercase character + t.matchesRegExp(new RegExp('.*[a-z].*')), // one lowercase character + t.matchesRegExp(new RegExp('.*\\d.*')), // one number + t.matchesRegExp( + new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'), + ), // one special character + t.hasMinLength(8), // Must be at least 8 characters in length + ]), + accessToken: t.isString(), + birthYear: t.cascade(t.isNumber(), [ + t.isInteger(), + t.isInInclusiveRange(1900, 2013), + ]), + email: t.cascade(t.isString(), [t.matchesRegExp(/^\S+@\S+$/)]), + tags: t.isArray(t.isString()), + enabled: t.isBoolean(), + like: t.isObject({ + id: t.cascade(t.isNumber(), [t.isInteger(), t.isPositive()]), + name: t.cascade(t.isString(), [t.hasMinLength(4)]), + }), +}); + +export const validData = { + username: 'Doe', + password: 'Password123_', + repeatPassword: 'Password123_', + birthYear: 2000, + email: 'john@doe.com', + tags: ['tag1', 'tag2'], + enabled: true, + accessToken: 'accessToken', + like: { + id: 1, + name: 'name', + }, +}; + +export const invalidData = { + password: '___', + email: '', + birthYear: 'birthYear', + like: { id: 'z' }, + tags: [1, 2, 3], +} as any as t.InferType; + +export const fields: Record = { + username: { + ref: { name: 'username' }, + name: 'username', + }, + password: { + ref: { name: 'password' }, + name: 'password', + }, + email: { + ref: { name: 'email' }, + name: 'email', + }, + birthday: { + ref: { name: 'birthday' }, + name: 'birthday', + }, +}; diff --git a/node_modules/@hookform/resolvers/typanion/src/__tests__/__snapshots__/typanion.ts.snap b/node_modules/@hookform/resolvers/typanion/src/__tests__/__snapshots__/typanion.ts.snap new file mode 100644 index 0000000000000000000000000000000000000000..a2e888e19ade603c8385b91b9998b79cfa98891e --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/src/__tests__/__snapshots__/typanion.ts.snap @@ -0,0 +1,67 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`typanionResolver > should return a single error from typanionResolver when validation fails 1`] = ` +{ + "errors": { + "accessToken": { + "message": "Expected a string (got undefined)", + "ref": undefined, + }, + "birthYear": { + "message": "Expected a number (got "birthYear")", + "ref": undefined, + }, + "email": { + "message": "Expected to match the pattern /^\\S+@\\S+$/ (got an empty string)", + "ref": { + "name": "email", + }, + }, + "enabled": { + "message": "Expected a boolean (got undefined)", + "ref": undefined, + }, + "like": { + "id": { + "message": "Expected a number (got "z")", + "ref": undefined, + }, + "name": { + "message": "Expected a string (got undefined)", + "ref": undefined, + }, + }, + "password": { + "message": "Expected to match the pattern /.*[A-Z].*/ (got "___")", + "ref": { + "name": "password", + }, + }, + "repeatPassword": { + "message": "Expected a string (got undefined)", + "ref": undefined, + }, + "tags": [ + { + "message": "Expected a string (got 1)", + "ref": undefined, + }, + { + "message": "Expected a string (got 2)", + "ref": undefined, + }, + { + "message": "Expected a string (got 3)", + "ref": undefined, + }, + ], + "username": { + "message": "Expected a string (got undefined)", + "ref": { + "name": "username", + }, + }, + }, + "values": {}, +} +`; diff --git a/node_modules/@hookform/resolvers/typanion/src/__tests__/typanion.ts b/node_modules/@hookform/resolvers/typanion/src/__tests__/typanion.ts new file mode 100644 index 0000000000000000000000000000000000000000..524d607d9760b88348dd984e668809aaa8f9d7c2 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/src/__tests__/typanion.ts @@ -0,0 +1,89 @@ +import { renderHook } from '@testing-library/react'; +import { SubmitHandler } from 'react-hook-form'; +import { useForm } from 'react-hook-form'; +import { Resolver } from 'react-hook-form'; +import * as t from 'typanion'; +import { typanionResolver } from '..'; +import { fields, invalidData, schema, validData } from './__fixtures__/data'; + +const tmpObj = { + validate: schema, +}; + +const shouldUseNativeValidation = false; + +describe('typanionResolver', () => { + it('should return values from typanionResolver when validation pass', async () => { + const schemaSpy = vi.spyOn(tmpObj, 'validate'); + + const result = await typanionResolver(schemaSpy as any)( + validData, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(schemaSpy).toHaveBeenCalledTimes(1); + expect(result).toEqual({ errors: {}, values: validData }); + }); + + it('should return a single error from typanionResolver when validation fails', async () => { + const result = await typanionResolver(schema)(invalidData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toMatchSnapshot(); + }); + + /** + * Type inference tests + */ + it('should correctly infer the output type from a typanion schema', () => { + const resolver = typanionResolver(t.isObject({ id: t.isNumber() })); + + expectTypeOf(resolver).toEqualTypeOf< + Resolver, unknown, ObjectType<{ id: number }>> + >(); + }); + + it('should correctly infer the output type from a typanion schema for the handleSubmit function in useForm', () => { + const schema = t.isObject({ id: t.isNumber() }); + + const { + result: { current: form }, + } = renderHook(() => + useForm({ + resolver: typanionResolver(schema), + }), + ); + + expectTypeOf(form.watch('id')).toEqualTypeOf(); + + expectTypeOf(form.handleSubmit) + .parameter(0) + .toEqualTypeOf>>(); + }); +}); + +/** + * Copied from Typanion source code because it's not exported + */ + +declare type ExtractIndex = { + // biome-ignore lint/complexity/noBannedTypes: for testing purposes + [K in keyof T as {} extends Record ? K : never]: T[K]; +}; +declare type RemoveIndex = { + // biome-ignore lint/complexity/noBannedTypes: for testing purposes + [K in keyof T as {} extends Record ? never : K]: T[K]; +}; +declare type UndefinedProperties = { + [P in keyof T]-?: undefined extends T[P] ? P : never; +}[keyof T]; +declare type UndefinedToOptional = Partial>> & + Pick>>; +declare type ObjectType = UndefinedToOptional> & + ExtractIndex; diff --git a/node_modules/@hookform/resolvers/typanion/src/index.ts b/node_modules/@hookform/resolvers/typanion/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..11df6dcb08305cf9f8d4b6374e053b50dbf35416 --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/src/index.ts @@ -0,0 +1 @@ +export * from './typanion'; diff --git a/node_modules/@hookform/resolvers/typanion/src/typanion.ts b/node_modules/@hookform/resolvers/typanion/src/typanion.ts new file mode 100644 index 0000000000000000000000000000000000000000..d79f91c3a916b37dee91e7beb08a2c08016ba43c --- /dev/null +++ b/node_modules/@hookform/resolvers/typanion/src/typanion.ts @@ -0,0 +1,85 @@ +import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers'; +import type { + FieldError, + FieldErrors, + FieldValues, + Resolver, +} from 'react-hook-form'; +import * as t from 'typanion'; + +function parseErrors(errors: string[], parsedErrors: FieldErrors = {}) { + return errors.reduce((acc, error) => { + const fieldIndex = error.indexOf(':'); + + const field = error.slice(1, fieldIndex); + const message = error.slice(fieldIndex + 1).trim(); + + acc[field] = { + message, + } as FieldError; + + return acc; + }, parsedErrors); +} + +export function typanionResolver( + schema: t.StrictValidator, + schemaOptions?: Pick, + resolverOptions?: { + mode?: 'async' | 'sync'; + raw?: false; + }, +): Resolver>; + +export function typanionResolver( + schema: t.StrictValidator, + schemaOptions: Pick | undefined, + resolverOptions: { + mode?: 'async' | 'sync'; + raw: true; + }, +): Resolver; + +/** + * Creates a resolver for react-hook-form using Typanion schema validation + * @param {t.StrictValidator} schema - The Typanion schema to validate against + * @param {Pick} [schemaOptions] - Optional Typanion validation options + * @returns {Resolver>} A resolver function compatible with react-hook-form + * @example + * const schema = t.isObject({ + * name: t.isString(), + * age: t.isInteger() + * }); + * + * useForm({ + * resolver: typanionResolver(schema) + * }); + */ +export function typanionResolver( + schema: t.StrictValidator, + schemaOptions: Pick = {}, +): Resolver { + return (values: Input, _, options) => { + const rawErrors: string[] = []; + const isValid = schema( + values, + Object.assign( + {}, + { + errors: rawErrors, + }, + schemaOptions, + ), + ); + const parsedErrors = parseErrors(rawErrors); + + if (isValid) { + options.shouldUseNativeValidation && + validateFieldsNatively(parsedErrors, options); + + return { values, errors: {} }; + } + + return { values: {}, errors: toNestErrors(parsedErrors, options) }; + }; +} diff --git a/node_modules/@hookform/resolvers/typebox/dist/index.d.ts b/node_modules/@hookform/resolvers/typebox/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7dfd5006e0c1a6db861c5ac42baf793245d70e2 --- /dev/null +++ b/node_modules/@hookform/resolvers/typebox/dist/index.d.ts @@ -0,0 +1 @@ +export * from './typebox'; diff --git a/node_modules/@hookform/resolvers/typebox/dist/typebox.d.ts b/node_modules/@hookform/resolvers/typebox/dist/typebox.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..60d2f33d37d62cadb175804ae43954d0ceabab42 --- /dev/null +++ b/node_modules/@hookform/resolvers/typebox/dist/typebox.d.ts @@ -0,0 +1,25 @@ +import { Static, StaticDecode, TObject } from '@sinclair/typebox'; +import { TypeCheck } from '@sinclair/typebox/compiler'; +import { Resolver } from 'react-hook-form'; +/** + * Creates a resolver for react-hook-form using Typebox schema validation + * @param {Schema | TypeCheck} schema - The Typebox schema to validate against + * @param {Object} options - Additional resolver configuration + * @param {string} [options.mode='async'] - Validation mode + * @returns {Resolver>} A resolver function compatible with react-hook-form + * @example + * const schema = Type.Object({ + * name: Type.String(), + * age: Type.Number() + * }); + * + * useForm({ + * resolver: typeboxResolver(schema) + * }); + * + * // Schemas using a custom/third-party `Kind` (e.g. ElysiaJS's `t.Files()`) must have + * // that kind registered with TypeBox's own `TypeRegistry` before validating, since + * // this resolver validates via `@sinclair/typebox`'s `Value.Errors`/`Value.Check`: + * // TypeRegistry.Set('Files', (schema, value) => Array.isArray(value)); + */ +export declare function typeboxResolver(schema: Schema | TypeCheck): Resolver, Context, StaticDecode>; diff --git a/node_modules/@hookform/resolvers/typebox/dist/typebox.js b/node_modules/@hookform/resolvers/typebox/dist/typebox.js new file mode 100644 index 0000000000000000000000000000000000000000..4c1fb76eb35b3f434240f8a4a24817397813fa9b --- /dev/null +++ b/node_modules/@hookform/resolvers/typebox/dist/typebox.js @@ -0,0 +1,2 @@ +var e=require("@hookform/resolvers"),r=require("@sinclair/typebox/compiler"),s=require("@sinclair/typebox/value"),t=require("react-hook-form");function a(e,r){for(var s=Object.create(null);e.length;){var a=e[0],o=a.type,i=a.message,l=a.path.substring(1).replace(/\//g,".");if(s[l]||(s[l]={message:i,type:""+o}),r){var n=s[l].types,u=n&&n[""+o];s[l]=t.appendErrors(l,r,s,""+o,u?[].concat(u,a.message):a.message)}e.shift()}return s}exports.typeboxResolver=function(t){return function(o,i,l){try{var n=Array.from(t instanceof r.TypeCheck?t.Errors(o):s.Value.Errors(t,o));return l.shouldUseNativeValidation&&e.validateFieldsNatively({},l),Promise.resolve(n.length?{values:{},errors:e.toNestErrors(a(n,!l.shouldUseNativeValidation&&"all"===l.criteriaMode),l)}:{errors:{},values:o})}catch(e){return Promise.reject(e)}}}; +//# sourceMappingURL=typebox.js.map diff --git a/node_modules/@hookform/resolvers/typebox/dist/typebox.js.map b/node_modules/@hookform/resolvers/typebox/dist/typebox.js.map new file mode 100644 index 0000000000000000000000000000000000000000..012f7f77444536cc0b798597166619570ca38129 --- /dev/null +++ b/node_modules/@hookform/resolvers/typebox/dist/typebox.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typebox.js","sources":["../src/typebox.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { Static, StaticDecode, TObject } from '@sinclair/typebox';\nimport { TypeCheck } from '@sinclair/typebox/compiler';\nimport { Value, type ValueError } from '@sinclair/typebox/value';\nimport { FieldError, Resolver, appendErrors } from 'react-hook-form';\n\nfunction parseErrorSchema(\n _errors: ValueError[],\n validateAllFieldCriteria: boolean,\n) {\n // See the matching comment in the zod resolver's `parseZod3Issues`.\n const errors: Record = Object.create(null);\n for (; _errors.length; ) {\n const error = _errors[0];\n const { type, message, path } = error;\n const _path = path.substring(1).replace(/\\//g, '.');\n\n if (!errors[_path]) {\n errors[_path] = { message, type: '' + type };\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types['' + type];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n '' + type,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n _errors.shift();\n }\n\n return errors;\n}\n\n/**\n * Creates a resolver for react-hook-form using Typebox schema validation\n * @param {Schema | TypeCheck} schema - The Typebox schema to validate against\n * @param {Object} options - Additional resolver configuration\n * @param {string} [options.mode='async'] - Validation mode\n * @returns {Resolver>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Type.Object({\n * name: Type.String(),\n * age: Type.Number()\n * });\n *\n * useForm({\n * resolver: typeboxResolver(schema)\n * });\n *\n * // Schemas using a custom/third-party `Kind` (e.g. ElysiaJS's `t.Files()`) must have\n * // that kind registered with TypeBox's own `TypeRegistry` before validating, since\n * // this resolver validates via `@sinclair/typebox`'s `Value.Errors`/`Value.Check`:\n * // TypeRegistry.Set('Files', (schema, value) => Array.isArray(value));\n */\nexport function typeboxResolver(\n schema: Schema | TypeCheck,\n): Resolver, Context, StaticDecode> {\n return async (values: Static, _, options) => {\n const errors = Array.from(\n schema instanceof TypeCheck\n ? schema.Errors(values)\n : Value.Errors(schema, values),\n );\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n if (!errors.length) {\n return {\n errors: {},\n values,\n };\n }\n\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n errors,\n !options.shouldUseNativeValidation && options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n}\n"],"names":["parseErrorSchema","_errors","validateAllFieldCriteria","errors","Object","create","length","error","type","message","_path","path","substring","replace","types","messages","appendErrors","concat","shift","schema","values","_","options","Array","from","TypeCheck","Errors","Value","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","toNestErrors","criteriaMode","e","reject"],"mappings":"+IAMA,SAASA,EACPC,EACAC,GAIA,IADA,IAAMC,EAAqCC,OAAOC,OAAO,MAClDJ,EAAQK,QAAU,CACvB,IAAMC,EAAQN,EAAQ,GACdO,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,UAAU,GAAGC,QAAQ,MAAO,KAM/C,GAJKV,EAAOO,KACVP,EAAOO,GAAS,CAAED,QAAAA,EAASD,KAAM,GAAKA,IAGpCN,EAA0B,CAC5B,IAAMY,EAAQX,EAAOO,GAAOI,MACtBC,EAAWD,GAASA,EAAM,GAAKN,GAErCL,EAAOO,GAASM,EAAAA,aACdN,EACAR,EACAC,EACA,GAAKK,EACLO,EACK,GAAgBE,OAAOF,EAAsBR,EAAME,SACpDF,EAAME,QAEd,CAEAR,EAAQiB,OACV,CAEA,OAAOf,CACT,yBAuBM,SACJgB,GAEA,OAAcC,SAAAA,EAAwBC,EAAGC,GAAO,IAC9C,IAAMnB,EAASoB,MAAMC,KACnBL,aAAkBM,EAASA,UACvBN,EAAOO,OAAON,GACdO,EAAKA,MAACD,OAAOP,EAAQC,IAK3B,OAFAE,EAAQM,2BAA6BC,EAAsBA,uBAAC,CAAE,EAAEP,GAShEQ,QAAAC,QAPK5B,EAAOG,OAOL,CACLc,OAAQ,CAAE,EACVjB,OAAQ6B,EAAAA,aACNhC,EACEG,GACCmB,EAAQM,2BAAsD,QAAzBN,EAAQW,cAEhDX,IAbK,CACLnB,OAAQ,GACRiB,OAAAA,GAcN,CAAC,MAAAc,GAAAJ,OAAAA,QAAAK,OAAAD,EACH,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@hookform/resolvers/typebox/dist/typebox.mjs b/node_modules/@hookform/resolvers/typebox/dist/typebox.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8179dd6561f834a7aa62c2bbf4276db2bc2da53e --- /dev/null +++ b/node_modules/@hookform/resolvers/typebox/dist/typebox.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{TypeCheck as o}from"@sinclair/typebox/compiler";import{Value as t}from"@sinclair/typebox/value";import{appendErrors as s}from"react-hook-form";function a(r,e){for(var o=Object.create(null);r.length;){var t=r[0],a=t.type,i=t.message,n=t.path.substring(1).replace(/\//g,".");if(o[n]||(o[n]={message:i,type:""+a}),e){var l=o[n].types,m=l&&l[""+a];o[n]=s(n,e,o,""+a,m?[].concat(m,t.message):t.message)}r.shift()}return o}function i(s){return function(i,n,l){try{var m=Array.from(s instanceof o?s.Errors(i):t.Errors(s,i));return l.shouldUseNativeValidation&&r({},l),Promise.resolve(m.length?{values:{},errors:e(a(m,!l.shouldUseNativeValidation&&"all"===l.criteriaMode),l)}:{errors:{},values:i})}catch(r){return Promise.reject(r)}}}export{i as typeboxResolver}; +//# sourceMappingURL=typebox.module.js.map diff --git a/node_modules/@hookform/resolvers/typebox/dist/typebox.modern.mjs b/node_modules/@hookform/resolvers/typebox/dist/typebox.modern.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b4c5046ec34ba787eff338afe975f5dd9a5b0422 --- /dev/null +++ b/node_modules/@hookform/resolvers/typebox/dist/typebox.modern.mjs @@ -0,0 +1,2 @@ +import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{TypeCheck as o}from"@sinclair/typebox/compiler";import{Value as t}from"@sinclair/typebox/value";import{appendErrors as s}from"react-hook-form";function a(r,e){const o=Object.create(null);for(;r.length;){const t=r[0],{type:a,message:i,path:n}=t,c=n.substring(1).replace(/\//g,".");if(o[c]||(o[c]={message:i,type:""+a}),e){const r=o[c].types,i=r&&r[""+a];o[c]=s(c,e,o,""+a,i?[].concat(i,t.message):t.message)}r.shift()}return o}function i(s){return async(i,n,c)=>{const l=Array.from(s instanceof o?s.Errors(i):t.Errors(s,i));return c.shouldUseNativeValidation&&r({},c),l.length?{values:{},errors:e(a(l,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}:{errors:{},values:i}}}export{i as typeboxResolver}; +//# sourceMappingURL=typebox.modern.mjs.map