@evervault/react-native 2.5.1 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/README.md +0 -2
  2. package/build/cjs/Card/Cvc.js +29 -0
  3. package/build/cjs/Card/Expiry.js +12 -0
  4. package/build/cjs/Card/Holder.js +15 -0
  5. package/build/cjs/Card/Number.js +27 -0
  6. package/build/cjs/Card/Root.js +70 -0
  7. package/build/cjs/Card/index.js +20 -0
  8. package/build/cjs/Card/schema.js +32 -0
  9. package/build/cjs/Card/types.js +21 -0
  10. package/build/cjs/Card/utils.js +87 -0
  11. package/build/cjs/EvervaultProvider.js +17 -0
  12. package/build/cjs/Input.js +107 -0
  13. package/build/cjs/ThreeDSecure/Frame.js +37 -0
  14. package/build/cjs/ThreeDSecure/Root.js +14 -0
  15. package/build/cjs/ThreeDSecure/config.js +7 -0
  16. package/build/cjs/ThreeDSecure/context.js +7 -0
  17. package/build/cjs/ThreeDSecure/event.js +20 -0
  18. package/build/cjs/ThreeDSecure/index.js +12 -0
  19. package/build/cjs/ThreeDSecure/session.js +141 -0
  20. package/build/cjs/ThreeDSecure/types.js +2 -0
  21. package/build/cjs/ThreeDSecure/useThreeDSecure.js +44 -0
  22. package/build/cjs/__mocks__/NativeEvervault.js +14 -0
  23. package/build/cjs/__mocks__/react-native-webview.js +10 -0
  24. package/build/cjs/context.js +7 -0
  25. package/build/cjs/index.js +25 -0
  26. package/build/cjs/node_modules/@hookform/resolvers/dist/resolvers.js +8 -0
  27. package/build/cjs/node_modules/@hookform/resolvers/zod/dist/zod.js +8 -0
  28. package/build/cjs/node_modules/react-hook-form/dist/index.esm.js +2221 -0
  29. package/build/cjs/node_modules/react-native-mask-input/lib/module/MaskInput.js +60 -0
  30. package/build/cjs/node_modules/react-native-mask-input/lib/module/formatWithMask.js +92 -0
  31. package/build/cjs/node_modules/react-native-mask-input/lib/module/index.js +10 -0
  32. package/build/cjs/node_modules/react-native-mask-input/lib/module/useMaskedInputProps.js +93 -0
  33. package/build/{index.cjs.js → cjs/node_modules/zod/lib/index.js} +193 -3490
  34. package/build/cjs/packages/card-validator/dist/evervault-card-validator.main.js +349 -0
  35. package/build/cjs/sdk.js +53 -0
  36. package/build/cjs/specs/NativeEvervault.js +7 -0
  37. package/build/cjs/useEvervault.js +14 -0
  38. package/build/cjs/utils.js +34 -0
  39. package/build/{Card → esm/Card}/Cvc.d.ts +0 -1
  40. package/build/esm/Card/Cvc.js +27 -0
  41. package/build/{Card → esm/Card}/Expiry.d.ts +0 -1
  42. package/build/esm/Card/Expiry.js +10 -0
  43. package/build/{Card → esm/Card}/Holder.d.ts +0 -1
  44. package/build/esm/Card/Holder.js +13 -0
  45. package/build/{Card → esm/Card}/Number.d.ts +0 -1
  46. package/build/esm/Card/Number.js +25 -0
  47. package/build/{Card → esm/Card}/Root.d.ts +0 -1
  48. package/build/esm/Card/Root.js +68 -0
  49. package/build/{Card → esm/Card}/index.d.ts +0 -1
  50. package/build/esm/Card/index.js +14 -0
  51. package/build/{Card → esm/Card}/schema.d.ts +0 -1
  52. package/build/esm/Card/schema.js +30 -0
  53. package/build/{Card → esm/Card}/types.d.ts +0 -1
  54. package/build/esm/Card/types.js +19 -0
  55. package/build/{Card → esm/Card}/utils.d.ts +0 -1
  56. package/build/esm/Card/utils.js +82 -0
  57. package/build/{EvervaultProvider.d.ts → esm/EvervaultProvider.d.ts} +0 -1
  58. package/build/esm/EvervaultProvider.js +15 -0
  59. package/build/{Input.d.ts → esm/Input.d.ts} +0 -1
  60. package/build/esm/Input.js +103 -0
  61. package/build/{ThreeDSecure → esm/ThreeDSecure}/Frame.d.ts +0 -1
  62. package/build/esm/ThreeDSecure/Frame.js +35 -0
  63. package/build/{ThreeDSecure → esm/ThreeDSecure}/Root.d.ts +0 -1
  64. package/build/esm/ThreeDSecure/Root.js +12 -0
  65. package/build/{ThreeDSecure → esm/ThreeDSecure}/config.d.ts +0 -1
  66. package/build/esm/ThreeDSecure/config.js +4 -0
  67. package/build/{ThreeDSecure → esm/ThreeDSecure}/context.d.ts +0 -1
  68. package/build/esm/ThreeDSecure/context.js +5 -0
  69. package/build/{ThreeDSecure → esm/ThreeDSecure}/event.d.ts +0 -1
  70. package/build/esm/ThreeDSecure/event.js +18 -0
  71. package/build/{ThreeDSecure → esm/ThreeDSecure}/index.d.ts +0 -1
  72. package/build/esm/ThreeDSecure/index.js +9 -0
  73. package/build/{ThreeDSecure → esm/ThreeDSecure}/session.d.ts +0 -1
  74. package/build/esm/ThreeDSecure/session.js +136 -0
  75. package/build/{ThreeDSecure → esm/ThreeDSecure}/types.d.ts +0 -1
  76. package/build/esm/ThreeDSecure/types.js +1 -0
  77. package/build/{ThreeDSecure → esm/ThreeDSecure}/useThreeDSecure.d.ts +0 -1
  78. package/build/esm/ThreeDSecure/useThreeDSecure.js +42 -0
  79. package/build/{__mocks__ → esm/__mocks__}/NativeEvervault.d.ts +0 -1
  80. package/build/esm/__mocks__/NativeEvervault.js +11 -0
  81. package/build/{__mocks__ → esm/__mocks__}/react-native-webview.d.ts +0 -1
  82. package/build/esm/__mocks__/react-native-webview.js +8 -0
  83. package/build/{context.d.ts → esm/context.d.ts} +0 -1
  84. package/build/esm/context.js +5 -0
  85. package/build/{index.d.ts → esm/index.d.ts} +0 -1
  86. package/build/esm/index.js +14 -0
  87. package/build/esm/node_modules/@hookform/resolvers/dist/resolvers.js +5 -0
  88. package/build/esm/node_modules/@hookform/resolvers/zod/dist/zod.js +6 -0
  89. package/build/esm/node_modules/react-hook-form/dist/index.esm.js +2211 -0
  90. package/build/esm/node_modules/react-native-mask-input/lib/module/MaskInput.js +37 -0
  91. package/build/esm/node_modules/react-native-mask-input/lib/module/formatWithMask.js +88 -0
  92. package/build/esm/node_modules/react-native-mask-input/lib/module/index.js +6 -0
  93. package/build/esm/node_modules/react-native-mask-input/lib/module/useMaskedInputProps.js +70 -0
  94. package/build/{index.esm.js → esm/node_modules/zod/lib/index.js} +1 -3377
  95. package/build/esm/packages/card-validator/dist/evervault-card-validator.main.js +345 -0
  96. package/build/{sdk.d.ts → esm/sdk.d.ts} +0 -1
  97. package/build/esm/sdk.js +51 -0
  98. package/build/{specs → esm/specs}/NativeEvervault.d.ts +0 -1
  99. package/build/esm/specs/NativeEvervault.js +5 -0
  100. package/build/{useEvervault.d.ts → esm/useEvervault.d.ts} +0 -1
  101. package/build/esm/useEvervault.js +12 -0
  102. package/build/{utils.d.ts → esm/utils.d.ts} +0 -1
  103. package/build/esm/utils.js +31 -0
  104. package/package.json +9 -21
  105. package/build/Card/Cvc.d.ts.map +0 -1
  106. package/build/Card/Cvc.test.d.ts +0 -2
  107. package/build/Card/Cvc.test.d.ts.map +0 -1
  108. package/build/Card/Expiry.d.ts.map +0 -1
  109. package/build/Card/Holder.d.ts.map +0 -1
  110. package/build/Card/Number.d.ts.map +0 -1
  111. package/build/Card/Number.test.d.ts +0 -2
  112. package/build/Card/Number.test.d.ts.map +0 -1
  113. package/build/Card/Root.d.ts.map +0 -1
  114. package/build/Card/Root.test.d.ts +0 -2
  115. package/build/Card/Root.test.d.ts.map +0 -1
  116. package/build/Card/index.d.ts.map +0 -1
  117. package/build/Card/schema.d.ts.map +0 -1
  118. package/build/Card/types.d.ts.map +0 -1
  119. package/build/Card/utils.d.ts.map +0 -1
  120. package/build/Card/utils.test.d.ts +0 -2
  121. package/build/Card/utils.test.d.ts.map +0 -1
  122. package/build/EvervaultProvider.d.ts.map +0 -1
  123. package/build/EvervaultProvider.test.d.ts +0 -2
  124. package/build/EvervaultProvider.test.d.ts.map +0 -1
  125. package/build/Input.d.ts.map +0 -1
  126. package/build/Input.test.d.ts +0 -2
  127. package/build/Input.test.d.ts.map +0 -1
  128. package/build/ThreeDSecure/Frame.d.ts.map +0 -1
  129. package/build/ThreeDSecure/Frame.test.d.ts +0 -2
  130. package/build/ThreeDSecure/Frame.test.d.ts.map +0 -1
  131. package/build/ThreeDSecure/Root.d.ts.map +0 -1
  132. package/build/ThreeDSecure/Root.test.d.ts +0 -2
  133. package/build/ThreeDSecure/Root.test.d.ts.map +0 -1
  134. package/build/ThreeDSecure/config.d.ts.map +0 -1
  135. package/build/ThreeDSecure/context.d.ts.map +0 -1
  136. package/build/ThreeDSecure/event.d.ts.map +0 -1
  137. package/build/ThreeDSecure/index.d.ts.map +0 -1
  138. package/build/ThreeDSecure/session.d.ts.map +0 -1
  139. package/build/ThreeDSecure/session.test.d.ts +0 -2
  140. package/build/ThreeDSecure/session.test.d.ts.map +0 -1
  141. package/build/ThreeDSecure/types.d.ts.map +0 -1
  142. package/build/ThreeDSecure/useThreeDSecure.d.ts.map +0 -1
  143. package/build/ThreeDSecure/useThreeDSecure.test.d.ts +0 -2
  144. package/build/ThreeDSecure/useThreeDSecure.test.d.ts.map +0 -1
  145. package/build/__mocks__/NativeEvervault.d.ts.map +0 -1
  146. package/build/__mocks__/react-native-webview.d.ts.map +0 -1
  147. package/build/context.d.ts.map +0 -1
  148. package/build/index.cjs.js.map +0 -1
  149. package/build/index.d.ts.map +0 -1
  150. package/build/sdk.d.ts.map +0 -1
  151. package/build/sdk.test.d.ts +0 -2
  152. package/build/sdk.test.d.ts.map +0 -1
  153. package/build/specs/NativeEvervault.d.ts.map +0 -1
  154. package/build/useEvervault.d.ts.map +0 -1
  155. package/build/useEvervault.test.d.ts +0 -2
  156. package/build/useEvervault.test.d.ts.map +0 -1
  157. package/build/utils.d.ts.map +0 -1
  158. package/src/Card/Cvc.test.tsx +0 -41
  159. package/src/Card/Cvc.tsx +0 -58
  160. package/src/Card/Expiry.tsx +0 -26
  161. package/src/Card/Holder.tsx +0 -27
  162. package/src/Card/Number.test.tsx +0 -76
  163. package/src/Card/Number.tsx +0 -54
  164. package/src/Card/Root.test.tsx +0 -341
  165. package/src/Card/Root.tsx +0 -150
  166. package/src/Card/index.ts +0 -28
  167. package/src/Card/schema.ts +0 -41
  168. package/src/Card/types.ts +0 -57
  169. package/src/Card/utils.test.ts +0 -271
  170. package/src/Card/utils.ts +0 -129
  171. package/src/EvervaultProvider.test.tsx +0 -24
  172. package/src/EvervaultProvider.tsx +0 -43
  173. package/src/Input.test.tsx +0 -420
  174. package/src/Input.tsx +0 -182
  175. package/src/ThreeDSecure/Frame.test.tsx +0 -87
  176. package/src/ThreeDSecure/Frame.tsx +0 -50
  177. package/src/ThreeDSecure/Root.test.tsx +0 -67
  178. package/src/ThreeDSecure/Root.tsx +0 -23
  179. package/src/ThreeDSecure/config.ts +0 -3
  180. package/src/ThreeDSecure/context.ts +0 -6
  181. package/src/ThreeDSecure/event.ts +0 -19
  182. package/src/ThreeDSecure/index.ts +0 -17
  183. package/src/ThreeDSecure/session.test.ts +0 -524
  184. package/src/ThreeDSecure/session.ts +0 -184
  185. package/src/ThreeDSecure/types.ts +0 -80
  186. package/src/ThreeDSecure/useThreeDSecure.test.tsx +0 -244
  187. package/src/ThreeDSecure/useThreeDSecure.ts +0 -64
  188. package/src/__mocks__/NativeEvervault.ts +0 -13
  189. package/src/__mocks__/react-native-webview.tsx +0 -6
  190. package/src/context.ts +0 -14
  191. package/src/index.ts +0 -21
  192. package/src/sdk.test.ts +0 -122
  193. package/src/sdk.ts +0 -71
  194. package/src/specs/NativeEvervault.ts +0 -67
  195. package/src/useEvervault.test.tsx +0 -31
  196. package/src/useEvervault.ts +0 -14
  197. package/src/utils.ts +0 -41
@@ -1,2286 +1,3 @@
1
- import { TurboModuleRegistry, TextInput, Platform, StyleSheet } from 'react-native';
2
- import { jsx } from 'react/jsx-runtime';
3
- import * as React from 'react';
4
- import React__default, { createContext, useMemo, useCallback, useContext, forwardRef, useRef, useImperativeHandle, useEffect, useState } from 'react';
5
- import { WebView } from 'react-native-webview';
6
-
7
- const NativeEvervault = TurboModuleRegistry.get("NativeEvervault");
8
-
9
- function getModule() {
10
- if (!NativeEvervault) {
11
- throw new Error("NativeEvervault is not available.");
12
- }
13
- return NativeEvervault;
14
- }
15
- const sdk = {
16
- verify() {
17
- getModule();
18
- return true;
19
- },
20
- initialize(teamId, appId) {
21
- const evervault = getModule();
22
- if (!teamId) {
23
- throw new Error("Team ID is required.");
24
- }
25
- if (!appId) {
26
- throw new Error("App ID is required.");
27
- }
28
- return evervault.initialize(teamId, appId);
29
- },
30
- async encrypt(instanceId, data) {
31
- const evervault = getModule();
32
- if (data === undefined) {
33
- return undefined;
34
- }
35
- else if (data === null) {
36
- return null;
37
- }
38
- else if (typeof data === "string") {
39
- return (await evervault.encryptString(instanceId, data));
40
- }
41
- else if (typeof data === "number") {
42
- return (await evervault.encryptNumber(instanceId, data));
43
- }
44
- else if (typeof data === "boolean") {
45
- return (await evervault.encryptBoolean(instanceId, data));
46
- }
47
- else if (Array.isArray(data)) {
48
- return (await evervault.encryptArray(instanceId, data));
49
- }
50
- else if (typeof data === "object") {
51
- return (await evervault.encryptObject(instanceId, data));
52
- }
53
- throw new Error("Unsupported data type.");
54
- },
55
- };
56
-
57
- const EvervaultContext = createContext(null);
58
-
59
- function EvervaultProvider({ teamId, appId, children, }) {
60
- const instanceId = useMemo(() => sdk.initialize(teamId, appId), [teamId, appId]);
61
- const encrypt = useCallback(function (data) {
62
- return sdk.encrypt(instanceId, data);
63
- }, [instanceId]);
64
- const context = useMemo(() => ({ teamId, appId, encrypt }), [teamId, appId, encrypt]);
65
- return (jsx(EvervaultContext.Provider, { value: context, children: children }));
66
- }
67
-
68
- function useEvervault() {
69
- const context = useContext(EvervaultContext);
70
- if (!context) {
71
- throw new Error("`useEvervault` must be used within an `EvervaultProvider`.");
72
- }
73
- return context;
74
- }
75
-
76
- var isCheckBoxInput = (element) => element.type === 'checkbox';
77
-
78
- var isDateObject = (value) => value instanceof Date;
79
-
80
- var isNullOrUndefined = (value) => value == null;
81
-
82
- const isObjectType = (value) => typeof value === 'object';
83
- var isObject = (value) => !isNullOrUndefined(value) &&
84
- !Array.isArray(value) &&
85
- isObjectType(value) &&
86
- !isDateObject(value);
87
-
88
- var getEventValue = (event) => isObject(event) && event.target
89
- ? isCheckBoxInput(event.target)
90
- ? event.target.checked
91
- : event.target.value
92
- : event;
93
-
94
- var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
95
-
96
- var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
97
-
98
- var isPlainObject = (tempObject) => {
99
- const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
100
- return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
101
- };
102
-
103
- var isWeb = typeof window !== 'undefined' &&
104
- typeof window.HTMLElement !== 'undefined' &&
105
- typeof document !== 'undefined';
106
-
107
- function cloneObject(data) {
108
- let copy;
109
- const isArray = Array.isArray(data);
110
- const isFileListInstance = typeof FileList !== 'undefined' ? data instanceof FileList : false;
111
- if (data instanceof Date) {
112
- copy = new Date(data);
113
- }
114
- else if (data instanceof Set) {
115
- copy = new Set(data);
116
- }
117
- else if (!(isWeb && (data instanceof Blob || isFileListInstance)) &&
118
- (isArray || isObject(data))) {
119
- copy = isArray ? [] : {};
120
- if (!isArray && !isPlainObject(data)) {
121
- copy = data;
122
- }
123
- else {
124
- for (const key in data) {
125
- if (data.hasOwnProperty(key)) {
126
- copy[key] = cloneObject(data[key]);
127
- }
128
- }
129
- }
130
- }
131
- else {
132
- return data;
133
- }
134
- return copy;
135
- }
136
-
137
- var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
138
-
139
- var isUndefined = (val) => val === undefined;
140
-
141
- var get = (object, path, defaultValue) => {
142
- if (!path || !isObject(object)) {
143
- return defaultValue;
144
- }
145
- const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);
146
- return isUndefined(result) || result === object
147
- ? isUndefined(object[path])
148
- ? defaultValue
149
- : object[path]
150
- : result;
151
- };
152
-
153
- var isBoolean = (value) => typeof value === 'boolean';
154
-
155
- var isKey = (value) => /^\w*$/.test(value);
156
-
157
- var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
158
-
159
- var set = (object, path, value) => {
160
- let index = -1;
161
- const tempPath = isKey(path) ? [path] : stringToPath(path);
162
- const length = tempPath.length;
163
- const lastIndex = length - 1;
164
- while (++index < length) {
165
- const key = tempPath[index];
166
- let newValue = value;
167
- if (index !== lastIndex) {
168
- const objValue = object[key];
169
- newValue =
170
- isObject(objValue) || Array.isArray(objValue)
171
- ? objValue
172
- : !isNaN(+tempPath[index + 1])
173
- ? []
174
- : {};
175
- }
176
- if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
177
- return;
178
- }
179
- object[key] = newValue;
180
- object = object[key];
181
- }
182
- return object;
183
- };
184
-
185
- const EVENTS = {
186
- BLUR: 'blur',
187
- FOCUS_OUT: 'focusout',
188
- CHANGE: 'change',
189
- };
190
- const VALIDATION_MODE = {
191
- onBlur: 'onBlur',
192
- onChange: 'onChange',
193
- onSubmit: 'onSubmit',
194
- onTouched: 'onTouched',
195
- all: 'all',
196
- };
197
- const INPUT_VALIDATION_RULES = {
198
- max: 'max',
199
- min: 'min',
200
- maxLength: 'maxLength',
201
- minLength: 'minLength',
202
- pattern: 'pattern',
203
- required: 'required',
204
- validate: 'validate',
205
- };
206
-
207
- const HookFormContext = React__default.createContext(null);
208
- /**
209
- * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
210
- *
211
- * @remarks
212
- * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
213
- *
214
- * @returns return all useForm methods
215
- *
216
- * @example
217
- * ```tsx
218
- * function App() {
219
- * const methods = useForm();
220
- * const onSubmit = data => console.log(data);
221
- *
222
- * return (
223
- * <FormProvider {...methods} >
224
- * <form onSubmit={methods.handleSubmit(onSubmit)}>
225
- * <NestedInput />
226
- * <input type="submit" />
227
- * </form>
228
- * </FormProvider>
229
- * );
230
- * }
231
- *
232
- * function NestedInput() {
233
- * const { register } = useFormContext(); // retrieve all hook methods
234
- * return <input {...register("test")} />;
235
- * }
236
- * ```
237
- */
238
- const useFormContext = () => React__default.useContext(HookFormContext);
239
- /**
240
- * A provider component that propagates the `useForm` methods to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useFormContext}.
241
- *
242
- * @remarks
243
- * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
244
- *
245
- * @param props - all useForm methods
246
- *
247
- * @example
248
- * ```tsx
249
- * function App() {
250
- * const methods = useForm();
251
- * const onSubmit = data => console.log(data);
252
- *
253
- * return (
254
- * <FormProvider {...methods} >
255
- * <form onSubmit={methods.handleSubmit(onSubmit)}>
256
- * <NestedInput />
257
- * <input type="submit" />
258
- * </form>
259
- * </FormProvider>
260
- * );
261
- * }
262
- *
263
- * function NestedInput() {
264
- * const { register } = useFormContext(); // retrieve all hook methods
265
- * return <input {...register("test")} />;
266
- * }
267
- * ```
268
- */
269
- const FormProvider = (props) => {
270
- const { children, ...data } = props;
271
- return (React__default.createElement(HookFormContext.Provider, { value: data }, children));
272
- };
273
-
274
- var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
275
- const result = {
276
- defaultValues: control._defaultValues,
277
- };
278
- for (const key in formState) {
279
- Object.defineProperty(result, key, {
280
- get: () => {
281
- const _key = key;
282
- if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
283
- control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
284
- }
285
- localProxyFormState && (localProxyFormState[_key] = true);
286
- return formState[_key];
287
- },
288
- });
289
- }
290
- return result;
291
- };
292
-
293
- var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
294
-
295
- var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
296
- updateFormState(formStateData);
297
- const { name, ...formState } = formStateData;
298
- return (isEmptyObject(formState) ||
299
- Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
300
- Object.keys(formState).find((key) => _proxyFormState[key] ===
301
- (!isRoot || VALIDATION_MODE.all)));
302
- };
303
-
304
- var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
305
-
306
- var shouldSubscribeByName = (name, signalName, exact) => !name ||
307
- !signalName ||
308
- name === signalName ||
309
- convertToArrayPayload(name).some((currentName) => currentName &&
310
- (exact
311
- ? currentName === signalName
312
- : currentName.startsWith(signalName) ||
313
- signalName.startsWith(currentName)));
314
-
315
- function useSubscribe(props) {
316
- const _props = React__default.useRef(props);
317
- _props.current = props;
318
- React__default.useEffect(() => {
319
- const subscription = !props.disabled &&
320
- _props.current.subject &&
321
- _props.current.subject.subscribe({
322
- next: _props.current.next,
323
- });
324
- return () => {
325
- subscription && subscription.unsubscribe();
326
- };
327
- }, [props.disabled]);
328
- }
329
-
330
- /**
331
- * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
332
- *
333
- * @remarks
334
- * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
335
- *
336
- * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
337
- *
338
- * @example
339
- * ```tsx
340
- * function App() {
341
- * const { register, handleSubmit, control } = useForm({
342
- * defaultValues: {
343
- * firstName: "firstName"
344
- * }});
345
- * const { dirtyFields } = useFormState({
346
- * control
347
- * });
348
- * const onSubmit = (data) => console.log(data);
349
- *
350
- * return (
351
- * <form onSubmit={handleSubmit(onSubmit)}>
352
- * <input {...register("firstName")} placeholder="First Name" />
353
- * {dirtyFields.firstName && <p>Field is dirty.</p>}
354
- * <input type="submit" />
355
- * </form>
356
- * );
357
- * }
358
- * ```
359
- */
360
- function useFormState(props) {
361
- const methods = useFormContext();
362
- const { control = methods.control, disabled, name, exact } = props || {};
363
- const [formState, updateFormState] = React__default.useState(control._formState);
364
- const _mounted = React__default.useRef(true);
365
- const _localProxyFormState = React__default.useRef({
366
- isDirty: false,
367
- isLoading: false,
368
- dirtyFields: false,
369
- touchedFields: false,
370
- validatingFields: false,
371
- isValidating: false,
372
- isValid: false,
373
- errors: false,
374
- });
375
- const _name = React__default.useRef(name);
376
- _name.current = name;
377
- useSubscribe({
378
- disabled,
379
- next: (value) => _mounted.current &&
380
- shouldSubscribeByName(_name.current, value.name, exact) &&
381
- shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
382
- updateFormState({
383
- ...control._formState,
384
- ...value,
385
- }),
386
- subject: control._subjects.state,
387
- });
388
- React__default.useEffect(() => {
389
- _mounted.current = true;
390
- _localProxyFormState.current.isValid && control._updateValid(true);
391
- return () => {
392
- _mounted.current = false;
393
- };
394
- }, [control]);
395
- return React__default.useMemo(() => getProxyFormState(formState, control, _localProxyFormState.current, false), [formState, control]);
396
- }
397
-
398
- var isString = (value) => typeof value === 'string';
399
-
400
- var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
401
- if (isString(names)) {
402
- isGlobal && _names.watch.add(names);
403
- return get(formValues, names, defaultValue);
404
- }
405
- if (Array.isArray(names)) {
406
- return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
407
- }
408
- isGlobal && (_names.watchAll = true);
409
- return formValues;
410
- };
411
-
412
- /**
413
- * Custom hook to subscribe to field change and isolate re-rendering at the component level.
414
- *
415
- * @remarks
416
- *
417
- * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
418
- *
419
- * @example
420
- * ```tsx
421
- * const { control } = useForm();
422
- * const values = useWatch({
423
- * name: "fieldName"
424
- * control,
425
- * })
426
- * ```
427
- */
428
- function useWatch(props) {
429
- const methods = useFormContext();
430
- const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};
431
- const _name = React__default.useRef(name);
432
- _name.current = name;
433
- useSubscribe({
434
- disabled,
435
- subject: control._subjects.values,
436
- next: (formState) => {
437
- if (shouldSubscribeByName(_name.current, formState.name, exact)) {
438
- updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
439
- }
440
- },
441
- });
442
- const [value, updateValue] = React__default.useState(control._getWatch(name, defaultValue));
443
- React__default.useEffect(() => control._removeUnmounted());
444
- return value;
445
- }
446
-
447
- /**
448
- * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
449
- *
450
- * @remarks
451
- * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
452
- *
453
- * @param props - the path name to the form field value, and validation rules.
454
- *
455
- * @returns field properties, field and form state. {@link UseControllerReturn}
456
- *
457
- * @example
458
- * ```tsx
459
- * function Input(props) {
460
- * const { field, fieldState, formState } = useController(props);
461
- * return (
462
- * <div>
463
- * <input {...field} placeholder={props.name} />
464
- * <p>{fieldState.isTouched && "Touched"}</p>
465
- * <p>{formState.isSubmitted ? "submitted" : ""}</p>
466
- * </div>
467
- * );
468
- * }
469
- * ```
470
- */
471
- function useController(props) {
472
- const methods = useFormContext();
473
- const { name, disabled, control = methods.control, shouldUnregister } = props;
474
- const isArrayField = isNameInFieldArray(control._names.array, name);
475
- const value = useWatch({
476
- control,
477
- name,
478
- defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
479
- exact: true,
480
- });
481
- const formState = useFormState({
482
- control,
483
- name,
484
- exact: true,
485
- });
486
- const _registerProps = React__default.useRef(control.register(name, {
487
- ...props.rules,
488
- value,
489
- ...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}),
490
- }));
491
- const fieldState = React__default.useMemo(() => Object.defineProperties({}, {
492
- invalid: {
493
- enumerable: true,
494
- get: () => !!get(formState.errors, name),
495
- },
496
- isDirty: {
497
- enumerable: true,
498
- get: () => !!get(formState.dirtyFields, name),
499
- },
500
- isTouched: {
501
- enumerable: true,
502
- get: () => !!get(formState.touchedFields, name),
503
- },
504
- isValidating: {
505
- enumerable: true,
506
- get: () => !!get(formState.validatingFields, name),
507
- },
508
- error: {
509
- enumerable: true,
510
- get: () => get(formState.errors, name),
511
- },
512
- }), [formState, name]);
513
- const field = React__default.useMemo(() => ({
514
- name,
515
- value,
516
- ...(isBoolean(disabled) || formState.disabled
517
- ? { disabled: formState.disabled || disabled }
518
- : {}),
519
- onChange: (event) => _registerProps.current.onChange({
520
- target: {
521
- value: getEventValue(event),
522
- name: name,
523
- },
524
- type: EVENTS.CHANGE,
525
- }),
526
- onBlur: () => _registerProps.current.onBlur({
527
- target: {
528
- value: get(control._formValues, name),
529
- name: name,
530
- },
531
- type: EVENTS.BLUR,
532
- }),
533
- ref: (elm) => {
534
- const field = get(control._fields, name);
535
- if (field && elm) {
536
- field._f.ref = {
537
- focus: () => elm.focus(),
538
- select: () => elm.select(),
539
- setCustomValidity: (message) => elm.setCustomValidity(message),
540
- reportValidity: () => elm.reportValidity(),
541
- };
542
- }
543
- },
544
- }), [
545
- name,
546
- control._formValues,
547
- disabled,
548
- formState.disabled,
549
- value,
550
- control._fields,
551
- ]);
552
- React__default.useEffect(() => {
553
- const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
554
- const updateMounted = (name, value) => {
555
- const field = get(control._fields, name);
556
- if (field && field._f) {
557
- field._f.mount = value;
558
- }
559
- };
560
- updateMounted(name, true);
561
- if (_shouldUnregisterField) {
562
- const value = cloneObject(get(control._options.defaultValues, name));
563
- set(control._defaultValues, name, value);
564
- if (isUndefined(get(control._formValues, name))) {
565
- set(control._formValues, name, value);
566
- }
567
- }
568
- !isArrayField && control.register(name);
569
- return () => {
570
- (isArrayField
571
- ? _shouldUnregisterField && !control._state.action
572
- : _shouldUnregisterField)
573
- ? control.unregister(name)
574
- : updateMounted(name, false);
575
- };
576
- }, [name, control, isArrayField, shouldUnregister]);
577
- React__default.useEffect(() => {
578
- control._updateDisabledField({
579
- disabled,
580
- fields: control._fields,
581
- name,
582
- });
583
- }, [disabled, name, control]);
584
- return React__default.useMemo(() => ({
585
- field,
586
- formState,
587
- fieldState,
588
- }), [field, formState, fieldState]);
589
- }
590
-
591
- var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
592
- ? {
593
- ...errors[name],
594
- types: {
595
- ...(errors[name] && errors[name].types ? errors[name].types : {}),
596
- [type]: message || true,
597
- },
598
- }
599
- : {};
600
-
601
- var getValidationModes = (mode) => ({
602
- isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
603
- isOnBlur: mode === VALIDATION_MODE.onBlur,
604
- isOnChange: mode === VALIDATION_MODE.onChange,
605
- isOnAll: mode === VALIDATION_MODE.all,
606
- isOnTouch: mode === VALIDATION_MODE.onTouched,
607
- });
608
-
609
- var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
610
- (_names.watchAll ||
611
- _names.watch.has(name) ||
612
- [..._names.watch].some((watchName) => name.startsWith(watchName) &&
613
- /^\.\w+/.test(name.slice(watchName.length))));
614
-
615
- const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
616
- for (const key of fieldsNames || Object.keys(fields)) {
617
- const field = get(fields, key);
618
- if (field) {
619
- const { _f, ...currentField } = field;
620
- if (_f) {
621
- if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
622
- return true;
623
- }
624
- else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
625
- return true;
626
- }
627
- else {
628
- if (iterateFieldsByAction(currentField, action)) {
629
- break;
630
- }
631
- }
632
- }
633
- else if (isObject(currentField)) {
634
- if (iterateFieldsByAction(currentField, action)) {
635
- break;
636
- }
637
- }
638
- }
639
- }
640
- return;
641
- };
642
-
643
- var updateFieldArrayRootError = (errors, error, name) => {
644
- const fieldArrayErrors = convertToArrayPayload(get(errors, name));
645
- set(fieldArrayErrors, 'root', error[name]);
646
- set(errors, name, fieldArrayErrors);
647
- return errors;
648
- };
649
-
650
- var isFileInput = (element) => element.type === 'file';
651
-
652
- var isFunction = (value) => typeof value === 'function';
653
-
654
- var isHTMLElement = (value) => {
655
- if (!isWeb) {
656
- return false;
657
- }
658
- const owner = value ? value.ownerDocument : 0;
659
- return (value instanceof
660
- (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
661
- };
662
-
663
- var isMessage = (value) => isString(value);
664
-
665
- var isRadioInput = (element) => element.type === 'radio';
666
-
667
- var isRegex = (value) => value instanceof RegExp;
668
-
669
- const defaultResult = {
670
- value: false,
671
- isValid: false,
672
- };
673
- const validResult = { value: true, isValid: true };
674
- var getCheckboxValue = (options) => {
675
- if (Array.isArray(options)) {
676
- if (options.length > 1) {
677
- const values = options
678
- .filter((option) => option && option.checked && !option.disabled)
679
- .map((option) => option.value);
680
- return { value: values, isValid: !!values.length };
681
- }
682
- return options[0].checked && !options[0].disabled
683
- ? // @ts-expect-error expected to work in the browser
684
- options[0].attributes && !isUndefined(options[0].attributes.value)
685
- ? isUndefined(options[0].value) || options[0].value === ''
686
- ? validResult
687
- : { value: options[0].value, isValid: true }
688
- : validResult
689
- : defaultResult;
690
- }
691
- return defaultResult;
692
- };
693
-
694
- const defaultReturn = {
695
- isValid: false,
696
- value: null,
697
- };
698
- var getRadioValue = (options) => Array.isArray(options)
699
- ? options.reduce((previous, option) => option && option.checked && !option.disabled
700
- ? {
701
- isValid: true,
702
- value: option.value,
703
- }
704
- : previous, defaultReturn)
705
- : defaultReturn;
706
-
707
- function getValidateError(result, ref, type = 'validate') {
708
- if (isMessage(result) ||
709
- (Array.isArray(result) && result.every(isMessage)) ||
710
- (isBoolean(result) && !result)) {
711
- return {
712
- type,
713
- message: isMessage(result) ? result : '',
714
- ref,
715
- };
716
- }
717
- }
718
-
719
- var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
720
- ? validationData
721
- : {
722
- value: validationData,
723
- message: '',
724
- };
725
-
726
- var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
727
- const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, } = field._f;
728
- const inputValue = get(formValues, name);
729
- if (!mount || disabledFieldNames.has(name)) {
730
- return {};
731
- }
732
- const inputRef = refs ? refs[0] : ref;
733
- const setCustomValidity = (message) => {
734
- if (shouldUseNativeValidation && inputRef.reportValidity) {
735
- inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
736
- inputRef.reportValidity();
737
- }
738
- };
739
- const error = {};
740
- const isRadio = isRadioInput(ref);
741
- const isCheckBox = isCheckBoxInput(ref);
742
- const isRadioOrCheckbox = isRadio || isCheckBox;
743
- const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
744
- isUndefined(ref.value) &&
745
- isUndefined(inputValue)) ||
746
- (isHTMLElement(ref) && ref.value === '') ||
747
- inputValue === '' ||
748
- (Array.isArray(inputValue) && !inputValue.length);
749
- const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
750
- const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
751
- const message = exceedMax ? maxLengthMessage : minLengthMessage;
752
- error[name] = {
753
- type: exceedMax ? maxType : minType,
754
- message,
755
- ref,
756
- ...appendErrorsCurry(exceedMax ? maxType : minType, message),
757
- };
758
- };
759
- if (isFieldArray
760
- ? !Array.isArray(inputValue) || !inputValue.length
761
- : required &&
762
- ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
763
- (isBoolean(inputValue) && !inputValue) ||
764
- (isCheckBox && !getCheckboxValue(refs).isValid) ||
765
- (isRadio && !getRadioValue(refs).isValid))) {
766
- const { value, message } = isMessage(required)
767
- ? { value: !!required, message: required }
768
- : getValueAndMessage(required);
769
- if (value) {
770
- error[name] = {
771
- type: INPUT_VALIDATION_RULES.required,
772
- message,
773
- ref: inputRef,
774
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
775
- };
776
- if (!validateAllFieldCriteria) {
777
- setCustomValidity(message);
778
- return error;
779
- }
780
- }
781
- }
782
- if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
783
- let exceedMax;
784
- let exceedMin;
785
- const maxOutput = getValueAndMessage(max);
786
- const minOutput = getValueAndMessage(min);
787
- if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
788
- const valueNumber = ref.valueAsNumber ||
789
- (inputValue ? +inputValue : inputValue);
790
- if (!isNullOrUndefined(maxOutput.value)) {
791
- exceedMax = valueNumber > maxOutput.value;
792
- }
793
- if (!isNullOrUndefined(minOutput.value)) {
794
- exceedMin = valueNumber < minOutput.value;
795
- }
796
- }
797
- else {
798
- const valueDate = ref.valueAsDate || new Date(inputValue);
799
- const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
800
- const isTime = ref.type == 'time';
801
- const isWeek = ref.type == 'week';
802
- if (isString(maxOutput.value) && inputValue) {
803
- exceedMax = isTime
804
- ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
805
- : isWeek
806
- ? inputValue > maxOutput.value
807
- : valueDate > new Date(maxOutput.value);
808
- }
809
- if (isString(minOutput.value) && inputValue) {
810
- exceedMin = isTime
811
- ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
812
- : isWeek
813
- ? inputValue < minOutput.value
814
- : valueDate < new Date(minOutput.value);
815
- }
816
- }
817
- if (exceedMax || exceedMin) {
818
- getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
819
- if (!validateAllFieldCriteria) {
820
- setCustomValidity(error[name].message);
821
- return error;
822
- }
823
- }
824
- }
825
- if ((maxLength || minLength) &&
826
- !isEmpty &&
827
- (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
828
- const maxLengthOutput = getValueAndMessage(maxLength);
829
- const minLengthOutput = getValueAndMessage(minLength);
830
- const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
831
- inputValue.length > +maxLengthOutput.value;
832
- const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
833
- inputValue.length < +minLengthOutput.value;
834
- if (exceedMax || exceedMin) {
835
- getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
836
- if (!validateAllFieldCriteria) {
837
- setCustomValidity(error[name].message);
838
- return error;
839
- }
840
- }
841
- }
842
- if (pattern && !isEmpty && isString(inputValue)) {
843
- const { value: patternValue, message } = getValueAndMessage(pattern);
844
- if (isRegex(patternValue) && !inputValue.match(patternValue)) {
845
- error[name] = {
846
- type: INPUT_VALIDATION_RULES.pattern,
847
- message,
848
- ref,
849
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
850
- };
851
- if (!validateAllFieldCriteria) {
852
- setCustomValidity(message);
853
- return error;
854
- }
855
- }
856
- }
857
- if (validate) {
858
- if (isFunction(validate)) {
859
- const result = await validate(inputValue, formValues);
860
- const validateError = getValidateError(result, inputRef);
861
- if (validateError) {
862
- error[name] = {
863
- ...validateError,
864
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
865
- };
866
- if (!validateAllFieldCriteria) {
867
- setCustomValidity(validateError.message);
868
- return error;
869
- }
870
- }
871
- }
872
- else if (isObject(validate)) {
873
- let validationResult = {};
874
- for (const key in validate) {
875
- if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
876
- break;
877
- }
878
- const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
879
- if (validateError) {
880
- validationResult = {
881
- ...validateError,
882
- ...appendErrorsCurry(key, validateError.message),
883
- };
884
- setCustomValidity(validateError.message);
885
- if (validateAllFieldCriteria) {
886
- error[name] = validationResult;
887
- }
888
- }
889
- }
890
- if (!isEmptyObject(validationResult)) {
891
- error[name] = {
892
- ref: inputRef,
893
- ...validationResult,
894
- };
895
- if (!validateAllFieldCriteria) {
896
- return error;
897
- }
898
- }
899
- }
900
- }
901
- setCustomValidity(true);
902
- return error;
903
- };
904
-
905
- function baseGet(object, updatePath) {
906
- const length = updatePath.slice(0, -1).length;
907
- let index = 0;
908
- while (index < length) {
909
- object = isUndefined(object) ? index++ : object[updatePath[index++]];
910
- }
911
- return object;
912
- }
913
- function isEmptyArray(obj) {
914
- for (const key in obj) {
915
- if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
916
- return false;
917
- }
918
- }
919
- return true;
920
- }
921
- function unset(object, path) {
922
- const paths = Array.isArray(path)
923
- ? path
924
- : isKey(path)
925
- ? [path]
926
- : stringToPath(path);
927
- const childObject = paths.length === 1 ? object : baseGet(object, paths);
928
- const index = paths.length - 1;
929
- const key = paths[index];
930
- if (childObject) {
931
- delete childObject[key];
932
- }
933
- if (index !== 0 &&
934
- ((isObject(childObject) && isEmptyObject(childObject)) ||
935
- (Array.isArray(childObject) && isEmptyArray(childObject)))) {
936
- unset(object, paths.slice(0, -1));
937
- }
938
- return object;
939
- }
940
-
941
- var createSubject = () => {
942
- let _observers = [];
943
- const next = (value) => {
944
- for (const observer of _observers) {
945
- observer.next && observer.next(value);
946
- }
947
- };
948
- const subscribe = (observer) => {
949
- _observers.push(observer);
950
- return {
951
- unsubscribe: () => {
952
- _observers = _observers.filter((o) => o !== observer);
953
- },
954
- };
955
- };
956
- const unsubscribe = () => {
957
- _observers = [];
958
- };
959
- return {
960
- get observers() {
961
- return _observers;
962
- },
963
- next,
964
- subscribe,
965
- unsubscribe,
966
- };
967
- };
968
-
969
- var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
970
-
971
- function deepEqual(object1, object2) {
972
- if (isPrimitive(object1) || isPrimitive(object2)) {
973
- return object1 === object2;
974
- }
975
- if (isDateObject(object1) && isDateObject(object2)) {
976
- return object1.getTime() === object2.getTime();
977
- }
978
- const keys1 = Object.keys(object1);
979
- const keys2 = Object.keys(object2);
980
- if (keys1.length !== keys2.length) {
981
- return false;
982
- }
983
- for (const key of keys1) {
984
- const val1 = object1[key];
985
- if (!keys2.includes(key)) {
986
- return false;
987
- }
988
- if (key !== 'ref') {
989
- const val2 = object2[key];
990
- if ((isDateObject(val1) && isDateObject(val2)) ||
991
- (isObject(val1) && isObject(val2)) ||
992
- (Array.isArray(val1) && Array.isArray(val2))
993
- ? !deepEqual(val1, val2)
994
- : val1 !== val2) {
995
- return false;
996
- }
997
- }
998
- }
999
- return true;
1000
- }
1001
-
1002
- var isMultipleSelect = (element) => element.type === `select-multiple`;
1003
-
1004
- var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
1005
-
1006
- var live = (ref) => isHTMLElement(ref) && ref.isConnected;
1007
-
1008
- var objectHasFunction = (data) => {
1009
- for (const key in data) {
1010
- if (isFunction(data[key])) {
1011
- return true;
1012
- }
1013
- }
1014
- return false;
1015
- };
1016
-
1017
- function markFieldsDirty(data, fields = {}) {
1018
- const isParentNodeArray = Array.isArray(data);
1019
- if (isObject(data) || isParentNodeArray) {
1020
- for (const key in data) {
1021
- if (Array.isArray(data[key]) ||
1022
- (isObject(data[key]) && !objectHasFunction(data[key]))) {
1023
- fields[key] = Array.isArray(data[key]) ? [] : {};
1024
- markFieldsDirty(data[key], fields[key]);
1025
- }
1026
- else if (!isNullOrUndefined(data[key])) {
1027
- fields[key] = true;
1028
- }
1029
- }
1030
- }
1031
- return fields;
1032
- }
1033
- function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
1034
- const isParentNodeArray = Array.isArray(data);
1035
- if (isObject(data) || isParentNodeArray) {
1036
- for (const key in data) {
1037
- if (Array.isArray(data[key]) ||
1038
- (isObject(data[key]) && !objectHasFunction(data[key]))) {
1039
- if (isUndefined(formValues) ||
1040
- isPrimitive(dirtyFieldsFromValues[key])) {
1041
- dirtyFieldsFromValues[key] = Array.isArray(data[key])
1042
- ? markFieldsDirty(data[key], [])
1043
- : { ...markFieldsDirty(data[key]) };
1044
- }
1045
- else {
1046
- getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1047
- }
1048
- }
1049
- else {
1050
- dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
1051
- }
1052
- }
1053
- }
1054
- return dirtyFieldsFromValues;
1055
- }
1056
- var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
1057
-
1058
- var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
1059
- ? value
1060
- : valueAsNumber
1061
- ? value === ''
1062
- ? NaN
1063
- : value
1064
- ? +value
1065
- : value
1066
- : valueAsDate && isString(value)
1067
- ? new Date(value)
1068
- : setValueAs
1069
- ? setValueAs(value)
1070
- : value;
1071
-
1072
- function getFieldValue(_f) {
1073
- const ref = _f.ref;
1074
- if (isFileInput(ref)) {
1075
- return ref.files;
1076
- }
1077
- if (isRadioInput(ref)) {
1078
- return getRadioValue(_f.refs).value;
1079
- }
1080
- if (isMultipleSelect(ref)) {
1081
- return [...ref.selectedOptions].map(({ value }) => value);
1082
- }
1083
- if (isCheckBoxInput(ref)) {
1084
- return getCheckboxValue(_f.refs).value;
1085
- }
1086
- return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1087
- }
1088
-
1089
- var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1090
- const fields = {};
1091
- for (const name of fieldsNames) {
1092
- const field = get(_fields, name);
1093
- field && set(fields, name, field._f);
1094
- }
1095
- return {
1096
- criteriaMode,
1097
- names: [...fieldsNames],
1098
- fields,
1099
- shouldUseNativeValidation,
1100
- };
1101
- };
1102
-
1103
- var getRuleValue = (rule) => isUndefined(rule)
1104
- ? rule
1105
- : isRegex(rule)
1106
- ? rule.source
1107
- : isObject(rule)
1108
- ? isRegex(rule.value)
1109
- ? rule.value.source
1110
- : rule.value
1111
- : rule;
1112
-
1113
- const ASYNC_FUNCTION = 'AsyncFunction';
1114
- var hasPromiseValidation = (fieldReference) => !!fieldReference &&
1115
- !!fieldReference.validate &&
1116
- !!((isFunction(fieldReference.validate) &&
1117
- fieldReference.validate.constructor.name === ASYNC_FUNCTION) ||
1118
- (isObject(fieldReference.validate) &&
1119
- Object.values(fieldReference.validate).find((validateFunction) => validateFunction.constructor.name === ASYNC_FUNCTION)));
1120
-
1121
- var hasValidation = (options) => options.mount &&
1122
- (options.required ||
1123
- options.min ||
1124
- options.max ||
1125
- options.maxLength ||
1126
- options.minLength ||
1127
- options.pattern ||
1128
- options.validate);
1129
-
1130
- function schemaErrorLookup(errors, _fields, name) {
1131
- const error = get(errors, name);
1132
- if (error || isKey(name)) {
1133
- return {
1134
- error,
1135
- name,
1136
- };
1137
- }
1138
- const names = name.split('.');
1139
- while (names.length) {
1140
- const fieldName = names.join('.');
1141
- const field = get(_fields, fieldName);
1142
- const foundError = get(errors, fieldName);
1143
- if (field && !Array.isArray(field) && name !== fieldName) {
1144
- return { name };
1145
- }
1146
- if (foundError && foundError.type) {
1147
- return {
1148
- name: fieldName,
1149
- error: foundError,
1150
- };
1151
- }
1152
- names.pop();
1153
- }
1154
- return {
1155
- name,
1156
- };
1157
- }
1158
-
1159
- var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1160
- if (mode.isOnAll) {
1161
- return false;
1162
- }
1163
- else if (!isSubmitted && mode.isOnTouch) {
1164
- return !(isTouched || isBlurEvent);
1165
- }
1166
- else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
1167
- return !isBlurEvent;
1168
- }
1169
- else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
1170
- return isBlurEvent;
1171
- }
1172
- return true;
1173
- };
1174
-
1175
- var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
1176
-
1177
- const defaultOptions = {
1178
- mode: VALIDATION_MODE.onSubmit,
1179
- reValidateMode: VALIDATION_MODE.onChange,
1180
- shouldFocusError: true,
1181
- };
1182
- function createFormControl(props = {}) {
1183
- let _options = {
1184
- ...defaultOptions,
1185
- ...props,
1186
- };
1187
- let _formState = {
1188
- submitCount: 0,
1189
- isDirty: false,
1190
- isLoading: isFunction(_options.defaultValues),
1191
- isValidating: false,
1192
- isSubmitted: false,
1193
- isSubmitting: false,
1194
- isSubmitSuccessful: false,
1195
- isValid: false,
1196
- touchedFields: {},
1197
- dirtyFields: {},
1198
- validatingFields: {},
1199
- errors: _options.errors || {},
1200
- disabled: _options.disabled || false,
1201
- };
1202
- let _fields = {};
1203
- let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
1204
- ? cloneObject(_options.defaultValues || _options.values) || {}
1205
- : {};
1206
- let _formValues = _options.shouldUnregister
1207
- ? {}
1208
- : cloneObject(_defaultValues);
1209
- let _state = {
1210
- action: false,
1211
- mount: false,
1212
- watch: false,
1213
- };
1214
- let _names = {
1215
- mount: new Set(),
1216
- disabled: new Set(),
1217
- unMount: new Set(),
1218
- array: new Set(),
1219
- watch: new Set(),
1220
- };
1221
- let delayErrorCallback;
1222
- let timer = 0;
1223
- const _proxyFormState = {
1224
- isDirty: false,
1225
- dirtyFields: false,
1226
- validatingFields: false,
1227
- touchedFields: false,
1228
- isValidating: false,
1229
- isValid: false,
1230
- errors: false,
1231
- };
1232
- const _subjects = {
1233
- values: createSubject(),
1234
- array: createSubject(),
1235
- state: createSubject(),
1236
- };
1237
- const validationModeBeforeSubmit = getValidationModes(_options.mode);
1238
- const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
1239
- const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1240
- const debounce = (callback) => (wait) => {
1241
- clearTimeout(timer);
1242
- timer = setTimeout(callback, wait);
1243
- };
1244
- const _updateValid = async (shouldUpdateValid) => {
1245
- if (!_options.disabled && (_proxyFormState.isValid || shouldUpdateValid)) {
1246
- const isValid = _options.resolver
1247
- ? isEmptyObject((await _executeSchema()).errors)
1248
- : await executeBuiltInValidation(_fields, true);
1249
- if (isValid !== _formState.isValid) {
1250
- _subjects.state.next({
1251
- isValid,
1252
- });
1253
- }
1254
- }
1255
- };
1256
- const _updateIsValidating = (names, isValidating) => {
1257
- if (!_options.disabled &&
1258
- (_proxyFormState.isValidating || _proxyFormState.validatingFields)) {
1259
- (names || Array.from(_names.mount)).forEach((name) => {
1260
- if (name) {
1261
- isValidating
1262
- ? set(_formState.validatingFields, name, isValidating)
1263
- : unset(_formState.validatingFields, name);
1264
- }
1265
- });
1266
- _subjects.state.next({
1267
- validatingFields: _formState.validatingFields,
1268
- isValidating: !isEmptyObject(_formState.validatingFields),
1269
- });
1270
- }
1271
- };
1272
- const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1273
- if (args && method && !_options.disabled) {
1274
- _state.action = true;
1275
- if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1276
- const fieldValues = method(get(_fields, name), args.argA, args.argB);
1277
- shouldSetValues && set(_fields, name, fieldValues);
1278
- }
1279
- if (shouldUpdateFieldsAndState &&
1280
- Array.isArray(get(_formState.errors, name))) {
1281
- const errors = method(get(_formState.errors, name), args.argA, args.argB);
1282
- shouldSetValues && set(_formState.errors, name, errors);
1283
- unsetEmptyArray(_formState.errors, name);
1284
- }
1285
- if (_proxyFormState.touchedFields &&
1286
- shouldUpdateFieldsAndState &&
1287
- Array.isArray(get(_formState.touchedFields, name))) {
1288
- const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1289
- shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1290
- }
1291
- if (_proxyFormState.dirtyFields) {
1292
- _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1293
- }
1294
- _subjects.state.next({
1295
- name,
1296
- isDirty: _getDirty(name, values),
1297
- dirtyFields: _formState.dirtyFields,
1298
- errors: _formState.errors,
1299
- isValid: _formState.isValid,
1300
- });
1301
- }
1302
- else {
1303
- set(_formValues, name, values);
1304
- }
1305
- };
1306
- const updateErrors = (name, error) => {
1307
- set(_formState.errors, name, error);
1308
- _subjects.state.next({
1309
- errors: _formState.errors,
1310
- });
1311
- };
1312
- const _setErrors = (errors) => {
1313
- _formState.errors = errors;
1314
- _subjects.state.next({
1315
- errors: _formState.errors,
1316
- isValid: false,
1317
- });
1318
- };
1319
- const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1320
- const field = get(_fields, name);
1321
- if (field) {
1322
- const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1323
- isUndefined(defaultValue) ||
1324
- (ref && ref.defaultChecked) ||
1325
- shouldSkipSetValueAs
1326
- ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
1327
- : setFieldValue(name, defaultValue);
1328
- _state.mount && _updateValid();
1329
- }
1330
- };
1331
- const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1332
- let shouldUpdateField = false;
1333
- let isPreviousDirty = false;
1334
- const output = {
1335
- name,
1336
- };
1337
- if (!_options.disabled) {
1338
- const disabledField = !!(get(_fields, name) &&
1339
- get(_fields, name)._f &&
1340
- get(_fields, name)._f.disabled);
1341
- if (!isBlurEvent || shouldDirty) {
1342
- if (_proxyFormState.isDirty) {
1343
- isPreviousDirty = _formState.isDirty;
1344
- _formState.isDirty = output.isDirty = _getDirty();
1345
- shouldUpdateField = isPreviousDirty !== output.isDirty;
1346
- }
1347
- const isCurrentFieldPristine = disabledField || deepEqual(get(_defaultValues, name), fieldValue);
1348
- isPreviousDirty = !!(!disabledField && get(_formState.dirtyFields, name));
1349
- isCurrentFieldPristine || disabledField
1350
- ? unset(_formState.dirtyFields, name)
1351
- : set(_formState.dirtyFields, name, true);
1352
- output.dirtyFields = _formState.dirtyFields;
1353
- shouldUpdateField =
1354
- shouldUpdateField ||
1355
- (_proxyFormState.dirtyFields &&
1356
- isPreviousDirty !== !isCurrentFieldPristine);
1357
- }
1358
- if (isBlurEvent) {
1359
- const isPreviousFieldTouched = get(_formState.touchedFields, name);
1360
- if (!isPreviousFieldTouched) {
1361
- set(_formState.touchedFields, name, isBlurEvent);
1362
- output.touchedFields = _formState.touchedFields;
1363
- shouldUpdateField =
1364
- shouldUpdateField ||
1365
- (_proxyFormState.touchedFields &&
1366
- isPreviousFieldTouched !== isBlurEvent);
1367
- }
1368
- }
1369
- shouldUpdateField && shouldRender && _subjects.state.next(output);
1370
- }
1371
- return shouldUpdateField ? output : {};
1372
- };
1373
- const shouldRenderByError = (name, isValid, error, fieldState) => {
1374
- const previousFieldError = get(_formState.errors, name);
1375
- const shouldUpdateValid = _proxyFormState.isValid &&
1376
- isBoolean(isValid) &&
1377
- _formState.isValid !== isValid;
1378
- if (_options.delayError && error) {
1379
- delayErrorCallback = debounce(() => updateErrors(name, error));
1380
- delayErrorCallback(_options.delayError);
1381
- }
1382
- else {
1383
- clearTimeout(timer);
1384
- delayErrorCallback = null;
1385
- error
1386
- ? set(_formState.errors, name, error)
1387
- : unset(_formState.errors, name);
1388
- }
1389
- if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
1390
- !isEmptyObject(fieldState) ||
1391
- shouldUpdateValid) {
1392
- const updatedFormState = {
1393
- ...fieldState,
1394
- ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
1395
- errors: _formState.errors,
1396
- name,
1397
- };
1398
- _formState = {
1399
- ..._formState,
1400
- ...updatedFormState,
1401
- };
1402
- _subjects.state.next(updatedFormState);
1403
- }
1404
- };
1405
- const _executeSchema = async (name) => {
1406
- _updateIsValidating(name, true);
1407
- const result = await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1408
- _updateIsValidating(name);
1409
- return result;
1410
- };
1411
- const executeSchemaAndUpdateState = async (names) => {
1412
- const { errors } = await _executeSchema(names);
1413
- if (names) {
1414
- for (const name of names) {
1415
- const error = get(errors, name);
1416
- error
1417
- ? set(_formState.errors, name, error)
1418
- : unset(_formState.errors, name);
1419
- }
1420
- }
1421
- else {
1422
- _formState.errors = errors;
1423
- }
1424
- return errors;
1425
- };
1426
- const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
1427
- valid: true,
1428
- }) => {
1429
- for (const name in fields) {
1430
- const field = fields[name];
1431
- if (field) {
1432
- const { _f, ...fieldValue } = field;
1433
- if (_f) {
1434
- const isFieldArrayRoot = _names.array.has(_f.name);
1435
- const isPromiseFunction = field._f && hasPromiseValidation(field._f);
1436
- if (isPromiseFunction && _proxyFormState.validatingFields) {
1437
- _updateIsValidating([name], true);
1438
- }
1439
- const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
1440
- if (isPromiseFunction && _proxyFormState.validatingFields) {
1441
- _updateIsValidating([name]);
1442
- }
1443
- if (fieldError[_f.name]) {
1444
- context.valid = false;
1445
- if (shouldOnlyCheckValid) {
1446
- break;
1447
- }
1448
- }
1449
- !shouldOnlyCheckValid &&
1450
- (get(fieldError, _f.name)
1451
- ? isFieldArrayRoot
1452
- ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
1453
- : set(_formState.errors, _f.name, fieldError[_f.name])
1454
- : unset(_formState.errors, _f.name));
1455
- }
1456
- !isEmptyObject(fieldValue) &&
1457
- (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
1458
- }
1459
- }
1460
- return context.valid;
1461
- };
1462
- const _removeUnmounted = () => {
1463
- for (const name of _names.unMount) {
1464
- const field = get(_fields, name);
1465
- field &&
1466
- (field._f.refs
1467
- ? field._f.refs.every((ref) => !live(ref))
1468
- : !live(field._f.ref)) &&
1469
- unregister(name);
1470
- }
1471
- _names.unMount = new Set();
1472
- };
1473
- const _getDirty = (name, data) => !_options.disabled &&
1474
- (name && data && set(_formValues, name, data),
1475
- !deepEqual(getValues(), _defaultValues));
1476
- const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1477
- ...(_state.mount
1478
- ? _formValues
1479
- : isUndefined(defaultValue)
1480
- ? _defaultValues
1481
- : isString(names)
1482
- ? { [names]: defaultValue }
1483
- : defaultValue),
1484
- }, isGlobal, defaultValue);
1485
- const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : []));
1486
- const setFieldValue = (name, value, options = {}) => {
1487
- const field = get(_fields, name);
1488
- let fieldValue = value;
1489
- if (field) {
1490
- const fieldReference = field._f;
1491
- if (fieldReference) {
1492
- !fieldReference.disabled &&
1493
- set(_formValues, name, getFieldValueAs(value, fieldReference));
1494
- fieldValue =
1495
- isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
1496
- ? ''
1497
- : value;
1498
- if (isMultipleSelect(fieldReference.ref)) {
1499
- [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
1500
- }
1501
- else if (fieldReference.refs) {
1502
- if (isCheckBoxInput(fieldReference.ref)) {
1503
- fieldReference.refs.length > 1
1504
- ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&
1505
- (checkboxRef.checked = Array.isArray(fieldValue)
1506
- ? !!fieldValue.find((data) => data === checkboxRef.value)
1507
- : fieldValue === checkboxRef.value))
1508
- : fieldReference.refs[0] &&
1509
- (fieldReference.refs[0].checked = !!fieldValue);
1510
- }
1511
- else {
1512
- fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
1513
- }
1514
- }
1515
- else if (isFileInput(fieldReference.ref)) {
1516
- fieldReference.ref.value = '';
1517
- }
1518
- else {
1519
- fieldReference.ref.value = fieldValue;
1520
- if (!fieldReference.ref.type) {
1521
- _subjects.values.next({
1522
- name,
1523
- values: { ..._formValues },
1524
- });
1525
- }
1526
- }
1527
- }
1528
- }
1529
- (options.shouldDirty || options.shouldTouch) &&
1530
- updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
1531
- options.shouldValidate && trigger(name);
1532
- };
1533
- const setValues = (name, value, options) => {
1534
- for (const fieldKey in value) {
1535
- const fieldValue = value[fieldKey];
1536
- const fieldName = `${name}.${fieldKey}`;
1537
- const field = get(_fields, fieldName);
1538
- (_names.array.has(name) ||
1539
- isObject(fieldValue) ||
1540
- (field && !field._f)) &&
1541
- !isDateObject(fieldValue)
1542
- ? setValues(fieldName, fieldValue, options)
1543
- : setFieldValue(fieldName, fieldValue, options);
1544
- }
1545
- };
1546
- const setValue = (name, value, options = {}) => {
1547
- const field = get(_fields, name);
1548
- const isFieldArray = _names.array.has(name);
1549
- const cloneValue = cloneObject(value);
1550
- set(_formValues, name, cloneValue);
1551
- if (isFieldArray) {
1552
- _subjects.array.next({
1553
- name,
1554
- values: { ..._formValues },
1555
- });
1556
- if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
1557
- options.shouldDirty) {
1558
- _subjects.state.next({
1559
- name,
1560
- dirtyFields: getDirtyFields(_defaultValues, _formValues),
1561
- isDirty: _getDirty(name, cloneValue),
1562
- });
1563
- }
1564
- }
1565
- else {
1566
- field && !field._f && !isNullOrUndefined(cloneValue)
1567
- ? setValues(name, cloneValue, options)
1568
- : setFieldValue(name, cloneValue, options);
1569
- }
1570
- isWatched(name, _names) && _subjects.state.next({ ..._formState });
1571
- _subjects.values.next({
1572
- name: _state.mount ? name : undefined,
1573
- values: { ..._formValues },
1574
- });
1575
- };
1576
- const onChange = async (event) => {
1577
- _state.mount = true;
1578
- const target = event.target;
1579
- let name = target.name;
1580
- let isFieldValueUpdated = true;
1581
- const field = get(_fields, name);
1582
- const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
1583
- const _updateIsFieldValueUpdated = (fieldValue) => {
1584
- isFieldValueUpdated =
1585
- Number.isNaN(fieldValue) ||
1586
- (isDateObject(fieldValue) && isNaN(fieldValue.getTime())) ||
1587
- deepEqual(fieldValue, get(_formValues, name, fieldValue));
1588
- };
1589
- if (field) {
1590
- let error;
1591
- let isValid;
1592
- const fieldValue = getCurrentFieldValue();
1593
- const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1594
- const shouldSkipValidation = (!hasValidation(field._f) &&
1595
- !_options.resolver &&
1596
- !get(_formState.errors, name) &&
1597
- !field._f.deps) ||
1598
- skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1599
- const watched = isWatched(name, _names, isBlurEvent);
1600
- set(_formValues, name, fieldValue);
1601
- if (isBlurEvent) {
1602
- field._f.onBlur && field._f.onBlur(event);
1603
- delayErrorCallback && delayErrorCallback(0);
1604
- }
1605
- else if (field._f.onChange) {
1606
- field._f.onChange(event);
1607
- }
1608
- const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
1609
- const shouldRender = !isEmptyObject(fieldState) || watched;
1610
- !isBlurEvent &&
1611
- _subjects.values.next({
1612
- name,
1613
- type: event.type,
1614
- values: { ..._formValues },
1615
- });
1616
- if (shouldSkipValidation) {
1617
- if (_proxyFormState.isValid) {
1618
- if (_options.mode === 'onBlur' && isBlurEvent) {
1619
- _updateValid();
1620
- }
1621
- else if (!isBlurEvent) {
1622
- _updateValid();
1623
- }
1624
- }
1625
- return (shouldRender &&
1626
- _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
1627
- }
1628
- !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1629
- if (_options.resolver) {
1630
- const { errors } = await _executeSchema([name]);
1631
- _updateIsFieldValueUpdated(fieldValue);
1632
- if (isFieldValueUpdated) {
1633
- const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1634
- const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1635
- error = errorLookupResult.error;
1636
- name = errorLookupResult.name;
1637
- isValid = isEmptyObject(errors);
1638
- }
1639
- }
1640
- else {
1641
- _updateIsValidating([name], true);
1642
- error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1643
- _updateIsValidating([name]);
1644
- _updateIsFieldValueUpdated(fieldValue);
1645
- if (isFieldValueUpdated) {
1646
- if (error) {
1647
- isValid = false;
1648
- }
1649
- else if (_proxyFormState.isValid) {
1650
- isValid = await executeBuiltInValidation(_fields, true);
1651
- }
1652
- }
1653
- }
1654
- if (isFieldValueUpdated) {
1655
- field._f.deps &&
1656
- trigger(field._f.deps);
1657
- shouldRenderByError(name, isValid, error, fieldState);
1658
- }
1659
- }
1660
- };
1661
- const _focusInput = (ref, key) => {
1662
- if (get(_formState.errors, key) && ref.focus) {
1663
- ref.focus();
1664
- return 1;
1665
- }
1666
- return;
1667
- };
1668
- const trigger = async (name, options = {}) => {
1669
- let isValid;
1670
- let validationResult;
1671
- const fieldNames = convertToArrayPayload(name);
1672
- if (_options.resolver) {
1673
- const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1674
- isValid = isEmptyObject(errors);
1675
- validationResult = name
1676
- ? !fieldNames.some((name) => get(errors, name))
1677
- : isValid;
1678
- }
1679
- else if (name) {
1680
- validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1681
- const field = get(_fields, fieldName);
1682
- return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1683
- }))).every(Boolean);
1684
- !(!validationResult && !_formState.isValid) && _updateValid();
1685
- }
1686
- else {
1687
- validationResult = isValid = await executeBuiltInValidation(_fields);
1688
- }
1689
- _subjects.state.next({
1690
- ...(!isString(name) ||
1691
- (_proxyFormState.isValid && isValid !== _formState.isValid)
1692
- ? {}
1693
- : { name }),
1694
- ...(_options.resolver || !name ? { isValid } : {}),
1695
- errors: _formState.errors,
1696
- });
1697
- options.shouldFocus &&
1698
- !validationResult &&
1699
- iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
1700
- return validationResult;
1701
- };
1702
- const getValues = (fieldNames) => {
1703
- const values = {
1704
- ...(_state.mount ? _formValues : _defaultValues),
1705
- };
1706
- return isUndefined(fieldNames)
1707
- ? values
1708
- : isString(fieldNames)
1709
- ? get(values, fieldNames)
1710
- : fieldNames.map((name) => get(values, name));
1711
- };
1712
- const getFieldState = (name, formState) => ({
1713
- invalid: !!get((formState || _formState).errors, name),
1714
- isDirty: !!get((formState || _formState).dirtyFields, name),
1715
- error: get((formState || _formState).errors, name),
1716
- isValidating: !!get(_formState.validatingFields, name),
1717
- isTouched: !!get((formState || _formState).touchedFields, name),
1718
- });
1719
- const clearErrors = (name) => {
1720
- name &&
1721
- convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1722
- _subjects.state.next({
1723
- errors: name ? _formState.errors : {},
1724
- });
1725
- };
1726
- const setError = (name, error, options) => {
1727
- const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1728
- const currentError = get(_formState.errors, name) || {};
1729
- // Don't override existing error messages elsewhere in the object tree.
1730
- const { ref: currentRef, message, type, ...restOfErrorTree } = currentError;
1731
- set(_formState.errors, name, {
1732
- ...restOfErrorTree,
1733
- ...error,
1734
- ref,
1735
- });
1736
- _subjects.state.next({
1737
- name,
1738
- errors: _formState.errors,
1739
- isValid: false,
1740
- });
1741
- options && options.shouldFocus && ref && ref.focus && ref.focus();
1742
- };
1743
- const watch = (name, defaultValue) => isFunction(name)
1744
- ? _subjects.values.subscribe({
1745
- next: (payload) => name(_getWatch(undefined, defaultValue), payload),
1746
- })
1747
- : _getWatch(name, defaultValue, true);
1748
- const unregister = (name, options = {}) => {
1749
- for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1750
- _names.mount.delete(fieldName);
1751
- _names.array.delete(fieldName);
1752
- if (!options.keepValue) {
1753
- unset(_fields, fieldName);
1754
- unset(_formValues, fieldName);
1755
- }
1756
- !options.keepError && unset(_formState.errors, fieldName);
1757
- !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1758
- !options.keepTouched && unset(_formState.touchedFields, fieldName);
1759
- !options.keepIsValidating &&
1760
- unset(_formState.validatingFields, fieldName);
1761
- !_options.shouldUnregister &&
1762
- !options.keepDefaultValue &&
1763
- unset(_defaultValues, fieldName);
1764
- }
1765
- _subjects.values.next({
1766
- values: { ..._formValues },
1767
- });
1768
- _subjects.state.next({
1769
- ..._formState,
1770
- ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
1771
- });
1772
- !options.keepIsValid && _updateValid();
1773
- };
1774
- const _updateDisabledField = ({ disabled, name, field, fields, }) => {
1775
- if ((isBoolean(disabled) && _state.mount) ||
1776
- !!disabled ||
1777
- _names.disabled.has(name)) {
1778
- disabled ? _names.disabled.add(name) : _names.disabled.delete(name);
1779
- updateTouchAndDirty(name, getFieldValue(field ? field._f : get(fields, name)._f), false, false, true);
1780
- }
1781
- };
1782
- const register = (name, options = {}) => {
1783
- let field = get(_fields, name);
1784
- const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled);
1785
- set(_fields, name, {
1786
- ...(field || {}),
1787
- _f: {
1788
- ...(field && field._f ? field._f : { ref: { name } }),
1789
- name,
1790
- mount: true,
1791
- ...options,
1792
- },
1793
- });
1794
- _names.mount.add(name);
1795
- if (field) {
1796
- _updateDisabledField({
1797
- field,
1798
- disabled: isBoolean(options.disabled)
1799
- ? options.disabled
1800
- : _options.disabled,
1801
- name,
1802
- });
1803
- }
1804
- else {
1805
- updateValidAndValue(name, true, options.value);
1806
- }
1807
- return {
1808
- ...(disabledIsDefined
1809
- ? { disabled: options.disabled || _options.disabled }
1810
- : {}),
1811
- ...(_options.progressive
1812
- ? {
1813
- required: !!options.required,
1814
- min: getRuleValue(options.min),
1815
- max: getRuleValue(options.max),
1816
- minLength: getRuleValue(options.minLength),
1817
- maxLength: getRuleValue(options.maxLength),
1818
- pattern: getRuleValue(options.pattern),
1819
- }
1820
- : {}),
1821
- name,
1822
- onChange,
1823
- onBlur: onChange,
1824
- ref: (ref) => {
1825
- if (ref) {
1826
- register(name, options);
1827
- field = get(_fields, name);
1828
- const fieldRef = isUndefined(ref.value)
1829
- ? ref.querySelectorAll
1830
- ? ref.querySelectorAll('input,select,textarea')[0] || ref
1831
- : ref
1832
- : ref;
1833
- const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1834
- const refs = field._f.refs || [];
1835
- if (radioOrCheckbox
1836
- ? refs.find((option) => option === fieldRef)
1837
- : fieldRef === field._f.ref) {
1838
- return;
1839
- }
1840
- set(_fields, name, {
1841
- _f: {
1842
- ...field._f,
1843
- ...(radioOrCheckbox
1844
- ? {
1845
- refs: [
1846
- ...refs.filter(live),
1847
- fieldRef,
1848
- ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
1849
- ],
1850
- ref: { type: fieldRef.type, name },
1851
- }
1852
- : { ref: fieldRef }),
1853
- },
1854
- });
1855
- updateValidAndValue(name, false, undefined, fieldRef);
1856
- }
1857
- else {
1858
- field = get(_fields, name, {});
1859
- if (field._f) {
1860
- field._f.mount = false;
1861
- }
1862
- (_options.shouldUnregister || options.shouldUnregister) &&
1863
- !(isNameInFieldArray(_names.array, name) && _state.action) &&
1864
- _names.unMount.add(name);
1865
- }
1866
- },
1867
- };
1868
- };
1869
- const _focusError = () => _options.shouldFocusError &&
1870
- iterateFieldsByAction(_fields, _focusInput, _names.mount);
1871
- const _disableForm = (disabled) => {
1872
- if (isBoolean(disabled)) {
1873
- _subjects.state.next({ disabled });
1874
- iterateFieldsByAction(_fields, (ref, name) => {
1875
- const currentField = get(_fields, name);
1876
- if (currentField) {
1877
- ref.disabled = currentField._f.disabled || disabled;
1878
- if (Array.isArray(currentField._f.refs)) {
1879
- currentField._f.refs.forEach((inputRef) => {
1880
- inputRef.disabled = currentField._f.disabled || disabled;
1881
- });
1882
- }
1883
- }
1884
- }, 0, false);
1885
- }
1886
- };
1887
- const handleSubmit = (onValid, onInvalid) => async (e) => {
1888
- let onValidError = undefined;
1889
- if (e) {
1890
- e.preventDefault && e.preventDefault();
1891
- e.persist && e.persist();
1892
- }
1893
- let fieldValues = cloneObject(_formValues);
1894
- if (_names.disabled.size) {
1895
- for (const name of _names.disabled) {
1896
- set(fieldValues, name, undefined);
1897
- }
1898
- }
1899
- _subjects.state.next({
1900
- isSubmitting: true,
1901
- });
1902
- if (_options.resolver) {
1903
- const { errors, values } = await _executeSchema();
1904
- _formState.errors = errors;
1905
- fieldValues = values;
1906
- }
1907
- else {
1908
- await executeBuiltInValidation(_fields);
1909
- }
1910
- unset(_formState.errors, 'root');
1911
- if (isEmptyObject(_formState.errors)) {
1912
- _subjects.state.next({
1913
- errors: {},
1914
- });
1915
- try {
1916
- await onValid(fieldValues, e);
1917
- }
1918
- catch (error) {
1919
- onValidError = error;
1920
- }
1921
- }
1922
- else {
1923
- if (onInvalid) {
1924
- await onInvalid({ ..._formState.errors }, e);
1925
- }
1926
- _focusError();
1927
- setTimeout(_focusError);
1928
- }
1929
- _subjects.state.next({
1930
- isSubmitted: true,
1931
- isSubmitting: false,
1932
- isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
1933
- submitCount: _formState.submitCount + 1,
1934
- errors: _formState.errors,
1935
- });
1936
- if (onValidError) {
1937
- throw onValidError;
1938
- }
1939
- };
1940
- const resetField = (name, options = {}) => {
1941
- if (get(_fields, name)) {
1942
- if (isUndefined(options.defaultValue)) {
1943
- setValue(name, cloneObject(get(_defaultValues, name)));
1944
- }
1945
- else {
1946
- setValue(name, options.defaultValue);
1947
- set(_defaultValues, name, cloneObject(options.defaultValue));
1948
- }
1949
- if (!options.keepTouched) {
1950
- unset(_formState.touchedFields, name);
1951
- }
1952
- if (!options.keepDirty) {
1953
- unset(_formState.dirtyFields, name);
1954
- _formState.isDirty = options.defaultValue
1955
- ? _getDirty(name, cloneObject(get(_defaultValues, name)))
1956
- : _getDirty();
1957
- }
1958
- if (!options.keepError) {
1959
- unset(_formState.errors, name);
1960
- _proxyFormState.isValid && _updateValid();
1961
- }
1962
- _subjects.state.next({ ..._formState });
1963
- }
1964
- };
1965
- const _reset = (formValues, keepStateOptions = {}) => {
1966
- const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
1967
- const cloneUpdatedValues = cloneObject(updatedValues);
1968
- const isEmptyResetValues = isEmptyObject(formValues);
1969
- const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;
1970
- if (!keepStateOptions.keepDefaultValues) {
1971
- _defaultValues = updatedValues;
1972
- }
1973
- if (!keepStateOptions.keepValues) {
1974
- if (keepStateOptions.keepDirtyValues) {
1975
- const fieldsToCheck = new Set([
1976
- ..._names.mount,
1977
- ...Object.keys(getDirtyFields(_defaultValues, _formValues)),
1978
- ]);
1979
- for (const fieldName of Array.from(fieldsToCheck)) {
1980
- get(_formState.dirtyFields, fieldName)
1981
- ? set(values, fieldName, get(_formValues, fieldName))
1982
- : setValue(fieldName, get(values, fieldName));
1983
- }
1984
- }
1985
- else {
1986
- if (isWeb && isUndefined(formValues)) {
1987
- for (const name of _names.mount) {
1988
- const field = get(_fields, name);
1989
- if (field && field._f) {
1990
- const fieldReference = Array.isArray(field._f.refs)
1991
- ? field._f.refs[0]
1992
- : field._f.ref;
1993
- if (isHTMLElement(fieldReference)) {
1994
- const form = fieldReference.closest('form');
1995
- if (form) {
1996
- form.reset();
1997
- break;
1998
- }
1999
- }
2000
- }
2001
- }
2002
- }
2003
- _fields = {};
2004
- }
2005
- _formValues = _options.shouldUnregister
2006
- ? keepStateOptions.keepDefaultValues
2007
- ? cloneObject(_defaultValues)
2008
- : {}
2009
- : cloneObject(values);
2010
- _subjects.array.next({
2011
- values: { ...values },
2012
- });
2013
- _subjects.values.next({
2014
- values: { ...values },
2015
- });
2016
- }
2017
- _names = {
2018
- mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(),
2019
- unMount: new Set(),
2020
- array: new Set(),
2021
- disabled: new Set(),
2022
- watch: new Set(),
2023
- watchAll: false,
2024
- focus: '',
2025
- };
2026
- _state.mount =
2027
- !_proxyFormState.isValid ||
2028
- !!keepStateOptions.keepIsValid ||
2029
- !!keepStateOptions.keepDirtyValues;
2030
- _state.watch = !!_options.shouldUnregister;
2031
- _subjects.state.next({
2032
- submitCount: keepStateOptions.keepSubmitCount
2033
- ? _formState.submitCount
2034
- : 0,
2035
- isDirty: isEmptyResetValues
2036
- ? false
2037
- : keepStateOptions.keepDirty
2038
- ? _formState.isDirty
2039
- : !!(keepStateOptions.keepDefaultValues &&
2040
- !deepEqual(formValues, _defaultValues)),
2041
- isSubmitted: keepStateOptions.keepIsSubmitted
2042
- ? _formState.isSubmitted
2043
- : false,
2044
- dirtyFields: isEmptyResetValues
2045
- ? {}
2046
- : keepStateOptions.keepDirtyValues
2047
- ? keepStateOptions.keepDefaultValues && _formValues
2048
- ? getDirtyFields(_defaultValues, _formValues)
2049
- : _formState.dirtyFields
2050
- : keepStateOptions.keepDefaultValues && formValues
2051
- ? getDirtyFields(_defaultValues, formValues)
2052
- : keepStateOptions.keepDirty
2053
- ? _formState.dirtyFields
2054
- : {},
2055
- touchedFields: keepStateOptions.keepTouched
2056
- ? _formState.touchedFields
2057
- : {},
2058
- errors: keepStateOptions.keepErrors ? _formState.errors : {},
2059
- isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful
2060
- ? _formState.isSubmitSuccessful
2061
- : false,
2062
- isSubmitting: false,
2063
- });
2064
- };
2065
- const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
2066
- ? formValues(_formValues)
2067
- : formValues, keepStateOptions);
2068
- const setFocus = (name, options = {}) => {
2069
- const field = get(_fields, name);
2070
- const fieldReference = field && field._f;
2071
- if (fieldReference) {
2072
- const fieldRef = fieldReference.refs
2073
- ? fieldReference.refs[0]
2074
- : fieldReference.ref;
2075
- if (fieldRef.focus) {
2076
- fieldRef.focus();
2077
- options.shouldSelect &&
2078
- isFunction(fieldRef.select) &&
2079
- fieldRef.select();
2080
- }
2081
- }
2082
- };
2083
- const _updateFormState = (updatedFormState) => {
2084
- _formState = {
2085
- ..._formState,
2086
- ...updatedFormState,
2087
- };
2088
- };
2089
- const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
2090
- _options.defaultValues().then((values) => {
2091
- reset(values, _options.resetOptions);
2092
- _subjects.state.next({
2093
- isLoading: false,
2094
- });
2095
- });
2096
- return {
2097
- control: {
2098
- register,
2099
- unregister,
2100
- getFieldState,
2101
- handleSubmit,
2102
- setError,
2103
- _executeSchema,
2104
- _getWatch,
2105
- _getDirty,
2106
- _updateValid,
2107
- _removeUnmounted,
2108
- _updateFieldArray,
2109
- _updateDisabledField,
2110
- _getFieldArray,
2111
- _reset,
2112
- _resetDefaultValues,
2113
- _updateFormState,
2114
- _disableForm,
2115
- _subjects,
2116
- _proxyFormState,
2117
- _setErrors,
2118
- get _fields() {
2119
- return _fields;
2120
- },
2121
- get _formValues() {
2122
- return _formValues;
2123
- },
2124
- get _state() {
2125
- return _state;
2126
- },
2127
- set _state(value) {
2128
- _state = value;
2129
- },
2130
- get _defaultValues() {
2131
- return _defaultValues;
2132
- },
2133
- get _names() {
2134
- return _names;
2135
- },
2136
- set _names(value) {
2137
- _names = value;
2138
- },
2139
- get _formState() {
2140
- return _formState;
2141
- },
2142
- set _formState(value) {
2143
- _formState = value;
2144
- },
2145
- get _options() {
2146
- return _options;
2147
- },
2148
- set _options(value) {
2149
- _options = {
2150
- ..._options,
2151
- ...value,
2152
- };
2153
- },
2154
- },
2155
- trigger,
2156
- register,
2157
- handleSubmit,
2158
- watch,
2159
- setValue,
2160
- getValues,
2161
- reset,
2162
- resetField,
2163
- clearErrors,
2164
- unregister,
2165
- setError,
2166
- setFocus,
2167
- getFieldState,
2168
- };
2169
- }
2170
-
2171
- /**
2172
- * Custom hook to manage the entire form.
2173
- *
2174
- * @remarks
2175
- * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2176
- *
2177
- * @param props - form configuration and validation parameters.
2178
- *
2179
- * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2180
- *
2181
- * @example
2182
- * ```tsx
2183
- * function App() {
2184
- * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2185
- * const onSubmit = data => console.log(data);
2186
- *
2187
- * console.log(watch("example"));
2188
- *
2189
- * return (
2190
- * <form onSubmit={handleSubmit(onSubmit)}>
2191
- * <input defaultValue="test" {...register("example")} />
2192
- * <input {...register("exampleRequired", { required: true })} />
2193
- * {errors.exampleRequired && <span>This field is required</span>}
2194
- * <button>Submit</button>
2195
- * </form>
2196
- * );
2197
- * }
2198
- * ```
2199
- */
2200
- function useForm(props = {}) {
2201
- const _formControl = React__default.useRef(undefined);
2202
- const _values = React__default.useRef(undefined);
2203
- const [formState, updateFormState] = React__default.useState({
2204
- isDirty: false,
2205
- isValidating: false,
2206
- isLoading: isFunction(props.defaultValues),
2207
- isSubmitted: false,
2208
- isSubmitting: false,
2209
- isSubmitSuccessful: false,
2210
- isValid: false,
2211
- submitCount: 0,
2212
- dirtyFields: {},
2213
- touchedFields: {},
2214
- validatingFields: {},
2215
- errors: props.errors || {},
2216
- disabled: props.disabled || false,
2217
- defaultValues: isFunction(props.defaultValues)
2218
- ? undefined
2219
- : props.defaultValues,
2220
- });
2221
- if (!_formControl.current) {
2222
- _formControl.current = {
2223
- ...createFormControl(props),
2224
- formState,
2225
- };
2226
- }
2227
- const control = _formControl.current.control;
2228
- control._options = props;
2229
- useSubscribe({
2230
- subject: control._subjects.state,
2231
- next: (value) => {
2232
- if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
2233
- updateFormState({ ...control._formState });
2234
- }
2235
- },
2236
- });
2237
- React__default.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
2238
- React__default.useEffect(() => {
2239
- if (control._proxyFormState.isDirty) {
2240
- const isDirty = control._getDirty();
2241
- if (isDirty !== formState.isDirty) {
2242
- control._subjects.state.next({
2243
- isDirty,
2244
- });
2245
- }
2246
- }
2247
- }, [control, formState.isDirty]);
2248
- React__default.useEffect(() => {
2249
- if (props.values && !deepEqual(props.values, _values.current)) {
2250
- control._reset(props.values, control._options.resetOptions);
2251
- _values.current = props.values;
2252
- updateFormState((state) => ({ ...state }));
2253
- }
2254
- else {
2255
- control._resetDefaultValues();
2256
- }
2257
- }, [props.values, control]);
2258
- React__default.useEffect(() => {
2259
- if (props.errors) {
2260
- control._setErrors(props.errors);
2261
- }
2262
- }, [props.errors, control]);
2263
- React__default.useEffect(() => {
2264
- if (!control._state.mount) {
2265
- control._updateValid();
2266
- control._state.mount = true;
2267
- }
2268
- if (control._state.watch) {
2269
- control._state.watch = false;
2270
- control._subjects.state.next({ ...control._formState });
2271
- }
2272
- control._removeUnmounted();
2273
- });
2274
- React__default.useEffect(() => {
2275
- props.shouldUnregister &&
2276
- control._subjects.values.next({
2277
- values: control._getWatch(),
2278
- });
2279
- }, [props.shouldUnregister, control]);
2280
- _formControl.current.formState = getProxyFormState(formState, control);
2281
- return _formControl.current;
2282
- }
2283
-
2284
1
  var util;
2285
2
  (function (util) {
2286
3
  util.assertEqual = (val) => val;
@@ -6682,1097 +4399,4 @@ var z = /*#__PURE__*/Object.freeze({
6682
4399
  ZodError: ZodError
6683
4400
  });
6684
4401
 
6685
- function g(e) {
6686
- let n = 0, t = false, s = e.length - 1, l;
6687
- for (; s >= 0; )
6688
- l = parseInt(e.charAt(s), 10), t && (l *= 2, l > 9 && (l = l % 10 + 1)), t = !t, n += l, s--;
6689
- return n % 10 === 0;
6690
- }
6691
- const h = [
6692
- {
6693
- name: "visa",
6694
- isLocal: false,
6695
- numberValidationRules: {
6696
- luhnCheck: true,
6697
- ranges: [4],
6698
- lengths: [16, 18, 19]
6699
- },
6700
- securityCodeValidationRules: {
6701
- lengths: [3]
6702
- }
6703
- },
6704
- {
6705
- name: "mastercard",
6706
- isLocal: false,
6707
- numberValidationRules: {
6708
- luhnCheck: true,
6709
- ranges: [[51, 55], [2221, 2229], [223, 229], [23, 26], [270, 271], 2720],
6710
- lengths: [16]
6711
- },
6712
- securityCodeValidationRules: {
6713
- lengths: [3]
6714
- }
6715
- },
6716
- {
6717
- name: "american-express",
6718
- isLocal: false,
6719
- numberValidationRules: {
6720
- luhnCheck: true,
6721
- ranges: [34, 37],
6722
- lengths: [15]
6723
- },
6724
- securityCodeValidationRules: {
6725
- lengths: [3, 4]
6726
- }
6727
- },
6728
- {
6729
- name: "diners-club",
6730
- isLocal: false,
6731
- numberValidationRules: {
6732
- luhnCheck: true,
6733
- ranges: [[300, 305], 3095, 36, 38, 39],
6734
- lengths: [14, 16, 19]
6735
- },
6736
- securityCodeValidationRules: {
6737
- lengths: [3]
6738
- }
6739
- },
6740
- {
6741
- name: "discover",
6742
- isLocal: false,
6743
- numberValidationRules: {
6744
- luhnCheck: true,
6745
- ranges: [6011, [644, 649], [65e4, 651999], [653150, 659999], 622],
6746
- lengths: [16, 19]
6747
- },
6748
- securityCodeValidationRules: {
6749
- lengths: [3]
6750
- }
6751
- },
6752
- {
6753
- name: "jcb",
6754
- isLocal: false,
6755
- numberValidationRules: {
6756
- luhnCheck: true,
6757
- ranges: [
6758
- 2131,
6759
- 1800,
6760
- [3088, 3094],
6761
- [3096, 3102],
6762
- [3112, 3120],
6763
- [3158, 3159],
6764
- [3337, 3349],
6765
- [3528, 3589]
6766
- ],
6767
- lengths: [16, 17, 18, 19]
6768
- },
6769
- securityCodeValidationRules: {
6770
- lengths: [3]
6771
- }
6772
- },
6773
- {
6774
- name: "unionpay",
6775
- isLocal: false,
6776
- numberValidationRules: {
6777
- luhnCheck: false,
6778
- ranges: [
6779
- 620,
6780
- [62100, 62182],
6781
- [62184, 62187],
6782
- [62185, 62197],
6783
- [62200, 62205],
6784
- [622010, 622999],
6785
- 622018,
6786
- [62207, 62209],
6787
- [623, 626],
6788
- 6270,
6789
- 6272,
6790
- 6276,
6791
- [627700, 627779],
6792
- [627781, 627799],
6793
- [6282, 6289],
6794
- 6291,
6795
- 6292,
6796
- 810,
6797
- [8110, 8131],
6798
- [8132, 8151],
6799
- [8152, 8163],
6800
- [8164, 8171]
6801
- ],
6802
- lengths: [14, 15, 16, 17, 18, 19]
6803
- },
6804
- securityCodeValidationRules: {
6805
- lengths: [3]
6806
- }
6807
- },
6808
- {
6809
- name: "maestro",
6810
- isLocal: false,
6811
- numberValidationRules: {
6812
- luhnCheck: true,
6813
- ranges: [
6814
- 5018,
6815
- 5020,
6816
- 5038,
6817
- 5893,
6818
- 6101,
6819
- 6304,
6820
- 6759,
6821
- 6761,
6822
- 6762,
6823
- 6763,
6824
- 493698,
6825
- [5e5, 504174],
6826
- [504176, 506698],
6827
- [506779, 508999],
6828
- 69
6829
- ],
6830
- lengths: [12, 13, 14, 15, 16, 17, 18, 19]
6831
- },
6832
- securityCodeValidationRules: {
6833
- lengths: [3]
6834
- }
6835
- },
6836
- {
6837
- name: "elo",
6838
- isLocal: true,
6839
- numberValidationRules: {
6840
- luhnCheck: true,
6841
- ranges: [
6842
- 401178,
6843
- 401179,
6844
- 438935,
6845
- 457631,
6846
- 457632,
6847
- 431274,
6848
- 451416,
6849
- 457393,
6850
- 504175,
6851
- [506699, 506778],
6852
- [509e3, 509999],
6853
- 627780,
6854
- 636297,
6855
- 636368,
6856
- [650031, 650033],
6857
- [650035, 650051],
6858
- [650405, 650439],
6859
- [650485, 650538],
6860
- [650541, 650598],
6861
- [650700, 650718],
6862
- [650720, 650727],
6863
- [650901, 650978],
6864
- [651652, 651679],
6865
- [655e3, 655019],
6866
- [655021, 655058]
6867
- ],
6868
- lengths: [16]
6869
- },
6870
- securityCodeValidationRules: {
6871
- lengths: [3]
6872
- }
6873
- },
6874
- {
6875
- name: "mir",
6876
- isLocal: true,
6877
- numberValidationRules: {
6878
- luhnCheck: true,
6879
- ranges: [[2200, 2204]],
6880
- lengths: [16, 17, 18, 19]
6881
- },
6882
- securityCodeValidationRules: {
6883
- lengths: [3]
6884
- }
6885
- },
6886
- {
6887
- name: "hiper",
6888
- isLocal: true,
6889
- numberValidationRules: {
6890
- luhnCheck: true,
6891
- ranges: [637095, 63737423, 63743358, 637568, 637599, 637609, 637612],
6892
- lengths: [16]
6893
- },
6894
- securityCodeValidationRules: {
6895
- lengths: [3]
6896
- }
6897
- },
6898
- {
6899
- name: "hipercard",
6900
- isLocal: true,
6901
- numberValidationRules: {
6902
- luhnCheck: true,
6903
- ranges: [606282],
6904
- lengths: [16]
6905
- },
6906
- securityCodeValidationRules: {
6907
- lengths: [3]
6908
- }
6909
- },
6910
- {
6911
- name: "szep",
6912
- isLocal: true,
6913
- numberValidationRules: {
6914
- luhnCheck: true,
6915
- ranges: [30867825, 61013170, 61013242],
6916
- lengths: [16]
6917
- },
6918
- securityCodeValidationRules: {
6919
- lengths: [3]
6920
- }
6921
- },
6922
- {
6923
- name: "uatp",
6924
- isLocal: false,
6925
- numberValidationRules: {
6926
- luhnCheck: true,
6927
- ranges: [1],
6928
- lengths: [15]
6929
- },
6930
- securityCodeValidationRules: {
6931
- lengths: [0]
6932
- }
6933
- },
6934
- {
6935
- name: "rupay",
6936
- isLocal: false,
6937
- numberValidationRules: {
6938
- luhnCheck: true,
6939
- ranges: [60, 81, 82, 508, [652100, 653149], [817200, 819899]],
6940
- lengths: [16]
6941
- },
6942
- securityCodeValidationRules: {
6943
- lengths: [3]
6944
- }
6945
- }
6946
- ];
6947
- function m(e, n, t) {
6948
- const s = String(n).length, l = e.substring(0, s), a = parseInt(l, 10);
6949
- return l.length < s ? false : (n = parseInt(String(n).substring(0, l.length), 10), t = parseInt(String(t).substring(0, l.length), 10), a >= n && a <= t);
6950
- }
6951
- function V(e, n) {
6952
- return e.startsWith(String(n));
6953
- }
6954
- function f(e) {
6955
- return e.length < 16 ? e.substring(0, 6) : e.substring(0, 8);
6956
- }
6957
- function C(e) {
6958
- const n = String(e).replace(/\s/g, "");
6959
- if (!/^\d*$/.test(n))
6960
- return {
6961
- brand: null,
6962
- localBrands: [],
6963
- bin: null,
6964
- lastFour: null,
6965
- isValid: false
6966
- };
6967
- const t = h.filter((i) => i.numberValidationRules.ranges.some((r) => {
6968
- if (Array.isArray(r)) {
6969
- if (r[0] && r[1])
6970
- return m(n, r[0], r[1]);
6971
- } else
6972
- return V(n, r);
6973
- return false;
6974
- })), s = t.filter((i) => !i.isLocal), l = t.filter((i) => i.isLocal), a = t.length > 0 && t.every((i) => {
6975
- const { lengths: r, luhnCheck: o } = i.numberValidationRules, c = r.includes(n.length), d = !o || g(n);
6976
- return c && d;
6977
- }), u = e.length > 5;
6978
- return {
6979
- brand: s.length > 0 ? s[0].name : null,
6980
- localBrands: l.map((i) => i.name),
6981
- bin: u ? f(e) : null,
6982
- lastFour: a ? n.substring(n.length - 4) : null,
6983
- isValid: a
6984
- };
6985
- }
6986
- function R(e, n) {
6987
- if (!/^\d{3,4}$/.test(e))
6988
- return {
6989
- cvc: null,
6990
- isValid: false
6991
- };
6992
- if (!n)
6993
- return {
6994
- cvc: e,
6995
- isValid: true
6996
- };
6997
- const t = C(n);
6998
- if (!t.isValid)
6999
- return {
7000
- cvc: null,
7001
- isValid: false
7002
- };
7003
- const s = [];
7004
- t.brand && s.push(t.brand), t.localBrands && s.push(...t.localBrands);
7005
- const l = h.filter((a) => s.includes(a.name)).some((a) => a.securityCodeValidationRules.lengths.includes(e.length));
7006
- return {
7007
- cvc: l ? e : null,
7008
- isValid: l
7009
- };
7010
- }
7011
- function b(e) {
7012
- var i;
7013
- const n = /^(0[1-9]|1[[0-2]).*$/, t = e.match(n), s = t ? parseInt(t[1].toString(), 10) : null, l = /^(0[1-9]|1[[0-2])(\d{2})$/, a = e.match(l), u = a ? parseInt(a[2].toString(), 10) : null;
7014
- if (s) {
7015
- const r = (/* @__PURE__ */ new Date()).getFullYear() % 100, o = (/* @__PURE__ */ new Date()).getMonth() + 1, c = !u || u < r || u === r && s < o;
7016
- return {
7017
- month: s.toString().padStart(2, "0"),
7018
- year: ((i = u == null ? void 0 : u.toString()) == null ? void 0 : i.padStart(2, "0")) ?? null,
7019
- isValid: !c
7020
- };
7021
- }
7022
- return {
7023
- month: null,
7024
- year: null,
7025
- isValid: false
7026
- };
7027
- }
7028
-
7029
- async function formatPayload(values, context) {
7030
- const number = values.number?.replace(/\s/g, "") || "";
7031
- const { brand, localBrands, bin, lastFour, isValid: isNumberValid, } = C(number);
7032
- if (number.length > 0 &&
7033
- brand !== "american-express" &&
7034
- values.cvc?.length === 4) {
7035
- context.form.setValue("cvc", values.cvc?.slice(0, 3));
7036
- }
7037
- const { cvc, isValid: isCvcValid } = R(values.cvc ?? "", number);
7038
- const formErrors = context.form.formState.errors;
7039
- const isValid = !Object.keys(formErrors).length;
7040
- const isComplete = areValuesComplete(values);
7041
- const errors = {};
7042
- if (formErrors.name?.message) {
7043
- errors.name = formErrors.name.message;
7044
- }
7045
- if (formErrors.number?.message) {
7046
- errors.number = formErrors.number.message;
7047
- }
7048
- if (formErrors.expiry?.message) {
7049
- errors.expiry = formErrors.expiry.message;
7050
- }
7051
- if (formErrors.cvc?.message) {
7052
- errors.cvc = formErrors.cvc.message;
7053
- }
7054
- return {
7055
- card: {
7056
- name: values.name ?? null,
7057
- brand,
7058
- localBrands,
7059
- bin,
7060
- lastFour,
7061
- expiry: formatExpiry(values.expiry ?? ""),
7062
- number: isNumberValid ? await context.encrypt(number) : null,
7063
- cvc: isCvcValid ? await context.encrypt(cvc ?? "") : null,
7064
- },
7065
- isComplete,
7066
- isValid: isValid && isComplete,
7067
- errors,
7068
- };
7069
- }
7070
- function areValuesComplete(values) {
7071
- if ("name" in values && !values.name?.length) {
7072
- return false;
7073
- }
7074
- if ("number" in values && !C(values.number ?? "").isValid) {
7075
- return false;
7076
- }
7077
- if ("expiry" in values && !b(values.expiry ?? "").isValid) {
7078
- return false;
7079
- }
7080
- if ("cvc" in values &&
7081
- !R(values.cvc ?? "", values.number).isValid) {
7082
- return false;
7083
- }
7084
- return true;
7085
- }
7086
- function isAcceptedBrand(acceptedBrands, cardNumberValidationResult) {
7087
- if (!acceptedBrands?.length)
7088
- return true;
7089
- if (!cardNumberValidationResult.isValid)
7090
- return false;
7091
- const { brand, localBrands } = cardNumberValidationResult;
7092
- const acceptedBrandsSet = new Set(acceptedBrands);
7093
- const isBrandAccepted = brand !== null && acceptedBrandsSet.has(brand);
7094
- const isLocalBrandAccepted = localBrands.some((localBrand) => acceptedBrandsSet.has(localBrand));
7095
- return isBrandAccepted || isLocalBrandAccepted;
7096
- }
7097
- function formatExpiry(expiry) {
7098
- const parsedExpiry = b(expiry);
7099
- if (!parsedExpiry.isValid) {
7100
- return null;
7101
- }
7102
- return {
7103
- month: parsedExpiry.month,
7104
- year: parsedExpiry.year,
7105
- };
7106
- }
7107
-
7108
- function getCardFormSchema(acceptedBrands) {
7109
- return z.object({
7110
- name: z.string().min(1, "Missing name"),
7111
- number: z
7112
- .string()
7113
- .min(1, "Required")
7114
- .refine((value) => C(value).isValid, {
7115
- message: "Invalid card number",
7116
- })
7117
- .refine((value) => isAcceptedBrand(acceptedBrands, C(value)), { message: "Brand not accepted" }),
7118
- expiry: z
7119
- .string()
7120
- .min(1, "Required")
7121
- .refine((value) => b(value).isValid, {
7122
- message: "Invalid expiry",
7123
- }),
7124
- cvc: z
7125
- .string()
7126
- .min(1, "Required")
7127
- .refine((value) => R(value).isValid, {
7128
- message: "Invalid CVC",
7129
- }),
7130
- });
7131
- }
7132
-
7133
- const r=(t,r,o)=>{if(t&&"reportValidity"in t){const s=get(o,r);t.setCustomValidity(s&&s.message||""),t.reportValidity();}},o=(e,t)=>{for(const o in t.fields){const s=t.fields[o];s&&s.ref&&"reportValidity"in s.ref?r(s.ref,o,e):s&&s.refs&&s.refs.forEach(t=>r(t,o,e));}},s$1=(r,s)=>{s.shouldUseNativeValidation&&o(r,s);const n={};for(const o in r){const f=get(s.fields,o),c=Object.assign(r[o]||{},{ref:f&&f.ref});if(i(s.names||Object.keys(r),o)){const r=Object.assign({},get(n,o));set(r,"root",c),set(n,o,r);}else set(n,o,c);}return n},i=(e,t)=>{const r=n$1(t);return e.some(e=>n$1(e).match(`^${r}\\.\\d+`))};function n$1(e){return e.replace(/\]|\[/g,"")}
7134
-
7135
- function n(r,e){for(var n={};r.length;){var s=r[0],t=s.code,i=s.message,a=s.path.join(".");if(!n[a])if("unionErrors"in s){var u=s.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code};}else n[a]={message:i,type:t};if("unionErrors"in s&&s.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[s.code];n[a]=appendErrors(a,e,n,t,f?[].concat(f,s.message):s.message);}r.shift();}return n}function s(o$1,s,t){return void 0===t&&(t={}),function(i,a,u){try{return Promise.resolve(function(e,n){try{var a=Promise.resolve(o$1["sync"===t.mode?"parse":"parseAsync"](i,s)).then(function(e){return u.shouldUseNativeValidation&&o({},u),{errors:{},values:t.raw?Object.assign({},i):e}});}catch(r){return n(r)}return a&&a.then?a.then(void 0,n):a}(0,function(r){if(function(r){return Array.isArray(null==r?void 0:r.errors)}(r))return {values:{},errors:s$1(n(r.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw r}))}catch(r){return Promise.reject(r)}}}
7136
-
7137
- // Taken from https://github.com/gregberge/react-merge-refs
7138
- function mergeRefs(...refs) {
7139
- return (value) => {
7140
- refs.forEach((ref) => {
7141
- if (typeof ref === "function") {
7142
- ref(value);
7143
- }
7144
- else if (ref != null) {
7145
- ref.current = value;
7146
- }
7147
- });
7148
- };
7149
- }
7150
-
7151
- function formatWithMask(props) {
7152
- const {
7153
- text,
7154
- mask,
7155
- obfuscationCharacter = '*',
7156
- maskAutoComplete = false
7157
- } = props; // make sure it'll not break with null or undefined inputs
7158
-
7159
- if (!text) return {
7160
- masked: '',
7161
- unmasked: '',
7162
- obfuscated: ''
7163
- };
7164
- if (!mask) return {
7165
- masked: text || '',
7166
- unmasked: text || '',
7167
- obfuscated: text || ''
7168
- };
7169
- let maskArray = typeof mask === 'function' ? mask(text) : mask;
7170
- let masked = '';
7171
- let obfuscated = '';
7172
- let unmasked = '';
7173
- let maskCharIndex = 0;
7174
- let valueCharIndex = 0;
7175
-
7176
- while (true) {
7177
- // if mask is ended, break.
7178
- if (maskCharIndex === maskArray.length) {
7179
- break;
7180
- }
7181
-
7182
- let maskChar = maskArray[maskCharIndex];
7183
- let valueChar = text[valueCharIndex]; // if value is ended, break.
7184
-
7185
- if (valueCharIndex === text.length) {
7186
- if (typeof maskChar === 'string' && maskAutoComplete) {
7187
- masked += maskChar;
7188
- obfuscated += maskChar;
7189
- maskCharIndex += 1;
7190
- continue;
7191
- }
7192
-
7193
- break;
7194
- } // value equals mask: add to masked result and advance on both mask and value indexes
7195
-
7196
-
7197
- if (maskChar === valueChar) {
7198
- masked += maskChar;
7199
- obfuscated += maskChar;
7200
- valueCharIndex += 1;
7201
- maskCharIndex += 1;
7202
- continue;
7203
- }
7204
-
7205
- let unmaskedValueChar = text[valueCharIndex]; // it's a regex maskChar: let's advance on value index and validate the value within the regex
7206
-
7207
- if (typeof maskChar === 'object') {
7208
- // advance on value index
7209
- valueCharIndex += 1;
7210
- const shouldObsfucateChar = Array.isArray(maskChar);
7211
- const maskCharRegex = Array.isArray(maskChar) ? maskChar[0] : maskChar;
7212
- const matchRegex = RegExp(maskCharRegex).test(valueChar); // value match regex: add to masked and unmasked result and advance on mask index too
7213
-
7214
- if (matchRegex) {
7215
- masked += valueChar;
7216
- obfuscated += shouldObsfucateChar ? obfuscationCharacter : valueChar;
7217
- unmasked += unmaskedValueChar;
7218
- maskCharIndex += 1;
7219
- }
7220
-
7221
- continue;
7222
- } else {
7223
- // it's a fixed maskChar: add to maskedResult and advance on mask index
7224
- masked += maskChar;
7225
- obfuscated += maskChar;
7226
- maskCharIndex += 1;
7227
- continue;
7228
- }
7229
- }
7230
-
7231
- return {
7232
- masked,
7233
- unmasked,
7234
- obfuscated
7235
- };
7236
- }
7237
-
7238
- var useMaskedInputProps = (props => {
7239
- const {
7240
- value,
7241
- mask,
7242
- onChangeText,
7243
- placeholderFillCharacter = '_',
7244
- obfuscationCharacter,
7245
- showObfuscatedValue,
7246
- maskAutoComplete
7247
- } = props;
7248
- const maskArray = React.useMemo(() => typeof mask === 'function' ? mask(value) : mask, [mask, value]);
7249
- const formattedValueResult = React.useMemo(() => {
7250
- return formatWithMask({
7251
- text: value || '',
7252
- mask,
7253
- obfuscationCharacter
7254
- });
7255
- }, [mask, obfuscationCharacter, value]);
7256
- const maskHasObfuscation = React.useMemo(() => maskArray && !!maskArray.find(maskItem => Array.isArray(maskItem)), [maskArray]);
7257
- const isValueObfuscated = React.useMemo(() => !!maskHasObfuscation && !!showObfuscatedValue, [maskHasObfuscation, showObfuscatedValue]);
7258
- const handleChangeText = React.useCallback(text => {
7259
- let textToFormat = text;
7260
-
7261
- if (isValueObfuscated) {
7262
- textToFormat = formattedValueResult.masked || '';
7263
-
7264
- if (textToFormat.length > text.length) {
7265
- textToFormat = textToFormat.slice(0, -1);
7266
- } else if (textToFormat.length < text.length) {
7267
- textToFormat = textToFormat + text[text.length - 1];
7268
- }
7269
- }
7270
-
7271
- const result = formatWithMask({
7272
- text: textToFormat,
7273
- mask,
7274
- obfuscationCharacter,
7275
- maskAutoComplete: maskAutoComplete && textToFormat.length > formattedValueResult.masked.length
7276
- });
7277
- onChangeText && onChangeText(result.masked, result.unmasked, result.obfuscated);
7278
- }, [isValueObfuscated, mask, obfuscationCharacter, onChangeText, formattedValueResult.masked, maskAutoComplete]);
7279
- const defaultPlaceholder = React.useMemo(() => {
7280
- if (maskArray) {
7281
- return maskArray.map(maskChar => {
7282
- if (typeof maskChar === 'string') {
7283
- return maskChar;
7284
- } else {
7285
- return placeholderFillCharacter;
7286
- }
7287
- }).join('');
7288
- } else {
7289
- return undefined;
7290
- }
7291
- }, [maskArray, placeholderFillCharacter]);
7292
- const inputValue = isValueObfuscated ? formattedValueResult.obfuscated : formattedValueResult.masked;
7293
- return {
7294
- onChangeText: handleChangeText,
7295
- value: inputValue,
7296
- selection: isValueObfuscated ? {
7297
- start: inputValue.length,
7298
- end: inputValue.length
7299
- } : undefined,
7300
- placeholder: defaultPlaceholder
7301
- };
7302
- });
7303
-
7304
- function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
7305
- var MaskInput = /*#__PURE__*/React.forwardRef(function (props, ref) {
7306
- const {
7307
- mask,
7308
- value,
7309
- onChangeText,
7310
- placeholderFillCharacter = '_',
7311
- obfuscationCharacter,
7312
- showObfuscatedValue,
7313
- selection,
7314
- maskAutoComplete,
7315
- ...rest
7316
- } = props;
7317
- const maskedInputProps = useMaskedInputProps({
7318
- value,
7319
- mask,
7320
- maskAutoComplete,
7321
- obfuscationCharacter,
7322
- onChangeText,
7323
- placeholderFillCharacter,
7324
- showObfuscatedValue
7325
- });
7326
- return /*#__PURE__*/React.createElement(TextInput, _extends({
7327
- placeholder: maskedInputProps.placeholder
7328
- }, rest, {
7329
- selection: maskedInputProps.selection || selection,
7330
- value: maskedInputProps.value,
7331
- onChangeText: maskedInputProps.onChangeText,
7332
- ref: ref
7333
- }));
7334
- });
7335
-
7336
- const EvervaultInputContext = createContext({
7337
- validationMode: "all",
7338
- });
7339
- function useForwardedInputRef(ref) {
7340
- const inputRef = useRef(null);
7341
- useImperativeHandle(ref, useCallback(() => ({
7342
- isFocused() {
7343
- return inputRef.current?.isFocused() ?? false;
7344
- },
7345
- focus() {
7346
- inputRef.current?.focus();
7347
- },
7348
- blur() {
7349
- inputRef.current?.blur();
7350
- },
7351
- clear() {
7352
- inputRef.current?.clear();
7353
- },
7354
- measure(callback) {
7355
- inputRef.current?.measure(callback);
7356
- },
7357
- measureInWindow(callback) {
7358
- inputRef.current?.measureInWindow(callback);
7359
- },
7360
- measureLayout(relativeToNativeComponentRef, onSuccess, onFail) {
7361
- inputRef.current?.measureLayout(relativeToNativeComponentRef, onSuccess, onFail);
7362
- },
7363
- }), [inputRef]));
7364
- return inputRef;
7365
- }
7366
- function mask(format) {
7367
- const maskArray = [];
7368
- let isObfuscated = false;
7369
- format.split("").forEach((char) => {
7370
- if (char === "[") {
7371
- isObfuscated = true;
7372
- return;
7373
- }
7374
- else if (char === "]") {
7375
- isObfuscated = false;
7376
- return;
7377
- }
7378
- let value = char;
7379
- if (char === "9") {
7380
- value = isObfuscated ? [/\d/] : /\d/;
7381
- }
7382
- maskArray.push(value);
7383
- });
7384
- return maskArray;
7385
- }
7386
- const EvervaultInput = forwardRef(function EvervaultInput({ name, mask, obfuscateValue, ...props }, ref) {
7387
- const { validationMode } = useContext(EvervaultInputContext);
7388
- const inputRef = useForwardedInputRef(ref);
7389
- const methods = useFormContext();
7390
- const { field, fieldState } = useController({
7391
- control: methods.control,
7392
- name,
7393
- shouldUnregister: true,
7394
- });
7395
- const obfuscationCharacter = useMemo(() => {
7396
- if (typeof obfuscateValue === "string") {
7397
- return obfuscateValue;
7398
- }
7399
- else {
7400
- return "•";
7401
- }
7402
- }, [obfuscateValue]);
7403
- return (jsx(MaskInput
7404
- // Overridable props
7405
- , {
7406
- // Overridable props
7407
- id: field.name, ...props,
7408
- // Strict props
7409
- ref: mergeRefs(inputRef, field.ref), editable: !field.disabled && (props.editable ?? true), onBlur: (evt) => {
7410
- const shouldValidate = validationMode === "onBlur" ||
7411
- validationMode === "onTouched" ||
7412
- validationMode === "all";
7413
- methods.setValue(field.name, field.value, {
7414
- shouldDirty: true,
7415
- shouldTouch: true,
7416
- shouldValidate,
7417
- });
7418
- props.onBlur?.(evt);
7419
- }, mask: mask, maskAutoComplete: !!mask, obfuscationCharacter: obfuscationCharacter, showObfuscatedValue: !!obfuscateValue, value: field.value, onChangeText: (masked, unmasked) => {
7420
- const shouldValidate = (validationMode === "onTouched" && fieldState.isTouched) ||
7421
- ((validationMode === "onChange" || validationMode === "all") &&
7422
- (!!fieldState.error || fieldState.isTouched));
7423
- methods.setValue(field.name, unmasked, {
7424
- shouldDirty: true,
7425
- shouldValidate,
7426
- });
7427
- },
7428
- // Remove unwanted props
7429
- defaultValue: undefined, onChange: undefined }));
7430
- });
7431
-
7432
- const DEFAULT_ACCEPTED_BRANDS = [];
7433
- const Card$1 = forwardRef(function Card({ children, defaultValues, onChange, onError, acceptedBrands = DEFAULT_ACCEPTED_BRANDS, validationMode = "all", }, ref) {
7434
- const evervault = useEvervault();
7435
- const resolver = useMemo(() => {
7436
- const schema = getCardFormSchema(acceptedBrands);
7437
- return s(schema);
7438
- }, [acceptedBrands]);
7439
- const methods = useForm({
7440
- defaultValues,
7441
- resolver,
7442
- mode: validationMode,
7443
- shouldUseNativeValidation: false,
7444
- });
7445
- const inputContext = useMemo(() => ({
7446
- validationMode,
7447
- }), [validationMode]);
7448
- // Use refs to prevent closures from being captured
7449
- const onChangeRef = useRef(onChange);
7450
- onChangeRef.current = onChange;
7451
- const onErrorRef = useRef(onError);
7452
- onErrorRef.current = onError;
7453
- useEffect(() => {
7454
- if (!onChange)
7455
- return;
7456
- let abortController;
7457
- function handleChange(values) {
7458
- if (abortController) {
7459
- abortController.abort();
7460
- }
7461
- abortController = new AbortController();
7462
- const signal = abortController.signal;
7463
- requestAnimationFrame(async () => {
7464
- try {
7465
- const payload = await formatPayload(values, {
7466
- encrypt: evervault.encrypt,
7467
- form: methods,
7468
- });
7469
- if (signal.aborted)
7470
- return;
7471
- onChangeRef.current?.(payload);
7472
- }
7473
- catch (error) {
7474
- onErrorRef.current?.(error);
7475
- }
7476
- });
7477
- }
7478
- handleChange(methods.getValues());
7479
- const subscription = methods.watch(handleChange);
7480
- return () => subscription.unsubscribe();
7481
- }, [evervault.encrypt]);
7482
- useImperativeHandle(ref, useCallback(() => ({
7483
- reset() {
7484
- methods.reset();
7485
- },
7486
- }), []));
7487
- return (jsx(FormProvider, { ...methods, children: jsx(EvervaultInputContext.Provider, { value: inputContext, children: children }) }));
7488
- });
7489
-
7490
- const CardHolder = forwardRef(function CardHolder(props, ref) {
7491
- return (jsx(EvervaultInput, { placeholder: "Johnny Appleseed", ...props, ref: ref, name: "name", inputMode: "text", autoComplete: Platform.select({
7492
- ios: "cc-name",
7493
- default: "name",
7494
- }), keyboardType: "default" }));
7495
- });
7496
-
7497
- const CARD_EXPIRY_MASK = mask("99 / 99");
7498
- const CardExpiry = forwardRef(function CardExpiry(props, ref) {
7499
- return (jsx(EvervaultInput, { placeholder: "MM / YY", ...props, ref: ref, name: "expiry", mask: CARD_EXPIRY_MASK, inputMode: "numeric", autoComplete: "cc-exp", keyboardType: "number-pad" }));
7500
- });
7501
-
7502
- const DEFAULT_CARD_CVC_MASK = mask("[999]");
7503
- const CARD_CVC_MASKS = {
7504
- "american-express": mask("[9999]"),
7505
- };
7506
- const CardCvc = forwardRef(function CardCvc(props, ref) {
7507
- const methods = useFormContext();
7508
- const number = methods.watch("number");
7509
- const mask = useMemo(() => {
7510
- if (!number) {
7511
- return DEFAULT_CARD_CVC_MASK;
7512
- }
7513
- const brand = C(number).brand;
7514
- if (brand && CARD_CVC_MASKS[brand]) {
7515
- return CARD_CVC_MASKS[brand];
7516
- }
7517
- return DEFAULT_CARD_CVC_MASK;
7518
- }, [number]);
7519
- return (jsx(EvervaultInput, { placeholder: "CVC", ...props, ref: ref, name: "cvc", mask: mask, inputMode: "numeric", autoComplete: "cc-csc", keyboardType: "number-pad" }));
7520
- });
7521
-
7522
- const DEFAULT_CARD_NUMBER_MASK = mask("9999 99[99 9999 9999]");
7523
- const CARD_NUMBER_MASKS = {
7524
- unionpay: mask("9999 99[99 9999 9999 999]"),
7525
- "american-express": mask("9999 99[9999 99999]"),
7526
- };
7527
- const CardNumber = forwardRef(function CardNumber(props, ref) {
7528
- const mask = useCallback((text) => {
7529
- if (!text) {
7530
- return DEFAULT_CARD_NUMBER_MASK;
7531
- }
7532
- const brand = C(text).brand;
7533
- if (brand && CARD_NUMBER_MASKS[brand]) {
7534
- return CARD_NUMBER_MASKS[brand];
7535
- }
7536
- return DEFAULT_CARD_NUMBER_MASK;
7537
- }, []);
7538
- return (jsx(EvervaultInput, { placeholder: "1234 1234 1234 1234", ...props, ref: ref, name: "number", mask: mask, inputMode: "numeric", autoComplete: "cc-number", keyboardType: "number-pad" }));
7539
- });
7540
-
7541
- const Card = Object.assign(Card$1, {
7542
- Holder: CardHolder,
7543
- Expiry: CardExpiry,
7544
- Cvc: CardCvc,
7545
- Number: CardNumber,
7546
- });
7547
-
7548
- const ThreeDSecureContext = createContext(null);
7549
-
7550
- function ThreeDSecure$1({ state, children }) {
7551
- useEvervault();
7552
- if (!state.session)
7553
- return null;
7554
- return (jsx(ThreeDSecureContext.Provider, { value: state, children: state.isVisible && children }));
7555
- }
7556
-
7557
- const EV_API_DOMAIN = process.env.EV_API_DOMAIN || "api.evervault.com";
7558
- const CHALLENGE_DOMAIN_3DS = process.env.CHALLENGE_DOMAIN_3DS || "3ds.evervault.com";
7559
-
7560
- function ThreeDSecureFrame({ style }) {
7561
- const evervault = useEvervault();
7562
- const context = useContext(ThreeDSecureContext);
7563
- if (!context) {
7564
- throw new Error("`ThreeDSecure.Frame` must be used within a `ThreeDSecure` component.");
7565
- }
7566
- const uri = useMemo(() => {
7567
- if (!context.session)
7568
- return null;
7569
- const params = new URLSearchParams();
7570
- params.set("session", context.session.sessionId);
7571
- params.set("app", evervault.appId);
7572
- params.set("team", evervault.teamId);
7573
- return `https://${CHALLENGE_DOMAIN_3DS}/?${params.toString()}`;
7574
- }, [context.session, evervault.appId, evervault.teamId]);
7575
- if (!uri)
7576
- return null;
7577
- return (jsx(WebView, { containerStyle: [defaultStyles.webView, style], source: { uri }, hideKeyboardAccessoryView: true, overScrollMode: "content" }));
7578
- }
7579
- const defaultStyles = StyleSheet.create({
7580
- webView: {
7581
- flex: 1,
7582
- width: "100%",
7583
- },
7584
- });
7585
-
7586
- class ThreeDSecureEvent {
7587
- type;
7588
- session;
7589
- _defaultPrevented;
7590
- constructor(type, session, _defaultPrevented = false) {
7591
- this.type = type;
7592
- this.session = session;
7593
- this._defaultPrevented = _defaultPrevented;
7594
- }
7595
- preventDefault() {
7596
- this._defaultPrevented = true;
7597
- }
7598
- get defaultPrevented() {
7599
- return this._defaultPrevented;
7600
- }
7601
- }
7602
-
7603
- function stopPolling(intervalRef, setIsVisible) {
7604
- setIsVisible(false);
7605
- if (intervalRef.current) {
7606
- clearInterval(intervalRef.current);
7607
- intervalRef.current = null;
7608
- }
7609
- }
7610
- async function startSession(session, options, intervalRef, setIsVisible) {
7611
- try {
7612
- const sessionState = await session.get();
7613
- function fail() {
7614
- stopPolling(intervalRef, setIsVisible);
7615
- options?.onFailure?.(new Error("3DS session failed"));
7616
- }
7617
- switch (sessionState.status) {
7618
- case "success": {
7619
- stopPolling(intervalRef, setIsVisible);
7620
- options?.onSuccess?.();
7621
- break;
7622
- }
7623
- case "failure": {
7624
- fail();
7625
- break;
7626
- }
7627
- case "action-required": {
7628
- const failOnChallenge = typeof options?.failOnChallenge === "function"
7629
- ? await options.failOnChallenge()
7630
- : options?.failOnChallenge ?? false;
7631
- if (failOnChallenge) {
7632
- fail();
7633
- break;
7634
- }
7635
- const event = new ThreeDSecureEvent("requestChallenge", session);
7636
- options?.onRequestChallenge?.(event);
7637
- if (event.defaultPrevented) {
7638
- fail();
7639
- break;
7640
- }
7641
- setIsVisible(true);
7642
- pollSession(session, options, intervalRef, setIsVisible);
7643
- }
7644
- }
7645
- }
7646
- catch (error) {
7647
- console.error("Error checking session state", error);
7648
- options?.onError?.(new Error("Failed to check 3DS session state"));
7649
- }
7650
- }
7651
- function pollSession(session, options, intervalRef, setIsVisible, interval = 3000) {
7652
- function fail() {
7653
- stopPolling(intervalRef, setIsVisible);
7654
- options?.onFailure?.(new Error("3DS session failed"));
7655
- }
7656
- intervalRef.current = setInterval(async () => {
7657
- try {
7658
- const pollResponse = await session.get();
7659
- switch (pollResponse.status) {
7660
- case "success": {
7661
- stopPolling(intervalRef, setIsVisible);
7662
- options?.onSuccess?.();
7663
- break;
7664
- }
7665
- case "failure": {
7666
- fail();
7667
- break;
7668
- }
7669
- case "action-required": {
7670
- const failOnChallenge = typeof options?.failOnChallenge === "function"
7671
- ? await options.failOnChallenge()
7672
- : options?.failOnChallenge ?? false;
7673
- if (failOnChallenge) {
7674
- fail();
7675
- break;
7676
- }
7677
- const event = new ThreeDSecureEvent("requestChallenge", session);
7678
- options?.onRequestChallenge?.(event);
7679
- if (event.defaultPrevented) {
7680
- fail();
7681
- break;
7682
- }
7683
- setIsVisible(true);
7684
- }
7685
- }
7686
- }
7687
- catch (error) {
7688
- stopPolling(intervalRef, setIsVisible);
7689
- console.error("Error polling session", error);
7690
- options?.onError?.(new Error("Error polling 3DS session"));
7691
- }
7692
- }, interval);
7693
- }
7694
- function threeDSecureSession({ sessionId, appId, options, intervalRef, setIsVisible, }) {
7695
- async function get() {
7696
- try {
7697
- const response = await fetch(`https://${EV_API_DOMAIN}/frontend/3ds/browser-sessions/${sessionId}`, {
7698
- headers: {
7699
- "x-evervault-app-id": appId,
7700
- },
7701
- });
7702
- const result = (await response.json());
7703
- return result;
7704
- }
7705
- catch (error) {
7706
- console.error("Error fetching 3DS session status", error);
7707
- throw error;
7708
- }
7709
- }
7710
- async function cancel() {
7711
- try {
7712
- await fetch(`https://${EV_API_DOMAIN}/frontend/3ds/browser-sessions/${sessionId}`, {
7713
- method: "PATCH",
7714
- headers: {
7715
- "Content-Type": "application/json",
7716
- "x-evervault-app-id": appId,
7717
- },
7718
- body: JSON.stringify({ outcome: "cancelled" }),
7719
- });
7720
- options?.onFailure?.(new Error("3DS session cancelled by user"));
7721
- stopPolling(intervalRef, setIsVisible);
7722
- }
7723
- catch (error) {
7724
- console.error("Error cancelling 3DS session", error);
7725
- throw error;
7726
- }
7727
- }
7728
- return {
7729
- sessionId,
7730
- get,
7731
- cancel,
7732
- };
7733
- }
7734
-
7735
- function useThreeDSecure(options) {
7736
- const { appId } = useEvervault();
7737
- const intervalRef = useRef(null);
7738
- const [session, setSession] = useState(null);
7739
- const [isVisible, setIsVisible] = useState(false);
7740
- const failOnChallenge = options?.failOnChallenge ?? false;
7741
- const start = useCallback((sessionId, options) => {
7742
- const startOptions = {
7743
- ...options,
7744
- failOnChallenge: options?.failOnChallenge ?? failOnChallenge,
7745
- };
7746
- const session = threeDSecureSession({
7747
- sessionId,
7748
- appId,
7749
- options: startOptions,
7750
- intervalRef,
7751
- setIsVisible,
7752
- });
7753
- setSession(session);
7754
- startSession(session, startOptions, intervalRef, setIsVisible);
7755
- }, [appId, failOnChallenge]);
7756
- const cancel = useCallback(async () => {
7757
- if (session) {
7758
- await session.cancel();
7759
- }
7760
- else {
7761
- console.warn("No 3DS session to cancel");
7762
- }
7763
- }, [session]);
7764
- return useMemo(() => ({
7765
- start,
7766
- cancel,
7767
- session,
7768
- isVisible,
7769
- }), [start, cancel, session, isVisible]);
7770
- }
7771
-
7772
- const ThreeDSecure = Object.assign(ThreeDSecure$1, {
7773
- Frame: ThreeDSecureFrame,
7774
- });
7775
-
7776
- const verifyInstallation = sdk.verify;
7777
-
7778
- export { Card, CardCvc, CardExpiry, CardHolder, CardNumber, EvervaultProvider, ThreeDSecure, useEvervault, useThreeDSecure, verifyInstallation };
4402
+ export { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };