@visiion/forms-library 1.0.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.
@@ -0,0 +1,2822 @@
1
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
2
+ import React, { useState, useEffect, useRef } from 'react';
3
+
4
+ /******************************************************************************
5
+ Copyright (c) Microsoft Corporation.
6
+
7
+ Permission to use, copy, modify, and/or distribute this software for any
8
+ purpose with or without fee is hereby granted.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
11
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
15
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16
+ PERFORMANCE OF THIS SOFTWARE.
17
+ ***************************************************************************** */
18
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
19
+
20
+
21
+ var __assign$1 = function() {
22
+ __assign$1 = Object.assign || function __assign(t) {
23
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
24
+ s = arguments[i];
25
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
26
+ }
27
+ return t;
28
+ };
29
+ return __assign$1.apply(this, arguments);
30
+ };
31
+
32
+ function __awaiter(thisArg, _arguments, P, generator) {
33
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
34
+ return new (P || (P = Promise))(function (resolve, reject) {
35
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
36
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
37
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
38
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
39
+ });
40
+ }
41
+
42
+ function __generator(thisArg, body) {
43
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
44
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
45
+ function verb(n) { return function (v) { return step([n, v]); }; }
46
+ function step(op) {
47
+ if (f) throw new TypeError("Generator is already executing.");
48
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
49
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
50
+ if (y = 0, t) op = [op[0] & 2, t.value];
51
+ switch (op[0]) {
52
+ case 0: case 1: t = op; break;
53
+ case 4: _.label++; return { value: op[1], done: false };
54
+ case 5: _.label++; y = op[1]; op = [0]; continue;
55
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
56
+ default:
57
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
58
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
59
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
60
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
61
+ if (t[2]) _.ops.pop();
62
+ _.trys.pop(); continue;
63
+ }
64
+ op = body.call(thisArg, _);
65
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
66
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
67
+ }
68
+ }
69
+
70
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
71
+ var e = new Error(message);
72
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
73
+ };
74
+
75
+ var DefaultContext = {
76
+ color: undefined,
77
+ size: undefined,
78
+ className: undefined,
79
+ style: undefined,
80
+ attr: undefined
81
+ };
82
+ var IconContext = React.createContext && React.createContext(DefaultContext);
83
+
84
+ var __assign = undefined && undefined.__assign || function () {
85
+ __assign = Object.assign || function (t) {
86
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
87
+ s = arguments[i];
88
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
89
+ }
90
+ return t;
91
+ };
92
+ return __assign.apply(this, arguments);
93
+ };
94
+ var __rest = undefined && undefined.__rest || function (s, e) {
95
+ var t = {};
96
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
97
+ if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
98
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
99
+ }
100
+ return t;
101
+ };
102
+ function Tree2Element(tree) {
103
+ return tree && tree.map(function (node, i) {
104
+ return React.createElement(node.tag, __assign({
105
+ key: i
106
+ }, node.attr), Tree2Element(node.child));
107
+ });
108
+ }
109
+ function GenIcon(data) {
110
+ // eslint-disable-next-line react/display-name
111
+ return function (props) {
112
+ return React.createElement(IconBase, __assign({
113
+ attr: __assign({}, data.attr)
114
+ }, props), Tree2Element(data.child));
115
+ };
116
+ }
117
+ function IconBase(props) {
118
+ var elem = function (conf) {
119
+ var attr = props.attr,
120
+ size = props.size,
121
+ title = props.title,
122
+ svgProps = __rest(props, ["attr", "size", "title"]);
123
+ var computedSize = size || conf.size || "1em";
124
+ var className;
125
+ if (conf.className) className = conf.className;
126
+ if (props.className) className = (className ? className + " " : "") + props.className;
127
+ return React.createElement("svg", __assign({
128
+ stroke: "currentColor",
129
+ fill: "currentColor",
130
+ strokeWidth: "0"
131
+ }, conf.attr, attr, svgProps, {
132
+ className: className,
133
+ style: __assign(__assign({
134
+ color: props.color || conf.color
135
+ }, conf.style), props.style),
136
+ height: computedSize,
137
+ width: computedSize,
138
+ xmlns: "http://www.w3.org/2000/svg"
139
+ }), title && React.createElement("title", null, title), props.children);
140
+ };
141
+ return IconContext !== undefined ? React.createElement(IconContext.Consumer, null, function (conf) {
142
+ return elem(conf);
143
+ }) : elem(DefaultContext);
144
+ }
145
+
146
+ // THIS FILE IS AUTO GENERATED
147
+ function IoHelpCircle (props) {
148
+ return GenIcon({"attr":{"viewBox":"0 0 512 512"},"child":[{"tag":"path","attr":{"d":"M256 64C150 64 64 150 64 256s86 192 192 192 192-86 192-192S362 64 256 64zm-6 304a20 20 0 1120-20 20 20 0 01-20 20zm33.44-102C267.23 276.88 265 286.85 265 296a14 14 0 01-28 0c0-21.91 10.08-39.33 30.82-53.26C287.1 229.8 298 221.6 298 203.57c0-12.26-7-21.57-21.49-28.46-3.41-1.62-11-3.2-20.34-3.09-11.72.15-20.82 2.95-27.83 8.59C215.12 191.25 214 202.83 214 203a14 14 0 11-28-1.35c.11-2.43 1.8-24.32 24.77-42.8 11.91-9.58 27.06-14.56 45-14.78 12.7-.15 24.63 2 32.72 5.82C312.7 161.34 326 180.43 326 203.57c0 33.83-22.61 49.02-42.56 62.43z"}}]})(props);
149
+ }
150
+
151
+ var InputWrapper = function (_a) {
152
+ var label = _a.label, error = _a.error, tooltip = _a.tooltip, required = _a.required, children = _a.children, _b = _a.className, className = _b === void 0 ? '' : _b;
153
+ return (jsxs("fieldset", { className: "flex max-w-1xl mx-auto flex-col gap-4 w-full ".concat(className), children: [label && (jsxs("div", { className: "flex items-center gap-2", children: [jsxs("label", { className: "font-roboto font-medium text-gray-700 text-sm leading-4", children: [label, required && jsx("span", { className: "text-red-500 ml-1", children: "*" })] }), tooltip && (jsxs("div", { className: "relative group flex-shrink-0", children: [jsx(IoHelpCircle, { className: "w-5 h-5 text-gray-400 cursor-help" }), jsxs("div", { className: "absolute left-full top-1/2 transform -translate-y-1/2 ml-2 px-3 py-2 bg-gray-800 text-white text-sm rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none whitespace-nowrap z-10", children: [tooltip, jsx("div", { className: "absolute top-1/2 right-full transform -translate-y-1/2 w-0 h-0 border-t-4 border-b-4 border-r-4 border-transparent border-r-gray-800" })] })] }))] })), children, error && (jsx("p", { className: "text-red-500 text-xs mt-1", children: error }))] }));
154
+ };
155
+
156
+ var TextInput = function (_a) {
157
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error;
158
+ return (jsx(InputWrapper, { label: field.label, error: error, tooltip: field.tooltip, required: field.required, children: jsxs("div", { className: "relative", children: [jsx("input", { id: field.id, name: field.name, type: "text", placeholder: field.placeholder, value: value || '', onChange: onChange, disabled: field.disabled, required: field.required, minLength: field.minLength, maxLength: field.maxLength, className: "w-full px-3 py-2 font-roboto font-normal text-gray-800 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 ".concat(error ? 'border-red-500' : 'border-gray-300', " ").concat(field.disabled ? 'bg-gray-100 cursor-not-allowed' : '') }), field.addon && (jsx("span", { className: "absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 text-sm", children: field.addon }))] }) }));
159
+ };
160
+
161
+ var SelectInput = function (_a) {
162
+ var _b;
163
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error;
164
+ return (jsx(InputWrapper, { label: field.label, error: error, tooltip: field.tooltip, required: field.required, children: jsxs("select", { id: field.id, name: field.name, value: value || '', onChange: onChange, disabled: field.disabled, required: field.required, className: "w-full px-3 py-2 font-roboto font-normal text-gray-800 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 ".concat(error ? 'border-red-500' : 'border-gray-300', " ").concat(field.disabled ? 'bg-gray-100 cursor-not-allowed' : ''), children: [jsx("option", { value: "", children: field.placeholder || 'Seleccione una opción' }), Array.isArray(field === null || field === void 0 ? void 0 : field.options) &&
165
+ ((_b = field === null || field === void 0 ? void 0 : field.options) === null || _b === void 0 ? void 0 : _b.map(function (option) { return (jsx("option", { value: option.value, children: option.label }, option.value)); }))] }) }));
166
+ };
167
+
168
+ var CheckboxInput = function (_a) {
169
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error;
170
+ return (jsxs("div", { className: "flex flex-col gap-2", children: [jsxs("div", { className: "flex items-center gap-2", children: [jsx("input", { id: field.id, name: field.name, type: "checkbox", checked: value || false, onChange: onChange, disabled: field.disabled, required: field.required, className: "w-4 h-4 text-orange-600 border-gray-300 rounded focus:ring-orange-500" }), jsxs("label", { htmlFor: field.id, className: "font-medium text-gray-700 cursor-pointer", children: [field.label, field.required && jsx("span", { className: "text-red-500 ml-1", children: "*" })] })] }), error && jsx("span", { className: "text-red-500 text-xs", children: error })] }));
171
+ };
172
+
173
+ var TextareaInput = function (_a) {
174
+ var field = _a.field, _b = _a.value, value = _b === void 0 ? '' : _b, onChange = _a.onChange, error = _a.error, id = _a.id, name = _a.name, label = _a.label, placeholder = _a.placeholder, className = _a.className, disabled = _a.disabled, required = _a.required, _c = _a.maxLength, maxLength = _c === void 0 ? 500 : _c, _d = _a.rows, rows = _d === void 0 ? 4 : _d, tooltip = _a.tooltip;
175
+ var _e = useState(value.length), charCount = _e[0], setCharCount = _e[1];
176
+ // Si se pasa un field, usar sus propiedades
177
+ var finalId = id || (field === null || field === void 0 ? void 0 : field.id);
178
+ var finalName = name || (field === null || field === void 0 ? void 0 : field.name);
179
+ var finalLabel = label || (field === null || field === void 0 ? void 0 : field.label);
180
+ var finalPlaceholder = placeholder || (field === null || field === void 0 ? void 0 : field.placeholder);
181
+ var finalDisabled = disabled !== undefined ? disabled : field === null || field === void 0 ? void 0 : field.disabled;
182
+ var finalRequired = required !== undefined ? required : field === null || field === void 0 ? void 0 : field.required;
183
+ var finalMaxLength = maxLength || (field === null || field === void 0 ? void 0 : field.maxLength) || 500;
184
+ var finalTooltip = tooltip || (field === null || field === void 0 ? void 0 : field.tooltip);
185
+ useEffect(function () {
186
+ setCharCount(value.length);
187
+ }, [value]);
188
+ var handleChange = function (e) {
189
+ var newValue = e.target.value;
190
+ if (newValue.length <= finalMaxLength) {
191
+ setCharCount(newValue.length);
192
+ if (onChange) {
193
+ // Crear un evento sintético compatible
194
+ var syntheticEvent = __assign$1(__assign$1({}, e), { target: __assign$1(__assign$1({}, e.target), { name: finalName || '', value: newValue }) });
195
+ onChange(syntheticEvent);
196
+ }
197
+ }
198
+ };
199
+ return (jsx(InputWrapper, { label: finalLabel, tooltip: finalTooltip, required: finalRequired, error: error, children: jsxs("div", { className: "space-y-2", children: [jsx("textarea", { id: finalId, name: finalName, placeholder: finalPlaceholder, value: value, onChange: handleChange, disabled: finalDisabled, required: finalRequired, rows: rows, className: "w-full px-3 py-2 font-roboto font-normal text-gray-800 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 resize-none ".concat(error ? 'border-red-500' : 'border-gray-300', " ").concat(finalDisabled ? 'bg-gray-100 cursor-not-allowed' : '', " ").concat(className || '') }), jsxs("div", { className: "flex justify-end text-gray-400 text-sm", children: [charCount, "/", finalMaxLength] })] }) }));
200
+ };
201
+
202
+ function clean(rut) {
203
+ return typeof rut === 'string' ? rut.replace(/^0+|[^0-9kK]+/g, '').toUpperCase() : '';
204
+ }
205
+ function formatRut(rut) {
206
+ rut = clean(rut);
207
+ var result = '';
208
+ if (rut.length > 0) {
209
+ result = "".concat(rut.slice(-4, -1), "-").concat(rut.substr(rut.length - 1));
210
+ }
211
+ for (var i = 4; i < rut.length; i += 3) {
212
+ result = "".concat(rut.slice(-3 - i, -i), ".").concat(result);
213
+ }
214
+ return result;
215
+ }
216
+ var serialRegex = /^[a-zA-Z0-9]+$/;
217
+ var validateOnlyNumbersAndLetters = function (value) {
218
+ if (value === '')
219
+ return true;
220
+ return serialRegex.test(value);
221
+ };
222
+ function validate(rut) {
223
+ if (typeof rut !== 'string') {
224
+ return false;
225
+ }
226
+ if (!/^0*(\d{1,3}(\.?\d{3})*)-?([\dkK])$/.test(rut)) {
227
+ return false;
228
+ }
229
+ rut = clean(rut);
230
+ var t = parseInt(rut.slice(0, -1), 10);
231
+ var m = 0;
232
+ var s = 1;
233
+ while (t > 0) {
234
+ // eslint-disable-next-line
235
+ s = (s + (t % 10) * (9 - (m++ % 6))) % 11;
236
+ t = Math.floor(t / 10);
237
+ }
238
+ var v = s > 0 ? "".concat(s - 1) : 'k';
239
+ return v.toLowerCase() === rut.slice(-1).toLowerCase();
240
+ }
241
+ /**
242
+ * Enmascara un RUT ocultando los dígitos del medio
243
+ * @param rut - RUT formateado (ej: "19.178.946-6")
244
+ * @returns RUT enmascarado (ej: "19.178.XXX-6")
245
+ */
246
+ function maskRut(rut) {
247
+ if (!rut || typeof rut !== 'string') {
248
+ return '';
249
+ }
250
+ // Limpiar el RUT para obtener solo números y dígito verificador
251
+ var cleanRut = clean(rut);
252
+ if (cleanRut.length < 2) {
253
+ return rut;
254
+ }
255
+ // Separar el dígito verificador
256
+ var numbers = cleanRut.slice(0, -1);
257
+ // Si el RUT tiene menos de 4 dígitos, no enmascarar
258
+ if (numbers.length < 4) {
259
+ return formatRut(cleanRut);
260
+ }
261
+ // Mantener la estructura completa pero enmascarar los dígitos del medio
262
+ var maskedRut = '';
263
+ if (numbers.length <= 3) {
264
+ // Para RUTs de 3 dígitos o menos
265
+ maskedRut = "".concat(numbers, "XXX-X");
266
+ }
267
+ else if (numbers.length <= 6) {
268
+ // Para RUTs de 4-6 dígitos: XX.XXX-X
269
+ var firstPart = numbers.slice(0, 2);
270
+ maskedRut = "".concat(firstPart, ".XXX-X");
271
+ }
272
+ else if (numbers.length === 7) {
273
+ // Para RUTs de 7 dígitos: X.XXX.XXX-X
274
+ var firstPart = numbers.slice(0, 1);
275
+ var secondPart = numbers.slice(1, 4);
276
+ maskedRut = "".concat(firstPart, ".").concat(secondPart, ".XXX-X");
277
+ }
278
+ else if (numbers.length === 8) {
279
+ // Para RUTs de 8 dígitos: XX.XXX.XXX-X
280
+ var firstPart = numbers.slice(0, 2);
281
+ var secondPart = numbers.slice(2, 5);
282
+ maskedRut = "".concat(firstPart, ".").concat(secondPart, ".XXX-X");
283
+ }
284
+ else if (numbers.length <= 9) {
285
+ // Para RUTs de 9 dígitos: XXX.XXX-X
286
+ var firstPart = numbers.slice(0, 3);
287
+ maskedRut = "".concat(firstPart, ".XXX-X");
288
+ }
289
+ else {
290
+ // Para RUTs de más de 9 dígitos: XX.XXX.XXX-X
291
+ var firstPart = numbers.slice(0, 2);
292
+ var secondPart = numbers.slice(2, 5);
293
+ maskedRut = "".concat(firstPart, ".").concat(secondPart, ".XXX-X");
294
+ }
295
+ return maskedRut;
296
+ }
297
+
298
+ var RutInput = function (_a) {
299
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error, onSearch = _a.onSearch, _b = _a.disabled, disabled = _b === void 0 ? false : _b, _c = _a.placeholder, placeholder = _c === void 0 ? '0.000.000-0' : _c, _d = _a.minLength, minLength = _d === void 0 ? 12 : _d, _e = _a.maxLength, maxLength = _e === void 0 ? 12 : _e;
300
+ var inputRef = useRef(null);
301
+ var _f = useState(false), isValidRut = _f[0], setIsValidRut = _f[1];
302
+ var _g = useState(clean(value)), displayValue = _g[0], setDisplayValue = _g[1];
303
+ useEffect(function () {
304
+ setIsValidRut(validate(clean(value)));
305
+ setDisplayValue(formatRut(clean(value)));
306
+ }, [value]);
307
+ // Validar RUT en tiempo real
308
+ var handleRutChange = function (e) {
309
+ var rutValue = e.target.value;
310
+ setIsValidRut(validate(clean(rutValue)));
311
+ onChange(e);
312
+ };
313
+ // Manejar búsqueda
314
+ var handleSearch = function () {
315
+ if (onSearch && value && isValidRut) {
316
+ onSearch(clean(displayValue));
317
+ }
318
+ };
319
+ // Manejar tecla Enter para búsqueda
320
+ var handleKeyDown = function (e) {
321
+ if (e.key === 'Enter' && onSearch && value && isValidRut) {
322
+ e.preventDefault();
323
+ onSearch(clean(displayValue));
324
+ }
325
+ };
326
+ return (jsxs(InputWrapper, { label: field.label, tooltip: field.tooltip, required: field.required, error: error, children: [jsxs("div", { className: "flex", children: [jsx("input", { ref: inputRef, id: field.id, name: field.name, type: "text", value: displayValue || '', onChange: handleRutChange, onKeyDown: handleKeyDown, placeholder: placeholder, minLength: minLength, maxLength: maxLength, disabled: disabled, className: "flex-1 px-3 py-2 border rounded-l-md focus:outline-none focus:ring-2 focus:ring-orange-500 h-10 ".concat(error ? 'border-red-500' : 'border-gray-300', " ").concat(disabled ? 'bg-gray-100 cursor-not-allowed' : '') }), onSearch && (jsx("button", { type: "button", onClick: handleSearch, disabled: !isValidRut || disabled, className: "flex items-center justify-center w-10 h-10 rounded-r-md border-l-0 border bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed ".concat(error ? 'border-red-500' : 'border-gray-300'), children: jsx("svg", { className: "w-5 h-5", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" }) }) }))] }), displayValue && !error && (jsx("span", { className: "text-sm ".concat(isValidRut ? 'text-green-600' : 'text-orange-600'), children: isValidRut ? '✓ RUT válido' : '⚠ Verificar formato del RUT' }))] }));
327
+ };
328
+
329
+ var Alert = function (_a) {
330
+ var _b = _a.type, type = _b === void 0 ? 'info' : _b, text = _a.text, icon = _a.icon, _c = _a.className, className = _c === void 0 ? '' : _c, _d = _a.iconClassName, iconClassName = _d === void 0 ? 'w-5 h-5' : _d, _e = _a.textClassName, textClassName = _e === void 0 ? 'ml-2 text-sm' : _e;
331
+ var getAlertStyles = function () {
332
+ switch (type) {
333
+ case 'info':
334
+ return 'bg-blue-50 border-blue-200 text-blue-800';
335
+ case 'warning':
336
+ return 'bg-yellow-50 border-yellow-200 text-yellow-800';
337
+ case 'error':
338
+ return 'bg-red-50 border-red-200 text-red-800';
339
+ default:
340
+ return 'bg-blue-50 border-blue-200 text-blue-800';
341
+ }
342
+ };
343
+ var getIcon = function () {
344
+ if (icon) {
345
+ if (typeof icon === 'string') {
346
+ return (jsx("span", { className: iconClassName, dangerouslySetInnerHTML: { __html: icon } }));
347
+ }
348
+ return React.createElement(icon, { className: iconClassName });
349
+ }
350
+ // Iconos por defecto
351
+ switch (type) {
352
+ case 'info':
353
+ return (jsx("svg", { className: iconClassName, fill: "currentColor", viewBox: "0 0 20 20", children: jsx("path", { fillRule: "evenodd", d: "M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z", clipRule: "evenodd" }) }));
354
+ case 'warning':
355
+ return (jsx("svg", { className: iconClassName, fill: "currentColor", viewBox: "0 0 20 20", children: jsx("path", { fillRule: "evenodd", d: "M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z", clipRule: "evenodd" }) }));
356
+ case 'error':
357
+ return (jsx("svg", { className: iconClassName, fill: "currentColor", viewBox: "0 0 20 20", children: jsx("path", { fillRule: "evenodd", d: "M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z", clipRule: "evenodd" }) }));
358
+ default:
359
+ return null;
360
+ }
361
+ };
362
+ return (jsxs("div", { className: "flex items-center p-4 border rounded-lg ".concat(getAlertStyles(), " ").concat(className), children: [getIcon(), jsx("span", { className: textClassName, dangerouslySetInnerHTML: { __html: text || '' } })] }));
363
+ };
364
+
365
+ var DynamicInput = function (_a) {
366
+ var _b, _c;
367
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error;
368
+ switch (field.type) {
369
+ case 'select':
370
+ return (jsx(SelectInput, { field: field, value: value, onChange: onChange, error: error }));
371
+ case 'textarea':
372
+ return (jsx(TextareaInput, { field: field, value: value, onChange: onChange, error: error }));
373
+ case 'checkbox':
374
+ return (jsx(CheckboxInput, { field: field, value: value, onChange: onChange, error: error }));
375
+ case 'rut':
376
+ return (jsx(RutInput, { field: field, value: value, onChange: onChange, error: error, onSearch: field.onSearch, disabled: field.disabled, placeholder: field.placeholder, minLength: field.minLength, maxLength: field.maxLength }));
377
+ case 'alert':
378
+ return jsx(Alert, __assign$1({}, field.props));
379
+ case 'subtitle':
380
+ return (jsxs("div", { className: "col-span-12", children: [jsx("h3", { className: "text-xl font-bold text-gray-800 mb-2", children: ((_b = field.props) === null || _b === void 0 ? void 0 : _b.title) || field.label }), ((_c = field.props) === null || _c === void 0 ? void 0 : _c.description) && (jsx("p", { className: "text-gray-600", children: field.props.description }))] }));
381
+ case 'text':
382
+ default:
383
+ return (jsx(TextInput, { field: field, value: value, onChange: onChange, error: error }));
384
+ }
385
+ };
386
+
387
+ var NavigationButton = function (_a) {
388
+ var direction = _a.direction, onClick = _a.onClick, _b = _a.disabled, disabled = _b === void 0 ? false : _b, _c = _a.label, label = _c === void 0 ? '' : _c;
389
+ var getButtonProps = function () {
390
+ switch (direction) {
391
+ case 'default':
392
+ return {
393
+ className: "flex items-center align-middle text-nowrap w-fit h-[40px] px-4 py-2 bg-white text-[16px] rounded border border-blue-600 text-blue-600 font-medium font-['Roboto'] hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed",
394
+ label: label || 'Volver',
395
+ };
396
+ case 'next':
397
+ return {
398
+ className: "flex items-center align-middle text-nowrap bg-blue-600 disabled:bg-gray-400 w-fit h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] text-white hover:bg-blue-700 disabled:cursor-not-allowed",
399
+ label: label || 'Siguiente',
400
+ icon: (jsx("svg", { className: "ml-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 5l7 7-7 7" }) })),
401
+ };
402
+ case 'back':
403
+ return {
404
+ className: "flex items-center align-middle text-nowrap w-fit h-[40px] px-4 py-2 bg-white text-[16px] rounded border border-blue-600 text-blue-600 font-medium font-['Roboto'] hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed",
405
+ label: label || 'Volver',
406
+ icon: (jsx("svg", { className: "mr-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M15 19l-7-7 7-7" }) })),
407
+ };
408
+ case 'guardar':
409
+ return {
410
+ className: "flex items-center align-middle text-nowrap bg-blue-600 disabled:bg-gray-400 w-fit h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] text-white hover:bg-blue-700 disabled:cursor-not-allowed",
411
+ label: label || 'Guardar',
412
+ icon: (jsx("svg", { className: "mr-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" }) })),
413
+ };
414
+ case 'success':
415
+ return {
416
+ className: "flex items-center align-middle text-nowrap disabled:bg-gray-400 min-w-40 h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] bg-green-600 text-white hover:bg-green-700 disabled:cursor-not-allowed",
417
+ label: label,
418
+ icon: null,
419
+ };
420
+ case 'out-light':
421
+ return {
422
+ className: "flex items-center align-middle text-nowrap w-fit h-[40px] px-4 py-2 bg-white text-[16px] rounded border border-blue-600 text-blue-600 font-medium font-['Roboto'] hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed",
423
+ label: label || 'Salir',
424
+ icon: (jsx("svg", { className: "mr-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" }) })),
425
+ };
426
+ case 'out':
427
+ return {
428
+ className: "flex items-center align-middle text-nowrap bg-blue-600 disabled:bg-gray-400 w-fit h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] text-white hover:bg-blue-700 disabled:cursor-not-allowed",
429
+ label: 'Salir',
430
+ icon: (jsx("svg", { className: "ml-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" }) })),
431
+ };
432
+ default:
433
+ return {
434
+ className: "flex items-center align-middle text-nowrap bg-blue-600 disabled:bg-gray-400 w-fit h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] text-white hover:bg-blue-700 disabled:cursor-not-allowed",
435
+ label: label || 'Siguiente',
436
+ icon: (jsx("svg", { className: "ml-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 5l7 7-7 7" }) })),
437
+ };
438
+ }
439
+ };
440
+ var _d = getButtonProps(), className = _d.className, buttonLabel = _d.label, icon = _d.icon;
441
+ return (jsxs("button", { onClick: onClick, disabled: disabled, className: className, children: [(direction === 'back' || direction === 'out-light' || direction === 'guardar') && icon, buttonLabel, (direction === 'next' || direction === 'out') && icon] }));
442
+ };
443
+
444
+ function getDefaultExportFromCjs (x) {
445
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
446
+ }
447
+
448
+ /**
449
+ * Based on Kendo UI Core expression code <https://github.com/telerik/kendo-ui-core#license-information>
450
+ */
451
+
452
+ function Cache(maxSize) {
453
+ this._maxSize = maxSize;
454
+ this.clear();
455
+ }
456
+ Cache.prototype.clear = function () {
457
+ this._size = 0;
458
+ this._values = Object.create(null);
459
+ };
460
+ Cache.prototype.get = function (key) {
461
+ return this._values[key]
462
+ };
463
+ Cache.prototype.set = function (key, value) {
464
+ this._size >= this._maxSize && this.clear();
465
+ if (!(key in this._values)) this._size++;
466
+
467
+ return (this._values[key] = value)
468
+ };
469
+
470
+ var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g,
471
+ DIGIT_REGEX = /^\d+$/,
472
+ LEAD_DIGIT_REGEX = /^\d/,
473
+ SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,
474
+ CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/,
475
+ MAX_CACHE_SIZE = 512;
476
+
477
+ var pathCache = new Cache(MAX_CACHE_SIZE),
478
+ setCache = new Cache(MAX_CACHE_SIZE),
479
+ getCache = new Cache(MAX_CACHE_SIZE);
480
+
481
+ var propertyExpr = {
482
+ Cache: Cache,
483
+
484
+ split: split,
485
+
486
+ normalizePath: normalizePath,
487
+
488
+ setter: function (path) {
489
+ var parts = normalizePath(path);
490
+
491
+ return (
492
+ setCache.get(path) ||
493
+ setCache.set(path, function setter(obj, value) {
494
+ var index = 0;
495
+ var len = parts.length;
496
+ var data = obj;
497
+
498
+ while (index < len - 1) {
499
+ var part = parts[index];
500
+ if (
501
+ part === '__proto__' ||
502
+ part === 'constructor' ||
503
+ part === 'prototype'
504
+ ) {
505
+ return obj
506
+ }
507
+
508
+ data = data[parts[index++]];
509
+ }
510
+ data[parts[index]] = value;
511
+ })
512
+ )
513
+ },
514
+
515
+ getter: function (path, safe) {
516
+ var parts = normalizePath(path);
517
+ return (
518
+ getCache.get(path) ||
519
+ getCache.set(path, function getter(data) {
520
+ var index = 0,
521
+ len = parts.length;
522
+ while (index < len) {
523
+ if (data != null || !safe) data = data[parts[index++]];
524
+ else return
525
+ }
526
+ return data
527
+ })
528
+ )
529
+ },
530
+
531
+ join: function (segments) {
532
+ return segments.reduce(function (path, part) {
533
+ return (
534
+ path +
535
+ (isQuoted(part) || DIGIT_REGEX.test(part)
536
+ ? '[' + part + ']'
537
+ : (path ? '.' : '') + part)
538
+ )
539
+ }, '')
540
+ },
541
+
542
+ forEach: function (path, cb, thisArg) {
543
+ forEach(Array.isArray(path) ? path : split(path), cb, thisArg);
544
+ },
545
+ };
546
+
547
+ function normalizePath(path) {
548
+ return (
549
+ pathCache.get(path) ||
550
+ pathCache.set(
551
+ path,
552
+ split(path).map(function (part) {
553
+ return part.replace(CLEAN_QUOTES_REGEX, '$2')
554
+ })
555
+ )
556
+ )
557
+ }
558
+
559
+ function split(path) {
560
+ return path.match(SPLIT_REGEX) || ['']
561
+ }
562
+
563
+ function forEach(parts, iter, thisArg) {
564
+ var len = parts.length,
565
+ part,
566
+ idx,
567
+ isArray,
568
+ isBracket;
569
+
570
+ for (idx = 0; idx < len; idx++) {
571
+ part = parts[idx];
572
+
573
+ if (part) {
574
+ if (shouldBeQuoted(part)) {
575
+ part = '"' + part + '"';
576
+ }
577
+
578
+ isBracket = isQuoted(part);
579
+ isArray = !isBracket && /^\d+$/.test(part);
580
+
581
+ iter.call(thisArg, part, isBracket, isArray, idx, parts);
582
+ }
583
+ }
584
+ }
585
+
586
+ function isQuoted(str) {
587
+ return (
588
+ typeof str === 'string' && str && ["'", '"'].indexOf(str.charAt(0)) !== -1
589
+ )
590
+ }
591
+
592
+ function hasLeadingNumber(part) {
593
+ return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)
594
+ }
595
+
596
+ function hasSpecialChars(part) {
597
+ return SPEC_CHAR_REGEX.test(part)
598
+ }
599
+
600
+ function shouldBeQuoted(part) {
601
+ return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))
602
+ }
603
+
604
+ const reWords = /[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g;
605
+
606
+ const words = (str) => str.match(reWords) || [];
607
+
608
+ const upperFirst = (str) => str[0].toUpperCase() + str.slice(1);
609
+
610
+ const join = (str, d) => words(str).join(d).toLowerCase();
611
+
612
+ const camelCase = (str) =>
613
+ words(str).reduce(
614
+ (acc, next) =>
615
+ `${acc}${
616
+ !acc
617
+ ? next.toLowerCase()
618
+ : next[0].toUpperCase() + next.slice(1).toLowerCase()
619
+ }`,
620
+ '',
621
+ );
622
+
623
+ const pascalCase = (str) => upperFirst(camelCase(str));
624
+
625
+ const snakeCase = (str) => join(str, '_');
626
+
627
+ const kebabCase = (str) => join(str, '-');
628
+
629
+ const sentenceCase = (str) => upperFirst(join(str, ' '));
630
+
631
+ const titleCase = (str) => words(str).map(upperFirst).join(' ');
632
+
633
+ var tinyCase = {
634
+ words,
635
+ upperFirst,
636
+ camelCase,
637
+ pascalCase,
638
+ snakeCase,
639
+ kebabCase,
640
+ sentenceCase,
641
+ titleCase,
642
+ };
643
+
644
+ var toposort$2 = {exports: {}};
645
+
646
+ /**
647
+ * Topological sorting function
648
+ *
649
+ * @param {Array} edges
650
+ * @returns {Array}
651
+ */
652
+
653
+ toposort$2.exports = function(edges) {
654
+ return toposort(uniqueNodes(edges), edges)
655
+ };
656
+
657
+ toposort$2.exports.array = toposort;
658
+
659
+ function toposort(nodes, edges) {
660
+ var cursor = nodes.length
661
+ , sorted = new Array(cursor)
662
+ , visited = {}
663
+ , i = cursor
664
+ // Better data structures make algorithm much faster.
665
+ , outgoingEdges = makeOutgoingEdges(edges)
666
+ , nodesHash = makeNodesHash(nodes);
667
+
668
+ // check for unknown nodes
669
+ edges.forEach(function(edge) {
670
+ if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {
671
+ throw new Error('Unknown node. There is an unknown node in the supplied edges.')
672
+ }
673
+ });
674
+
675
+ while (i--) {
676
+ if (!visited[i]) visit(nodes[i], i, new Set());
677
+ }
678
+
679
+ return sorted
680
+
681
+ function visit(node, i, predecessors) {
682
+ if(predecessors.has(node)) {
683
+ var nodeRep;
684
+ try {
685
+ nodeRep = ", node was:" + JSON.stringify(node);
686
+ } catch(e) {
687
+ nodeRep = "";
688
+ }
689
+ throw new Error('Cyclic dependency' + nodeRep)
690
+ }
691
+
692
+ if (!nodesHash.has(node)) {
693
+ throw new Error('Found unknown node. Make sure to provided all involved nodes. Unknown node: '+JSON.stringify(node))
694
+ }
695
+
696
+ if (visited[i]) return;
697
+ visited[i] = true;
698
+
699
+ var outgoing = outgoingEdges.get(node) || new Set();
700
+ outgoing = Array.from(outgoing);
701
+
702
+ if (i = outgoing.length) {
703
+ predecessors.add(node);
704
+ do {
705
+ var child = outgoing[--i];
706
+ visit(child, nodesHash.get(child), predecessors);
707
+ } while (i)
708
+ predecessors.delete(node);
709
+ }
710
+
711
+ sorted[--cursor] = node;
712
+ }
713
+ }
714
+
715
+ function uniqueNodes(arr){
716
+ var res = new Set();
717
+ for (var i = 0, len = arr.length; i < len; i++) {
718
+ var edge = arr[i];
719
+ res.add(edge[0]);
720
+ res.add(edge[1]);
721
+ }
722
+ return Array.from(res)
723
+ }
724
+
725
+ function makeOutgoingEdges(arr){
726
+ var edges = new Map();
727
+ for (var i = 0, len = arr.length; i < len; i++) {
728
+ var edge = arr[i];
729
+ if (!edges.has(edge[0])) edges.set(edge[0], new Set());
730
+ if (!edges.has(edge[1])) edges.set(edge[1], new Set());
731
+ edges.get(edge[0]).add(edge[1]);
732
+ }
733
+ return edges
734
+ }
735
+
736
+ function makeNodesHash(arr){
737
+ var res = new Map();
738
+ for (var i = 0, len = arr.length; i < len; i++) {
739
+ res.set(arr[i], i);
740
+ }
741
+ return res
742
+ }
743
+
744
+ var toposortExports = toposort$2.exports;
745
+ var toposort$1 = /*@__PURE__*/getDefaultExportFromCjs(toposortExports);
746
+
747
+ const toString = Object.prototype.toString;
748
+ const errorToString = Error.prototype.toString;
749
+ const regExpToString = RegExp.prototype.toString;
750
+ const symbolToString = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : () => '';
751
+ const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
752
+ function printNumber(val) {
753
+ if (val != +val) return 'NaN';
754
+ const isNegativeZero = val === 0 && 1 / val < 0;
755
+ return isNegativeZero ? '-0' : '' + val;
756
+ }
757
+ function printSimpleValue(val, quoteStrings = false) {
758
+ if (val == null || val === true || val === false) return '' + val;
759
+ const typeOf = typeof val;
760
+ if (typeOf === 'number') return printNumber(val);
761
+ if (typeOf === 'string') return quoteStrings ? `"${val}"` : val;
762
+ if (typeOf === 'function') return '[Function ' + (val.name || 'anonymous') + ']';
763
+ if (typeOf === 'symbol') return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');
764
+ const tag = toString.call(val).slice(8, -1);
765
+ if (tag === 'Date') return isNaN(val.getTime()) ? '' + val : val.toISOString(val);
766
+ if (tag === 'Error' || val instanceof Error) return '[' + errorToString.call(val) + ']';
767
+ if (tag === 'RegExp') return regExpToString.call(val);
768
+ return null;
769
+ }
770
+ function printValue(value, quoteStrings) {
771
+ let result = printSimpleValue(value, quoteStrings);
772
+ if (result !== null) return result;
773
+ return JSON.stringify(value, function (key, value) {
774
+ let result = printSimpleValue(this[key], quoteStrings);
775
+ if (result !== null) return result;
776
+ return value;
777
+ }, 2);
778
+ }
779
+
780
+ function toArray(value) {
781
+ return value == null ? [] : [].concat(value);
782
+ }
783
+
784
+ let _Symbol$toStringTag, _Symbol$hasInstance, _Symbol$toStringTag2;
785
+ let strReg = /\$\{\s*(\w+)\s*\}/g;
786
+ _Symbol$toStringTag = Symbol.toStringTag;
787
+ class ValidationErrorNoStack {
788
+ constructor(errorOrErrors, value, field, type) {
789
+ this.name = void 0;
790
+ this.message = void 0;
791
+ this.value = void 0;
792
+ this.path = void 0;
793
+ this.type = void 0;
794
+ this.params = void 0;
795
+ this.errors = void 0;
796
+ this.inner = void 0;
797
+ this[_Symbol$toStringTag] = 'Error';
798
+ this.name = 'ValidationError';
799
+ this.value = value;
800
+ this.path = field;
801
+ this.type = type;
802
+ this.errors = [];
803
+ this.inner = [];
804
+ toArray(errorOrErrors).forEach(err => {
805
+ if (ValidationError.isError(err)) {
806
+ this.errors.push(...err.errors);
807
+ const innerErrors = err.inner.length ? err.inner : [err];
808
+ this.inner.push(...innerErrors);
809
+ } else {
810
+ this.errors.push(err);
811
+ }
812
+ });
813
+ this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];
814
+ }
815
+ }
816
+ _Symbol$hasInstance = Symbol.hasInstance;
817
+ _Symbol$toStringTag2 = Symbol.toStringTag;
818
+ class ValidationError extends Error {
819
+ static formatError(message, params) {
820
+ // Attempt to make the path more friendly for error message interpolation.
821
+ const path = params.label || params.path || 'this';
822
+ // Store the original path under `originalPath` so it isn't lost to custom
823
+ // message functions; e.g., ones provided in `setLocale()` calls.
824
+ params = Object.assign({}, params, {
825
+ path,
826
+ originalPath: params.path
827
+ });
828
+ if (typeof message === 'string') return message.replace(strReg, (_, key) => printValue(params[key]));
829
+ if (typeof message === 'function') return message(params);
830
+ return message;
831
+ }
832
+ static isError(err) {
833
+ return err && err.name === 'ValidationError';
834
+ }
835
+ constructor(errorOrErrors, value, field, type, disableStack) {
836
+ const errorNoStack = new ValidationErrorNoStack(errorOrErrors, value, field, type);
837
+ if (disableStack) {
838
+ return errorNoStack;
839
+ }
840
+ super();
841
+ this.value = void 0;
842
+ this.path = void 0;
843
+ this.type = void 0;
844
+ this.params = void 0;
845
+ this.errors = [];
846
+ this.inner = [];
847
+ this[_Symbol$toStringTag2] = 'Error';
848
+ this.name = errorNoStack.name;
849
+ this.message = errorNoStack.message;
850
+ this.type = errorNoStack.type;
851
+ this.value = errorNoStack.value;
852
+ this.path = errorNoStack.path;
853
+ this.errors = errorNoStack.errors;
854
+ this.inner = errorNoStack.inner;
855
+ if (Error.captureStackTrace) {
856
+ Error.captureStackTrace(this, ValidationError);
857
+ }
858
+ }
859
+ static [_Symbol$hasInstance](inst) {
860
+ return ValidationErrorNoStack[Symbol.hasInstance](inst) || super[Symbol.hasInstance](inst);
861
+ }
862
+ }
863
+
864
+ let mixed = {
865
+ default: '${path} is invalid',
866
+ required: '${path} is a required field',
867
+ defined: '${path} must be defined',
868
+ notNull: '${path} cannot be null',
869
+ oneOf: '${path} must be one of the following values: ${values}',
870
+ notOneOf: '${path} must not be one of the following values: ${values}',
871
+ notType: ({
872
+ path,
873
+ type,
874
+ value,
875
+ originalValue
876
+ }) => {
877
+ const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : '.';
878
+ return type !== 'mixed' ? `${path} must be a \`${type}\` type, ` + `but the final value was: \`${printValue(value, true)}\`` + castMsg : `${path} must match the configured type. ` + `The validated value was: \`${printValue(value, true)}\`` + castMsg;
879
+ }
880
+ };
881
+ let string = {
882
+ length: '${path} must be exactly ${length} characters',
883
+ min: '${path} must be at least ${min} characters',
884
+ max: '${path} must be at most ${max} characters',
885
+ matches: '${path} must match the following: "${regex}"',
886
+ email: '${path} must be a valid email',
887
+ url: '${path} must be a valid URL',
888
+ uuid: '${path} must be a valid UUID',
889
+ datetime: '${path} must be a valid ISO date-time',
890
+ datetime_precision: '${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits',
891
+ datetime_offset: '${path} must be a valid ISO date-time with UTC "Z" timezone',
892
+ trim: '${path} must be a trimmed string',
893
+ lowercase: '${path} must be a lowercase string',
894
+ uppercase: '${path} must be a upper case string'
895
+ };
896
+ let number = {
897
+ min: '${path} must be greater than or equal to ${min}',
898
+ max: '${path} must be less than or equal to ${max}',
899
+ lessThan: '${path} must be less than ${less}',
900
+ moreThan: '${path} must be greater than ${more}',
901
+ positive: '${path} must be a positive number',
902
+ negative: '${path} must be a negative number',
903
+ integer: '${path} must be an integer'
904
+ };
905
+ let date = {
906
+ min: '${path} field must be later than ${min}',
907
+ max: '${path} field must be at earlier than ${max}'
908
+ };
909
+ let boolean = {
910
+ isValue: '${path} field must be ${value}'
911
+ };
912
+ let object = {
913
+ noUnknown: '${path} field has unspecified keys: ${unknown}',
914
+ exact: '${path} object contains unknown properties: ${properties}'
915
+ };
916
+ let array = {
917
+ min: '${path} field must have at least ${min} items',
918
+ max: '${path} field must have less than or equal to ${max} items',
919
+ length: '${path} must have ${length} items'
920
+ };
921
+ let tuple = {
922
+ notType: params => {
923
+ const {
924
+ path,
925
+ value,
926
+ spec
927
+ } = params;
928
+ const typeLen = spec.types.length;
929
+ if (Array.isArray(value)) {
930
+ if (value.length < typeLen) return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
931
+ if (value.length > typeLen) return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
932
+ }
933
+ return ValidationError.formatError(mixed.notType, params);
934
+ }
935
+ };
936
+ Object.assign(Object.create(null), {
937
+ mixed,
938
+ string,
939
+ number,
940
+ date,
941
+ object,
942
+ array,
943
+ boolean,
944
+ tuple
945
+ });
946
+
947
+ const isSchema = obj => obj && obj.__isYupSchema__;
948
+
949
+ class Condition {
950
+ static fromOptions(refs, config) {
951
+ if (!config.then && !config.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');
952
+ let {
953
+ is,
954
+ then,
955
+ otherwise
956
+ } = config;
957
+ let check = typeof is === 'function' ? is : (...values) => values.every(value => value === is);
958
+ return new Condition(refs, (values, schema) => {
959
+ var _branch;
960
+ let branch = check(...values) ? then : otherwise;
961
+ return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;
962
+ });
963
+ }
964
+ constructor(refs, builder) {
965
+ this.fn = void 0;
966
+ this.refs = refs;
967
+ this.refs = refs;
968
+ this.fn = builder;
969
+ }
970
+ resolve(base, options) {
971
+ let values = this.refs.map(ref =>
972
+ // TODO: ? operator here?
973
+ ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context));
974
+ let schema = this.fn(values, base, options);
975
+ if (schema === undefined ||
976
+ // @ts-ignore this can be base
977
+ schema === base) {
978
+ return base;
979
+ }
980
+ if (!isSchema(schema)) throw new TypeError('conditions must return a schema object');
981
+ return schema.resolve(options);
982
+ }
983
+ }
984
+
985
+ const prefixes = {
986
+ context: '$',
987
+ value: '.'
988
+ };
989
+ class Reference {
990
+ constructor(key, options = {}) {
991
+ this.key = void 0;
992
+ this.isContext = void 0;
993
+ this.isValue = void 0;
994
+ this.isSibling = void 0;
995
+ this.path = void 0;
996
+ this.getter = void 0;
997
+ this.map = void 0;
998
+ if (typeof key !== 'string') throw new TypeError('ref must be a string, got: ' + key);
999
+ this.key = key.trim();
1000
+ if (key === '') throw new TypeError('ref must be a non-empty string');
1001
+ this.isContext = this.key[0] === prefixes.context;
1002
+ this.isValue = this.key[0] === prefixes.value;
1003
+ this.isSibling = !this.isContext && !this.isValue;
1004
+ let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : '';
1005
+ this.path = this.key.slice(prefix.length);
1006
+ this.getter = this.path && propertyExpr.getter(this.path, true);
1007
+ this.map = options.map;
1008
+ }
1009
+ getValue(value, parent, context) {
1010
+ let result = this.isContext ? context : this.isValue ? value : parent;
1011
+ if (this.getter) result = this.getter(result || {});
1012
+ if (this.map) result = this.map(result);
1013
+ return result;
1014
+ }
1015
+
1016
+ /**
1017
+ *
1018
+ * @param {*} value
1019
+ * @param {Object} options
1020
+ * @param {Object=} options.context
1021
+ * @param {Object=} options.parent
1022
+ */
1023
+ cast(value, options) {
1024
+ return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);
1025
+ }
1026
+ resolve() {
1027
+ return this;
1028
+ }
1029
+ describe() {
1030
+ return {
1031
+ type: 'ref',
1032
+ key: this.key
1033
+ };
1034
+ }
1035
+ toString() {
1036
+ return `Ref(${this.key})`;
1037
+ }
1038
+ static isRef(value) {
1039
+ return value && value.__isYupRef;
1040
+ }
1041
+ }
1042
+
1043
+ // @ts-ignore
1044
+ Reference.prototype.__isYupRef = true;
1045
+
1046
+ const isAbsent = value => value == null;
1047
+
1048
+ function createValidation(config) {
1049
+ function validate({
1050
+ value,
1051
+ path = '',
1052
+ options,
1053
+ originalValue,
1054
+ schema
1055
+ }, panic, next) {
1056
+ const {
1057
+ name,
1058
+ test,
1059
+ params,
1060
+ message,
1061
+ skipAbsent
1062
+ } = config;
1063
+ let {
1064
+ parent,
1065
+ context,
1066
+ abortEarly = schema.spec.abortEarly,
1067
+ disableStackTrace = schema.spec.disableStackTrace
1068
+ } = options;
1069
+ function resolve(item) {
1070
+ return Reference.isRef(item) ? item.getValue(value, parent, context) : item;
1071
+ }
1072
+ function createError(overrides = {}) {
1073
+ const nextParams = Object.assign({
1074
+ value,
1075
+ originalValue,
1076
+ label: schema.spec.label,
1077
+ path: overrides.path || path,
1078
+ spec: schema.spec,
1079
+ disableStackTrace: overrides.disableStackTrace || disableStackTrace
1080
+ }, params, overrides.params);
1081
+ for (const key of Object.keys(nextParams)) nextParams[key] = resolve(nextParams[key]);
1082
+ const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, nextParams.disableStackTrace);
1083
+ error.params = nextParams;
1084
+ return error;
1085
+ }
1086
+ const invalid = abortEarly ? panic : next;
1087
+ let ctx = {
1088
+ path,
1089
+ parent,
1090
+ type: name,
1091
+ from: options.from,
1092
+ createError,
1093
+ resolve,
1094
+ options,
1095
+ originalValue,
1096
+ schema
1097
+ };
1098
+ const handleResult = validOrError => {
1099
+ if (ValidationError.isError(validOrError)) invalid(validOrError);else if (!validOrError) invalid(createError());else next(null);
1100
+ };
1101
+ const handleError = err => {
1102
+ if (ValidationError.isError(err)) invalid(err);else panic(err);
1103
+ };
1104
+ const shouldSkip = skipAbsent && isAbsent(value);
1105
+ if (shouldSkip) {
1106
+ return handleResult(true);
1107
+ }
1108
+ let result;
1109
+ try {
1110
+ var _result;
1111
+ result = test.call(ctx, value, ctx);
1112
+ if (typeof ((_result = result) == null ? void 0 : _result.then) === 'function') {
1113
+ if (options.sync) {
1114
+ throw new Error(`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. ` + `This test will finish after the validate call has returned`);
1115
+ }
1116
+ return Promise.resolve(result).then(handleResult, handleError);
1117
+ }
1118
+ } catch (err) {
1119
+ handleError(err);
1120
+ return;
1121
+ }
1122
+ handleResult(result);
1123
+ }
1124
+ validate.OPTIONS = config;
1125
+ return validate;
1126
+ }
1127
+
1128
+ function getIn(schema, path, value, context = value) {
1129
+ let parent, lastPart, lastPartDebug;
1130
+
1131
+ // root path: ''
1132
+ if (!path) return {
1133
+ parent,
1134
+ parentPath: path,
1135
+ schema
1136
+ };
1137
+ propertyExpr.forEach(path, (_part, isBracket, isArray) => {
1138
+ let part = isBracket ? _part.slice(1, _part.length - 1) : _part;
1139
+ schema = schema.resolve({
1140
+ context,
1141
+ parent,
1142
+ value
1143
+ });
1144
+ let isTuple = schema.type === 'tuple';
1145
+ let idx = isArray ? parseInt(part, 10) : 0;
1146
+ if (schema.innerType || isTuple) {
1147
+ if (isTuple && !isArray) throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${lastPartDebug}" must contain an index to the tuple element, e.g. "${lastPartDebug}[0]"`);
1148
+ if (value && idx >= value.length) {
1149
+ throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. ` + `because there is no value at that index. `);
1150
+ }
1151
+ parent = value;
1152
+ value = value && value[idx];
1153
+ schema = isTuple ? schema.spec.types[idx] : schema.innerType;
1154
+ }
1155
+
1156
+ // sometimes the array index part of a path doesn't exist: "nested.arr.child"
1157
+ // in these cases the current part is the next schema and should be processed
1158
+ // in this iteration. For cases where the index signature is included this
1159
+ // check will fail and we'll handle the `child` part on the next iteration like normal
1160
+ if (!isArray) {
1161
+ if (!schema.fields || !schema.fields[part]) throw new Error(`The schema does not contain the path: ${path}. ` + `(failed at: ${lastPartDebug} which is a type: "${schema.type}")`);
1162
+ parent = value;
1163
+ value = value && value[part];
1164
+ schema = schema.fields[part];
1165
+ }
1166
+ lastPart = part;
1167
+ lastPartDebug = isBracket ? '[' + _part + ']' : '.' + _part;
1168
+ });
1169
+ return {
1170
+ schema,
1171
+ parent,
1172
+ parentPath: lastPart
1173
+ };
1174
+ }
1175
+
1176
+ class ReferenceSet extends Set {
1177
+ describe() {
1178
+ const description = [];
1179
+ for (const item of this.values()) {
1180
+ description.push(Reference.isRef(item) ? item.describe() : item);
1181
+ }
1182
+ return description;
1183
+ }
1184
+ resolveAll(resolve) {
1185
+ let result = [];
1186
+ for (const item of this.values()) {
1187
+ result.push(resolve(item));
1188
+ }
1189
+ return result;
1190
+ }
1191
+ clone() {
1192
+ return new ReferenceSet(this.values());
1193
+ }
1194
+ merge(newItems, removeItems) {
1195
+ const next = this.clone();
1196
+ newItems.forEach(value => next.add(value));
1197
+ removeItems.forEach(value => next.delete(value));
1198
+ return next;
1199
+ }
1200
+ }
1201
+
1202
+ // tweaked from https://github.com/Kelin2025/nanoclone/blob/0abeb7635bda9b68ef2277093f76dbe3bf3948e1/src/index.js
1203
+ function clone(src, seen = new Map()) {
1204
+ if (isSchema(src) || !src || typeof src !== 'object') return src;
1205
+ if (seen.has(src)) return seen.get(src);
1206
+ let copy;
1207
+ if (src instanceof Date) {
1208
+ // Date
1209
+ copy = new Date(src.getTime());
1210
+ seen.set(src, copy);
1211
+ } else if (src instanceof RegExp) {
1212
+ // RegExp
1213
+ copy = new RegExp(src);
1214
+ seen.set(src, copy);
1215
+ } else if (Array.isArray(src)) {
1216
+ // Array
1217
+ copy = new Array(src.length);
1218
+ seen.set(src, copy);
1219
+ for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);
1220
+ } else if (src instanceof Map) {
1221
+ // Map
1222
+ copy = new Map();
1223
+ seen.set(src, copy);
1224
+ for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));
1225
+ } else if (src instanceof Set) {
1226
+ // Set
1227
+ copy = new Set();
1228
+ seen.set(src, copy);
1229
+ for (const v of src) copy.add(clone(v, seen));
1230
+ } else if (src instanceof Object) {
1231
+ // Object
1232
+ copy = {};
1233
+ seen.set(src, copy);
1234
+ for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);
1235
+ } else {
1236
+ throw Error(`Unable to clone ${src}`);
1237
+ }
1238
+ return copy;
1239
+ }
1240
+
1241
+ // If `CustomSchemaMeta` isn't extended with any keys, we'll fall back to a
1242
+ // loose Record definition allowing free form usage.
1243
+ class Schema {
1244
+ constructor(options) {
1245
+ this.type = void 0;
1246
+ this.deps = [];
1247
+ this.tests = void 0;
1248
+ this.transforms = void 0;
1249
+ this.conditions = [];
1250
+ this._mutate = void 0;
1251
+ this.internalTests = {};
1252
+ this._whitelist = new ReferenceSet();
1253
+ this._blacklist = new ReferenceSet();
1254
+ this.exclusiveTests = Object.create(null);
1255
+ this._typeCheck = void 0;
1256
+ this.spec = void 0;
1257
+ this.tests = [];
1258
+ this.transforms = [];
1259
+ this.withMutation(() => {
1260
+ this.typeError(mixed.notType);
1261
+ });
1262
+ this.type = options.type;
1263
+ this._typeCheck = options.check;
1264
+ this.spec = Object.assign({
1265
+ strip: false,
1266
+ strict: false,
1267
+ abortEarly: true,
1268
+ recursive: true,
1269
+ disableStackTrace: false,
1270
+ nullable: false,
1271
+ optional: true,
1272
+ coerce: true
1273
+ }, options == null ? void 0 : options.spec);
1274
+ this.withMutation(s => {
1275
+ s.nonNullable();
1276
+ });
1277
+ }
1278
+
1279
+ // TODO: remove
1280
+ get _type() {
1281
+ return this.type;
1282
+ }
1283
+ clone(spec) {
1284
+ if (this._mutate) {
1285
+ if (spec) Object.assign(this.spec, spec);
1286
+ return this;
1287
+ }
1288
+
1289
+ // if the nested value is a schema we can skip cloning, since
1290
+ // they are already immutable
1291
+ const next = Object.create(Object.getPrototypeOf(this));
1292
+
1293
+ // @ts-expect-error this is readonly
1294
+ next.type = this.type;
1295
+ next._typeCheck = this._typeCheck;
1296
+ next._whitelist = this._whitelist.clone();
1297
+ next._blacklist = this._blacklist.clone();
1298
+ next.internalTests = Object.assign({}, this.internalTests);
1299
+ next.exclusiveTests = Object.assign({}, this.exclusiveTests);
1300
+
1301
+ // @ts-expect-error this is readonly
1302
+ next.deps = [...this.deps];
1303
+ next.conditions = [...this.conditions];
1304
+ next.tests = [...this.tests];
1305
+ next.transforms = [...this.transforms];
1306
+ next.spec = clone(Object.assign({}, this.spec, spec));
1307
+ return next;
1308
+ }
1309
+ label(label) {
1310
+ let next = this.clone();
1311
+ next.spec.label = label;
1312
+ return next;
1313
+ }
1314
+ meta(...args) {
1315
+ if (args.length === 0) return this.spec.meta;
1316
+ let next = this.clone();
1317
+ next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);
1318
+ return next;
1319
+ }
1320
+ withMutation(fn) {
1321
+ let before = this._mutate;
1322
+ this._mutate = true;
1323
+ let result = fn(this);
1324
+ this._mutate = before;
1325
+ return result;
1326
+ }
1327
+ concat(schema) {
1328
+ if (!schema || schema === this) return this;
1329
+ if (schema.type !== this.type && this.type !== 'mixed') throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`);
1330
+ let base = this;
1331
+ let combined = schema.clone();
1332
+ const mergedSpec = Object.assign({}, base.spec, combined.spec);
1333
+ combined.spec = mergedSpec;
1334
+ combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests);
1335
+
1336
+ // manually merge the blacklist/whitelist (the other `schema` takes
1337
+ // precedence in case of conflicts)
1338
+ combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);
1339
+ combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist);
1340
+
1341
+ // start with the current tests
1342
+ combined.tests = base.tests;
1343
+ combined.exclusiveTests = base.exclusiveTests;
1344
+
1345
+ // manually add the new tests to ensure
1346
+ // the deduping logic is consistent
1347
+ combined.withMutation(next => {
1348
+ schema.tests.forEach(fn => {
1349
+ next.test(fn.OPTIONS);
1350
+ });
1351
+ });
1352
+ combined.transforms = [...base.transforms, ...combined.transforms];
1353
+ return combined;
1354
+ }
1355
+ isType(v) {
1356
+ if (v == null) {
1357
+ if (this.spec.nullable && v === null) return true;
1358
+ if (this.spec.optional && v === undefined) return true;
1359
+ return false;
1360
+ }
1361
+ return this._typeCheck(v);
1362
+ }
1363
+ resolve(options) {
1364
+ let schema = this;
1365
+ if (schema.conditions.length) {
1366
+ let conditions = schema.conditions;
1367
+ schema = schema.clone();
1368
+ schema.conditions = [];
1369
+ schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);
1370
+ schema = schema.resolve(options);
1371
+ }
1372
+ return schema;
1373
+ }
1374
+ resolveOptions(options) {
1375
+ var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack;
1376
+ return Object.assign({}, options, {
1377
+ from: options.from || [],
1378
+ strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,
1379
+ abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,
1380
+ recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive,
1381
+ disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace
1382
+ });
1383
+ }
1384
+
1385
+ /**
1386
+ * Run the configured transform pipeline over an input value.
1387
+ */
1388
+
1389
+ cast(value, options = {}) {
1390
+ let resolvedSchema = this.resolve(Object.assign({
1391
+ value
1392
+ }, options));
1393
+ let allowOptionality = options.assert === 'ignore-optionality';
1394
+ let result = resolvedSchema._cast(value, options);
1395
+ if (options.assert !== false && !resolvedSchema.isType(result)) {
1396
+ if (allowOptionality && isAbsent(result)) {
1397
+ return result;
1398
+ }
1399
+ let formattedValue = printValue(value);
1400
+ let formattedResult = printValue(result);
1401
+ throw new TypeError(`The value of ${options.path || 'field'} could not be cast to a value ` + `that satisfies the schema type: "${resolvedSchema.type}". \n\n` + `attempted value: ${formattedValue} \n` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ''));
1402
+ }
1403
+ return result;
1404
+ }
1405
+ _cast(rawValue, options) {
1406
+ let value = rawValue === undefined ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this), rawValue);
1407
+ if (value === undefined) {
1408
+ value = this.getDefault(options);
1409
+ }
1410
+ return value;
1411
+ }
1412
+ _validate(_value, options = {}, panic, next) {
1413
+ let {
1414
+ path,
1415
+ originalValue = _value,
1416
+ strict = this.spec.strict
1417
+ } = options;
1418
+ let value = _value;
1419
+ if (!strict) {
1420
+ value = this._cast(value, Object.assign({
1421
+ assert: false
1422
+ }, options));
1423
+ }
1424
+ let initialTests = [];
1425
+ for (let test of Object.values(this.internalTests)) {
1426
+ if (test) initialTests.push(test);
1427
+ }
1428
+ this.runTests({
1429
+ path,
1430
+ value,
1431
+ originalValue,
1432
+ options,
1433
+ tests: initialTests
1434
+ }, panic, initialErrors => {
1435
+ // even if we aren't ending early we can't proceed further if the types aren't correct
1436
+ if (initialErrors.length) {
1437
+ return next(initialErrors, value);
1438
+ }
1439
+ this.runTests({
1440
+ path,
1441
+ value,
1442
+ originalValue,
1443
+ options,
1444
+ tests: this.tests
1445
+ }, panic, next);
1446
+ });
1447
+ }
1448
+
1449
+ /**
1450
+ * Executes a set of validations, either schema, produced Tests or a nested
1451
+ * schema validate result.
1452
+ */
1453
+ runTests(runOptions, panic, next) {
1454
+ let fired = false;
1455
+ let {
1456
+ tests,
1457
+ value,
1458
+ originalValue,
1459
+ path,
1460
+ options
1461
+ } = runOptions;
1462
+ let panicOnce = arg => {
1463
+ if (fired) return;
1464
+ fired = true;
1465
+ panic(arg, value);
1466
+ };
1467
+ let nextOnce = arg => {
1468
+ if (fired) return;
1469
+ fired = true;
1470
+ next(arg, value);
1471
+ };
1472
+ let count = tests.length;
1473
+ let nestedErrors = [];
1474
+ if (!count) return nextOnce([]);
1475
+ let args = {
1476
+ value,
1477
+ originalValue,
1478
+ path,
1479
+ options,
1480
+ schema: this
1481
+ };
1482
+ for (let i = 0; i < tests.length; i++) {
1483
+ const test = tests[i];
1484
+ test(args, panicOnce, function finishTestRun(err) {
1485
+ if (err) {
1486
+ Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err);
1487
+ }
1488
+ if (--count <= 0) {
1489
+ nextOnce(nestedErrors);
1490
+ }
1491
+ });
1492
+ }
1493
+ }
1494
+ asNestedTest({
1495
+ key,
1496
+ index,
1497
+ parent,
1498
+ parentPath,
1499
+ originalParent,
1500
+ options
1501
+ }) {
1502
+ const k = key != null ? key : index;
1503
+ if (k == null) {
1504
+ throw TypeError('Must include `key` or `index` for nested validations');
1505
+ }
1506
+ const isIndex = typeof k === 'number';
1507
+ let value = parent[k];
1508
+ const testOptions = Object.assign({}, options, {
1509
+ // Nested validations fields are always strict:
1510
+ // 1. parent isn't strict so the casting will also have cast inner values
1511
+ // 2. parent is strict in which case the nested values weren't cast either
1512
+ strict: true,
1513
+ parent,
1514
+ value,
1515
+ originalValue: originalParent[k],
1516
+ // FIXME: tests depend on `index` being passed around deeply,
1517
+ // we should not let the options.key/index bleed through
1518
+ key: undefined,
1519
+ // index: undefined,
1520
+ [isIndex ? 'index' : 'key']: k,
1521
+ path: isIndex || k.includes('.') ? `${parentPath || ''}[${isIndex ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : '') + key
1522
+ });
1523
+ return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);
1524
+ }
1525
+ validate(value, options) {
1526
+ var _options$disableStack2;
1527
+ let schema = this.resolve(Object.assign({}, options, {
1528
+ value
1529
+ }));
1530
+ let disableStackTrace = (_options$disableStack2 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace;
1531
+ return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {
1532
+ if (ValidationError.isError(error)) error.value = parsed;
1533
+ reject(error);
1534
+ }, (errors, validated) => {
1535
+ if (errors.length) reject(new ValidationError(errors, validated, undefined, undefined, disableStackTrace));else resolve(validated);
1536
+ }));
1537
+ }
1538
+ validateSync(value, options) {
1539
+ var _options$disableStack3;
1540
+ let schema = this.resolve(Object.assign({}, options, {
1541
+ value
1542
+ }));
1543
+ let result;
1544
+ let disableStackTrace = (_options$disableStack3 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace;
1545
+ schema._validate(value, Object.assign({}, options, {
1546
+ sync: true
1547
+ }), (error, parsed) => {
1548
+ if (ValidationError.isError(error)) error.value = parsed;
1549
+ throw error;
1550
+ }, (errors, validated) => {
1551
+ if (errors.length) throw new ValidationError(errors, value, undefined, undefined, disableStackTrace);
1552
+ result = validated;
1553
+ });
1554
+ return result;
1555
+ }
1556
+ isValid(value, options) {
1557
+ return this.validate(value, options).then(() => true, err => {
1558
+ if (ValidationError.isError(err)) return false;
1559
+ throw err;
1560
+ });
1561
+ }
1562
+ isValidSync(value, options) {
1563
+ try {
1564
+ this.validateSync(value, options);
1565
+ return true;
1566
+ } catch (err) {
1567
+ if (ValidationError.isError(err)) return false;
1568
+ throw err;
1569
+ }
1570
+ }
1571
+ _getDefault(options) {
1572
+ let defaultValue = this.spec.default;
1573
+ if (defaultValue == null) {
1574
+ return defaultValue;
1575
+ }
1576
+ return typeof defaultValue === 'function' ? defaultValue.call(this, options) : clone(defaultValue);
1577
+ }
1578
+ getDefault(options
1579
+ // If schema is defaulted we know it's at least not undefined
1580
+ ) {
1581
+ let schema = this.resolve(options || {});
1582
+ return schema._getDefault(options);
1583
+ }
1584
+ default(def) {
1585
+ if (arguments.length === 0) {
1586
+ return this._getDefault();
1587
+ }
1588
+ let next = this.clone({
1589
+ default: def
1590
+ });
1591
+ return next;
1592
+ }
1593
+ strict(isStrict = true) {
1594
+ return this.clone({
1595
+ strict: isStrict
1596
+ });
1597
+ }
1598
+ nullability(nullable, message) {
1599
+ const next = this.clone({
1600
+ nullable
1601
+ });
1602
+ next.internalTests.nullable = createValidation({
1603
+ message,
1604
+ name: 'nullable',
1605
+ test(value) {
1606
+ return value === null ? this.schema.spec.nullable : true;
1607
+ }
1608
+ });
1609
+ return next;
1610
+ }
1611
+ optionality(optional, message) {
1612
+ const next = this.clone({
1613
+ optional
1614
+ });
1615
+ next.internalTests.optionality = createValidation({
1616
+ message,
1617
+ name: 'optionality',
1618
+ test(value) {
1619
+ return value === undefined ? this.schema.spec.optional : true;
1620
+ }
1621
+ });
1622
+ return next;
1623
+ }
1624
+ optional() {
1625
+ return this.optionality(true);
1626
+ }
1627
+ defined(message = mixed.defined) {
1628
+ return this.optionality(false, message);
1629
+ }
1630
+ nullable() {
1631
+ return this.nullability(true);
1632
+ }
1633
+ nonNullable(message = mixed.notNull) {
1634
+ return this.nullability(false, message);
1635
+ }
1636
+ required(message = mixed.required) {
1637
+ return this.clone().withMutation(next => next.nonNullable(message).defined(message));
1638
+ }
1639
+ notRequired() {
1640
+ return this.clone().withMutation(next => next.nullable().optional());
1641
+ }
1642
+ transform(fn) {
1643
+ let next = this.clone();
1644
+ next.transforms.push(fn);
1645
+ return next;
1646
+ }
1647
+
1648
+ /**
1649
+ * Adds a test function to the schema's queue of tests.
1650
+ * tests can be exclusive or non-exclusive.
1651
+ *
1652
+ * - exclusive tests, will replace any existing tests of the same name.
1653
+ * - non-exclusive: can be stacked
1654
+ *
1655
+ * If a non-exclusive test is added to a schema with an exclusive test of the same name
1656
+ * the exclusive test is removed and further tests of the same name will be stacked.
1657
+ *
1658
+ * If an exclusive test is added to a schema with non-exclusive tests of the same name
1659
+ * the previous tests are removed and further tests of the same name will replace each other.
1660
+ */
1661
+
1662
+ test(...args) {
1663
+ let opts;
1664
+ if (args.length === 1) {
1665
+ if (typeof args[0] === 'function') {
1666
+ opts = {
1667
+ test: args[0]
1668
+ };
1669
+ } else {
1670
+ opts = args[0];
1671
+ }
1672
+ } else if (args.length === 2) {
1673
+ opts = {
1674
+ name: args[0],
1675
+ test: args[1]
1676
+ };
1677
+ } else {
1678
+ opts = {
1679
+ name: args[0],
1680
+ message: args[1],
1681
+ test: args[2]
1682
+ };
1683
+ }
1684
+ if (opts.message === undefined) opts.message = mixed.default;
1685
+ if (typeof opts.test !== 'function') throw new TypeError('`test` is a required parameters');
1686
+ let next = this.clone();
1687
+ let validate = createValidation(opts);
1688
+ let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;
1689
+ if (opts.exclusive) {
1690
+ if (!opts.name) throw new TypeError('Exclusive tests must provide a unique `name` identifying the test');
1691
+ }
1692
+ if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;
1693
+ next.tests = next.tests.filter(fn => {
1694
+ if (fn.OPTIONS.name === opts.name) {
1695
+ if (isExclusive) return false;
1696
+ if (fn.OPTIONS.test === validate.OPTIONS.test) return false;
1697
+ }
1698
+ return true;
1699
+ });
1700
+ next.tests.push(validate);
1701
+ return next;
1702
+ }
1703
+ when(keys, options) {
1704
+ if (!Array.isArray(keys) && typeof keys !== 'string') {
1705
+ options = keys;
1706
+ keys = '.';
1707
+ }
1708
+ let next = this.clone();
1709
+ let deps = toArray(keys).map(key => new Reference(key));
1710
+ deps.forEach(dep => {
1711
+ // @ts-ignore readonly array
1712
+ if (dep.isSibling) next.deps.push(dep.key);
1713
+ });
1714
+ next.conditions.push(typeof options === 'function' ? new Condition(deps, options) : Condition.fromOptions(deps, options));
1715
+ return next;
1716
+ }
1717
+ typeError(message) {
1718
+ let next = this.clone();
1719
+ next.internalTests.typeError = createValidation({
1720
+ message,
1721
+ name: 'typeError',
1722
+ skipAbsent: true,
1723
+ test(value) {
1724
+ if (!this.schema._typeCheck(value)) return this.createError({
1725
+ params: {
1726
+ type: this.schema.type
1727
+ }
1728
+ });
1729
+ return true;
1730
+ }
1731
+ });
1732
+ return next;
1733
+ }
1734
+ oneOf(enums, message = mixed.oneOf) {
1735
+ let next = this.clone();
1736
+ enums.forEach(val => {
1737
+ next._whitelist.add(val);
1738
+ next._blacklist.delete(val);
1739
+ });
1740
+ next.internalTests.whiteList = createValidation({
1741
+ message,
1742
+ name: 'oneOf',
1743
+ skipAbsent: true,
1744
+ test(value) {
1745
+ let valids = this.schema._whitelist;
1746
+ let resolved = valids.resolveAll(this.resolve);
1747
+ return resolved.includes(value) ? true : this.createError({
1748
+ params: {
1749
+ values: Array.from(valids).join(', '),
1750
+ resolved
1751
+ }
1752
+ });
1753
+ }
1754
+ });
1755
+ return next;
1756
+ }
1757
+ notOneOf(enums, message = mixed.notOneOf) {
1758
+ let next = this.clone();
1759
+ enums.forEach(val => {
1760
+ next._blacklist.add(val);
1761
+ next._whitelist.delete(val);
1762
+ });
1763
+ next.internalTests.blacklist = createValidation({
1764
+ message,
1765
+ name: 'notOneOf',
1766
+ test(value) {
1767
+ let invalids = this.schema._blacklist;
1768
+ let resolved = invalids.resolveAll(this.resolve);
1769
+ if (resolved.includes(value)) return this.createError({
1770
+ params: {
1771
+ values: Array.from(invalids).join(', '),
1772
+ resolved
1773
+ }
1774
+ });
1775
+ return true;
1776
+ }
1777
+ });
1778
+ return next;
1779
+ }
1780
+ strip(strip = true) {
1781
+ let next = this.clone();
1782
+ next.spec.strip = strip;
1783
+ return next;
1784
+ }
1785
+
1786
+ /**
1787
+ * Return a serialized description of the schema including validations, flags, types etc.
1788
+ *
1789
+ * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).
1790
+ */
1791
+ describe(options) {
1792
+ const next = (options ? this.resolve(options) : this).clone();
1793
+ const {
1794
+ label,
1795
+ meta,
1796
+ optional,
1797
+ nullable
1798
+ } = next.spec;
1799
+ const description = {
1800
+ meta,
1801
+ label,
1802
+ optional,
1803
+ nullable,
1804
+ default: next.getDefault(options),
1805
+ type: next.type,
1806
+ oneOf: next._whitelist.describe(),
1807
+ notOneOf: next._blacklist.describe(),
1808
+ tests: next.tests.map(fn => ({
1809
+ name: fn.OPTIONS.name,
1810
+ params: fn.OPTIONS.params
1811
+ })).filter((n, idx, list) => list.findIndex(c => c.name === n.name) === idx)
1812
+ };
1813
+ return description;
1814
+ }
1815
+ }
1816
+ // @ts-expect-error
1817
+ Schema.prototype.__isYupSchema__ = true;
1818
+ for (const method of ['validate', 'validateSync']) Schema.prototype[`${method}At`] = function (path, value, options = {}) {
1819
+ const {
1820
+ parent,
1821
+ parentPath,
1822
+ schema
1823
+ } = getIn(this, path, value, options.context);
1824
+ return schema[method](parent && parent[parentPath], Object.assign({}, options, {
1825
+ parent,
1826
+ path
1827
+ }));
1828
+ };
1829
+ for (const alias of ['equals', 'is']) Schema.prototype[alias] = Schema.prototype.oneOf;
1830
+ for (const alias of ['not', 'nope']) Schema.prototype[alias] = Schema.prototype.notOneOf;
1831
+
1832
+ /**
1833
+ * This file is a modified version of the file from the following repository:
1834
+ * Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
1835
+ * NON-CONFORMANT EDITION.
1836
+ * © 2011 Colin Snover <http://zetafleet.com>
1837
+ * Released under MIT license.
1838
+ */
1839
+
1840
+ // prettier-ignore
1841
+ // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
1842
+ const isoReg = /^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
1843
+ function parseIsoDate(date) {
1844
+ const struct = parseDateStruct(date);
1845
+ if (!struct) return Date.parse ? Date.parse(date) : Number.NaN;
1846
+
1847
+ // timestamps without timezone identifiers should be considered local time
1848
+ if (struct.z === undefined && struct.plusMinus === undefined) {
1849
+ return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf();
1850
+ }
1851
+ let totalMinutesOffset = 0;
1852
+ if (struct.z !== 'Z' && struct.plusMinus !== undefined) {
1853
+ totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset;
1854
+ if (struct.plusMinus === '+') totalMinutesOffset = 0 - totalMinutesOffset;
1855
+ }
1856
+ return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond);
1857
+ }
1858
+ function parseDateStruct(date) {
1859
+ var _regexResult$7$length, _regexResult$;
1860
+ const regexResult = isoReg.exec(date);
1861
+ if (!regexResult) return null;
1862
+
1863
+ // use of toNumber() avoids NaN timestamps caused by “undefined”
1864
+ // values being passed to Date constructor
1865
+ return {
1866
+ year: toNumber(regexResult[1]),
1867
+ month: toNumber(regexResult[2], 1) - 1,
1868
+ day: toNumber(regexResult[3], 1),
1869
+ hour: toNumber(regexResult[4]),
1870
+ minute: toNumber(regexResult[5]),
1871
+ second: toNumber(regexResult[6]),
1872
+ millisecond: regexResult[7] ?
1873
+ // allow arbitrary sub-second precision beyond milliseconds
1874
+ toNumber(regexResult[7].substring(0, 3)) : 0,
1875
+ precision: (_regexResult$7$length = (_regexResult$ = regexResult[7]) == null ? void 0 : _regexResult$.length) != null ? _regexResult$7$length : undefined,
1876
+ z: regexResult[8] || undefined,
1877
+ plusMinus: regexResult[9] || undefined,
1878
+ hourOffset: toNumber(regexResult[10]),
1879
+ minuteOffset: toNumber(regexResult[11])
1880
+ };
1881
+ }
1882
+ function toNumber(str, defaultValue = 0) {
1883
+ return Number(str) || defaultValue;
1884
+ }
1885
+
1886
+ // Taken from HTML spec: https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
1887
+ let rEmail =
1888
+ // eslint-disable-next-line
1889
+ /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1890
+ let rUrl =
1891
+ // eslint-disable-next-line
1892
+ /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
1893
+
1894
+ // eslint-disable-next-line
1895
+ let rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
1896
+ let yearMonthDay = '^\\d{4}-\\d{2}-\\d{2}';
1897
+ let hourMinuteSecond = '\\d{2}:\\d{2}:\\d{2}';
1898
+ let zOrOffset = '(([+-]\\d{2}(:?\\d{2})?)|Z)';
1899
+ let rIsoDateTime = new RegExp(`${yearMonthDay}T${hourMinuteSecond}(\\.\\d+)?${zOrOffset}$`);
1900
+ let isTrimmed = value => isAbsent(value) || value === value.trim();
1901
+ let objStringTag = {}.toString();
1902
+ function create$6() {
1903
+ return new StringSchema();
1904
+ }
1905
+ class StringSchema extends Schema {
1906
+ constructor() {
1907
+ super({
1908
+ type: 'string',
1909
+ check(value) {
1910
+ if (value instanceof String) value = value.valueOf();
1911
+ return typeof value === 'string';
1912
+ }
1913
+ });
1914
+ this.withMutation(() => {
1915
+ this.transform((value, _raw, ctx) => {
1916
+ if (!ctx.spec.coerce || ctx.isType(value)) return value;
1917
+
1918
+ // don't ever convert arrays
1919
+ if (Array.isArray(value)) return value;
1920
+ const strValue = value != null && value.toString ? value.toString() : value;
1921
+
1922
+ // no one wants plain objects converted to [Object object]
1923
+ if (strValue === objStringTag) return value;
1924
+ return strValue;
1925
+ });
1926
+ });
1927
+ }
1928
+ required(message) {
1929
+ return super.required(message).withMutation(schema => schema.test({
1930
+ message: message || mixed.required,
1931
+ name: 'required',
1932
+ skipAbsent: true,
1933
+ test: value => !!value.length
1934
+ }));
1935
+ }
1936
+ notRequired() {
1937
+ return super.notRequired().withMutation(schema => {
1938
+ schema.tests = schema.tests.filter(t => t.OPTIONS.name !== 'required');
1939
+ return schema;
1940
+ });
1941
+ }
1942
+ length(length, message = string.length) {
1943
+ return this.test({
1944
+ message,
1945
+ name: 'length',
1946
+ exclusive: true,
1947
+ params: {
1948
+ length
1949
+ },
1950
+ skipAbsent: true,
1951
+ test(value) {
1952
+ return value.length === this.resolve(length);
1953
+ }
1954
+ });
1955
+ }
1956
+ min(min, message = string.min) {
1957
+ return this.test({
1958
+ message,
1959
+ name: 'min',
1960
+ exclusive: true,
1961
+ params: {
1962
+ min
1963
+ },
1964
+ skipAbsent: true,
1965
+ test(value) {
1966
+ return value.length >= this.resolve(min);
1967
+ }
1968
+ });
1969
+ }
1970
+ max(max, message = string.max) {
1971
+ return this.test({
1972
+ name: 'max',
1973
+ exclusive: true,
1974
+ message,
1975
+ params: {
1976
+ max
1977
+ },
1978
+ skipAbsent: true,
1979
+ test(value) {
1980
+ return value.length <= this.resolve(max);
1981
+ }
1982
+ });
1983
+ }
1984
+ matches(regex, options) {
1985
+ let excludeEmptyString = false;
1986
+ let message;
1987
+ let name;
1988
+ if (options) {
1989
+ if (typeof options === 'object') {
1990
+ ({
1991
+ excludeEmptyString = false,
1992
+ message,
1993
+ name
1994
+ } = options);
1995
+ } else {
1996
+ message = options;
1997
+ }
1998
+ }
1999
+ return this.test({
2000
+ name: name || 'matches',
2001
+ message: message || string.matches,
2002
+ params: {
2003
+ regex
2004
+ },
2005
+ skipAbsent: true,
2006
+ test: value => value === '' && excludeEmptyString || value.search(regex) !== -1
2007
+ });
2008
+ }
2009
+ email(message = string.email) {
2010
+ return this.matches(rEmail, {
2011
+ name: 'email',
2012
+ message,
2013
+ excludeEmptyString: true
2014
+ });
2015
+ }
2016
+ url(message = string.url) {
2017
+ return this.matches(rUrl, {
2018
+ name: 'url',
2019
+ message,
2020
+ excludeEmptyString: true
2021
+ });
2022
+ }
2023
+ uuid(message = string.uuid) {
2024
+ return this.matches(rUUID, {
2025
+ name: 'uuid',
2026
+ message,
2027
+ excludeEmptyString: false
2028
+ });
2029
+ }
2030
+ datetime(options) {
2031
+ let message = '';
2032
+ let allowOffset;
2033
+ let precision;
2034
+ if (options) {
2035
+ if (typeof options === 'object') {
2036
+ ({
2037
+ message = '',
2038
+ allowOffset = false,
2039
+ precision = undefined
2040
+ } = options);
2041
+ } else {
2042
+ message = options;
2043
+ }
2044
+ }
2045
+ return this.matches(rIsoDateTime, {
2046
+ name: 'datetime',
2047
+ message: message || string.datetime,
2048
+ excludeEmptyString: true
2049
+ }).test({
2050
+ name: 'datetime_offset',
2051
+ message: message || string.datetime_offset,
2052
+ params: {
2053
+ allowOffset
2054
+ },
2055
+ skipAbsent: true,
2056
+ test: value => {
2057
+ if (!value || allowOffset) return true;
2058
+ const struct = parseDateStruct(value);
2059
+ if (!struct) return false;
2060
+ return !!struct.z;
2061
+ }
2062
+ }).test({
2063
+ name: 'datetime_precision',
2064
+ message: message || string.datetime_precision,
2065
+ params: {
2066
+ precision
2067
+ },
2068
+ skipAbsent: true,
2069
+ test: value => {
2070
+ if (!value || precision == undefined) return true;
2071
+ const struct = parseDateStruct(value);
2072
+ if (!struct) return false;
2073
+ return struct.precision === precision;
2074
+ }
2075
+ });
2076
+ }
2077
+
2078
+ //-- transforms --
2079
+ ensure() {
2080
+ return this.default('').transform(val => val === null ? '' : val);
2081
+ }
2082
+ trim(message = string.trim) {
2083
+ return this.transform(val => val != null ? val.trim() : val).test({
2084
+ message,
2085
+ name: 'trim',
2086
+ test: isTrimmed
2087
+ });
2088
+ }
2089
+ lowercase(message = string.lowercase) {
2090
+ return this.transform(value => !isAbsent(value) ? value.toLowerCase() : value).test({
2091
+ message,
2092
+ name: 'string_case',
2093
+ exclusive: true,
2094
+ skipAbsent: true,
2095
+ test: value => isAbsent(value) || value === value.toLowerCase()
2096
+ });
2097
+ }
2098
+ uppercase(message = string.uppercase) {
2099
+ return this.transform(value => !isAbsent(value) ? value.toUpperCase() : value).test({
2100
+ message,
2101
+ name: 'string_case',
2102
+ exclusive: true,
2103
+ skipAbsent: true,
2104
+ test: value => isAbsent(value) || value === value.toUpperCase()
2105
+ });
2106
+ }
2107
+ }
2108
+ create$6.prototype = StringSchema.prototype;
2109
+
2110
+ //
2111
+ // Number Interfaces
2112
+ //
2113
+
2114
+ let invalidDate = new Date('');
2115
+ let isDate = obj => Object.prototype.toString.call(obj) === '[object Date]';
2116
+ class DateSchema extends Schema {
2117
+ constructor() {
2118
+ super({
2119
+ type: 'date',
2120
+ check(v) {
2121
+ return isDate(v) && !isNaN(v.getTime());
2122
+ }
2123
+ });
2124
+ this.withMutation(() => {
2125
+ this.transform((value, _raw, ctx) => {
2126
+ // null -> InvalidDate isn't useful; treat all nulls as null and let it fail on
2127
+ // nullability check vs TypeErrors
2128
+ if (!ctx.spec.coerce || ctx.isType(value) || value === null) return value;
2129
+ value = parseIsoDate(value);
2130
+
2131
+ // 0 is a valid timestamp equivalent to 1970-01-01T00:00:00Z(unix epoch) or before.
2132
+ return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE;
2133
+ });
2134
+ });
2135
+ }
2136
+ prepareParam(ref, name) {
2137
+ let param;
2138
+ if (!Reference.isRef(ref)) {
2139
+ let cast = this.cast(ref);
2140
+ if (!this._typeCheck(cast)) throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`);
2141
+ param = cast;
2142
+ } else {
2143
+ param = ref;
2144
+ }
2145
+ return param;
2146
+ }
2147
+ min(min, message = date.min) {
2148
+ let limit = this.prepareParam(min, 'min');
2149
+ return this.test({
2150
+ message,
2151
+ name: 'min',
2152
+ exclusive: true,
2153
+ params: {
2154
+ min
2155
+ },
2156
+ skipAbsent: true,
2157
+ test(value) {
2158
+ return value >= this.resolve(limit);
2159
+ }
2160
+ });
2161
+ }
2162
+ max(max, message = date.max) {
2163
+ let limit = this.prepareParam(max, 'max');
2164
+ return this.test({
2165
+ message,
2166
+ name: 'max',
2167
+ exclusive: true,
2168
+ params: {
2169
+ max
2170
+ },
2171
+ skipAbsent: true,
2172
+ test(value) {
2173
+ return value <= this.resolve(limit);
2174
+ }
2175
+ });
2176
+ }
2177
+ }
2178
+ DateSchema.INVALID_DATE = invalidDate;
2179
+
2180
+ // @ts-expect-error
2181
+ function sortFields(fields, excludedEdges = []) {
2182
+ let edges = [];
2183
+ let nodes = new Set();
2184
+ let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));
2185
+ function addNode(depPath, key) {
2186
+ let node = propertyExpr.split(depPath)[0];
2187
+ nodes.add(node);
2188
+ if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);
2189
+ }
2190
+ for (const key of Object.keys(fields)) {
2191
+ let value = fields[key];
2192
+ nodes.add(key);
2193
+ if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);else if (isSchema(value) && 'deps' in value) value.deps.forEach(path => addNode(path, key));
2194
+ }
2195
+ return toposort$1.array(Array.from(nodes), edges).reverse();
2196
+ }
2197
+
2198
+ function findIndex(arr, err) {
2199
+ let idx = Infinity;
2200
+ arr.some((key, ii) => {
2201
+ var _err$path;
2202
+ if ((_err$path = err.path) != null && _err$path.includes(key)) {
2203
+ idx = ii;
2204
+ return true;
2205
+ }
2206
+ });
2207
+ return idx;
2208
+ }
2209
+ function sortByKeyOrder(keys) {
2210
+ return (a, b) => {
2211
+ return findIndex(keys, a) - findIndex(keys, b);
2212
+ };
2213
+ }
2214
+
2215
+ const parseJson = (value, _, ctx) => {
2216
+ if (typeof value !== 'string') {
2217
+ return value;
2218
+ }
2219
+ let parsed = value;
2220
+ try {
2221
+ parsed = JSON.parse(value);
2222
+ } catch (err) {
2223
+ /* */
2224
+ }
2225
+ return ctx.isType(parsed) ? parsed : value;
2226
+ };
2227
+
2228
+ // @ts-ignore
2229
+ function deepPartial(schema) {
2230
+ if ('fields' in schema) {
2231
+ const partial = {};
2232
+ for (const [key, fieldSchema] of Object.entries(schema.fields)) {
2233
+ partial[key] = deepPartial(fieldSchema);
2234
+ }
2235
+ return schema.setFields(partial);
2236
+ }
2237
+ if (schema.type === 'array') {
2238
+ const nextArray = schema.optional();
2239
+ if (nextArray.innerType) nextArray.innerType = deepPartial(nextArray.innerType);
2240
+ return nextArray;
2241
+ }
2242
+ if (schema.type === 'tuple') {
2243
+ return schema.optional().clone({
2244
+ types: schema.spec.types.map(deepPartial)
2245
+ });
2246
+ }
2247
+ if ('optional' in schema) {
2248
+ return schema.optional();
2249
+ }
2250
+ return schema;
2251
+ }
2252
+ const deepHas = (obj, p) => {
2253
+ const path = [...propertyExpr.normalizePath(p)];
2254
+ if (path.length === 1) return path[0] in obj;
2255
+ let last = path.pop();
2256
+ let parent = propertyExpr.getter(propertyExpr.join(path), true)(obj);
2257
+ return !!(parent && last in parent);
2258
+ };
2259
+ let isObject = obj => Object.prototype.toString.call(obj) === '[object Object]';
2260
+ function unknown(ctx, value) {
2261
+ let known = Object.keys(ctx.fields);
2262
+ return Object.keys(value).filter(key => known.indexOf(key) === -1);
2263
+ }
2264
+ const defaultSort = sortByKeyOrder([]);
2265
+ function create$3(spec) {
2266
+ return new ObjectSchema(spec);
2267
+ }
2268
+ class ObjectSchema extends Schema {
2269
+ constructor(spec) {
2270
+ super({
2271
+ type: 'object',
2272
+ check(value) {
2273
+ return isObject(value) || typeof value === 'function';
2274
+ }
2275
+ });
2276
+ this.fields = Object.create(null);
2277
+ this._sortErrors = defaultSort;
2278
+ this._nodes = [];
2279
+ this._excludedEdges = [];
2280
+ this.withMutation(() => {
2281
+ if (spec) {
2282
+ this.shape(spec);
2283
+ }
2284
+ });
2285
+ }
2286
+ _cast(_value, options = {}) {
2287
+ var _options$stripUnknown;
2288
+ let value = super._cast(_value, options);
2289
+
2290
+ //should ignore nulls here
2291
+ if (value === undefined) return this.getDefault(options);
2292
+ if (!this._typeCheck(value)) return value;
2293
+ let fields = this.fields;
2294
+ let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;
2295
+ let props = [].concat(this._nodes, Object.keys(value).filter(v => !this._nodes.includes(v)));
2296
+ let intermediateValue = {}; // is filled during the transform below
2297
+ let innerOptions = Object.assign({}, options, {
2298
+ parent: intermediateValue,
2299
+ __validating: options.__validating || false
2300
+ });
2301
+ let isChanged = false;
2302
+ for (const prop of props) {
2303
+ let field = fields[prop];
2304
+ let exists = (prop in value);
2305
+ if (field) {
2306
+ let fieldValue;
2307
+ let inputValue = value[prop];
2308
+
2309
+ // safe to mutate since this is fired in sequence
2310
+ innerOptions.path = (options.path ? `${options.path}.` : '') + prop;
2311
+ field = field.resolve({
2312
+ value: inputValue,
2313
+ context: options.context,
2314
+ parent: intermediateValue
2315
+ });
2316
+ let fieldSpec = field instanceof Schema ? field.spec : undefined;
2317
+ let strict = fieldSpec == null ? void 0 : fieldSpec.strict;
2318
+ if (fieldSpec != null && fieldSpec.strip) {
2319
+ isChanged = isChanged || prop in value;
2320
+ continue;
2321
+ }
2322
+ fieldValue = !options.__validating || !strict ?
2323
+ // TODO: use _cast, this is double resolving
2324
+ field.cast(value[prop], innerOptions) : value[prop];
2325
+ if (fieldValue !== undefined) {
2326
+ intermediateValue[prop] = fieldValue;
2327
+ }
2328
+ } else if (exists && !strip) {
2329
+ intermediateValue[prop] = value[prop];
2330
+ }
2331
+ if (exists !== prop in intermediateValue || intermediateValue[prop] !== value[prop]) {
2332
+ isChanged = true;
2333
+ }
2334
+ }
2335
+ return isChanged ? intermediateValue : value;
2336
+ }
2337
+ _validate(_value, options = {}, panic, next) {
2338
+ let {
2339
+ from = [],
2340
+ originalValue = _value,
2341
+ recursive = this.spec.recursive
2342
+ } = options;
2343
+ options.from = [{
2344
+ schema: this,
2345
+ value: originalValue
2346
+ }, ...from];
2347
+ // this flag is needed for handling `strict` correctly in the context of
2348
+ // validation vs just casting. e.g strict() on a field is only used when validating
2349
+ options.__validating = true;
2350
+ options.originalValue = originalValue;
2351
+ super._validate(_value, options, panic, (objectErrors, value) => {
2352
+ if (!recursive || !isObject(value)) {
2353
+ next(objectErrors, value);
2354
+ return;
2355
+ }
2356
+ originalValue = originalValue || value;
2357
+ let tests = [];
2358
+ for (let key of this._nodes) {
2359
+ let field = this.fields[key];
2360
+ if (!field || Reference.isRef(field)) {
2361
+ continue;
2362
+ }
2363
+ tests.push(field.asNestedTest({
2364
+ options,
2365
+ key,
2366
+ parent: value,
2367
+ parentPath: options.path,
2368
+ originalParent: originalValue
2369
+ }));
2370
+ }
2371
+ this.runTests({
2372
+ tests,
2373
+ value,
2374
+ originalValue,
2375
+ options
2376
+ }, panic, fieldErrors => {
2377
+ next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);
2378
+ });
2379
+ });
2380
+ }
2381
+ clone(spec) {
2382
+ const next = super.clone(spec);
2383
+ next.fields = Object.assign({}, this.fields);
2384
+ next._nodes = this._nodes;
2385
+ next._excludedEdges = this._excludedEdges;
2386
+ next._sortErrors = this._sortErrors;
2387
+ return next;
2388
+ }
2389
+ concat(schema) {
2390
+ let next = super.concat(schema);
2391
+ let nextFields = next.fields;
2392
+ for (let [field, schemaOrRef] of Object.entries(this.fields)) {
2393
+ const target = nextFields[field];
2394
+ nextFields[field] = target === undefined ? schemaOrRef : target;
2395
+ }
2396
+ return next.withMutation(s =>
2397
+ // XXX: excludes here is wrong
2398
+ s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges]));
2399
+ }
2400
+ _getDefault(options) {
2401
+ if ('default' in this.spec) {
2402
+ return super._getDefault(options);
2403
+ }
2404
+
2405
+ // if there is no default set invent one
2406
+ if (!this._nodes.length) {
2407
+ return undefined;
2408
+ }
2409
+ let dft = {};
2410
+ this._nodes.forEach(key => {
2411
+ var _innerOptions;
2412
+ const field = this.fields[key];
2413
+ let innerOptions = options;
2414
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
2415
+ innerOptions = Object.assign({}, innerOptions, {
2416
+ parent: innerOptions.value,
2417
+ value: innerOptions.value[key]
2418
+ });
2419
+ }
2420
+ dft[key] = field && 'getDefault' in field ? field.getDefault(innerOptions) : undefined;
2421
+ });
2422
+ return dft;
2423
+ }
2424
+ setFields(shape, excludedEdges) {
2425
+ let next = this.clone();
2426
+ next.fields = shape;
2427
+ next._nodes = sortFields(shape, excludedEdges);
2428
+ next._sortErrors = sortByKeyOrder(Object.keys(shape));
2429
+ // XXX: this carries over edges which may not be what you want
2430
+ if (excludedEdges) next._excludedEdges = excludedEdges;
2431
+ return next;
2432
+ }
2433
+ shape(additions, excludes = []) {
2434
+ return this.clone().withMutation(next => {
2435
+ let edges = next._excludedEdges;
2436
+ if (excludes.length) {
2437
+ if (!Array.isArray(excludes[0])) excludes = [excludes];
2438
+ edges = [...next._excludedEdges, ...excludes];
2439
+ }
2440
+
2441
+ // XXX: excludes here is wrong
2442
+ return next.setFields(Object.assign(next.fields, additions), edges);
2443
+ });
2444
+ }
2445
+ partial() {
2446
+ const partial = {};
2447
+ for (const [key, schema] of Object.entries(this.fields)) {
2448
+ partial[key] = 'optional' in schema && schema.optional instanceof Function ? schema.optional() : schema;
2449
+ }
2450
+ return this.setFields(partial);
2451
+ }
2452
+ deepPartial() {
2453
+ const next = deepPartial(this);
2454
+ return next;
2455
+ }
2456
+ pick(keys) {
2457
+ const picked = {};
2458
+ for (const key of keys) {
2459
+ if (this.fields[key]) picked[key] = this.fields[key];
2460
+ }
2461
+ return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b)));
2462
+ }
2463
+ omit(keys) {
2464
+ const remaining = [];
2465
+ for (const key of Object.keys(this.fields)) {
2466
+ if (keys.includes(key)) continue;
2467
+ remaining.push(key);
2468
+ }
2469
+ return this.pick(remaining);
2470
+ }
2471
+ from(from, to, alias) {
2472
+ let fromGetter = propertyExpr.getter(from, true);
2473
+ return this.transform(obj => {
2474
+ if (!obj) return obj;
2475
+ let newObj = obj;
2476
+ if (deepHas(obj, from)) {
2477
+ newObj = Object.assign({}, obj);
2478
+ if (!alias) delete newObj[from];
2479
+ newObj[to] = fromGetter(obj);
2480
+ }
2481
+ return newObj;
2482
+ });
2483
+ }
2484
+
2485
+ /** Parse an input JSON string to an object */
2486
+ json() {
2487
+ return this.transform(parseJson);
2488
+ }
2489
+
2490
+ /**
2491
+ * Similar to `noUnknown` but only validates that an object is the right shape without stripping the unknown keys
2492
+ */
2493
+ exact(message) {
2494
+ return this.test({
2495
+ name: 'exact',
2496
+ exclusive: true,
2497
+ message: message || object.exact,
2498
+ test(value) {
2499
+ if (value == null) return true;
2500
+ const unknownKeys = unknown(this.schema, value);
2501
+ return unknownKeys.length === 0 || this.createError({
2502
+ params: {
2503
+ properties: unknownKeys.join(', ')
2504
+ }
2505
+ });
2506
+ }
2507
+ });
2508
+ }
2509
+ stripUnknown() {
2510
+ return this.clone({
2511
+ noUnknown: true
2512
+ });
2513
+ }
2514
+ noUnknown(noAllow = true, message = object.noUnknown) {
2515
+ if (typeof noAllow !== 'boolean') {
2516
+ message = noAllow;
2517
+ noAllow = true;
2518
+ }
2519
+ let next = this.test({
2520
+ name: 'noUnknown',
2521
+ exclusive: true,
2522
+ message: message,
2523
+ test(value) {
2524
+ if (value == null) return true;
2525
+ const unknownKeys = unknown(this.schema, value);
2526
+ return !noAllow || unknownKeys.length === 0 || this.createError({
2527
+ params: {
2528
+ unknown: unknownKeys.join(', ')
2529
+ }
2530
+ });
2531
+ }
2532
+ });
2533
+ next.spec.noUnknown = noAllow;
2534
+ return next;
2535
+ }
2536
+ unknown(allow = true, message = object.noUnknown) {
2537
+ return this.noUnknown(!allow, message);
2538
+ }
2539
+ transformKeys(fn) {
2540
+ return this.transform(obj => {
2541
+ if (!obj) return obj;
2542
+ const result = {};
2543
+ for (const key of Object.keys(obj)) result[fn(key)] = obj[key];
2544
+ return result;
2545
+ });
2546
+ }
2547
+ camelCase() {
2548
+ return this.transformKeys(tinyCase.camelCase);
2549
+ }
2550
+ snakeCase() {
2551
+ return this.transformKeys(tinyCase.snakeCase);
2552
+ }
2553
+ constantCase() {
2554
+ return this.transformKeys(key => tinyCase.snakeCase(key).toUpperCase());
2555
+ }
2556
+ describe(options) {
2557
+ const next = (options ? this.resolve(options) : this).clone();
2558
+ const base = super.describe(options);
2559
+ base.fields = {};
2560
+ for (const [key, value] of Object.entries(next.fields)) {
2561
+ var _innerOptions2;
2562
+ let innerOptions = options;
2563
+ if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) {
2564
+ innerOptions = Object.assign({}, innerOptions, {
2565
+ parent: innerOptions.value,
2566
+ value: innerOptions.value[key]
2567
+ });
2568
+ }
2569
+ base.fields[key] = value.describe(innerOptions);
2570
+ }
2571
+ return base;
2572
+ }
2573
+ }
2574
+ create$3.prototype = ObjectSchema.prototype;
2575
+
2576
+ var createValidationSchema = function (fields) {
2577
+ var schema = {};
2578
+ fields.forEach(function (field) {
2579
+ // Excluir campos que no tienen name o son de tipos especiales
2580
+ if (!field.name ||
2581
+ ['declaration', 'subtitle', 'alert', 'status'].includes(field.type)) {
2582
+ return;
2583
+ }
2584
+ if (field.validations && field.validations.length > 0) {
2585
+ var fieldSchema_1 = create$6();
2586
+ field.validations.forEach(function (validation) {
2587
+ switch (validation.type) {
2588
+ case 'required':
2589
+ fieldSchema_1 = fieldSchema_1.required(validation.params[0] || 'Este campo es requerido');
2590
+ break;
2591
+ case 'min':
2592
+ var minLength = parseInt(validation.params[0]);
2593
+ var minMessage = validation.params[1] || "M\u00EDnimo ".concat(minLength, " caracteres");
2594
+ fieldSchema_1 = fieldSchema_1.min(minLength, minMessage);
2595
+ break;
2596
+ case 'max':
2597
+ var maxLength = parseInt(validation.params[0]);
2598
+ var maxMessage = validation.params[1] || "M\u00E1ximo ".concat(maxLength, " caracteres");
2599
+ fieldSchema_1 = fieldSchema_1.max(maxLength, maxMessage);
2600
+ break;
2601
+ case 'email':
2602
+ var emailMessage = validation.params[0] || 'Email inválido';
2603
+ fieldSchema_1 = fieldSchema_1.email(emailMessage);
2604
+ break;
2605
+ case 'pattern':
2606
+ var pattern = new RegExp(validation.params[0]);
2607
+ var patternMessage = validation.params[1] || 'Formato inválido';
2608
+ fieldSchema_1 = fieldSchema_1.matches(pattern, patternMessage);
2609
+ break;
2610
+ case 'custom':
2611
+ // Para validaciones personalizadas
2612
+ var customValidator = validation.params[0];
2613
+ if (customValidator === 'rut') {
2614
+ fieldSchema_1 = fieldSchema_1.test('rut', validation.params[1] || 'RUT inválido', function (value) {
2615
+ if (!value)
2616
+ return true; // Si está vacío, la validación required se encargará
2617
+ return validate(clean(value));
2618
+ });
2619
+ }
2620
+ else {
2621
+ fieldSchema_1 = fieldSchema_1.test('custom', validation.params[1] || 'Validación fallida', function (value) {
2622
+ // Aquí puedes implementar lógica personalizada
2623
+ return value; // Por defecto pasa la validación
2624
+ });
2625
+ }
2626
+ break;
2627
+ }
2628
+ });
2629
+ schema[field.name] = fieldSchema_1;
2630
+ }
2631
+ else if (field.required) {
2632
+ // Validación básica de requerido si no hay validaciones específicas
2633
+ schema[field.name] = create$6().required("El campo ".concat(field.label, " es requerido"));
2634
+ }
2635
+ });
2636
+ return create$3().shape(schema);
2637
+ };
2638
+ // Validaciones predefinidas
2639
+ var commonValidations = {
2640
+ required: function (message) { return ({
2641
+ type: 'required',
2642
+ params: [message || 'Este campo es requerido'],
2643
+ }); },
2644
+ min: function (length, message) { return ({
2645
+ type: 'min',
2646
+ params: [length.toString(), message || "M\u00EDnimo ".concat(length, " caracteres")],
2647
+ }); },
2648
+ max: function (length, message) { return ({
2649
+ type: 'max',
2650
+ params: [length.toString(), message || "M\u00E1ximo ".concat(length, " caracteres")],
2651
+ }); },
2652
+ email: function (message) { return ({
2653
+ type: 'email',
2654
+ params: [message || 'Email inválido'],
2655
+ }); },
2656
+ pattern: function (regex, message) { return ({
2657
+ type: 'pattern',
2658
+ params: [regex, message || 'Formato inválido'],
2659
+ }); },
2660
+ };
2661
+
2662
+ var GenericForm = function (_a) {
2663
+ var _b, _c, _d, _e, _f, _g, _h;
2664
+ var config = _a.config, _j = _a.stepperData, stepperData = _j === void 0 ? {} : _j, onStepComplete = _a.onStepComplete, _k = _a.loading, loading = _k === void 0 ? false : _k, _l = _a.className, className = _l === void 0 ? '' : _l;
2665
+ // Función para obtener datos del stepper o valores por defecto
2666
+ var getFieldValue = function (field) {
2667
+ var _a;
2668
+ // Prioridad 1: Valor por defecto del campo (máxima prioridad)
2669
+ if ((field === null || field === void 0 ? void 0 : field.value) !== undefined) {
2670
+ return field.value;
2671
+ }
2672
+ // Prioridad 2: Datos del stepper si existe
2673
+ if ((stepperData === null || stepperData === void 0 ? void 0 : stepperData[field === null || field === void 0 ? void 0 : field.name]) !== undefined) {
2674
+ return stepperData[field === null || field === void 0 ? void 0 : field.name];
2675
+ }
2676
+ // Prioridad 3: Datos iniciales de la configuración
2677
+ if (((_a = config.initialData) === null || _a === void 0 ? void 0 : _a[field.name]) !== undefined) {
2678
+ return config.initialData[field.name];
2679
+ }
2680
+ // Prioridad 4: Valor vacío
2681
+ return '';
2682
+ };
2683
+ // Inicializar formData con datos existentes o valores por defecto
2684
+ var getInitialFormData = function () {
2685
+ var initialData = {};
2686
+ if (Array.isArray(config.fields)) {
2687
+ config.fields.forEach(function (field) {
2688
+ initialData[field.name] = getFieldValue(field);
2689
+ });
2690
+ }
2691
+ return initialData;
2692
+ };
2693
+ var _m = useState(getInitialFormData), formData = _m[0], setFormData = _m[1];
2694
+ var _o = useState({}), errors = _o[0], setErrors = _o[1];
2695
+ // Sincronizar formData cuando cambie stepperData
2696
+ useEffect(function () {
2697
+ if (stepperData && Array.isArray(config.fields)) {
2698
+ var updatedFormData_1 = {};
2699
+ config.fields.forEach(function (field) {
2700
+ updatedFormData_1[field.name] =
2701
+ (stepperData === null || stepperData === void 0 ? void 0 : stepperData[field.name]) ||
2702
+ formData[field.name] ||
2703
+ (field === null || field === void 0 ? void 0 : field.value);
2704
+ });
2705
+ setFormData(function (prev) { return (__assign$1(__assign$1({}, prev), updatedFormData_1)); });
2706
+ }
2707
+ }, [stepperData, config.fields]);
2708
+ var handleInputChange = function (e) {
2709
+ var _a = e.target, name = _a.name, value = _a.value, type = _a.type;
2710
+ var checked = type === 'checkbox' ? e.target.checked : undefined;
2711
+ var newValue = type === 'checkbox' ? checked : value;
2712
+ // Actualizar estado local
2713
+ setFormData(function (prevData) {
2714
+ var _a;
2715
+ return (__assign$1(__assign$1({}, prevData), (_a = {}, _a[name] = newValue, _a)));
2716
+ });
2717
+ // Limpiar error del campo
2718
+ if (errors[name]) {
2719
+ setErrors(function (prev) {
2720
+ var _a;
2721
+ return (__assign$1(__assign$1({}, prev), (_a = {}, _a[name] = '', _a)));
2722
+ });
2723
+ }
2724
+ };
2725
+ var validateForm = function () { return __awaiter(void 0, void 0, void 0, function () {
2726
+ var validationSchema, validationError_1, newErrors_1;
2727
+ return __generator(this, function (_a) {
2728
+ switch (_a.label) {
2729
+ case 0:
2730
+ _a.trys.push([0, 2, , 3]);
2731
+ validationSchema = createValidationSchema(config.fields);
2732
+ // Validar los datos del formulario
2733
+ return [4 /*yield*/, validationSchema.validate(__assign$1(__assign$1({}, formData), stepperData), { abortEarly: false })];
2734
+ case 1:
2735
+ // Validar los datos del formulario
2736
+ _a.sent();
2737
+ // Si llega aquí, la validación fue exitosa
2738
+ setErrors({});
2739
+ return [2 /*return*/, true];
2740
+ case 2:
2741
+ validationError_1 = _a.sent();
2742
+ newErrors_1 = {};
2743
+ if (validationError_1.inner) {
2744
+ validationError_1.inner.forEach(function (error) {
2745
+ newErrors_1[error.path] = error.message;
2746
+ });
2747
+ }
2748
+ setErrors(newErrors_1);
2749
+ return [2 /*return*/, false];
2750
+ case 3: return [2 /*return*/];
2751
+ }
2752
+ });
2753
+ }); };
2754
+ var handleNext = function () { return __awaiter(void 0, void 0, void 0, function () {
2755
+ var isValid;
2756
+ return __generator(this, function (_a) {
2757
+ switch (_a.label) {
2758
+ case 0: return [4 /*yield*/, validateForm()];
2759
+ case 1:
2760
+ isValid = _a.sent();
2761
+ if (isValid) {
2762
+ if (onStepComplete) {
2763
+ onStepComplete(2); // Asumiendo que es el paso 2, se puede hacer configurable
2764
+ }
2765
+ if (config.onNext) {
2766
+ config.onNext(__assign$1(__assign$1({}, stepperData), formData));
2767
+ }
2768
+ }
2769
+ return [2 /*return*/];
2770
+ }
2771
+ });
2772
+ }); };
2773
+ var handleOut = function () {
2774
+ if (config.onOut) {
2775
+ config.onOut();
2776
+ }
2777
+ };
2778
+ var handleBack = function () {
2779
+ if (config.onBack) {
2780
+ config.onBack();
2781
+ }
2782
+ };
2783
+ var renderField = function (field) {
2784
+ var _a, _b, _c;
2785
+ // Prioridad: field.value > formData > getFieldValue
2786
+ var fieldValue = (_b = (_a = formData[field.name]) !== null && _a !== void 0 ? _a : field.value) !== null && _b !== void 0 ? _b : getFieldValue(field);
2787
+ // Preparar el campo con las funciones de búsqueda si están disponibles
2788
+ var fieldWithHandlers = __assign$1(__assign$1({}, field), { onSearch: function (value) {
2789
+ var _a;
2790
+ if (field.onSearch) {
2791
+ (_a = config.onSearch) === null || _a === void 0 ? void 0 : _a.call(config, field, value, __assign$1(__assign$1({}, stepperData), formData));
2792
+ }
2793
+ } });
2794
+ return (jsx("div", { className: (_c = field.className) !== null && _c !== void 0 ? _c : 'col-span-12 md:col-span-6', children: jsx(DynamicInput, { field: fieldWithHandlers, value: fieldValue, onChange: handleInputChange, error: errors[field.name] }) }, field.id));
2795
+ };
2796
+ var buttonHandlers = {
2797
+ handleBack: handleBack,
2798
+ handleNext: handleNext,
2799
+ handleOut: handleOut,
2800
+ // agrega más handlers si es necesario
2801
+ };
2802
+ var isButtonDisabled = function (btn) {
2803
+ if (config.fields.length === 0)
2804
+ return false;
2805
+ if (btn.direction === 'back' || btn.direction === 'out-light')
2806
+ return false;
2807
+ // Tu lógica de disabled para los demás botones:
2808
+ return (btn.disabled ||
2809
+ loading ||
2810
+ !Object.values(formData).some(function (value) { return value !== '' && value !== false; }));
2811
+ };
2812
+ if (loading) {
2813
+ return (jsxs("div", { className: "min-h-[550px] flex flex-col justify-between gap-10 ".concat(className), children: [jsxs("div", { className: "flex flex-col gap-10", children: [jsxs("div", { id: "title", children: [jsx("div", { className: "h-8 bg-gray-200 rounded animate-pulse w-3/4 mb-2" }), jsx("div", { className: "w-full h-[3px] bg-gray-200 rounded-full animate-pulse" })] }), jsxs("div", { className: "text-gray-500 text-lg font-normal flex flex-col gap-2", children: [jsx("div", { className: "h-6 bg-gray-200 rounded animate-pulse w-1/2 ml-5" }), jsx("div", { className: "w-full h-[1px] bg-gray-200 animate-pulse" })] }), jsx("div", { children: jsx("div", { className: "flex max-w-1xl mx-auto flex-col gap-4", children: jsx("div", { className: "grid grid-cols-12 gap-4", children: (_b = config === null || config === void 0 ? void 0 : config.fields) === null || _b === void 0 ? void 0 : _b.map(function (field) { return (jsxs("div", { className: "col-span-12 md:col-span-6", children: [jsx("div", { className: "h-4 bg-gray-200 rounded animate-pulse w-1/3 mb-2" }), jsx("div", { className: "h-10 bg-gray-200 rounded animate-pulse w-full" })] }, field.id)); }) }) }) })] }), jsxs("div", { className: "flex justify-between", children: [jsxs("div", { className: "flex gap-2", children: [jsx("div", { className: "h-10 bg-gray-200 rounded animate-pulse w-20" }), jsx("div", { className: "h-10 bg-gray-200 rounded animate-pulse w-20" })] }), jsx("div", { className: "h-10 bg-gray-200 rounded animate-pulse w-24" })] })] }));
2814
+ }
2815
+ return (jsxs("div", { className: "min-h-[550px] flex flex-col justify-between gap-10 ".concat(className), children: [jsxs("div", { className: "flex flex-col gap-10", children: [jsxs("div", { id: "title", children: [jsx("h1", { className: "text-gray-800 text-3xl font-bold font-roboto", children: config.title }), jsx("div", { className: "w-full h-[3px] bg-orange-500 rounded-full mt-2" })] }), (config === null || config === void 0 ? void 0 : config.subtitle) && (jsx(Fragment, { children: jsxs("div", { className: "text-gray-500 text-lg font-normal flex flex-col gap-2", children: [jsx("h3", { className: "pl-5 text-[24px] text-gray-800 text-xl font-bold font-roboto", children: config.subtitle }), jsx("hr", { className: "w-full border-gray-400" })] }) })), config.showInfoAlert && config.infoMessage && (jsx(Alert, { type: (_c = config.infoMessage.type) !== null && _c !== void 0 ? _c : 'info', text: config.infoMessage.message })), jsx("div", { children: jsx("form", { className: "flex max-w-1xl mx-auto flex-col gap-4", children: jsx("div", { className: "grid grid-cols-12 gap-4", children: config.fields.map(renderField) }) }) })] }), ((_d = config === null || config === void 0 ? void 0 : config.navigation) === null || _d === void 0 ? void 0 : _d.buttons) && (jsx("div", { className: (_f = (_e = config.navigation) === null || _e === void 0 ? void 0 : _e.containerClass) !== null && _f !== void 0 ? _f : 'flex justify-between', children: (_h = (_g = config === null || config === void 0 ? void 0 : config.navigation) === null || _g === void 0 ? void 0 : _g.buttons) === null || _h === void 0 ? void 0 : _h.map(function (btn) {
2816
+ var _a;
2817
+ return btn.show ? (jsx("div", { className: (_a = btn.className) !== null && _a !== void 0 ? _a : '', children: jsx(NavigationButton, { direction: btn.direction, onClick: buttonHandlers[btn.onClick], disabled: isButtonDisabled(btn), label: btn.label }) }, btn.key)) : null;
2818
+ }) }))] }));
2819
+ };
2820
+
2821
+ export { Alert, CheckboxInput, DynamicInput, GenericForm, InputWrapper, NavigationButton, RutInput, SelectInput, TextInput, TextareaInput, clean as cleanRut, commonValidations, createValidationSchema, formatRut, maskRut, validateOnlyNumbersAndLetters, validate as validateRut };
2822
+ //# sourceMappingURL=index.esm.js.map