@regle/core 1.1.0-beta.1 → 1.1.0-beta.3

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.
@@ -1,2710 +0,0 @@
1
- 'use strict';
2
-
3
- var vue = require('vue');
4
-
5
- // ../shared/utils/isEmpty.ts
6
- function isEmpty(value, considerEmptyArrayInvalid = true) {
7
- if (value === void 0 || value === null) {
8
- return true;
9
- }
10
- if (value instanceof Date) {
11
- return isNaN(value.getTime());
12
- } else if (value.constructor.name == "File" || value.constructor.name == "FileList") {
13
- return value.size <= 0;
14
- } else if (Array.isArray(value)) {
15
- if (considerEmptyArrayInvalid) {
16
- return value.length === 0;
17
- }
18
- return false;
19
- } else if (typeof value === "object" && value != null) {
20
- return Object.keys(value).length === 0;
21
- }
22
- return !String(value).length;
23
- }
24
-
25
- // ../shared/utils/symbol.ts
26
- var RegleRuleSymbol = Symbol("regle-rule");
27
-
28
- // ../shared/utils/cloneDeep.ts
29
- function getRegExpFlags(regExp) {
30
- if (typeof regExp.source.flags == "string") {
31
- return regExp.source.flags;
32
- } else {
33
- let flags = [];
34
- regExp.global && flags.push("g");
35
- regExp.ignoreCase && flags.push("i");
36
- regExp.multiline && flags.push("m");
37
- regExp.sticky && flags.push("y");
38
- regExp.unicode && flags.push("u");
39
- return flags.join("");
40
- }
41
- }
42
- function cloneDeep(obj) {
43
- let result = obj;
44
- let type = {}.toString.call(obj).slice(8, -1);
45
- if (type == "Set") {
46
- result = new Set([...obj].map((value) => cloneDeep(value)));
47
- }
48
- if (type == "Map") {
49
- result = new Map([...obj].map((kv) => [cloneDeep(kv[0]), cloneDeep(kv[1])]));
50
- }
51
- if (type == "Date") {
52
- result = new Date(obj.getTime());
53
- }
54
- if (type == "RegExp") {
55
- result = RegExp(obj.source, getRegExpFlags(obj));
56
- }
57
- if (type == "Array" || type == "Object") {
58
- result = Array.isArray(obj) ? [] : {};
59
- for (let key in obj) {
60
- result[key] = cloneDeep(obj[key]);
61
- }
62
- }
63
- return result;
64
- }
65
-
66
- // ../shared/utils/object.utils.ts
67
- function isObject(obj) {
68
- if (obj && (obj instanceof Date || obj.constructor.name == "File" || obj.constructor.name == "FileList")) {
69
- return false;
70
- }
71
- return typeof obj === "object" && obj !== null && !Array.isArray(obj);
72
- }
73
-
74
- // ../shared/utils/toDate.ts
75
- function toDate(argument) {
76
- const argStr = Object.prototype.toString.call(argument);
77
- if (argument == null) {
78
- return /* @__PURE__ */ new Date(NaN);
79
- } else if (argument instanceof Date || typeof argument === "object" && argStr === "[object Date]") {
80
- return new Date(argument.getTime());
81
- } else if (typeof argument === "number" || argStr === "[object Number]") {
82
- return new Date(argument);
83
- } else if (typeof argument === "string" || argStr === "[object String]") {
84
- return new Date(argument);
85
- } else {
86
- return /* @__PURE__ */ new Date(NaN);
87
- }
88
- }
89
-
90
- // ../shared/utils/debounce.ts
91
- function debounce(func, wait, immediate) {
92
- let timeout;
93
- const debouncedFn = (...args) => new Promise((resolve) => {
94
- clearTimeout(timeout);
95
- timeout = setTimeout(() => {
96
- timeout = void 0;
97
- {
98
- Promise.resolve(func.apply(this, [...args])).then(resolve);
99
- }
100
- }, wait);
101
- });
102
- debouncedFn.cancel = () => {
103
- clearTimeout(timeout);
104
- timeout = void 0;
105
- };
106
- return debouncedFn;
107
- }
108
-
109
- // src/types/rules/rule.internal.types.ts
110
- var InternalRuleType = {
111
- Inline: "__inline",
112
- Async: "__async"
113
- };
114
- function mergeBooleanGroupProperties(entries, property) {
115
- return entries.some((entry) => {
116
- return entry[property];
117
- });
118
- }
119
- function mergeArrayGroupProperties(entries, property) {
120
- return entries.reduce((all, entry) => {
121
- const fetchedProperty = entry[property] || [];
122
- return all.concat(fetchedProperty);
123
- }, []);
124
- }
125
- function unwrapRuleParameters(params) {
126
- try {
127
- return params.map((param) => vue.toValue(param));
128
- } catch (e) {
129
- return [];
130
- }
131
- }
132
- function createReactiveParams(params) {
133
- return params.map((param) => {
134
- if (param instanceof Function) {
135
- return vue.computed(param);
136
- } else if (vue.isRef(param)) {
137
- return param;
138
- }
139
- return vue.toRef(() => param);
140
- });
141
- }
142
- function getFunctionParametersLength(func) {
143
- const funcStr = func.toString();
144
- const cleanStr = funcStr.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
145
- const paramsMatch = cleanStr.match(
146
- /^(?:async\s*)?(?:function\b.*?\(|\((.*?)\)|(\w+))\s*=>|\((.*?)\)\s*=>|function.*?\((.*?)\)|\((.*?)\)/
147
- );
148
- if (!paramsMatch) return 0;
149
- const paramsSection = paramsMatch[0] || paramsMatch[1] || paramsMatch[2] || paramsMatch[3] || paramsMatch[4] || "";
150
- const paramList = paramsSection.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
151
- return paramList.length;
152
- }
153
-
154
- // src/core/createRule/defineRuleProcessors.ts
155
- function defineRuleProcessors(definition, ...params) {
156
- const { validator, type } = definition;
157
- const isAsync = type === InternalRuleType.Async || validator.constructor.name === "AsyncFunction";
158
- const defaultProcessors = {
159
- validator(value, ...args) {
160
- return definition.validator(value, ...unwrapRuleParameters(args.length ? args : params));
161
- },
162
- message(metadata) {
163
- if (typeof definition.message === "function") {
164
- return definition.message({
165
- ...metadata,
166
- $params: unwrapRuleParameters(metadata?.$params?.length ? metadata.$params : params)
167
- });
168
- } else {
169
- return definition.message;
170
- }
171
- },
172
- active(metadata) {
173
- if (typeof definition.active === "function") {
174
- return definition.active({
175
- ...metadata,
176
- $params: unwrapRuleParameters(metadata?.$params?.length ? metadata.$params : params)
177
- });
178
- } else {
179
- return definition.active ?? true;
180
- }
181
- },
182
- tooltip(metadata) {
183
- if (typeof definition.tooltip === "function") {
184
- return definition.tooltip({
185
- ...metadata,
186
- $params: unwrapRuleParameters(metadata?.$params?.length ? metadata.$params : params)
187
- });
188
- } else {
189
- return definition.tooltip ?? [];
190
- }
191
- },
192
- exec(value) {
193
- const validator2 = definition.validator(value, ...unwrapRuleParameters(params));
194
- let rawResult;
195
- if (validator2 instanceof Promise) {
196
- return validator2.then((result) => {
197
- rawResult = result;
198
- if (typeof rawResult === "object" && "$valid" in rawResult) {
199
- return rawResult.$valid;
200
- } else if (typeof rawResult === "boolean") {
201
- return rawResult;
202
- }
203
- return false;
204
- });
205
- } else {
206
- rawResult = validator2;
207
- }
208
- if (typeof rawResult === "object" && "$valid" in rawResult) {
209
- return rawResult.$valid;
210
- } else if (typeof rawResult === "boolean") {
211
- return rawResult;
212
- }
213
- return false;
214
- }
215
- };
216
- const processors = {
217
- ...defaultProcessors,
218
- _validator: definition.validator,
219
- _message: definition.message,
220
- _active: definition.active,
221
- _tooltip: definition.tooltip,
222
- _type: definition.type,
223
- _message_patched: false,
224
- _tooltip_patched: false,
225
- _async: isAsync,
226
- _params: createReactiveParams(params),
227
- _brand: RegleRuleSymbol
228
- };
229
- return processors;
230
- }
231
-
232
- // src/core/createRule/createRule.ts
233
- function createRule(definition) {
234
- if (typeof definition.validator === "function") {
235
- let fakeParams = [];
236
- const staticProcessors = defineRuleProcessors(definition, ...fakeParams);
237
- const isAsync = definition.async ?? definition.validator.constructor.name === "AsyncFunction";
238
- if (getFunctionParametersLength(definition.validator) > 1) {
239
- const ruleFactory = function(...params) {
240
- return defineRuleProcessors(definition, ...params);
241
- };
242
- ruleFactory.validator = staticProcessors.validator;
243
- ruleFactory.message = staticProcessors.message;
244
- ruleFactory.active = staticProcessors.active;
245
- ruleFactory.tooltip = staticProcessors.tooltip;
246
- ruleFactory.type = staticProcessors.type;
247
- ruleFactory.exec = staticProcessors.exec;
248
- ruleFactory._validator = staticProcessors.validator;
249
- ruleFactory._message = staticProcessors.message;
250
- ruleFactory._active = staticProcessors.active;
251
- ruleFactory._tooltip = staticProcessors.tooltip;
252
- ruleFactory._type = definition.type;
253
- ruleFactory._message_pacthed = false;
254
- ruleFactory._tooltip_pacthed = false;
255
- ruleFactory._async = isAsync;
256
- return ruleFactory;
257
- } else {
258
- return staticProcessors;
259
- }
260
- }
261
- throw new Error("Validator must be a function");
262
- }
263
- function useStorage() {
264
- const ruleDeclStorage = vue.shallowRef(/* @__PURE__ */ new Map());
265
- const fieldsStorage = vue.shallowRef(/* @__PURE__ */ new Map());
266
- const collectionsStorage = vue.shallowRef(/* @__PURE__ */ new Map());
267
- const dirtyStorage = vue.shallowRef(/* @__PURE__ */ new Map());
268
- const ruleStatusStorage = vue.shallowRef(/* @__PURE__ */ new Map());
269
- const arrayStatusStorage = vue.shallowRef(/* @__PURE__ */ new Map());
270
- function getFieldsEntry($path) {
271
- const existingFields = fieldsStorage.value.get($path);
272
- if (existingFields) {
273
- return existingFields;
274
- } else {
275
- const $fields = vue.ref({});
276
- fieldsStorage.value.set($path, $fields);
277
- return $fields;
278
- }
279
- }
280
- function getCollectionsEntry($path) {
281
- const existingEach = collectionsStorage.value.get($path);
282
- if (existingEach) {
283
- return existingEach;
284
- } else {
285
- const $each = vue.ref([]);
286
- collectionsStorage.value.set($path, $each);
287
- return $each;
288
- }
289
- }
290
- function addArrayStatus($arrayId, itemId, value) {
291
- arrayStatusStorage.value.set(`${$arrayId}-${itemId}`, value);
292
- }
293
- function getArrayStatus($arrayId, itemId) {
294
- return arrayStatusStorage.value.get(`${$arrayId}-${itemId}`);
295
- }
296
- function deleteArrayStatus($arrayId, itemId) {
297
- if ($arrayId && itemId != null) {
298
- arrayStatusStorage.value.delete(`${$arrayId}-${itemId}`);
299
- }
300
- }
301
- function setDirtyEntry($path, dirty) {
302
- dirtyStorage.value.set($path, dirty);
303
- }
304
- function getDirtyState(path) {
305
- return dirtyStorage.value.get(path) ?? false;
306
- }
307
- function addRuleDeclEntry($path, options) {
308
- ruleDeclStorage.value.set($path, options);
309
- }
310
- function checkRuleDeclEntry($path, newRules) {
311
- const storedRulesDefs = ruleDeclStorage.value.get($path);
312
- if (!storedRulesDefs) return void 0;
313
- const storedRules = storedRulesDefs;
314
- const isValidCache = areRulesChanged(newRules, storedRules);
315
- if (!isValidCache) return { valid: false };
316
- return { valid: true };
317
- }
318
- function areRulesChanged(newRules, storedRules) {
319
- const storedRulesKeys = Object.keys(storedRules);
320
- const newRulesKeys = Object.keys(newRules);
321
- if (newRulesKeys.length !== storedRulesKeys.length) return false;
322
- const hasAllValidators = newRulesKeys.every((ruleKey) => storedRulesKeys.includes(ruleKey));
323
- if (!hasAllValidators) return false;
324
- return newRulesKeys.every((ruleKey) => {
325
- const newRuleElement = newRules[ruleKey];
326
- const storedRuleElement = storedRules[ruleKey];
327
- if (!storedRuleElement || !newRuleElement || typeof newRuleElement === "function" || typeof storedRuleElement === "function")
328
- return false;
329
- if (typeof newRuleElement === "number") {
330
- return false;
331
- } else if (typeof newRuleElement === "boolean") {
332
- return false;
333
- } else if (!newRuleElement._params) return true;
334
- else {
335
- return newRuleElement._params?.every((paramKey, index) => {
336
- if (typeof storedRuleElement === "number" || typeof storedRuleElement === "boolean") {
337
- return true;
338
- } else {
339
- const storedParams = unwrapRuleParameters(storedRuleElement._params);
340
- const newParams = unwrapRuleParameters(newRuleElement._params);
341
- return storedParams?.[index] === newParams?.[index];
342
- }
343
- });
344
- }
345
- });
346
- }
347
- function trySetRuleStatusRef(path) {
348
- const ruleStatus = ruleStatusStorage.value.get(path);
349
- if (ruleStatus) {
350
- return ruleStatus;
351
- } else {
352
- const $pending = vue.ref(false);
353
- const $valid = vue.ref(true);
354
- const $metadata = vue.ref({});
355
- const $validating = vue.ref(false);
356
- ruleStatusStorage.value.set(path, { $pending, $valid, $metadata, $validating });
357
- return { $pending, $valid, $metadata, $validating };
358
- }
359
- }
360
- if (vue.getCurrentScope()) {
361
- vue.onScopeDispose(() => {
362
- ruleDeclStorage.value.clear();
363
- fieldsStorage.value.clear();
364
- collectionsStorage.value.clear();
365
- dirtyStorage.value.clear();
366
- ruleStatusStorage.value.clear();
367
- arrayStatusStorage.value.clear();
368
- });
369
- }
370
- return {
371
- addRuleDeclEntry,
372
- setDirtyEntry,
373
- checkRuleDeclEntry,
374
- getDirtyState,
375
- trySetRuleStatusRef,
376
- getFieldsEntry,
377
- getCollectionsEntry,
378
- getArrayStatus,
379
- addArrayStatus,
380
- deleteArrayStatus,
381
- arrayStatusStorage
382
- };
383
- }
384
- function isRefObject(obj) {
385
- return isObject(obj.value);
386
- }
387
- function unwrapGetter(getter, value, index) {
388
- const scope = vue.effectScope();
389
- let unwrapped;
390
- if (getter instanceof Function) {
391
- unwrapped = scope.run(() => getter(value, index ?? 0));
392
- } else {
393
- unwrapped = getter;
394
- }
395
- return { scope, unwrapped };
396
- }
397
- var VersionIs = {
398
- LessThan: -1,
399
- EqualTo: 0,
400
- GreaterThan: 1
401
- };
402
- function versionCompare(current, other) {
403
- const cp = String(current).split(".");
404
- const op = String(other).split(".");
405
- for (let depth = 0; depth < Math.min(cp.length, op.length); depth++) {
406
- const cn = Number(cp[depth]);
407
- const on = Number(op[depth]);
408
- if (cn > on) return VersionIs.GreaterThan;
409
- if (on > cn) return VersionIs.LessThan;
410
- if (!isNaN(cn) && isNaN(on)) return VersionIs.GreaterThan;
411
- if (isNaN(cn) && !isNaN(on)) return VersionIs.LessThan;
412
- }
413
- return VersionIs.EqualTo;
414
- }
415
- var isVueSuperiorOrEqualTo3dotFive = versionCompare(vue.version, "3.5.0") === -1 ? false : true;
416
-
417
- // src/utils/randomId.ts
418
- function uniqueIDNuxt() {
419
- return Math.floor(Math.random() * Date.now()).toString();
420
- }
421
- function randomId() {
422
- if (typeof window === "undefined") {
423
- return uniqueIDNuxt();
424
- } else {
425
- const uint32 = window.crypto.getRandomValues(new Uint32Array(1))[0];
426
- return uint32.toString(10);
427
- }
428
- }
429
- function tryOnScopeDispose(fn) {
430
- if (vue.getCurrentScope()) {
431
- vue.onScopeDispose(fn);
432
- return true;
433
- }
434
- return false;
435
- }
436
- function createGlobalState(stateFactory) {
437
- let initialized = false;
438
- let state;
439
- const scope = vue.effectScope(true);
440
- return (...args) => {
441
- if (!initialized) {
442
- state = scope.run(() => stateFactory(...args));
443
- initialized = true;
444
- }
445
- return state;
446
- };
447
- }
448
-
449
- // src/core/useRegle/guards/ruleDef.guards.ts
450
- function isNestedRulesDef(state, rules) {
451
- return isRefObject(state) || isObject(rules.value) && !isEmpty(rules.value) && !Object.entries(rules.value).some(([key, rule]) => isRuleDef(rule) || typeof rule === "function");
452
- }
453
- function isCollectionRulesDef(rules, state, schemaMode = false) {
454
- return !!rules.value && isObject(rules.value) && "$each" in rules.value || schemaMode && Array.isArray(state.value) && state.value.some(isObject) || Array.isArray(state.value) && state.value.some(isObject);
455
- }
456
- function isValidatorRulesDef(rules) {
457
- return !!rules.value && isObject(rules.value);
458
- }
459
- function isRuleDef(rule) {
460
- return isObject(rule) && "_validator" in rule;
461
- }
462
- function isFormRuleDefinition(rule) {
463
- return !(typeof rule.value === "function");
464
- }
465
-
466
- // src/core/useRegle/guards/rule.status.guards.ts
467
- function isNestedRulesStatus(rule) {
468
- return isObject(rule) && "$fields" in rule;
469
- }
470
- function isFieldStatus(rule) {
471
- return !!rule && "$rules" in rule;
472
- }
473
-
474
- // src/core/useRegle/useErrors.ts
475
- function extractRulesErrors({
476
- field,
477
- silent = false
478
- }) {
479
- return Object.entries(field.$rules ?? {}).map(([_, rule]) => {
480
- if (silent && !rule.$valid) {
481
- return rule.$message;
482
- } else if (!rule.$valid && field.$error && !rule.$validating) {
483
- return rule.$message;
484
- }
485
- return null;
486
- }).filter((msg) => !!msg).reduce((acc, value) => {
487
- if (typeof value === "string") {
488
- return acc?.concat([value]);
489
- } else {
490
- return acc?.concat(value);
491
- }
492
- }, []).concat(field.$error ? field.$externalErrors ?? [] : []).concat(field.$error ? field.$schemaErrors ?? [] : []);
493
- }
494
- function extractRulesTooltips({ field }) {
495
- return Object.entries(field.$rules ?? {}).map(([_, rule]) => rule.$tooltip).filter((tooltip) => !!tooltip).reduce((acc, value) => {
496
- if (typeof value === "string") {
497
- return acc?.concat([value]);
498
- } else {
499
- return acc?.concat(value);
500
- }
501
- }, []);
502
- }
503
- function isCollectionError(errors) {
504
- return isObject(errors) && "$each" in errors;
505
- }
506
- function flatErrors(errors, options) {
507
- const { includePath = false } = options ?? {};
508
- if (Array.isArray(errors) && errors.every((err) => !isObject(err))) {
509
- return errors;
510
- } else if (isCollectionError(errors)) {
511
- const selfErrors = includePath ? errors.$self?.map((err) => ({ error: err, path: "" })) ?? [] : errors.$self ?? [];
512
- const eachErrors = errors.$each?.map((err) => interateErrors(err, includePath)) ?? [];
513
- return selfErrors?.concat(eachErrors.flat());
514
- } else {
515
- return Object.entries(errors).map(([key, value]) => interateErrors(value, includePath, [key])).flat();
516
- }
517
- }
518
- function interateErrors(errors, includePath = false, _path) {
519
- const path = includePath && !_path ? [] : _path;
520
- if (Array.isArray(errors) && errors.every((err) => !isObject(err))) {
521
- if (includePath) {
522
- return errors.map((err) => ({ error: err, path: path?.join(".") ?? "" }));
523
- }
524
- return errors;
525
- } else if (isCollectionError(errors)) {
526
- const selfErrors = path?.length ? errors.$self?.map((err) => ({ error: err, path: path.join(".") })) ?? [] : errors.$self ?? [];
527
- const eachErrors = errors.$each?.map((err, index) => interateErrors(err, includePath, path?.concat(index.toString()))) ?? [];
528
- return selfErrors?.concat(eachErrors.flat());
529
- } else {
530
- return Object.entries(errors).map(([key, value]) => interateErrors(value, includePath, path?.concat(key))).flat();
531
- }
532
- }
533
- function createReactiveRuleStatus({
534
- customMessages,
535
- rule,
536
- ruleKey,
537
- state,
538
- path,
539
- storage,
540
- $debounce,
541
- modifiers
542
- }) {
543
- let scope = vue.effectScope();
544
- let scopeState = {};
545
- let $unwatchState;
546
- const $haveAsync = vue.ref(false);
547
- const { $pending, $valid, $metadata, $validating } = storage.trySetRuleStatusRef(`${path}.${ruleKey}`);
548
- function $watch() {
549
- scope = vue.effectScope();
550
- scopeState = scope.run(() => {
551
- const $fieldDirty = vue.ref(false);
552
- const $fieldError = vue.ref(false);
553
- const $fieldInvalid = vue.ref(true);
554
- const $fieldPending = vue.ref(false);
555
- const $fieldCorrect = vue.ref(false);
556
- const $defaultMetadata = vue.computed(() => ({
557
- $value: state.value,
558
- $error: $fieldError.value,
559
- $dirty: $fieldDirty.value,
560
- $pending: $fieldPending.value,
561
- $correct: $fieldCorrect.value,
562
- $invalid: $fieldInvalid.value,
563
- $rule: {
564
- $valid: $valid.value,
565
- $invalid: !$valid.value,
566
- $pending: $pending.value
567
- },
568
- $params: $params.value,
569
- ...$metadata.value
570
- }));
571
- const $active = vue.computed(() => {
572
- if (isFormRuleDefinition(rule)) {
573
- if (typeof rule.value.active === "function") {
574
- return rule.value.active($defaultMetadata.value);
575
- } else {
576
- return !!rule.value.active;
577
- }
578
- } else {
579
- return true;
580
- }
581
- });
582
- function computeRuleProcessor(key) {
583
- let result = "";
584
- const customProcessor = customMessages ? customMessages[ruleKey]?.[key] : void 0;
585
- if (customProcessor) {
586
- if (typeof customProcessor === "function") {
587
- result = customProcessor($defaultMetadata.value);
588
- } else {
589
- result = customProcessor;
590
- }
591
- }
592
- if (isFormRuleDefinition(rule)) {
593
- const patchedKey = `_${key}_patched`;
594
- if (!(customProcessor && !rule.value[patchedKey])) {
595
- if (typeof rule.value[key] === "function") {
596
- result = rule.value[key]($defaultMetadata.value);
597
- } else {
598
- result = rule.value[key] ?? "";
599
- }
600
- }
601
- }
602
- return result;
603
- }
604
- const $message = vue.computed(() => {
605
- let message = computeRuleProcessor("message");
606
- if (isEmpty(message)) {
607
- message = "This field is not valid";
608
- }
609
- return message;
610
- });
611
- const $tooltip = vue.computed(() => {
612
- return computeRuleProcessor("tooltip");
613
- });
614
- const $type = vue.computed(() => {
615
- if (isFormRuleDefinition(rule) && rule.value.type) {
616
- return rule.value.type;
617
- } else {
618
- return ruleKey;
619
- }
620
- });
621
- const $validator = vue.computed(() => {
622
- if (isFormRuleDefinition(rule)) {
623
- return rule.value.validator;
624
- } else {
625
- return rule.value;
626
- }
627
- });
628
- const $params = vue.computed(() => {
629
- if (typeof rule.value === "function") {
630
- return [];
631
- }
632
- return unwrapRuleParameters(rule.value._params ?? []);
633
- });
634
- const $path = vue.computed(() => `${path}.${$type.value}`);
635
- return {
636
- $active,
637
- $message,
638
- $type,
639
- $validator,
640
- $params,
641
- $path,
642
- $tooltip,
643
- $fieldCorrect,
644
- $fieldError,
645
- $fieldDirty,
646
- $fieldPending,
647
- $fieldInvalid
648
- };
649
- });
650
- $unwatchState = vue.watch(scopeState?.$params, () => {
651
- if (modifiers.$autoDirty.value || modifiers.$rewardEarly.value && scopeState.$fieldError.value) {
652
- $parse();
653
- }
654
- });
655
- }
656
- $watch();
657
- function updatePendingState() {
658
- $valid.value = true;
659
- if (scopeState.$fieldDirty.value) {
660
- $pending.value = true;
661
- }
662
- }
663
- async function computeAsyncResult() {
664
- let ruleResult = false;
665
- try {
666
- const validator = scopeState.$validator.value;
667
- if (typeof validator !== "function") {
668
- console.error(`${path}: Incorrect rule format, it needs to be either a function or created with "createRule".`);
669
- return false;
670
- }
671
- const resultOrPromise = validator(state.value, ...scopeState.$params.value);
672
- let cachedValue = state.value;
673
- updatePendingState();
674
- let validatorResult;
675
- if (resultOrPromise instanceof Promise) {
676
- validatorResult = await resultOrPromise;
677
- } else {
678
- validatorResult = resultOrPromise;
679
- }
680
- if (state.value !== cachedValue) {
681
- return true;
682
- }
683
- if (typeof validatorResult === "boolean") {
684
- ruleResult = validatorResult;
685
- } else {
686
- const { $valid: $valid2, ...rest } = validatorResult;
687
- ruleResult = $valid2;
688
- $metadata.value = rest;
689
- }
690
- } catch (e) {
691
- ruleResult = false;
692
- } finally {
693
- $pending.value = false;
694
- }
695
- return ruleResult;
696
- }
697
- const $computeAsyncDebounce = debounce(computeAsyncResult, $debounce ?? 200);
698
- async function $parse() {
699
- try {
700
- $validating.value = true;
701
- let ruleResult = false;
702
- if (isRuleDef(rule.value) && rule.value._async) {
703
- ruleResult = await $computeAsyncDebounce();
704
- } else {
705
- const validator = scopeState.$validator.value;
706
- const resultOrPromise = validator(state.value, ...scopeState.$params.value);
707
- if (resultOrPromise instanceof Promise) {
708
- console.warn(
709
- 'You used a async validator function on a non-async rule, please use "async await" or the "withAsync" helper'
710
- );
711
- } else {
712
- if (resultOrPromise != null) {
713
- if (typeof resultOrPromise === "boolean") {
714
- ruleResult = resultOrPromise;
715
- } else {
716
- const { $valid: $valid2, ...rest } = resultOrPromise;
717
- ruleResult = $valid2;
718
- $metadata.value = rest;
719
- }
720
- }
721
- }
722
- }
723
- $valid.value = ruleResult;
724
- return ruleResult;
725
- } catch (e) {
726
- return false;
727
- } finally {
728
- $validating.value = false;
729
- }
730
- }
731
- function $reset() {
732
- $valid.value = true;
733
- $metadata.value = {};
734
- $pending.value = false;
735
- $validating.value = false;
736
- $watch();
737
- }
738
- function $unwatch() {
739
- $unwatchState();
740
- scope.stop();
741
- scope = vue.effectScope();
742
- }
743
- return vue.reactive({
744
- ...scopeState,
745
- $pending,
746
- $valid,
747
- $metadata,
748
- $haveAsync,
749
- $validating,
750
- $parse,
751
- $unwatch,
752
- $watch,
753
- $reset
754
- });
755
- }
756
-
757
- // src/core/useRegle/root/createReactiveFieldStatus.ts
758
- function createReactiveFieldStatus({
759
- state,
760
- rulesDef,
761
- customMessages,
762
- path,
763
- fieldName,
764
- storage,
765
- options,
766
- externalErrors,
767
- schemaErrors,
768
- schemaMode,
769
- onUnwatch,
770
- $isArray,
771
- initialState,
772
- shortcuts,
773
- onValidate
774
- }) {
775
- let scope = vue.effectScope();
776
- let scopeState;
777
- let fieldScopes = [];
778
- let $unwatchState;
779
- let $unwatchValid;
780
- let $unwatchDirty;
781
- let $unwatchAsync;
782
- let $unwatchRuleFieldValues;
783
- let $commit = () => {
784
- };
785
- function createReactiveRulesResult() {
786
- const declaredRules = rulesDef.value;
787
- const storeResult = storage.checkRuleDeclEntry(path, declaredRules);
788
- $localOptions.value = Object.fromEntries(
789
- Object.entries(declaredRules).filter(([ruleKey]) => ruleKey.startsWith("$"))
790
- );
791
- $watch();
792
- $rules.value = Object.fromEntries(
793
- Object.entries(rulesDef.value).filter(([ruleKey]) => !ruleKey.startsWith("$")).map(([ruleKey, rule]) => {
794
- if (rule) {
795
- const ruleRef = vue.toRef(() => rule);
796
- return [
797
- ruleKey,
798
- createReactiveRuleStatus({
799
- modifiers: {
800
- $autoDirty: scopeState.$autoDirty,
801
- $rewardEarly: scopeState.$rewardEarly
802
- },
803
- customMessages,
804
- rule: ruleRef,
805
- ruleKey,
806
- state,
807
- path,
808
- storage,
809
- $debounce: $localOptions.value.$debounce
810
- })
811
- ];
812
- }
813
- return [];
814
- }).filter((ruleDef) => !!ruleDef.length)
815
- );
816
- scopeState.processShortcuts();
817
- define$commit();
818
- if (storeResult?.valid != null) {
819
- scopeState.$dirty.value = storage.getDirtyState(path);
820
- if (scopeState.$dirty.value && scopeState.$autoDirty.value || scopeState.$rewardEarly.value && scopeState.$error.value) {
821
- $commit();
822
- }
823
- }
824
- storage.addRuleDeclEntry(path, declaredRules);
825
- }
826
- function define$commit() {
827
- $commit = scopeState.$debounce.value ? debounce($commitHandler, scopeState.$debounce.value ?? scopeState.$haveAnyAsyncRule ? 100 : 0) : $commitHandler;
828
- }
829
- function $unwatch() {
830
- if ($rules.value) {
831
- Object.entries($rules.value).forEach(([_, rule]) => {
832
- rule.$unwatch();
833
- });
834
- }
835
- $unwatchDirty();
836
- $unwatchRuleFieldValues?.();
837
- if (scopeState.$dirty.value) {
838
- storage.setDirtyEntry(path, scopeState.$dirty.value);
839
- }
840
- $unwatchState?.();
841
- $unwatchValid?.();
842
- scope.stop();
843
- scope = vue.effectScope();
844
- fieldScopes.forEach((s) => s.stop());
845
- fieldScopes = [];
846
- onUnwatch?.();
847
- $unwatchAsync?.();
848
- }
849
- function $watch() {
850
- if ($rules.value) {
851
- Object.entries($rules.value).forEach(([_, rule]) => {
852
- rule.$watch();
853
- });
854
- }
855
- scopeState = scope.run(() => {
856
- const $dirty = vue.ref(false);
857
- const triggerPunishment2 = vue.ref(false);
858
- const $anyDirty = vue.computed(() => $dirty.value);
859
- const $debounce2 = vue.computed(() => {
860
- return $localOptions.value.$debounce;
861
- });
862
- const $lazy2 = vue.computed(() => {
863
- if ($localOptions.value.$lazy != null) {
864
- return $localOptions.value.$lazy;
865
- } else if (vue.unref(options.lazy) != null) {
866
- return vue.unref(options.lazy);
867
- }
868
- return false;
869
- });
870
- const $rewardEarly2 = vue.computed(() => {
871
- if ($localOptions.value.$rewardEarly != null) {
872
- return $localOptions.value.$rewardEarly;
873
- } else if (vue.unref(options.rewardEarly) != null) {
874
- return vue.unref(options.rewardEarly);
875
- }
876
- return false;
877
- });
878
- const $clearExternalErrorsOnChange2 = vue.computed(() => {
879
- if ($localOptions.value.$clearExternalErrorsOnChange != null) {
880
- return $localOptions.value.$clearExternalErrorsOnChange;
881
- } else if (vue.unref(options.clearExternalErrorsOnChange) != null) {
882
- return vue.unref(options.clearExternalErrorsOnChange);
883
- }
884
- return true;
885
- });
886
- const $autoDirty2 = vue.computed(() => {
887
- if ($localOptions.value.$autoDirty != null) {
888
- return $localOptions.value.$autoDirty;
889
- } else if (vue.unref(options.autoDirty) != null) {
890
- return vue.unref(options.autoDirty);
891
- } else if ($rewardEarly2.value) {
892
- return false;
893
- }
894
- return true;
895
- });
896
- const $validating2 = vue.computed(() => {
897
- return Object.entries($rules.value).some(([key, ruleResult]) => {
898
- return ruleResult.$validating;
899
- });
900
- });
901
- const $silentValue = vue.computed({
902
- get: () => state.value,
903
- set(value) {
904
- $unwatchState();
905
- state.value = value;
906
- define$watchState();
907
- }
908
- });
909
- const $error = vue.computed(() => {
910
- return $invalid.value && !$pending.value && $dirty.value;
911
- });
912
- const $errors = vue.computed(() => {
913
- return extractRulesErrors({
914
- field: {
915
- $rules: $rules.value,
916
- $error: $error.value,
917
- $externalErrors: externalErrors?.value,
918
- $schemaErrors: schemaErrors?.value
919
- }
920
- });
921
- });
922
- const $silentErrors = vue.computed(() => {
923
- return extractRulesErrors({
924
- field: {
925
- $rules: $rules.value,
926
- $error: $error.value,
927
- $externalErrors: externalErrors?.value,
928
- $schemaErrors: schemaErrors?.value
929
- },
930
- silent: true
931
- });
932
- });
933
- const $edited = vue.computed(() => {
934
- if ($dirty.value) {
935
- if (initialState.value instanceof Date && state.value instanceof Date) {
936
- return toDate(initialState.value).getDate() !== toDate(state.value).getDate();
937
- }
938
- if (initialState.value == null) {
939
- return !!state.value;
940
- }
941
- if (Array.isArray(state.value) && Array.isArray(initialState.value)) {
942
- return state.value.length !== initialState.value.length;
943
- }
944
- return initialState.value !== state.value;
945
- }
946
- return false;
947
- });
948
- const $anyEdited = vue.computed(() => $edited.value);
949
- const $tooltips = vue.computed(() => {
950
- return extractRulesTooltips({
951
- field: {
952
- $rules: $rules.value
953
- }
954
- });
955
- });
956
- const $ready = vue.computed(() => {
957
- if (!$autoDirty2.value) {
958
- return !($invalid.value || $pending.value);
959
- }
960
- return $anyDirty.value && !($invalid.value || $pending.value);
961
- });
962
- const $pending = vue.computed(() => {
963
- if (triggerPunishment2.value || !$rewardEarly2.value) {
964
- return Object.entries($rules.value).some(([key, ruleResult]) => {
965
- return ruleResult.$pending;
966
- });
967
- }
968
- return false;
969
- });
970
- const $invalid = vue.computed(() => {
971
- if (externalErrors?.value?.length || schemaErrors?.value?.length) {
972
- return true;
973
- } else if ($inactive.value) {
974
- return false;
975
- } else if (!$rewardEarly2.value || $rewardEarly2.value && triggerPunishment2.value) {
976
- return Object.entries($rules.value).some(([_, ruleResult]) => {
977
- return !ruleResult.$valid;
978
- });
979
- }
980
- return false;
981
- });
982
- const $name = vue.computed(() => fieldName);
983
- const $inactive = vue.computed(() => {
984
- if (isEmpty($rules.value) && !schemaMode) {
985
- return true;
986
- }
987
- return false;
988
- });
989
- const $correct = vue.computed(() => {
990
- if (externalErrors?.value?.length) {
991
- return false;
992
- } else if ($inactive.value) {
993
- return false;
994
- } else if ($dirty.value && !isEmpty(state.value) && !$validating2.value) {
995
- if (schemaMode) {
996
- return !schemaErrors?.value?.length;
997
- } else {
998
- const atLeastOneActiveRule = Object.values($rules.value).some((ruleResult) => ruleResult.$active);
999
- if (atLeastOneActiveRule) {
1000
- return Object.values($rules.value).filter((ruleResult) => ruleResult.$active).every((ruleResult) => ruleResult.$valid);
1001
- } else {
1002
- return false;
1003
- }
1004
- }
1005
- }
1006
- return false;
1007
- });
1008
- const $haveAnyAsyncRule2 = vue.computed(() => {
1009
- return Object.entries($rules.value).some(([key, ruleResult]) => {
1010
- return ruleResult.$haveAsync;
1011
- });
1012
- });
1013
- function processShortcuts() {
1014
- if (shortcuts?.fields) {
1015
- Object.entries(shortcuts.fields).forEach(([key, value]) => {
1016
- const scope2 = vue.effectScope();
1017
- $shortcuts2[key] = scope2.run(() => {
1018
- const result = vue.ref();
1019
- vue.watchEffect(() => {
1020
- result.value = value(
1021
- vue.reactive({
1022
- $dirty,
1023
- $externalErrors: externalErrors?.value ?? [],
1024
- $value: state,
1025
- $silentValue,
1026
- $rules,
1027
- $error,
1028
- $pending,
1029
- $invalid,
1030
- $correct,
1031
- $errors,
1032
- $ready,
1033
- $silentErrors,
1034
- $anyDirty,
1035
- $tooltips,
1036
- $name,
1037
- $inactive,
1038
- $edited,
1039
- $anyEdited
1040
- })
1041
- );
1042
- });
1043
- return result;
1044
- });
1045
- fieldScopes.push(scope2);
1046
- });
1047
- }
1048
- }
1049
- const $shortcuts2 = {};
1050
- vue.watch($invalid, (value) => {
1051
- if (!value) {
1052
- triggerPunishment2.value = false;
1053
- }
1054
- });
1055
- return {
1056
- $error,
1057
- $pending,
1058
- $invalid,
1059
- $correct,
1060
- $debounce: $debounce2,
1061
- $lazy: $lazy2,
1062
- $errors,
1063
- $ready,
1064
- $silentErrors,
1065
- $rewardEarly: $rewardEarly2,
1066
- $autoDirty: $autoDirty2,
1067
- $clearExternalErrorsOnChange: $clearExternalErrorsOnChange2,
1068
- $anyDirty,
1069
- $edited,
1070
- $anyEdited,
1071
- $name,
1072
- $haveAnyAsyncRule: $haveAnyAsyncRule2,
1073
- $shortcuts: $shortcuts2,
1074
- $validating: $validating2,
1075
- $tooltips,
1076
- $dirty,
1077
- triggerPunishment: triggerPunishment2,
1078
- processShortcuts,
1079
- $silentValue,
1080
- $inactive
1081
- };
1082
- });
1083
- define$watchState();
1084
- $unwatchDirty = vue.watch(scopeState.$dirty, (newDirty) => {
1085
- storage.setDirtyEntry(path, newDirty);
1086
- Object.values($rules.value).forEach((rule) => {
1087
- rule.$fieldDirty = newDirty;
1088
- });
1089
- });
1090
- $unwatchRuleFieldValues = vue.watch(
1091
- [scopeState.$error, scopeState.$correct, scopeState.$invalid, scopeState.$pending],
1092
- () => {
1093
- Object.values($rules.value).forEach((rule) => {
1094
- rule.$fieldError = scopeState.$error.value;
1095
- rule.$fieldInvalid = scopeState.$invalid.value;
1096
- rule.$fieldPending = scopeState.$pending.value;
1097
- rule.$fieldCorrect = scopeState.$correct.value;
1098
- });
1099
- }
1100
- );
1101
- $unwatchValid = vue.watch(scopeState.$invalid, (invalid) => {
1102
- if (scopeState.$rewardEarly.value && !invalid) {
1103
- scopeState.triggerPunishment.value = false;
1104
- }
1105
- });
1106
- $unwatchAsync = vue.watch(scopeState.$haveAnyAsyncRule, define$commit);
1107
- }
1108
- function define$watchState() {
1109
- $unwatchState = vue.watch(
1110
- state,
1111
- () => {
1112
- if (scopeState.$autoDirty.value) {
1113
- if (!scopeState.$dirty.value) {
1114
- scopeState.$dirty.value = true;
1115
- }
1116
- }
1117
- if (rulesDef.value instanceof Function) {
1118
- createReactiveRulesResult();
1119
- }
1120
- if (scopeState.$autoDirty.value || scopeState.$rewardEarly.value && scopeState.$error.value) {
1121
- $commit();
1122
- }
1123
- if (scopeState.$rewardEarly.value !== true && scopeState.$clearExternalErrorsOnChange.value) {
1124
- $clearExternalErrors();
1125
- }
1126
- },
1127
- { deep: $isArray ? true : isVueSuperiorOrEqualTo3dotFive ? 1 : true }
1128
- );
1129
- }
1130
- function $commitHandler() {
1131
- Object.values($rules.value).forEach((rule) => {
1132
- rule.$parse();
1133
- });
1134
- }
1135
- const $rules = vue.ref({});
1136
- const $localOptions = vue.ref({});
1137
- createReactiveRulesResult();
1138
- function $reset(options2, fromParent) {
1139
- $clearExternalErrors();
1140
- scopeState.$dirty.value = false;
1141
- scopeState.triggerPunishment.value = false;
1142
- storage.setDirtyEntry(path, false);
1143
- if (!fromParent) {
1144
- if (options2?.toInitialState) {
1145
- $unwatch();
1146
- state.value = cloneDeep(initialState);
1147
- } else if (options2?.toState) {
1148
- $unwatch();
1149
- let newInitialState;
1150
- if (typeof options2?.toState === "function") {
1151
- newInitialState = options2?.toState();
1152
- } else {
1153
- newInitialState = options2?.toState;
1154
- }
1155
- initialState.value = cloneDeep(newInitialState);
1156
- state.value = cloneDeep(newInitialState);
1157
- } else {
1158
- initialState.value = isObject(state.value) ? cloneDeep(state.value) : Array.isArray(state.value) ? [...state.value] : state.value;
1159
- }
1160
- }
1161
- if (options2?.clearExternalErrors) {
1162
- $clearExternalErrors();
1163
- }
1164
- if (!fromParent) {
1165
- Object.entries($rules.value).forEach(([_, rule]) => {
1166
- rule.$reset();
1167
- });
1168
- }
1169
- if (!scopeState.$lazy.value && scopeState.$autoDirty.value) {
1170
- Object.values($rules.value).forEach((rule) => {
1171
- return rule.$parse();
1172
- });
1173
- }
1174
- if (!fromParent) {
1175
- createReactiveRulesResult();
1176
- }
1177
- }
1178
- function $touch(runCommit = true, withConditions = false) {
1179
- if (!scopeState.$dirty.value) {
1180
- scopeState.$dirty.value = true;
1181
- }
1182
- if (withConditions && runCommit) {
1183
- if (scopeState.$autoDirty.value || scopeState.$rewardEarly.value && scopeState.$error.value) {
1184
- $commit();
1185
- }
1186
- } else if (runCommit) {
1187
- $commit();
1188
- }
1189
- }
1190
- async function $validate() {
1191
- try {
1192
- if (schemaMode) {
1193
- if (onValidate) {
1194
- $touch(false);
1195
- return onValidate();
1196
- } else {
1197
- return { valid: false, data: state.value };
1198
- }
1199
- }
1200
- const data = state.value;
1201
- scopeState.triggerPunishment.value = true;
1202
- if (!scopeState.$dirty.value) {
1203
- scopeState.$dirty.value = true;
1204
- } else if (scopeState.$autoDirty.value && scopeState.$dirty.value && !scopeState.$pending.value) {
1205
- return { valid: !scopeState.$error.value, data };
1206
- }
1207
- if (schemaMode) {
1208
- return { valid: !schemaErrors?.value?.length, data };
1209
- } else if (isEmpty($rules.value)) {
1210
- return { valid: true, data };
1211
- }
1212
- const results = await Promise.allSettled(
1213
- Object.entries($rules.value).map(([key, rule]) => {
1214
- return rule.$parse();
1215
- })
1216
- );
1217
- const validationResults = results.every((value) => {
1218
- if (value.status === "fulfilled") {
1219
- return value.value === true;
1220
- } else {
1221
- return false;
1222
- }
1223
- });
1224
- return { valid: validationResults, data };
1225
- } catch (e) {
1226
- return { valid: false, data: state.value };
1227
- }
1228
- }
1229
- function $extractDirtyFields(filterNullishValues = true) {
1230
- if (scopeState.$dirty.value) {
1231
- return state.value;
1232
- }
1233
- if (filterNullishValues) {
1234
- return { _null: true };
1235
- }
1236
- return null;
1237
- }
1238
- function $clearExternalErrors() {
1239
- if (externalErrors?.value?.length) {
1240
- externalErrors.value = [];
1241
- }
1242
- }
1243
- if (!scopeState.$lazy.value && !scopeState.$dirty.value && scopeState.$autoDirty.value) {
1244
- $commit();
1245
- }
1246
- const {
1247
- $shortcuts,
1248
- $validating,
1249
- $autoDirty,
1250
- $rewardEarly,
1251
- $clearExternalErrorsOnChange,
1252
- $haveAnyAsyncRule,
1253
- $debounce,
1254
- $lazy,
1255
- triggerPunishment,
1256
- ...restScope
1257
- } = scopeState;
1258
- return vue.reactive({
1259
- ...restScope,
1260
- $externalErrors: externalErrors,
1261
- $value: state,
1262
- $rules,
1263
- ...$shortcuts,
1264
- $reset,
1265
- $touch,
1266
- $validate,
1267
- $unwatch,
1268
- $watch,
1269
- $extractDirtyFields,
1270
- $clearExternalErrors
1271
- });
1272
- }
1273
- function createCollectionElement({
1274
- $id,
1275
- path,
1276
- index,
1277
- options,
1278
- storage,
1279
- stateValue,
1280
- customMessages,
1281
- rules,
1282
- externalErrors,
1283
- schemaErrors,
1284
- initialState,
1285
- shortcuts,
1286
- fieldName,
1287
- schemaMode
1288
- }) {
1289
- const $fieldId = rules.$key ? rules.$key : randomId();
1290
- let $path = `${path}.${String($fieldId)}`;
1291
- if (typeof stateValue.value === "object" && stateValue.value != null) {
1292
- if (!stateValue.value.$id) {
1293
- Object.defineProperties(stateValue.value, {
1294
- $id: {
1295
- value: $fieldId,
1296
- enumerable: false,
1297
- configurable: false,
1298
- writable: false
1299
- }
1300
- });
1301
- } else {
1302
- $path = `${path}.${stateValue.value.$id}`;
1303
- }
1304
- }
1305
- const $externalErrors = vue.toRef(externalErrors?.value ?? [], index);
1306
- const $schemaErrors = vue.computed(() => schemaErrors?.value?.[index]);
1307
- const $status = createReactiveChildrenStatus({
1308
- state: stateValue,
1309
- rulesDef: vue.toRef(() => rules),
1310
- customMessages,
1311
- path: $path,
1312
- storage,
1313
- options,
1314
- externalErrors: $externalErrors,
1315
- schemaErrors: $schemaErrors,
1316
- initialState,
1317
- shortcuts,
1318
- fieldName,
1319
- schemaMode
1320
- });
1321
- if ($status) {
1322
- const valueId = stateValue.value?.$id;
1323
- $status.$id = valueId ?? String($fieldId);
1324
- storage.addArrayStatus($id, $status.$id, $status);
1325
- }
1326
- return $status;
1327
- }
1328
-
1329
- // src/core/useRegle/root/collections/createReactiveCollectionRoot.ts
1330
- function createReactiveCollectionStatus({
1331
- state,
1332
- rulesDef,
1333
- customMessages,
1334
- path,
1335
- storage,
1336
- options,
1337
- externalErrors,
1338
- schemaErrors,
1339
- schemaMode,
1340
- initialState,
1341
- shortcuts,
1342
- fieldName
1343
- }) {
1344
- let scope = vue.effectScope();
1345
- let scopeState;
1346
- let immediateScope = vue.effectScope();
1347
- let immediateScopeState;
1348
- let collectionScopes = [];
1349
- if (!Array.isArray(state.value) && !rulesDef.value.$each) {
1350
- return void 0;
1351
- }
1352
- const $id = vue.ref();
1353
- const $value = vue.ref(state.value);
1354
- let $unwatchState;
1355
- const $selfStatus = vue.ref({});
1356
- const $eachStatus = storage.getCollectionsEntry(path);
1357
- immediateScopeState = immediateScope.run(() => {
1358
- const isPrimitiveArray = vue.computed(() => {
1359
- if (Array.isArray(state.value) && state.value.length) {
1360
- return state.value.every((s) => typeof s !== "object");
1361
- } else if (rulesDef.value.$each && !(rulesDef.value.$each instanceof Function)) {
1362
- return Object.values(rulesDef.value.$each).every((rule) => isRuleDef(rule) || typeof rule === "function");
1363
- }
1364
- return false;
1365
- });
1366
- return {
1367
- isPrimitiveArray
1368
- };
1369
- });
1370
- createStatus();
1371
- $watch();
1372
- function createStatus() {
1373
- if (typeof state.value === "object") {
1374
- if (state.value != null && !state.value?.$id && state.value !== null) {
1375
- $id.value = randomId();
1376
- Object.defineProperties(state.value, {
1377
- $id: {
1378
- value: $id.value,
1379
- enumerable: false,
1380
- configurable: false,
1381
- writable: false
1382
- }
1383
- });
1384
- } else if (state.value?.$id) {
1385
- $id.value = state.value.$id;
1386
- }
1387
- }
1388
- $value.value = $selfStatus.value.$value;
1389
- if (Array.isArray(state.value) && !immediateScopeState.isPrimitiveArray.value) {
1390
- $eachStatus.value = state.value.filter((value) => typeof value === "object").map((value, index) => {
1391
- const { scope: scope2, unwrapped } = unwrapGetter(
1392
- rulesDef.value.$each,
1393
- vue.toRef(() => value),
1394
- index
1395
- );
1396
- if (scope2) {
1397
- collectionScopes.push(scope2);
1398
- }
1399
- const initialStateRef = vue.toRef(initialState.value ?? [], index);
1400
- const $externalErrors = vue.toRef(externalErrors?.value ?? {}, `$each`);
1401
- const $schemaErrors = vue.computed(() => schemaErrors?.value?.$each);
1402
- const element = createCollectionElement({
1403
- $id: $id.value,
1404
- path,
1405
- customMessages,
1406
- rules: unwrapped ?? {},
1407
- stateValue: vue.toRef(() => value),
1408
- index,
1409
- options,
1410
- storage,
1411
- externalErrors: $externalErrors,
1412
- schemaErrors: $schemaErrors,
1413
- initialState: initialStateRef,
1414
- shortcuts,
1415
- fieldName,
1416
- schemaMode
1417
- });
1418
- if (element) {
1419
- return element;
1420
- }
1421
- return null;
1422
- }).filter((each) => !!each);
1423
- } else {
1424
- $eachStatus.value = [];
1425
- }
1426
- $selfStatus.value = createReactiveFieldStatus({
1427
- state,
1428
- rulesDef,
1429
- customMessages,
1430
- path,
1431
- storage,
1432
- options,
1433
- externalErrors: vue.toRef(externalErrors?.value ?? {}, `$self`),
1434
- schemaErrors: vue.computed(() => schemaErrors?.value?.$self),
1435
- $isArray: true,
1436
- initialState,
1437
- shortcuts,
1438
- fieldName,
1439
- schemaMode
1440
- });
1441
- }
1442
- function updateStatus() {
1443
- if (Array.isArray(state.value) && !immediateScopeState.isPrimitiveArray.value) {
1444
- const previousStatus = cloneDeep($eachStatus.value);
1445
- $eachStatus.value = state.value.filter((value) => typeof value === "object").map((value, index) => {
1446
- const currentValue = vue.toRef(() => value);
1447
- if (value.$id && $eachStatus.value.find((each) => each.$id === value.$id)) {
1448
- const existingStatus = storage.getArrayStatus($id.value, value.$id);
1449
- if (existingStatus) {
1450
- existingStatus.$value = currentValue;
1451
- return existingStatus;
1452
- }
1453
- return null;
1454
- } else {
1455
- const { scope: scope2, unwrapped } = unwrapGetter(rulesDef.value.$each, currentValue, index);
1456
- if (scope2) {
1457
- collectionScopes.push(scope2);
1458
- }
1459
- const $externalErrors = vue.toRef(externalErrors?.value ?? {}, `$each`);
1460
- const $schemaErrors = vue.computed(() => schemaErrors?.value?.$each ?? []);
1461
- const element = createCollectionElement({
1462
- $id: $id.value,
1463
- path,
1464
- customMessages,
1465
- rules: unwrapped ?? {},
1466
- stateValue: currentValue,
1467
- index,
1468
- options,
1469
- storage,
1470
- externalErrors: $externalErrors,
1471
- schemaErrors: $schemaErrors,
1472
- initialState: vue.toRef(initialState.value ?? [], index),
1473
- shortcuts,
1474
- fieldName,
1475
- schemaMode
1476
- });
1477
- if (element) {
1478
- return element;
1479
- }
1480
- return null;
1481
- }
1482
- }).filter((each) => !!each);
1483
- previousStatus.filter(($each) => !state.value?.find((f) => $each.$id === f.$id)).forEach((_, index) => {
1484
- storage.deleteArrayStatus($id.value, index.toString());
1485
- });
1486
- } else {
1487
- $eachStatus.value = [];
1488
- }
1489
- }
1490
- function define$watchState() {
1491
- $unwatchState = vue.watch(
1492
- state,
1493
- () => {
1494
- if (state.value != null && !Object.hasOwn(state.value, "$id")) {
1495
- createStatus();
1496
- } else {
1497
- updateStatus();
1498
- }
1499
- },
1500
- { deep: isVueSuperiorOrEqualTo3dotFive ? 1 : true, flush: "pre" }
1501
- );
1502
- }
1503
- function $watch() {
1504
- define$watchState();
1505
- scope = vue.effectScope();
1506
- scopeState = scope.run(() => {
1507
- const $silentValue = vue.computed({
1508
- get: () => state.value,
1509
- set(value) {
1510
- $unwatchState();
1511
- state.value = value;
1512
- define$watchState();
1513
- }
1514
- });
1515
- const $dirty = vue.computed(() => {
1516
- return $selfStatus.value.$dirty && (!$eachStatus.value.length || $eachStatus.value.every((statusOrField) => {
1517
- return statusOrField.$dirty;
1518
- }));
1519
- });
1520
- const $anyDirty = vue.computed(() => {
1521
- return $selfStatus.value.$anyDirty || $eachStatus.value.some((statusOrField) => {
1522
- return statusOrField.$anyDirty;
1523
- });
1524
- });
1525
- const $invalid = vue.computed(() => {
1526
- return $selfStatus.value.$invalid || $eachStatus.value.some((statusOrField) => {
1527
- return statusOrField.$invalid;
1528
- });
1529
- });
1530
- const $correct = vue.computed(() => {
1531
- return (isEmpty($selfStatus.value.$rules) ? true : $selfStatus.value.$correct) && (!$eachStatus.value.length || $eachStatus.value.every((statusOrField) => {
1532
- return statusOrField.$correct || statusOrField.$anyDirty && !statusOrField.$invalid;
1533
- }));
1534
- });
1535
- const $error = vue.computed(() => {
1536
- return $selfStatus.value.$error || $eachStatus.value.some((statusOrField) => {
1537
- return statusOrField.$error;
1538
- });
1539
- });
1540
- const $ready = vue.computed(() => {
1541
- return !($invalid.value || $pending.value);
1542
- });
1543
- const $pending = vue.computed(() => {
1544
- return $selfStatus.value.$pending || $eachStatus.value.some((statusOrField) => {
1545
- return statusOrField.$pending;
1546
- });
1547
- });
1548
- const $edited = vue.computed(() => {
1549
- return !!$eachStatus.value.length && $eachStatus.value.every((statusOrField) => {
1550
- return statusOrField.$edited;
1551
- });
1552
- });
1553
- const $anyEdited = vue.computed(() => {
1554
- return $selfStatus.value.$anyEdited || $eachStatus.value.some((statusOrField) => {
1555
- return statusOrField.$anyEdited;
1556
- });
1557
- });
1558
- const $errors = vue.computed(() => {
1559
- return {
1560
- $self: $selfStatus.value.$errors,
1561
- $each: $eachStatus.value.map(($each) => $each.$errors)
1562
- };
1563
- });
1564
- const $silentErrors = vue.computed(() => {
1565
- return {
1566
- $self: $selfStatus.value.$silentErrors,
1567
- $each: $eachStatus.value.map(($each) => $each.$silentErrors)
1568
- };
1569
- });
1570
- const $name = vue.computed(() => fieldName);
1571
- function processShortcuts() {
1572
- if (shortcuts?.collections) {
1573
- Object.entries(shortcuts?.collections).forEach(([key, value]) => {
1574
- const scope2 = vue.effectScope();
1575
- $shortcuts2[key] = scope2.run(() => {
1576
- const result = vue.ref();
1577
- vue.watchEffect(() => {
1578
- result.value = value(
1579
- vue.reactive({
1580
- $dirty,
1581
- $error,
1582
- $silentValue,
1583
- $pending,
1584
- $invalid,
1585
- $correct,
1586
- $errors,
1587
- $ready,
1588
- $silentErrors,
1589
- $anyDirty,
1590
- $name,
1591
- $each: $eachStatus,
1592
- $self: $selfStatus,
1593
- $value: state,
1594
- $edited,
1595
- $anyEdited
1596
- })
1597
- );
1598
- });
1599
- return result;
1600
- });
1601
- collectionScopes.push(scope2);
1602
- });
1603
- }
1604
- }
1605
- const $shortcuts2 = {};
1606
- processShortcuts();
1607
- return {
1608
- $dirty,
1609
- $anyDirty,
1610
- $invalid,
1611
- $correct,
1612
- $error,
1613
- $pending,
1614
- $errors,
1615
- $silentErrors,
1616
- $ready,
1617
- $name,
1618
- $shortcuts: $shortcuts2,
1619
- $silentValue,
1620
- $edited,
1621
- $anyEdited
1622
- };
1623
- });
1624
- if (immediateScopeState.isPrimitiveArray.value && rulesDef.value.$each) {
1625
- console.warn(
1626
- `${path} is a Array of primitives. Tracking can be lost when reassigning the Array. We advise to use an Array of objects instead`
1627
- );
1628
- }
1629
- }
1630
- function $unwatch() {
1631
- if ($unwatchState) {
1632
- $unwatchState();
1633
- }
1634
- if ($selfStatus.value) {
1635
- $selfStatus.value.$unwatch();
1636
- }
1637
- if ($eachStatus.value) {
1638
- $eachStatus.value.forEach((element) => {
1639
- if ("$dirty" in element) {
1640
- element.$unwatch();
1641
- }
1642
- });
1643
- }
1644
- scope.stop();
1645
- scope = vue.effectScope();
1646
- immediateScope.stop();
1647
- immediateScope = vue.effectScope(true);
1648
- collectionScopes.forEach((s) => s.stop());
1649
- collectionScopes = [];
1650
- }
1651
- function $touch(runCommit = true, withConditions = false) {
1652
- $selfStatus.value.$touch(runCommit, withConditions);
1653
- $eachStatus.value.forEach(($each) => {
1654
- $each.$touch(runCommit, withConditions);
1655
- });
1656
- }
1657
- function $reset(options2, fromParent) {
1658
- $unwatch();
1659
- if (!fromParent) {
1660
- if (options2?.toInitialState) {
1661
- state.value = cloneDeep(initialState.value);
1662
- } else if (options2?.toState) {
1663
- let newInitialState;
1664
- if (typeof options2?.toState === "function") {
1665
- newInitialState = options2?.toState();
1666
- } else {
1667
- newInitialState = options2?.toState;
1668
- }
1669
- initialState.value = cloneDeep(newInitialState);
1670
- state.value = cloneDeep(newInitialState);
1671
- } else {
1672
- initialState.value = cloneDeep(state.value);
1673
- }
1674
- }
1675
- if (options2?.clearExternalErrors) {
1676
- $clearExternalErrors();
1677
- }
1678
- $selfStatus.value.$reset();
1679
- $eachStatus.value.forEach(($each) => {
1680
- $each.$reset(options2, true);
1681
- });
1682
- if (!fromParent) {
1683
- createStatus();
1684
- }
1685
- }
1686
- async function $validate() {
1687
- const data = state.value;
1688
- try {
1689
- const results = await Promise.allSettled([
1690
- $selfStatus.value.$validate(),
1691
- ...$eachStatus.value.map((status) => {
1692
- return status.$validate();
1693
- })
1694
- ]);
1695
- const validationResults = results.every((value) => {
1696
- if (value.status === "fulfilled") {
1697
- return value.value.valid === true;
1698
- } else {
1699
- return false;
1700
- }
1701
- });
1702
- return { valid: validationResults, data };
1703
- } catch (e) {
1704
- return { valid: false, data };
1705
- }
1706
- }
1707
- function $clearExternalErrors() {
1708
- $selfStatus.value.$clearExternalErrors();
1709
- $eachStatus.value.forEach(($each) => {
1710
- $each.$clearExternalErrors();
1711
- });
1712
- }
1713
- function $extractDirtyFields(filterNullishValues = true) {
1714
- let dirtyFields = $eachStatus.value.map(($each) => {
1715
- if (isNestedRulesStatus($each)) {
1716
- return $each.$extractDirtyFields(filterNullishValues);
1717
- }
1718
- });
1719
- if (filterNullishValues) {
1720
- if (dirtyFields.every((value) => {
1721
- return isEmpty(value);
1722
- })) {
1723
- dirtyFields = [];
1724
- }
1725
- }
1726
- return dirtyFields;
1727
- }
1728
- const { $shortcuts, ...restScopeState } = scopeState;
1729
- return vue.reactive({
1730
- $self: $selfStatus,
1731
- ...restScopeState,
1732
- ...$shortcuts,
1733
- $each: $eachStatus,
1734
- $value: state,
1735
- $validate,
1736
- $unwatch,
1737
- $watch,
1738
- $touch,
1739
- $reset,
1740
- $extractDirtyFields,
1741
- $clearExternalErrors
1742
- });
1743
- }
1744
-
1745
- // src/core/useRegle/root/createReactiveNestedStatus.ts
1746
- function createReactiveNestedStatus({
1747
- rulesDef,
1748
- state,
1749
- path = "",
1750
- rootRules,
1751
- externalErrors,
1752
- schemaErrors,
1753
- rootSchemaErrors,
1754
- validationGroups,
1755
- initialState,
1756
- fieldName,
1757
- ...commonArgs
1758
- }) {
1759
- let scope = vue.effectScope();
1760
- let scopeState;
1761
- let nestedScopes = [];
1762
- let $unwatchRules = null;
1763
- let $unwatchSchemaErrors = null;
1764
- let $unwatchExternalErrors = null;
1765
- let $unwatchState = null;
1766
- async function createReactiveFieldsStatus(watchSources = true) {
1767
- const mapOfRulesDef = Object.entries(rulesDef.value);
1768
- const scopedRulesStatus = Object.fromEntries(
1769
- mapOfRulesDef.filter(([_, rule]) => !!rule).map(([statePropKey, statePropRules]) => {
1770
- if (statePropRules) {
1771
- const stateRef = vue.toRef(state.value ?? {}, statePropKey);
1772
- const statePropRulesRef = vue.toRef(() => statePropRules);
1773
- const $externalErrors = vue.toRef(externalErrors?.value ?? {}, statePropKey);
1774
- const $schemaErrors = vue.computed(() => schemaErrors?.value?.[statePropKey]);
1775
- const initialStateRef = vue.toRef(initialState?.value ?? {}, statePropKey);
1776
- return [
1777
- statePropKey,
1778
- createReactiveChildrenStatus({
1779
- state: stateRef,
1780
- rulesDef: statePropRulesRef,
1781
- path: path ? `${path}.${statePropKey}` : statePropKey,
1782
- externalErrors: $externalErrors,
1783
- schemaErrors: $schemaErrors,
1784
- initialState: initialStateRef,
1785
- fieldName: statePropKey,
1786
- ...commonArgs
1787
- })
1788
- ];
1789
- }
1790
- return [];
1791
- })
1792
- );
1793
- const externalRulesStatus = Object.fromEntries(
1794
- Object.entries(vue.unref(externalErrors) ?? {}).filter(([key, errors]) => !(key in rulesDef.value) && !!errors).map(([key]) => {
1795
- const stateRef = vue.toRef(state.value ?? {}, key);
1796
- const $externalErrors = vue.toRef(externalErrors?.value ?? {}, key);
1797
- const $schemaErrors = vue.computed(() => schemaErrors?.value?.[key]);
1798
- const initialStateRef = vue.toRef(initialState?.value ?? {}, key);
1799
- return [
1800
- key,
1801
- createReactiveChildrenStatus({
1802
- state: stateRef,
1803
- rulesDef: vue.computed(() => ({})),
1804
- path: path ? `${path}.${key}` : key,
1805
- externalErrors: $externalErrors,
1806
- schemaErrors: $schemaErrors,
1807
- initialState: initialStateRef,
1808
- fieldName: key,
1809
- ...commonArgs
1810
- })
1811
- ];
1812
- })
1813
- );
1814
- const schemasRulesStatus = Object.fromEntries(
1815
- Object.entries(vue.unref(schemaErrors) ?? {}).map(([key]) => {
1816
- const stateRef = vue.toRef(state.value ?? {}, key);
1817
- const $externalErrors = vue.toRef(externalErrors?.value ?? {}, key);
1818
- const $schemaErrors = vue.computed(() => schemaErrors?.value?.[key]);
1819
- const initialStateRef = vue.toRef(initialState?.value ?? {}, key);
1820
- return [
1821
- key,
1822
- createReactiveChildrenStatus({
1823
- state: stateRef,
1824
- rulesDef: vue.computed(() => ({})),
1825
- path: path ? `${path}.${key}` : key,
1826
- externalErrors: $externalErrors,
1827
- schemaErrors: $schemaErrors,
1828
- initialState: initialStateRef,
1829
- fieldName: key,
1830
- ...commonArgs
1831
- })
1832
- ];
1833
- })
1834
- );
1835
- const statesWithNoRules = Object.fromEntries(
1836
- Object.entries(state.value ?? {}).filter(
1837
- ([key]) => !(key in rulesDef.value) && !(key in (externalRulesStatus ?? {})) && !(key in (schemasRulesStatus ?? {}))
1838
- ).map(([key]) => {
1839
- const stateRef = vue.toRef(state.value ?? {}, key);
1840
- const $externalErrors = vue.toRef(externalErrors?.value ?? {}, key);
1841
- const $schemaErrors = vue.computed(() => schemaErrors?.value?.[key]);
1842
- const initialStateRef = vue.toRef(initialState?.value ?? {}, key);
1843
- return [
1844
- key,
1845
- createReactiveChildrenStatus({
1846
- state: stateRef,
1847
- rulesDef: vue.computed(() => ({})),
1848
- path: path ? `${path}.${key}` : key,
1849
- externalErrors: $externalErrors,
1850
- schemaErrors: $schemaErrors,
1851
- initialState: initialStateRef,
1852
- fieldName: key,
1853
- ...commonArgs
1854
- })
1855
- ];
1856
- })
1857
- );
1858
- $fields.value = {
1859
- ...scopedRulesStatus,
1860
- ...externalRulesStatus,
1861
- ...schemasRulesStatus,
1862
- ...statesWithNoRules
1863
- };
1864
- if (watchSources) {
1865
- $watch();
1866
- }
1867
- }
1868
- const $fields = commonArgs.storage.getFieldsEntry(path);
1869
- createReactiveFieldsStatus();
1870
- function define$WatchExternalErrors() {
1871
- if (externalErrors) {
1872
- $unwatchExternalErrors = vue.watch(
1873
- externalErrors,
1874
- () => {
1875
- $unwatch();
1876
- createReactiveFieldsStatus();
1877
- },
1878
- { deep: true }
1879
- );
1880
- }
1881
- }
1882
- function define$watchState() {
1883
- $unwatchState = vue.watch(
1884
- state,
1885
- () => {
1886
- $unwatch();
1887
- createReactiveFieldsStatus();
1888
- $touch(true, true);
1889
- },
1890
- { flush: "sync" }
1891
- );
1892
- }
1893
- function $watch() {
1894
- if (rootRules) {
1895
- $unwatchRules?.();
1896
- $unwatchRules = vue.watch(
1897
- rootRules,
1898
- () => {
1899
- $unwatch();
1900
- createReactiveFieldsStatus();
1901
- },
1902
- { deep: true, flush: "pre" }
1903
- );
1904
- define$WatchExternalErrors();
1905
- }
1906
- if (rootSchemaErrors) {
1907
- $unwatchSchemaErrors?.();
1908
- $unwatchSchemaErrors = vue.watch(
1909
- rootSchemaErrors,
1910
- () => {
1911
- $unwatch();
1912
- createReactiveFieldsStatus();
1913
- },
1914
- { deep: true, flush: "post" }
1915
- );
1916
- }
1917
- define$watchState();
1918
- scopeState = scope.run(() => {
1919
- const $silentValue = vue.computed({
1920
- get: () => state.value,
1921
- set(value) {
1922
- $unwatch();
1923
- state.value = value;
1924
- createReactiveFieldsStatus();
1925
- }
1926
- });
1927
- const $dirty = vue.computed(() => {
1928
- return !!Object.entries($fields.value).length && Object.entries($fields.value).every(([_, statusOrField]) => {
1929
- return statusOrField?.$dirty;
1930
- });
1931
- });
1932
- const $anyDirty = vue.computed(() => {
1933
- return Object.entries($fields.value).some(([_, statusOrField]) => {
1934
- return statusOrField?.$anyDirty;
1935
- });
1936
- });
1937
- const $invalid = vue.computed(() => {
1938
- return !!Object.entries($fields.value).length && Object.entries($fields.value).some(([_, statusOrField]) => {
1939
- return statusOrField?.$invalid;
1940
- });
1941
- });
1942
- const $correct = vue.computed(() => {
1943
- const fields = Object.entries($fields.value).filter(([_, statusOrField]) => {
1944
- if (isFieldStatus(statusOrField)) {
1945
- return !statusOrField.$inactive;
1946
- }
1947
- return true;
1948
- });
1949
- if (fields.length) {
1950
- return fields.every(([_, statusOrField]) => {
1951
- return statusOrField?.$correct || statusOrField.$anyDirty && !statusOrField.$invalid;
1952
- });
1953
- }
1954
- return false;
1955
- });
1956
- const $error = vue.computed(() => {
1957
- return !!Object.entries($fields.value).length && Object.entries($fields.value).some(([_, statusOrField]) => {
1958
- return statusOrField?.$error;
1959
- });
1960
- });
1961
- const $rewardEarly = vue.computed(() => {
1962
- if (vue.unref(commonArgs.options.rewardEarly) != null) {
1963
- return vue.unref(commonArgs.options.rewardEarly);
1964
- }
1965
- return false;
1966
- });
1967
- const $autoDirty = vue.computed(() => {
1968
- if (vue.unref(commonArgs.options.autoDirty) != null) {
1969
- return vue.unref(commonArgs.options.autoDirty);
1970
- } else if ($rewardEarly.value) {
1971
- return false;
1972
- }
1973
- return true;
1974
- });
1975
- const $ready = vue.computed(() => {
1976
- if (!$autoDirty.value) {
1977
- return !($invalid.value || $pending.value);
1978
- }
1979
- return $anyDirty.value && !($invalid.value || $pending.value);
1980
- });
1981
- const $localPending2 = vue.ref(false);
1982
- const $pending = vue.computed(() => {
1983
- return $localPending2.value || Object.entries($fields.value).some(([key, statusOrField]) => {
1984
- return statusOrField?.$pending;
1985
- });
1986
- });
1987
- const $errors = vue.computed(() => {
1988
- return Object.fromEntries(
1989
- Object.entries($fields.value).map(([key, statusOrField]) => {
1990
- return [key, statusOrField?.$errors];
1991
- })
1992
- );
1993
- });
1994
- const $silentErrors = vue.computed(() => {
1995
- return Object.fromEntries(
1996
- Object.entries($fields.value).map(([key, statusOrField]) => {
1997
- return [key, statusOrField?.$silentErrors];
1998
- })
1999
- );
2000
- });
2001
- const $edited = vue.computed(() => {
2002
- return !!Object.entries($fields.value).length && Object.entries($fields.value).every(([_, statusOrField]) => {
2003
- return statusOrField?.$edited;
2004
- });
2005
- });
2006
- const $anyEdited = vue.computed(() => {
2007
- return Object.entries($fields.value).some(([_, statusOrField]) => {
2008
- return statusOrField?.$anyEdited;
2009
- });
2010
- });
2011
- const $name = vue.computed(() => fieldName);
2012
- function processShortcuts() {
2013
- if (commonArgs.shortcuts?.nested) {
2014
- Object.entries(commonArgs.shortcuts.nested).forEach(([key, value]) => {
2015
- const scope2 = vue.effectScope();
2016
- $shortcuts2[key] = scope2.run(() => {
2017
- const result = vue.ref();
2018
- vue.watchEffect(() => {
2019
- result.value = value(
2020
- vue.reactive({
2021
- $dirty,
2022
- $value: state,
2023
- $silentValue,
2024
- $error,
2025
- $pending,
2026
- $invalid,
2027
- $correct,
2028
- $ready,
2029
- $anyDirty,
2030
- $name,
2031
- $silentErrors,
2032
- $errors,
2033
- $fields,
2034
- $edited,
2035
- $anyEdited
2036
- })
2037
- );
2038
- });
2039
- return result;
2040
- });
2041
- nestedScopes.push(scope2);
2042
- });
2043
- }
2044
- }
2045
- const $groups = vue.computed({
2046
- get: () => {
2047
- if (validationGroups) {
2048
- return Object.fromEntries(
2049
- Object.entries(validationGroups?.($fields.value) ?? {}).map(([key, entries]) => {
2050
- if (entries.length) {
2051
- return [
2052
- key,
2053
- {
2054
- ...Object.fromEntries(
2055
- ["$invalid", "$error", "$pending", "$dirty", "$correct"].map((property) => [
2056
- property,
2057
- mergeBooleanGroupProperties(entries, property)
2058
- ])
2059
- ),
2060
- ...Object.fromEntries(
2061
- ["$errors", "$silentErrors"].map((property) => [
2062
- property,
2063
- mergeArrayGroupProperties(entries, property)
2064
- ])
2065
- )
2066
- }
2067
- ];
2068
- }
2069
- return [];
2070
- })
2071
- );
2072
- }
2073
- return {};
2074
- },
2075
- set() {
2076
- }
2077
- });
2078
- const $shortcuts2 = {};
2079
- processShortcuts();
2080
- return {
2081
- $dirty,
2082
- $anyDirty,
2083
- $invalid,
2084
- $correct,
2085
- $error,
2086
- $pending,
2087
- $errors,
2088
- $silentErrors,
2089
- $ready,
2090
- $name,
2091
- $shortcuts: $shortcuts2,
2092
- $groups,
2093
- $silentValue,
2094
- $edited,
2095
- $anyEdited,
2096
- $localPending: $localPending2
2097
- };
2098
- });
2099
- }
2100
- function $unwatch() {
2101
- $unwatchRules?.();
2102
- $unwatchExternalErrors?.();
2103
- $unwatchState?.();
2104
- $unwatchSchemaErrors?.();
2105
- nestedScopes = [];
2106
- scopeState = {};
2107
- if ($fields.value) {
2108
- Object.entries($fields.value).forEach(([_, field]) => {
2109
- field.$unwatch();
2110
- });
2111
- }
2112
- }
2113
- function $clearExternalErrors() {
2114
- Object.entries($fields.value).forEach(([_, field]) => {
2115
- field.$clearExternalErrors();
2116
- });
2117
- }
2118
- function $reset(options, fromParent) {
2119
- $unwatchExternalErrors?.();
2120
- $unwatch();
2121
- if (!fromParent) {
2122
- if (options?.toInitialState) {
2123
- state.value = cloneDeep({ ...initialState.value ?? {} });
2124
- } else if (options?.toState) {
2125
- let newInitialState;
2126
- if (typeof options?.toState === "function") {
2127
- newInitialState = options?.toState();
2128
- } else {
2129
- newInitialState = options?.toState;
2130
- }
2131
- initialState.value = cloneDeep(newInitialState);
2132
- state.value = cloneDeep(newInitialState);
2133
- } else {
2134
- initialState.value = cloneDeep(state.value);
2135
- }
2136
- }
2137
- Object.values($fields.value).forEach((statusOrField) => {
2138
- statusOrField.$reset(options, true);
2139
- });
2140
- if (options?.clearExternalErrors) {
2141
- $clearExternalErrors();
2142
- }
2143
- define$WatchExternalErrors();
2144
- if (!fromParent) {
2145
- createReactiveFieldsStatus();
2146
- }
2147
- }
2148
- function $touch(runCommit = true, withConditions = false) {
2149
- Object.values($fields.value).forEach((statusOrField) => {
2150
- statusOrField.$touch(runCommit, withConditions);
2151
- });
2152
- }
2153
- function filterNullishFields(fields) {
2154
- return fields.filter(([key, value]) => {
2155
- if (isObject(value)) {
2156
- return !(value && typeof value === "object" && "_null" in value) && !isEmpty(value);
2157
- } else if (Array.isArray(value)) {
2158
- return value.length;
2159
- } else {
2160
- return true;
2161
- }
2162
- });
2163
- }
2164
- function $extractDirtyFields(filterNullishValues = true) {
2165
- let dirtyFields = Object.entries($fields.value).map(([key, field]) => {
2166
- return [key, field.$extractDirtyFields(filterNullishValues)];
2167
- });
2168
- if (filterNullishValues) {
2169
- dirtyFields = filterNullishFields(dirtyFields);
2170
- }
2171
- return Object.fromEntries(dirtyFields);
2172
- }
2173
- async function $validate() {
2174
- try {
2175
- if (commonArgs.schemaMode) {
2176
- if (commonArgs.onValidate) {
2177
- $touch(false);
2178
- scopeState.$localPending.value = true;
2179
- return commonArgs.onValidate();
2180
- } else {
2181
- return { valid: false, data: state.value };
2182
- }
2183
- } else {
2184
- const data = state.value;
2185
- const results = await Promise.allSettled(
2186
- Object.values($fields.value).map((statusOrField) => {
2187
- return statusOrField.$validate();
2188
- })
2189
- );
2190
- const validationResults = results.every((value) => {
2191
- if (value.status === "fulfilled") {
2192
- return value.value.valid === true;
2193
- } else {
2194
- return false;
2195
- }
2196
- });
2197
- return { valid: validationResults, data };
2198
- }
2199
- } catch (e) {
2200
- return { valid: false, data: state.value };
2201
- } finally {
2202
- scopeState.$localPending.value = false;
2203
- }
2204
- }
2205
- const { $shortcuts, $localPending, ...restScopeState } = scopeState;
2206
- return vue.reactive({
2207
- ...restScopeState,
2208
- ...$shortcuts,
2209
- $fields,
2210
- $value: state,
2211
- $reset,
2212
- $touch,
2213
- $validate,
2214
- $unwatch,
2215
- $watch,
2216
- $clearExternalErrors,
2217
- $extractDirtyFields
2218
- });
2219
- }
2220
- function createReactiveChildrenStatus({
2221
- rulesDef,
2222
- ...properties
2223
- }) {
2224
- if (isCollectionRulesDef(rulesDef, properties.state, properties.schemaMode)) {
2225
- return createReactiveCollectionStatus({
2226
- rulesDef,
2227
- ...properties
2228
- });
2229
- } else if (isNestedRulesDef(properties.state, rulesDef)) {
2230
- if (isRefObject(properties.state)) {
2231
- return createReactiveNestedStatus({
2232
- rulesDef,
2233
- ...properties
2234
- });
2235
- } else {
2236
- const scope = vue.effectScope();
2237
- const scopeState = scope.run(() => {
2238
- const fakeState = vue.toRef(properties.state.value ? properties.state : vue.ref({}));
2239
- vue.watch(
2240
- () => properties.state.value,
2241
- (value) => {
2242
- fakeState.value = value;
2243
- },
2244
- { deep: true }
2245
- );
2246
- vue.watch(
2247
- fakeState,
2248
- (value) => {
2249
- properties.state.value = value;
2250
- },
2251
- { deep: true }
2252
- );
2253
- return { fakeState };
2254
- });
2255
- const { state, ...restProperties } = properties;
2256
- return createReactiveNestedStatus({
2257
- rulesDef,
2258
- ...restProperties,
2259
- state: scopeState.fakeState
2260
- });
2261
- }
2262
- } else if (isValidatorRulesDef(rulesDef)) {
2263
- return createReactiveFieldStatus({
2264
- rulesDef,
2265
- ...properties
2266
- });
2267
- }
2268
- return void 0;
2269
- }
2270
-
2271
- // src/core/useRegle/root/useRootStorage.ts
2272
- function useRootStorage({
2273
- initialState,
2274
- options,
2275
- scopeRules,
2276
- state,
2277
- customRules,
2278
- shortcuts,
2279
- schemaErrors,
2280
- schemaMode = false,
2281
- onValidate
2282
- }) {
2283
- const storage = useStorage();
2284
- const regle = vue.ref();
2285
- if (isNestedRulesDef(state, scopeRules)) {
2286
- regle.value = createReactiveNestedStatus({
2287
- rootRules: scopeRules,
2288
- rulesDef: scopeRules,
2289
- state,
2290
- customMessages: customRules?.(),
2291
- storage,
2292
- options,
2293
- externalErrors: options.externalErrors,
2294
- validationGroups: options.validationGroups,
2295
- initialState,
2296
- shortcuts,
2297
- fieldName: "root",
2298
- path: "",
2299
- schemaErrors,
2300
- rootSchemaErrors: schemaErrors,
2301
- schemaMode,
2302
- onValidate
2303
- });
2304
- } else if (isValidatorRulesDef(scopeRules)) {
2305
- regle.value = createReactiveFieldStatus({
2306
- rulesDef: scopeRules,
2307
- state,
2308
- customMessages: customRules?.(),
2309
- storage,
2310
- options,
2311
- externalErrors: options.externalErrors,
2312
- initialState,
2313
- shortcuts,
2314
- fieldName: "root",
2315
- path: "",
2316
- schemaMode,
2317
- schemaErrors,
2318
- onValidate
2319
- });
2320
- }
2321
- if (vue.getCurrentScope()) {
2322
- vue.onScopeDispose(() => {
2323
- regle.value?.$unwatch();
2324
- });
2325
- }
2326
- return vue.reactive({ regle });
2327
- }
2328
-
2329
- // src/core/useRegle/useRegle.ts
2330
- function createUseRegleComposable(customRules, options, shortcuts) {
2331
- const globalOptions = {
2332
- autoDirty: options?.autoDirty,
2333
- lazy: options?.lazy,
2334
- rewardEarly: options?.rewardEarly,
2335
- clearExternalErrorsOnChange: options?.clearExternalErrorsOnChange
2336
- };
2337
- function useRegle2(state, rulesFactory, options2) {
2338
- const scopeRules = vue.isRef(rulesFactory) ? rulesFactory : vue.computed(typeof rulesFactory === "function" ? rulesFactory : () => rulesFactory);
2339
- const resolvedOptions = {
2340
- ...globalOptions,
2341
- ...options2
2342
- };
2343
- const processedState = vue.isRef(state) ? state : vue.ref(state);
2344
- const initialState = vue.ref(
2345
- isObject(processedState.value) ? { ...cloneDeep(processedState.value) } : cloneDeep(processedState.value)
2346
- );
2347
- const regle = useRootStorage({
2348
- scopeRules,
2349
- state: processedState,
2350
- options: resolvedOptions,
2351
- initialState,
2352
- customRules,
2353
- shortcuts
2354
- });
2355
- return {
2356
- r$: regle.regle
2357
- };
2358
- }
2359
- return useRegle2;
2360
- }
2361
- var useRegle = createUseRegleComposable();
2362
- function createInferRuleHelper() {
2363
- function inferRules2(state, rulesFactory) {
2364
- return rulesFactory;
2365
- }
2366
- return inferRules2;
2367
- }
2368
- var inferRules = createInferRuleHelper();
2369
-
2370
- // src/core/defineRegleConfig.ts
2371
- function defineRegleConfig({
2372
- rules,
2373
- modifiers,
2374
- shortcuts
2375
- }) {
2376
- const useRegle2 = createUseRegleComposable(rules, modifiers, shortcuts);
2377
- const inferRules2 = createInferRuleHelper();
2378
- return { useRegle: useRegle2, inferRules: inferRules2 };
2379
- }
2380
- function mergeRegles(regles, _scoped) {
2381
- const scoped = _scoped == null ? false : _scoped;
2382
- const $value = vue.computed({
2383
- get: () => {
2384
- if (scoped) {
2385
- return Object.values(regles).map((r) => r.$value);
2386
- } else {
2387
- return Object.fromEntries(Object.entries(regles).map(([key, r]) => [key, r.$value]));
2388
- }
2389
- },
2390
- set: (value) => {
2391
- if (!scoped) {
2392
- if (typeof value === "object") {
2393
- Object.entries(value).forEach(([key, newValue]) => regles[key].$value = newValue);
2394
- }
2395
- }
2396
- }
2397
- });
2398
- const $silentValue = vue.computed({
2399
- get: () => Object.fromEntries(Object.entries(regles).map(([key, r]) => [key, r.$silentValue])),
2400
- set: (value) => {
2401
- if (typeof value === "object") {
2402
- Object.entries(value).forEach(([key, newValue]) => regles[key].$silentValue = newValue);
2403
- }
2404
- }
2405
- });
2406
- const $dirty = vue.computed(() => {
2407
- const entries = Object.entries(regles);
2408
- return !!entries.length && entries.every(([_, regle]) => {
2409
- return regle?.$dirty;
2410
- });
2411
- });
2412
- const $anyDirty = vue.computed(() => {
2413
- return Object.entries(regles).some(([_, regle]) => {
2414
- return regle?.$anyDirty;
2415
- });
2416
- });
2417
- const $invalid = vue.computed(() => {
2418
- return Object.entries(regles).some(([_, regle]) => {
2419
- return regle?.$invalid;
2420
- });
2421
- });
2422
- const $correct = vue.computed(() => {
2423
- const entries = Object.entries(regles);
2424
- return !!entries.length && entries.every(([_, regle]) => {
2425
- return regle?.$correct || regle.$anyDirty && !regle.$invalid;
2426
- });
2427
- });
2428
- const $error = vue.computed(() => {
2429
- return Object.entries(regles).some(([_, regle]) => {
2430
- return regle?.$error;
2431
- });
2432
- });
2433
- const $ready = vue.computed(() => {
2434
- const entries = Object.entries(regles);
2435
- return !!entries.length && entries.every(([_, regle]) => {
2436
- return regle?.$ready;
2437
- });
2438
- });
2439
- const $pending = vue.computed(() => {
2440
- return Object.entries(regles).some(([_, regle]) => {
2441
- return regle?.$pending;
2442
- });
2443
- });
2444
- const $errors = vue.computed(() => {
2445
- if (scoped) {
2446
- return Object.entries(regles).map(([_, regle]) => {
2447
- return regle.$errors;
2448
- });
2449
- } else {
2450
- return Object.fromEntries(
2451
- Object.entries(regles).map(([key, regle]) => {
2452
- return [key, regle.$errors];
2453
- })
2454
- );
2455
- }
2456
- });
2457
- const $silentErrors = vue.computed(() => {
2458
- if (scoped) {
2459
- return Object.entries(regles).map(([_, regle]) => {
2460
- return regle.$silentErrors;
2461
- });
2462
- } else {
2463
- return Object.fromEntries(
2464
- Object.entries(regles).map(([key, regle]) => {
2465
- return [key, regle.$silentErrors];
2466
- })
2467
- );
2468
- }
2469
- });
2470
- const $edited = vue.computed(() => {
2471
- const entries = Object.entries(regles);
2472
- return !!entries.length && entries.every(([_, regle]) => {
2473
- return regle?.$edited;
2474
- });
2475
- });
2476
- const $anyEdited = vue.computed(() => {
2477
- return Object.entries(regles).some(([_, regle]) => {
2478
- return regle?.$anyEdited;
2479
- });
2480
- });
2481
- const $instances = vue.computed(() => {
2482
- if (scoped) {
2483
- return Object.values(regles);
2484
- } else {
2485
- return regles;
2486
- }
2487
- });
2488
- function $reset(options) {
2489
- Object.values(regles).forEach((regle) => {
2490
- regle.$reset(options);
2491
- });
2492
- }
2493
- function $touch() {
2494
- Object.values(regles).forEach((regle) => {
2495
- regle.$touch();
2496
- });
2497
- }
2498
- function $extractDirtyFields(filterNullishValues = true) {
2499
- return Object.values(regles).map((regle) => regle.$extractDirtyFields(filterNullishValues));
2500
- }
2501
- function $clearExternalErrors() {
2502
- Object.values(regles).forEach((regle) => {
2503
- regle.$clearExternalErrors();
2504
- });
2505
- }
2506
- async function $validate() {
2507
- try {
2508
- const data = $value.value;
2509
- const results = await Promise.allSettled(
2510
- Object.values(regles).map((regle) => {
2511
- return regle.$validate();
2512
- })
2513
- );
2514
- const validationResults = results.every((value) => {
2515
- if (value.status === "fulfilled") {
2516
- return value.value.valid === true;
2517
- } else {
2518
- return false;
2519
- }
2520
- });
2521
- return { valid: validationResults, data };
2522
- } catch (e) {
2523
- return { valid: false, data: $value.value };
2524
- }
2525
- }
2526
- return vue.reactive({
2527
- ...!scoped && {
2528
- $silentValue
2529
- },
2530
- $errors,
2531
- $silentErrors,
2532
- $instances,
2533
- $value,
2534
- $dirty,
2535
- $anyDirty,
2536
- $invalid,
2537
- $correct,
2538
- $error,
2539
- $pending,
2540
- $ready,
2541
- $edited,
2542
- $anyEdited,
2543
- $reset,
2544
- $touch,
2545
- $validate,
2546
- $extractDirtyFields,
2547
- $clearExternalErrors
2548
- });
2549
- }
2550
- function createUseCollectScope(instances) {
2551
- function useCollectScope2(namespace) {
2552
- const computedNamespace = vue.computed(() => vue.toValue(namespace));
2553
- setEmptyNamespace();
2554
- const r$ = vue.ref(collectRegles(instances.value));
2555
- const regle = vue.reactive({ r$ });
2556
- function setEmptyNamespace() {
2557
- if (computedNamespace.value && !instances.value[computedNamespace.value]) {
2558
- instances.value[computedNamespace.value] = {};
2559
- }
2560
- }
2561
- vue.watch(computedNamespace, setEmptyNamespace);
2562
- vue.watch(
2563
- instances,
2564
- (newInstances) => {
2565
- r$.value = collectRegles(newInstances);
2566
- },
2567
- { deep: true }
2568
- );
2569
- function collectRegles(r$Instances) {
2570
- if (computedNamespace.value) {
2571
- const namespaceInstances = r$Instances[computedNamespace.value] ?? {};
2572
- return mergeRegles(namespaceInstances, true);
2573
- } else {
2574
- return mergeRegles(r$Instances["~~global"] ?? {}, true);
2575
- }
2576
- }
2577
- return { r$: regle.r$ };
2578
- }
2579
- return { useCollectScope: useCollectScope2 };
2580
- }
2581
- function createUseScopedRegleComposable(instances, customUseRegle) {
2582
- const scopedUseRegle = customUseRegle ?? useRegle;
2583
- const useScopedRegle2 = (state, rulesFactory, options) => {
2584
- const { namespace, ...restOptions } = options ?? {};
2585
- const computedNamespace = vue.computed(() => vue.toValue(namespace));
2586
- const $id = vue.ref(`${Object.keys(instances.value).length + 1}-${randomId()}`);
2587
- const instanceName = vue.computed(() => {
2588
- return `instance-${$id.value}`;
2589
- });
2590
- const { r$ } = scopedUseRegle(state, rulesFactory, restOptions);
2591
- register();
2592
- tryOnScopeDispose(dispose);
2593
- vue.watch(computedNamespace, (newName, oldName) => {
2594
- dispose(oldName);
2595
- register();
2596
- });
2597
- if (vue.getCurrentInstance()) {
2598
- vue.onMounted(() => {
2599
- const currentInstance = vue.getCurrentInstance();
2600
- if (typeof window !== "undefined" && currentInstance?.proxy?.$el?.parentElement) {
2601
- if (document.documentElement && !document.documentElement.contains(currentInstance?.proxy?.$el?.parentElement)) {
2602
- dispose();
2603
- }
2604
- }
2605
- });
2606
- }
2607
- function dispose(oldName) {
2608
- const nameToClean = oldName ?? computedNamespace.value;
2609
- if (nameToClean) {
2610
- if (instances.value[nameToClean]) {
2611
- delete instances.value[nameToClean][instanceName.value];
2612
- }
2613
- } else if (instances.value["~~global"][instanceName.value]) {
2614
- delete instances.value["~~global"][instanceName.value];
2615
- }
2616
- }
2617
- function register() {
2618
- if (computedNamespace.value) {
2619
- if (!instances.value[computedNamespace.value]) {
2620
- instances.value[computedNamespace.value] = {};
2621
- }
2622
- instances.value[computedNamespace.value][instanceName.value] = r$;
2623
- } else {
2624
- if (!instances.value["~~global"]) {
2625
- instances.value["~~global"] = {};
2626
- }
2627
- instances.value["~~global"][instanceName.value] = r$;
2628
- }
2629
- }
2630
- return { r$, dispose, register };
2631
- };
2632
- return { useScopedRegle: useScopedRegle2 };
2633
- }
2634
-
2635
- // src/core/createScopedUseRegle/createScopedUseRegle.ts
2636
- function createScopedUseRegle(options) {
2637
- const useInstances = options?.customStore ? () => {
2638
- if (options.customStore) {
2639
- if (!options.customStore?.value["~~global"]) {
2640
- options.customStore.value["~~global"] = {};
2641
- } else if (options.customStore?.value) {
2642
- options.customStore.value = { "~~global": {} };
2643
- }
2644
- }
2645
- return options.customStore;
2646
- } : createGlobalState(() => {
2647
- const $inst = vue.ref({ "~~global": {} });
2648
- return $inst;
2649
- });
2650
- const instances = useInstances();
2651
- const { useScopedRegle: useScopedRegle2 } = createUseScopedRegleComposable(instances, options?.customUseRegle);
2652
- const { useCollectScope: useCollectScope2 } = createUseCollectScope(instances);
2653
- return {
2654
- useScopedRegle: useScopedRegle2,
2655
- useCollectScope: useCollectScope2
2656
- };
2657
- }
2658
- var { useCollectScope, useScopedRegle } = createScopedUseRegle();
2659
- function createVariant(root, disciminantKey, variants) {
2660
- const watchableRoot = vue.computed(() => vue.toValue(root)[disciminantKey]);
2661
- const computedRules = vue.computed(() => {
2662
- const selectedVariant = variants.find((variant) => {
2663
- if (variant[disciminantKey] && "literal" in variant[disciminantKey]) {
2664
- const literalRule = variant[disciminantKey]["literal"];
2665
- if (isRuleDef(literalRule)) {
2666
- return vue.unref(literalRule._params?.[0]) === watchableRoot.value;
2667
- }
2668
- }
2669
- });
2670
- if (selectedVariant) {
2671
- return selectedVariant;
2672
- } else {
2673
- const anyDiscriminantRules = variants.find(
2674
- (variant) => isObject(variant[disciminantKey]) && !Object.keys(variant[disciminantKey]).some((key) => key === "literal")
2675
- );
2676
- if (anyDiscriminantRules) {
2677
- return anyDiscriminantRules;
2678
- } else {
2679
- return {};
2680
- }
2681
- }
2682
- });
2683
- return computedRules;
2684
- }
2685
- function discriminateVariant(root, discriminantKey, discriminantValue) {
2686
- return isObject(root[discriminantKey]) && "$value" in root[discriminantKey] && root[discriminantKey]?.$value === discriminantValue;
2687
- }
2688
- function inferVariantRef(root, discriminantKey, discriminantValue) {
2689
- let returnedRef;
2690
- if (discriminateVariant(root, discriminantKey, discriminantValue)) {
2691
- returnedRef = vue.toRef(root, discriminantKey);
2692
- }
2693
- return returnedRef;
2694
- }
2695
-
2696
- exports.InternalRuleType = InternalRuleType;
2697
- exports.createRule = createRule;
2698
- exports.createScopedUseRegle = createScopedUseRegle;
2699
- exports.createVariant = createVariant;
2700
- exports.defineRegleConfig = defineRegleConfig;
2701
- exports.discriminateVariant = discriminateVariant;
2702
- exports.flatErrors = flatErrors;
2703
- exports.inferRules = inferRules;
2704
- exports.inferVariantRef = inferVariantRef;
2705
- exports.mergeRegles = mergeRegles;
2706
- exports.unwrapRuleParameters = unwrapRuleParameters;
2707
- exports.useCollectScope = useCollectScope;
2708
- exports.useRegle = useRegle;
2709
- exports.useRootStorage = useRootStorage;
2710
- exports.useScopedRegle = useScopedRegle;