@regle/core 0.4.5 → 0.4.6-beta.2

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,1976 @@
1
+ import { unref, version, isRef, toRef, computed, ref, onScopeDispose, reactive, shallowRef, effectScope, watch, watchEffect } from 'vue';
2
+
3
+ // src/types/rules/rule.internal.types.ts
4
+ var InternalRuleType = /* @__PURE__ */ ((InternalRuleType2) => {
5
+ InternalRuleType2["Inline"] = "__inline";
6
+ InternalRuleType2["Async"] = "__async";
7
+ return InternalRuleType2;
8
+ })(InternalRuleType || {});
9
+ function mergeBooleanGroupProperties(entries, property) {
10
+ return entries.some((entry) => {
11
+ return entry[property];
12
+ });
13
+ }
14
+ function mergeArrayGroupProperties(entries, property) {
15
+ return entries.reduce((all, entry) => {
16
+ const fetchedProperty = entry[property] || [];
17
+ return all.concat(fetchedProperty);
18
+ }, []);
19
+ }
20
+ function unwrapRuleParameters(params) {
21
+ try {
22
+ return params.map((param) => {
23
+ if (param instanceof Function) {
24
+ try {
25
+ const result = param();
26
+ return result;
27
+ } catch (e) {
28
+ return null;
29
+ }
30
+ }
31
+ return unref(param);
32
+ });
33
+ } catch (e) {
34
+ return [];
35
+ }
36
+ }
37
+ function createReactiveParams(params) {
38
+ return params.map((param) => {
39
+ if (param instanceof Function) {
40
+ return param;
41
+ } else if (isRef(param)) {
42
+ return param;
43
+ }
44
+ return toRef(() => param);
45
+ });
46
+ }
47
+ function getFunctionParametersLength(func) {
48
+ const funcStr = func.toString();
49
+ const cleanStr = funcStr.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
50
+ const paramsMatch = cleanStr.match(
51
+ /^(?:async\s*)?(?:function\b.*?\(|\((.*?)\)|(\w+))\s*=>|\((.*?)\)\s*=>|function.*?\((.*?)\)|\((.*?)\)/
52
+ );
53
+ if (!paramsMatch) return 0;
54
+ const paramsSection = paramsMatch[0] || paramsMatch[1] || paramsMatch[2] || paramsMatch[3] || paramsMatch[4] || "";
55
+ const paramList = paramsSection.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
56
+ return paramList.length;
57
+ }
58
+
59
+ // src/core/createRule/defineRuleProcessors.ts
60
+ function defineRuleProcessors(definition, ...params) {
61
+ const { validator, type } = definition;
62
+ const isAsync = type === "__async" /* Async */ || validator.constructor.name === "AsyncFunction";
63
+ const defaultProcessors = {
64
+ validator(value, ...args) {
65
+ return definition.validator(value, ...unwrapRuleParameters(args.length ? args : params));
66
+ },
67
+ message(metadata) {
68
+ if (typeof definition.message === "function") {
69
+ return definition.message({
70
+ ...metadata,
71
+ $params: unwrapRuleParameters(metadata?.$params?.length ? metadata.$params : params)
72
+ });
73
+ } else {
74
+ return definition.message;
75
+ }
76
+ },
77
+ active(metadata) {
78
+ if (typeof definition.active === "function") {
79
+ return definition.active({
80
+ ...metadata,
81
+ $params: unwrapRuleParameters(metadata?.$params?.length ? metadata.$params : params)
82
+ });
83
+ } else {
84
+ return definition.active ?? true;
85
+ }
86
+ },
87
+ tooltip(metadata) {
88
+ if (typeof definition.tooltip === "function") {
89
+ return definition.tooltip({
90
+ ...metadata,
91
+ $params: unwrapRuleParameters(metadata?.$params?.length ? metadata.$params : params)
92
+ });
93
+ } else {
94
+ return definition.tooltip ?? [];
95
+ }
96
+ },
97
+ exec(value) {
98
+ const validator2 = definition.validator(value, ...unwrapRuleParameters(params));
99
+ let rawResult;
100
+ if (validator2 instanceof Promise) {
101
+ return validator2.then((result) => {
102
+ rawResult = result;
103
+ if (typeof rawResult === "object" && "$valid" in rawResult) {
104
+ return rawResult.$valid;
105
+ } else if (typeof rawResult === "boolean") {
106
+ return rawResult;
107
+ }
108
+ return false;
109
+ });
110
+ } else {
111
+ rawResult = validator2;
112
+ }
113
+ if (typeof rawResult === "object" && "$valid" in rawResult) {
114
+ return rawResult.$valid;
115
+ } else if (typeof rawResult === "boolean") {
116
+ return rawResult;
117
+ }
118
+ return false;
119
+ }
120
+ };
121
+ const processors = {
122
+ ...defaultProcessors,
123
+ _validator: definition.validator,
124
+ _message: definition.message,
125
+ _active: definition.active,
126
+ _tooltip: definition.tooltip,
127
+ _type: definition.type,
128
+ _message_patched: false,
129
+ _tooltip_patched: false,
130
+ _async: isAsync,
131
+ _params: createReactiveParams(params)
132
+ };
133
+ return processors;
134
+ }
135
+
136
+ // src/core/createRule/createRule.ts
137
+ function createRule(definition) {
138
+ if (typeof definition.validator === "function") {
139
+ let fakeParams = [];
140
+ const staticProcessors = defineRuleProcessors(definition, ...fakeParams);
141
+ const isAsync = definition.validator.constructor.name === "AsyncFunction";
142
+ if (getFunctionParametersLength(definition.validator) > 1) {
143
+ const ruleFactory = function(...params) {
144
+ return defineRuleProcessors(definition, ...params);
145
+ };
146
+ ruleFactory.validator = staticProcessors.validator;
147
+ ruleFactory.message = staticProcessors.message;
148
+ ruleFactory.active = staticProcessors.active;
149
+ ruleFactory.tooltip = staticProcessors.tooltip;
150
+ ruleFactory.type = staticProcessors.type;
151
+ ruleFactory.exec = staticProcessors.exec;
152
+ ruleFactory._validator = staticProcessors.validator;
153
+ ruleFactory._message = staticProcessors.message;
154
+ ruleFactory._active = staticProcessors.active;
155
+ ruleFactory._tooltip = staticProcessors.tooltip;
156
+ ruleFactory._type = definition.type;
157
+ ruleFactory._message_pacthed = false;
158
+ ruleFactory._tooltip_pacthed = false;
159
+ ruleFactory._async = isAsync;
160
+ return ruleFactory;
161
+ } else {
162
+ return staticProcessors;
163
+ }
164
+ }
165
+ throw new Error("Validator must be a function");
166
+ }
167
+ function isObject(obj) {
168
+ return typeof obj === "object" && obj !== null && !Array.isArray(obj);
169
+ }
170
+ function isRefObject(obj) {
171
+ return isObject(obj.value);
172
+ }
173
+ function cloneDeep(obj) {
174
+ let result = obj;
175
+ let type = {}.toString.call(obj).slice(8, -1);
176
+ if (type == "Set") {
177
+ result = new Set([...obj].map((value) => cloneDeep(value)));
178
+ }
179
+ if (type == "Map") {
180
+ result = new Map([...obj].map((kv) => [cloneDeep(kv[0]), cloneDeep(kv[1])]));
181
+ }
182
+ if (type == "Date") {
183
+ result = new Date(obj.getTime());
184
+ }
185
+ if (type == "RegExp") {
186
+ result = RegExp(obj.source, getRegExpFlags(obj));
187
+ }
188
+ if (type == "Array" || type == "Object") {
189
+ result = Array.isArray(obj) ? [] : {};
190
+ for (let key in obj) {
191
+ result[key] = cloneDeep(obj[key]);
192
+ }
193
+ }
194
+ return result;
195
+ }
196
+ function getRegExpFlags(regExp) {
197
+ if (typeof regExp.source.flags == "string") {
198
+ return regExp.source.flags;
199
+ } else {
200
+ let flags = [];
201
+ regExp.global && flags.push("g");
202
+ regExp.ignoreCase && flags.push("i");
203
+ regExp.multiline && flags.push("m");
204
+ regExp.sticky && flags.push("y");
205
+ regExp.unicode && flags.push("u");
206
+ return flags.join("");
207
+ }
208
+ }
209
+ function unwrapGetter(getter, value, index) {
210
+ if (getter instanceof Function) {
211
+ return getter(value, index ?? 0);
212
+ }
213
+ return getter;
214
+ }
215
+
216
+ // src/utils/debounce.ts
217
+ function debounce(func, wait, immediate) {
218
+ let timeout;
219
+ const debouncedFn = (...args) => new Promise((resolve) => {
220
+ clearTimeout(timeout);
221
+ timeout = setTimeout(() => {
222
+ timeout = void 0;
223
+ {
224
+ Promise.resolve(func.apply(this, [...args])).then(resolve);
225
+ }
226
+ }, wait);
227
+ });
228
+ debouncedFn.cancel = () => {
229
+ clearTimeout(timeout);
230
+ timeout = void 0;
231
+ };
232
+ return debouncedFn;
233
+ }
234
+ function versionCompare(current, other) {
235
+ const cp = String(current).split(".");
236
+ const op = String(other).split(".");
237
+ for (let depth = 0; depth < Math.min(cp.length, op.length); depth++) {
238
+ const cn = Number(cp[depth]);
239
+ const on = Number(op[depth]);
240
+ if (cn > on) return 1 /* GreaterThan */;
241
+ if (on > cn) return -1 /* LessThan */;
242
+ if (!isNaN(cn) && isNaN(on)) return 1 /* GreaterThan */;
243
+ if (isNaN(cn) && !isNaN(on)) return -1 /* LessThan */;
244
+ }
245
+ return 0 /* EqualTo */;
246
+ }
247
+ var isVueSuperiorOrEqualTo3dotFive = versionCompare(version, "3.5.0") === -1 ? false : true;
248
+
249
+ // src/utils/randomId.ts
250
+ function uniqueIDNuxt() {
251
+ return Math.floor(Math.random() * Date.now()).toString();
252
+ }
253
+ function randomId() {
254
+ if (typeof window === "undefined") {
255
+ return uniqueIDNuxt();
256
+ } else {
257
+ const uint32 = window.crypto.getRandomValues(new Uint32Array(1))[0];
258
+ return uint32.toString(10);
259
+ }
260
+ }
261
+ function useStorage() {
262
+ const ruleDeclStorage = shallowRef(/* @__PURE__ */ new Map());
263
+ const fieldsStorage = shallowRef(/* @__PURE__ */ new Map());
264
+ const collectionsStorage = shallowRef(/* @__PURE__ */ new Map());
265
+ const dirtyStorage = shallowRef(/* @__PURE__ */ new Map());
266
+ const ruleStatusStorage = shallowRef(/* @__PURE__ */ new Map());
267
+ const arrayStatusStorage = shallowRef(/* @__PURE__ */ new Map());
268
+ function getFieldsEntry($path) {
269
+ const existingFields = fieldsStorage.value.get($path);
270
+ if (existingFields) {
271
+ return existingFields;
272
+ } else {
273
+ const $fields = ref({});
274
+ fieldsStorage.value.set($path, $fields);
275
+ return $fields;
276
+ }
277
+ }
278
+ function getCollectionsEntry($path) {
279
+ const existingEach = collectionsStorage.value.get($path);
280
+ if (existingEach) {
281
+ return existingEach;
282
+ } else {
283
+ const $each = ref([]);
284
+ collectionsStorage.value.set($path, $each);
285
+ return $each;
286
+ }
287
+ }
288
+ function addArrayStatus($arrayId, itemId, value) {
289
+ arrayStatusStorage.value.set(`${$arrayId}-${itemId}`, value);
290
+ }
291
+ function getArrayStatus($arrayId, itemId) {
292
+ return arrayStatusStorage.value.get(`${$arrayId}-${itemId}`);
293
+ }
294
+ function deleteArrayStatus($arrayId, itemId) {
295
+ if ($arrayId && itemId != null) {
296
+ arrayStatusStorage.value.delete(`${$arrayId}-${itemId}`);
297
+ }
298
+ }
299
+ function setDirtyEntry($path, dirty) {
300
+ dirtyStorage.value.set($path, dirty);
301
+ }
302
+ function getDirtyState(path) {
303
+ return dirtyStorage.value.get(path) ?? false;
304
+ }
305
+ function addRuleDeclEntry($path, options) {
306
+ ruleDeclStorage.value.set($path, options);
307
+ }
308
+ function checkRuleDeclEntry($path, newRules) {
309
+ const storedRulesDefs = ruleDeclStorage.value.get($path);
310
+ if (!storedRulesDefs) return void 0;
311
+ const storedRules = storedRulesDefs;
312
+ const isValidCache = areRulesChanged(newRules, storedRules);
313
+ if (!isValidCache) return { valid: false };
314
+ return { valid: true };
315
+ }
316
+ function areRulesChanged(newRules, storedRules) {
317
+ const storedRulesKeys = Object.keys(storedRules);
318
+ const newRulesKeys = Object.keys(newRules);
319
+ if (newRulesKeys.length !== storedRulesKeys.length) return false;
320
+ const hasAllValidators = newRulesKeys.every((ruleKey) => storedRulesKeys.includes(ruleKey));
321
+ if (!hasAllValidators) return false;
322
+ return newRulesKeys.every((ruleKey) => {
323
+ const newRuleElement = newRules[ruleKey];
324
+ const storedRuleElement = storedRules[ruleKey];
325
+ if (!storedRuleElement || !newRuleElement || typeof newRuleElement === "function" || typeof storedRuleElement === "function")
326
+ return false;
327
+ if (typeof newRuleElement === "number") {
328
+ return false;
329
+ } else if (typeof newRuleElement === "boolean") {
330
+ return false;
331
+ } else if (!newRuleElement._params) return true;
332
+ else {
333
+ return newRuleElement._params?.every((paramKey, index) => {
334
+ if (typeof storedRuleElement === "number" || typeof storedRuleElement === "boolean") {
335
+ return true;
336
+ } else {
337
+ const storedParams = unwrapRuleParameters(storedRuleElement._params);
338
+ const newParams = unwrapRuleParameters(newRuleElement._params);
339
+ return storedParams?.[index] === newParams?.[index];
340
+ }
341
+ });
342
+ }
343
+ });
344
+ }
345
+ function trySetRuleStatusRef(path) {
346
+ const ruleStatus = ruleStatusStorage.value.get(path);
347
+ if (ruleStatus) {
348
+ return ruleStatus;
349
+ } else {
350
+ const $pending = ref(false);
351
+ const $valid = ref(true);
352
+ const $metadata = ref({});
353
+ const $validating = ref(false);
354
+ ruleStatusStorage.value.set(path, { $pending, $valid, $metadata, $validating });
355
+ return { $pending, $valid, $metadata, $validating };
356
+ }
357
+ }
358
+ onScopeDispose(() => {
359
+ ruleDeclStorage.value.clear();
360
+ fieldsStorage.value.clear();
361
+ collectionsStorage.value.clear();
362
+ dirtyStorage.value.clear();
363
+ ruleStatusStorage.value.clear();
364
+ arrayStatusStorage.value.clear();
365
+ });
366
+ return {
367
+ addRuleDeclEntry,
368
+ setDirtyEntry,
369
+ checkRuleDeclEntry,
370
+ getDirtyState,
371
+ trySetRuleStatusRef,
372
+ getFieldsEntry,
373
+ getCollectionsEntry,
374
+ getArrayStatus,
375
+ addArrayStatus,
376
+ deleteArrayStatus,
377
+ arrayStatusStorage
378
+ };
379
+ }
380
+
381
+ // ../shared/utils/isEmpty.ts
382
+ function isEmpty(value) {
383
+ if (value === void 0 || value === null) {
384
+ return true;
385
+ }
386
+ if (value instanceof Date) {
387
+ return isNaN(value.getTime());
388
+ }
389
+ if (Array.isArray(value)) {
390
+ return false;
391
+ }
392
+ if (typeof value === "object" && value != null) {
393
+ return Object.keys(value).length === 0;
394
+ }
395
+ return !String(value).length;
396
+ }
397
+
398
+ // src/core/useRegle/guards/ruleDef.guards.ts
399
+ function isNestedRulesDef(state, rules) {
400
+ return isObject(state.value) && isObject(rules.value) && !Object.entries(rules.value).some((rule) => isRuleDef(rule));
401
+ }
402
+ function isCollectionRulesDef(rules, state) {
403
+ return !!rules.value && "$each" in rules.value || Array.isArray(state.value);
404
+ }
405
+ function isValidatorRulesDef(rules) {
406
+ return !!rules.value && isObject(rules.value);
407
+ }
408
+ function isRuleDef(rule) {
409
+ return isObject(rule) && "_validator" in rule;
410
+ }
411
+ function isFormRuleDefinition(rule) {
412
+ return !(typeof rule.value === "function");
413
+ }
414
+
415
+ // src/core/useRegle/guards/rule.status.guards.ts
416
+ function isNestedRulesStatus(rule) {
417
+ return isObject(rule) && "$fields" in rule;
418
+ }
419
+
420
+ // src/core/useRegle/useErrors.ts
421
+ function extractRulesErrors({
422
+ field,
423
+ silent = false
424
+ }) {
425
+ return Object.entries(field.$rules ?? {}).map(([ruleKey, rule]) => {
426
+ if (silent) {
427
+ return rule.$message;
428
+ } else if (!rule.$valid && field.$dirty && !rule.$validating) {
429
+ return rule.$message;
430
+ }
431
+ return null;
432
+ }).filter((msg) => !!msg).reduce((acc, value) => {
433
+ if (typeof value === "string") {
434
+ return acc?.concat([value]);
435
+ } else {
436
+ return acc?.concat(value);
437
+ }
438
+ }, []).concat(field.$dirty ? field.$externalErrors ?? [] : []);
439
+ }
440
+ function extractRulesTooltips({ field }) {
441
+ return Object.entries(field.$rules ?? {}).map(([ruleKey, rule]) => rule.$tooltip).filter((tooltip) => !!tooltip).reduce((acc, value) => {
442
+ if (typeof value === "string") {
443
+ return acc?.concat([value]);
444
+ } else {
445
+ return acc?.concat(value);
446
+ }
447
+ }, []);
448
+ }
449
+ function createReactiveRuleStatus({
450
+ fieldProperties,
451
+ customMessages,
452
+ rule,
453
+ ruleKey,
454
+ state,
455
+ path,
456
+ storage,
457
+ $debounce,
458
+ modifiers
459
+ }) {
460
+ let scope = effectScope();
461
+ let scopeState = {};
462
+ let $unwatchState;
463
+ const $haveAsync = ref(false);
464
+ const { $pending, $valid, $metadata, $validating } = storage.trySetRuleStatusRef(`${path}.${ruleKey}`);
465
+ function $watch() {
466
+ scope = effectScope();
467
+ scopeState = scope.run(() => {
468
+ const $defaultMetadata = computed(() => ({
469
+ $value: state.value,
470
+ $error: fieldProperties.$error.value,
471
+ $dirty: fieldProperties.$dirty.value,
472
+ $pending: fieldProperties.$pending.value,
473
+ $valid: fieldProperties.$valid.value,
474
+ $invalid: fieldProperties.$invalid.value,
475
+ $rule: {
476
+ $valid: $valid.value,
477
+ $invalid: !$valid.value,
478
+ $pending: $pending.value
479
+ },
480
+ $params: $params.value,
481
+ ...$metadata.value
482
+ }));
483
+ const $active = computed(() => {
484
+ if (isFormRuleDefinition(rule)) {
485
+ if (typeof rule.value.active === "function") {
486
+ return rule.value.active($defaultMetadata.value);
487
+ } else {
488
+ return !!rule.value.active;
489
+ }
490
+ } else {
491
+ return true;
492
+ }
493
+ });
494
+ function computeRuleProcessor(key) {
495
+ let result = "";
496
+ const customProcessor = customMessages ? customMessages[ruleKey]?.[key] : void 0;
497
+ if (customProcessor) {
498
+ if (typeof customProcessor === "function") {
499
+ result = customProcessor($defaultMetadata.value);
500
+ } else {
501
+ result = customProcessor;
502
+ }
503
+ }
504
+ if (isFormRuleDefinition(rule)) {
505
+ const patchedKey = `_${key}_patched`;
506
+ if (!(customProcessor && !rule.value[patchedKey])) {
507
+ if (typeof rule.value[key] === "function") {
508
+ result = rule.value[key]($defaultMetadata.value);
509
+ } else {
510
+ result = rule.value[key] ?? "";
511
+ }
512
+ }
513
+ }
514
+ return result;
515
+ }
516
+ const $message = computed(() => {
517
+ let message = computeRuleProcessor("message");
518
+ if (isEmpty(message)) {
519
+ message = "This field is not valid";
520
+ }
521
+ return message;
522
+ });
523
+ const $tooltip = computed(() => {
524
+ return computeRuleProcessor("tooltip");
525
+ });
526
+ const $type = computed(() => {
527
+ if (isFormRuleDefinition(rule) && rule.value.type) {
528
+ return rule.value.type;
529
+ } else {
530
+ return ruleKey;
531
+ }
532
+ });
533
+ const $validator = computed(() => {
534
+ if (isFormRuleDefinition(rule)) {
535
+ return rule.value.validator;
536
+ } else {
537
+ return rule.value;
538
+ }
539
+ });
540
+ const $params = computed(() => {
541
+ if (typeof rule.value === "function") {
542
+ return [];
543
+ }
544
+ return unwrapRuleParameters(rule.value._params ?? []);
545
+ });
546
+ const $path = computed(() => `${path}.${$type.value}`);
547
+ return {
548
+ $active,
549
+ $message,
550
+ $type,
551
+ $validator,
552
+ $params,
553
+ $path,
554
+ $tooltip
555
+ };
556
+ });
557
+ $unwatchState = watch(scopeState?.$params, () => {
558
+ if (modifiers.$autoDirty.value || modifiers.$rewardEarly.value && fieldProperties.$error.value) {
559
+ $validate();
560
+ }
561
+ });
562
+ }
563
+ $watch();
564
+ function updatePendingState() {
565
+ $valid.value = true;
566
+ if (fieldProperties.$dirty.value) {
567
+ $pending.value = true;
568
+ }
569
+ }
570
+ async function computeAsyncResult() {
571
+ let ruleResult = false;
572
+ try {
573
+ const validator = scopeState.$validator.value;
574
+ const resultOrPromise = validator(state.value, ...scopeState.$params.value);
575
+ let cachedValue = state.value;
576
+ updatePendingState();
577
+ let validatorResult;
578
+ if (resultOrPromise instanceof Promise) {
579
+ validatorResult = await resultOrPromise;
580
+ } else {
581
+ validatorResult = resultOrPromise;
582
+ }
583
+ if (state.value !== cachedValue) {
584
+ return true;
585
+ }
586
+ if (typeof validatorResult === "boolean") {
587
+ ruleResult = validatorResult;
588
+ } else {
589
+ const { $valid: $valid2, ...rest } = validatorResult;
590
+ ruleResult = $valid2;
591
+ $metadata.value = rest;
592
+ }
593
+ } catch (e) {
594
+ ruleResult = false;
595
+ } finally {
596
+ $pending.value = false;
597
+ }
598
+ return ruleResult;
599
+ }
600
+ const $computeAsyncDebounce = debounce(computeAsyncResult, $debounce ?? 200);
601
+ async function $validate() {
602
+ try {
603
+ $validating.value = true;
604
+ let ruleResult = false;
605
+ if (isRuleDef(rule.value) && rule.value._async) {
606
+ ruleResult = await $computeAsyncDebounce();
607
+ } else {
608
+ const validator = scopeState.$validator.value;
609
+ const resultOrPromise = validator(state.value, ...scopeState.$params.value);
610
+ if (resultOrPromise instanceof Promise) {
611
+ console.warn(
612
+ 'You used a async validator function on a non-async rule, please use "async await" or the "withAsync" helper'
613
+ );
614
+ } else {
615
+ if (resultOrPromise != null) {
616
+ if (typeof resultOrPromise === "boolean") {
617
+ ruleResult = resultOrPromise;
618
+ } else {
619
+ const { $valid: $valid2, ...rest } = resultOrPromise;
620
+ ruleResult = $valid2;
621
+ $metadata.value = rest;
622
+ }
623
+ }
624
+ }
625
+ }
626
+ $valid.value = ruleResult;
627
+ return ruleResult;
628
+ } catch (e) {
629
+ return false;
630
+ } finally {
631
+ $validating.value = false;
632
+ }
633
+ }
634
+ function $reset() {
635
+ $valid.value = true;
636
+ $metadata.value = {};
637
+ $pending.value = false;
638
+ $validating.value = false;
639
+ $watch();
640
+ }
641
+ function $unwatch() {
642
+ $unwatchState();
643
+ scope.stop();
644
+ scope = effectScope();
645
+ }
646
+ return reactive({
647
+ ...scopeState,
648
+ $pending,
649
+ $valid,
650
+ $metadata,
651
+ $haveAsync,
652
+ $validating,
653
+ $validate,
654
+ $unwatch,
655
+ $watch,
656
+ $reset
657
+ });
658
+ }
659
+
660
+ // src/core/useRegle/useStateProperties/createReactiveFieldStatus.ts
661
+ function createReactiveFieldStatus({
662
+ state,
663
+ rulesDef,
664
+ customMessages,
665
+ path,
666
+ fieldName,
667
+ storage,
668
+ options,
669
+ externalErrors,
670
+ onUnwatch,
671
+ $isArray,
672
+ initialState,
673
+ shortcuts
674
+ }) {
675
+ let scope = effectScope();
676
+ let scopeState;
677
+ let fieldScopes = [];
678
+ let $unwatchState;
679
+ let $unwatchValid;
680
+ let $unwatchDirty;
681
+ let $unwatchAsync;
682
+ let $commit = () => {
683
+ };
684
+ function createReactiveRulesResult() {
685
+ const declaredRules = rulesDef.value;
686
+ const storeResult = storage.checkRuleDeclEntry(path, declaredRules);
687
+ $localOptions.value = Object.fromEntries(
688
+ Object.entries(declaredRules).filter(([ruleKey]) => ruleKey.startsWith("$"))
689
+ );
690
+ $watch();
691
+ $rules.value = Object.fromEntries(
692
+ Object.entries(rulesDef.value).filter(([ruleKey]) => !ruleKey.startsWith("$")).map(([ruleKey, rule]) => {
693
+ if (rule) {
694
+ const ruleRef = toRef(() => rule);
695
+ return [
696
+ ruleKey,
697
+ createReactiveRuleStatus({
698
+ fieldProperties: {
699
+ $dirty: scopeState.$dirty,
700
+ $error: scopeState.$error,
701
+ $invalid: scopeState.$invalid,
702
+ $pending: scopeState.$pending,
703
+ $valid: scopeState.$valid
704
+ },
705
+ modifiers: {
706
+ $autoDirty: scopeState.$autoDirty,
707
+ $rewardEarly: scopeState.$rewardEarly
708
+ },
709
+ customMessages,
710
+ rule: ruleRef,
711
+ ruleKey,
712
+ state,
713
+ path,
714
+ storage,
715
+ $debounce: $localOptions.value.$debounce
716
+ })
717
+ ];
718
+ }
719
+ return [];
720
+ }).filter((ruleDef) => !!ruleDef.length)
721
+ );
722
+ scopeState.processShortcuts();
723
+ define$commit();
724
+ if (storeResult?.valid != null) {
725
+ scopeState.$dirty.value = storage.getDirtyState(path);
726
+ if (scopeState.$dirty.value) {
727
+ $commit();
728
+ }
729
+ }
730
+ storage.addRuleDeclEntry(path, declaredRules);
731
+ }
732
+ function define$commit() {
733
+ $commit = scopeState.$debounce.value ? debounce($commitHandler, scopeState.$debounce.value ?? scopeState.$haveAnyAsyncRule ? 100 : 0) : $commitHandler;
734
+ }
735
+ function $unwatch() {
736
+ if ($rules.value) {
737
+ Object.entries($rules.value).forEach(([_, rule]) => {
738
+ rule.$unwatch();
739
+ });
740
+ }
741
+ $unwatchDirty();
742
+ if (scopeState.$dirty.value) {
743
+ storage.setDirtyEntry(path, scopeState.$dirty.value);
744
+ }
745
+ $unwatchState?.();
746
+ $unwatchValid?.();
747
+ scope.stop();
748
+ scope = effectScope();
749
+ fieldScopes.forEach((s) => s.stop());
750
+ fieldScopes = [];
751
+ onUnwatch?.();
752
+ $unwatchAsync?.();
753
+ }
754
+ function $watch() {
755
+ if ($rules.value) {
756
+ Object.entries($rules.value).forEach(([_, rule]) => {
757
+ rule.$watch();
758
+ });
759
+ }
760
+ scopeState = scope.run(() => {
761
+ const $dirty = ref(false);
762
+ const triggerPunishment = ref(false);
763
+ const $anyDirty = computed(() => $dirty.value);
764
+ const $debounce2 = computed(() => {
765
+ return $localOptions.value.$debounce;
766
+ });
767
+ const $lazy2 = computed(() => {
768
+ if ($localOptions.value.$lazy != null) {
769
+ return $localOptions.value.$lazy;
770
+ }
771
+ return unref(options.lazy);
772
+ });
773
+ const $rewardEarly2 = computed(() => {
774
+ if ($autoDirty2.value === true) {
775
+ return false;
776
+ }
777
+ if ($localOptions.value.$rewardEarly != null) {
778
+ return $localOptions.value.$rewardEarly;
779
+ }
780
+ return unref(options.rewardEarly);
781
+ });
782
+ const $clearExternalErrorsOnChange2 = computed(() => {
783
+ if ($localOptions.value.$clearExternalErrorsOnChange != null) {
784
+ return $localOptions.value.$clearExternalErrorsOnChange;
785
+ }
786
+ return unref(options.clearExternalErrorsOnChange);
787
+ });
788
+ const $autoDirty2 = computed(() => {
789
+ if ($localOptions.value.$autoDirty != null) {
790
+ return $localOptions.value.$autoDirty;
791
+ }
792
+ return unref(options.autoDirty);
793
+ });
794
+ const $validating2 = computed(() => {
795
+ return Object.entries($rules.value).some(([key, ruleResult]) => {
796
+ return ruleResult.$validating;
797
+ });
798
+ });
799
+ const $error = computed(() => {
800
+ return $invalid.value && !$pending.value && $dirty.value;
801
+ });
802
+ const $errors = computed(() => {
803
+ if ($error.value) {
804
+ return extractRulesErrors({
805
+ field: {
806
+ $dirty: $dirty.value,
807
+ $externalErrors: externalErrors?.value,
808
+ $rules: $rules.value
809
+ }
810
+ });
811
+ }
812
+ return [];
813
+ });
814
+ const $tooltips = computed(() => {
815
+ return extractRulesTooltips({
816
+ field: {
817
+ $rules: $rules.value
818
+ }
819
+ });
820
+ });
821
+ const $silentErrors = computed(() => {
822
+ return extractRulesErrors({
823
+ field: {
824
+ $dirty: $dirty.value,
825
+ $externalErrors: externalErrors?.value,
826
+ $rules: $rules.value
827
+ },
828
+ silent: true
829
+ });
830
+ });
831
+ const $ready = computed(() => {
832
+ return !($invalid.value || $pending.value);
833
+ });
834
+ const $pending = computed(() => {
835
+ if (triggerPunishment.value || !$rewardEarly2.value) {
836
+ return Object.entries($rules.value).some(([key, ruleResult]) => {
837
+ return ruleResult.$pending;
838
+ });
839
+ }
840
+ return false;
841
+ });
842
+ const $invalid = computed(() => {
843
+ if (externalErrors?.value?.length) {
844
+ return true;
845
+ } else if (isEmpty($rules.value)) {
846
+ return false;
847
+ } else if (!$rewardEarly2.value || $rewardEarly2.value && triggerPunishment.value) {
848
+ return Object.entries($rules.value).some(([key, ruleResult]) => {
849
+ return !ruleResult.$valid;
850
+ });
851
+ }
852
+ return false;
853
+ });
854
+ const $name = computed(() => fieldName);
855
+ const $valid = computed(() => {
856
+ if (externalErrors?.value?.length) {
857
+ return false;
858
+ } else if (isEmpty($rules.value)) {
859
+ return false;
860
+ } else if ($dirty.value && !isEmpty(state.value) && !$validating2.value) {
861
+ return Object.values($rules.value).every((ruleResult) => {
862
+ return ruleResult.$valid && ruleResult.$active;
863
+ });
864
+ }
865
+ return false;
866
+ });
867
+ const $haveAnyAsyncRule2 = computed(() => {
868
+ return Object.entries($rules.value).some(([key, ruleResult]) => {
869
+ return ruleResult.$haveAsync;
870
+ });
871
+ });
872
+ function processShortcuts() {
873
+ if (shortcuts?.fields) {
874
+ Object.entries(shortcuts.fields).forEach(([key, value]) => {
875
+ const scope2 = effectScope();
876
+ $shortcuts2[key] = scope2.run(() => {
877
+ const result = ref();
878
+ watchEffect(() => {
879
+ result.value = value(
880
+ reactive({
881
+ $dirty,
882
+ $externalErrors: externalErrors?.value ?? [],
883
+ $value: state,
884
+ $rules,
885
+ $error,
886
+ $pending,
887
+ $invalid,
888
+ $valid,
889
+ $errors,
890
+ $ready,
891
+ $silentErrors,
892
+ $anyDirty,
893
+ $tooltips,
894
+ $name
895
+ })
896
+ );
897
+ });
898
+ return result;
899
+ });
900
+ fieldScopes.push(scope2);
901
+ });
902
+ }
903
+ }
904
+ const $shortcuts2 = {};
905
+ watch($valid, (value) => {
906
+ if (value) {
907
+ triggerPunishment.value = false;
908
+ }
909
+ });
910
+ return {
911
+ $error,
912
+ $pending,
913
+ $invalid,
914
+ $valid,
915
+ $debounce: $debounce2,
916
+ $lazy: $lazy2,
917
+ $errors,
918
+ $ready,
919
+ $silentErrors,
920
+ $rewardEarly: $rewardEarly2,
921
+ $autoDirty: $autoDirty2,
922
+ $clearExternalErrorsOnChange: $clearExternalErrorsOnChange2,
923
+ $anyDirty,
924
+ $name,
925
+ $haveAnyAsyncRule: $haveAnyAsyncRule2,
926
+ $shortcuts: $shortcuts2,
927
+ $validating: $validating2,
928
+ $tooltips,
929
+ $dirty,
930
+ triggerPunishment,
931
+ processShortcuts
932
+ };
933
+ });
934
+ $unwatchState = watch(
935
+ state,
936
+ () => {
937
+ if (scopeState.$autoDirty.value) {
938
+ if (!scopeState.$dirty.value) {
939
+ scopeState.$dirty.value = true;
940
+ }
941
+ }
942
+ if (rulesDef.value instanceof Function) {
943
+ createReactiveRulesResult();
944
+ }
945
+ if (scopeState.$autoDirty.value || scopeState.$rewardEarly.value && scopeState.$error.value) {
946
+ $commit();
947
+ }
948
+ if (scopeState.$rewardEarly.value !== true && scopeState.$clearExternalErrorsOnChange.value) {
949
+ $clearExternalErrors();
950
+ }
951
+ },
952
+ { deep: $isArray ? true : isVueSuperiorOrEqualTo3dotFive ? 1 : true }
953
+ );
954
+ $unwatchDirty = watch(scopeState.$dirty, () => {
955
+ storage.setDirtyEntry(path, scopeState.$dirty.value);
956
+ });
957
+ $unwatchValid = watch(scopeState.$valid, (valid) => {
958
+ if (scopeState.$rewardEarly.value && valid) {
959
+ scopeState.triggerPunishment.value = false;
960
+ }
961
+ });
962
+ $unwatchAsync = watch(scopeState.$haveAnyAsyncRule, define$commit);
963
+ }
964
+ function $commitHandler() {
965
+ Object.values($rules.value).forEach((rule) => {
966
+ rule.$validate();
967
+ });
968
+ }
969
+ const $rules = ref({});
970
+ const $localOptions = ref({});
971
+ createReactiveRulesResult();
972
+ function $reset() {
973
+ $clearExternalErrors();
974
+ scopeState.$dirty.value = false;
975
+ storage.setDirtyEntry(path, false);
976
+ Object.entries($rules.value).forEach(([key, rule]) => {
977
+ rule.$reset();
978
+ });
979
+ if (!scopeState.$lazy.value && scopeState.$autoDirty.value) {
980
+ Object.values($rules.value).forEach((rule) => {
981
+ return rule.$validate();
982
+ });
983
+ }
984
+ }
985
+ function $touch(runCommit = true, withConditions = false) {
986
+ if (!scopeState.$dirty.value) {
987
+ scopeState.$dirty.value = true;
988
+ }
989
+ if (withConditions && runCommit) {
990
+ if (scopeState.$autoDirty.value || scopeState.$rewardEarly.value && scopeState.$error.value) {
991
+ $commit();
992
+ }
993
+ } else if (runCommit) {
994
+ $commit();
995
+ }
996
+ }
997
+ async function $validate() {
998
+ try {
999
+ const data = state.value;
1000
+ scopeState.triggerPunishment.value = true;
1001
+ if (!scopeState.$dirty.value) {
1002
+ scopeState.$dirty.value = true;
1003
+ } else if (scopeState.$autoDirty.value && scopeState.$dirty.value && !scopeState.$pending.value) {
1004
+ return { result: !scopeState.$error.value, data };
1005
+ }
1006
+ if (isEmpty($rules.value)) {
1007
+ return { result: true, data };
1008
+ }
1009
+ const results = await Promise.allSettled(
1010
+ Object.entries($rules.value).map(([key, rule]) => {
1011
+ return rule.$validate();
1012
+ })
1013
+ );
1014
+ const validationResults = results.every((value) => {
1015
+ if (value.status === "fulfilled") {
1016
+ return value.value === true;
1017
+ } else {
1018
+ return false;
1019
+ }
1020
+ });
1021
+ return { result: validationResults, data };
1022
+ } catch (e) {
1023
+ return { result: false, data: state.value };
1024
+ }
1025
+ }
1026
+ function $resetAll() {
1027
+ $unwatch();
1028
+ state.value = cloneDeep(initialState);
1029
+ $reset();
1030
+ }
1031
+ function $extractDirtyFields(filterNullishValues = true) {
1032
+ if (scopeState.$dirty.value) {
1033
+ return state.value;
1034
+ }
1035
+ if (filterNullishValues) {
1036
+ return { _null: true };
1037
+ }
1038
+ return null;
1039
+ }
1040
+ function $clearExternalErrors() {
1041
+ if (externalErrors?.value?.length) {
1042
+ externalErrors.value = [];
1043
+ }
1044
+ }
1045
+ if (!scopeState.$lazy.value && !scopeState.$dirty.value && scopeState.$autoDirty.value) {
1046
+ $commit();
1047
+ }
1048
+ const {
1049
+ $shortcuts,
1050
+ $validating,
1051
+ $autoDirty,
1052
+ $rewardEarly,
1053
+ $clearExternalErrorsOnChange,
1054
+ $haveAnyAsyncRule,
1055
+ $debounce,
1056
+ $lazy,
1057
+ ...restScope
1058
+ } = scopeState;
1059
+ return reactive({
1060
+ ...restScope,
1061
+ $externalErrors: externalErrors,
1062
+ $value: state,
1063
+ $rules,
1064
+ ...$shortcuts,
1065
+ $reset,
1066
+ $touch,
1067
+ $validate,
1068
+ $unwatch,
1069
+ $watch,
1070
+ $resetAll,
1071
+ $extractDirtyFields,
1072
+ $clearExternalErrors
1073
+ });
1074
+ }
1075
+ function createCollectionElement({
1076
+ $id,
1077
+ path,
1078
+ index,
1079
+ options,
1080
+ storage,
1081
+ stateValue,
1082
+ customMessages,
1083
+ rules,
1084
+ externalErrors,
1085
+ initialState,
1086
+ shortcuts,
1087
+ fieldName
1088
+ }) {
1089
+ const $fieldId = rules.$key ? rules.$key : randomId();
1090
+ let $path = `${path}.${String($fieldId)}`;
1091
+ if (typeof stateValue.value === "object" && stateValue.value != null) {
1092
+ if (!stateValue.value.$id) {
1093
+ Object.defineProperties(stateValue.value, {
1094
+ $id: {
1095
+ value: $fieldId,
1096
+ enumerable: false,
1097
+ configurable: false,
1098
+ writable: false
1099
+ }
1100
+ });
1101
+ } else {
1102
+ $path = `${path}.${stateValue.value.$id}`;
1103
+ }
1104
+ }
1105
+ const $status = createReactiveChildrenStatus({
1106
+ state: stateValue,
1107
+ rulesDef: toRef(() => rules),
1108
+ customMessages,
1109
+ path: $path,
1110
+ storage,
1111
+ options,
1112
+ externalErrors: toRef(externalErrors?.value ?? [], index),
1113
+ initialState: initialState?.[index],
1114
+ shortcuts,
1115
+ fieldName
1116
+ });
1117
+ if ($status) {
1118
+ const valueId = stateValue.value?.$id;
1119
+ $status.$id = valueId ?? String($fieldId);
1120
+ storage.addArrayStatus($id, $status.$id, $status);
1121
+ }
1122
+ return $status;
1123
+ }
1124
+
1125
+ // src/core/useRegle/useStateProperties/collections/createReactiveCollectionRoot.ts
1126
+ function createReactiveCollectionStatus({
1127
+ state,
1128
+ rulesDef,
1129
+ customMessages,
1130
+ path,
1131
+ storage,
1132
+ options,
1133
+ externalErrors,
1134
+ initialState,
1135
+ shortcuts,
1136
+ fieldName
1137
+ }) {
1138
+ let scope = effectScope();
1139
+ let scopeState;
1140
+ let immediateScope = effectScope();
1141
+ let immediateScopeState;
1142
+ let collectionScopes = [];
1143
+ if (!Array.isArray(state.value) && !rulesDef.value.$each) {
1144
+ return null;
1145
+ }
1146
+ const $id = ref();
1147
+ const $value = ref(state.value);
1148
+ let $unwatchState;
1149
+ const $fieldStatus = ref({});
1150
+ const $eachStatus = storage.getCollectionsEntry(path);
1151
+ immediateScopeState = immediateScope.run(() => {
1152
+ const isPrimitiveArray = computed(() => {
1153
+ if (Array.isArray(state.value) && state.value.length) {
1154
+ return state.value.some((s) => typeof s !== "object");
1155
+ } else if (rulesDef.value.$each && !(rulesDef.value.$each instanceof Function)) {
1156
+ return Object.values(rulesDef.value.$each).every((rule) => isRuleDef(rule));
1157
+ }
1158
+ return false;
1159
+ });
1160
+ return {
1161
+ isPrimitiveArray
1162
+ };
1163
+ });
1164
+ createStatus();
1165
+ $watch();
1166
+ function createStatus() {
1167
+ if (typeof state.value === "object") {
1168
+ if (state.value != null && !state.value?.$id && state.value !== null) {
1169
+ $id.value = randomId();
1170
+ Object.defineProperties(state.value, {
1171
+ $id: {
1172
+ value: $id.value,
1173
+ enumerable: false,
1174
+ configurable: false,
1175
+ writable: false
1176
+ }
1177
+ });
1178
+ } else if (state.value?.$id) {
1179
+ $id.value = state.value.$id;
1180
+ }
1181
+ }
1182
+ if (immediateScopeState.isPrimitiveArray.value) {
1183
+ return;
1184
+ }
1185
+ $value.value = $fieldStatus.value.$value;
1186
+ if (Array.isArray(state.value)) {
1187
+ $eachStatus.value = state.value.map((value, index) => {
1188
+ const unwrapped$Each = unwrapGetter(
1189
+ rulesDef.value.$each,
1190
+ toRef(() => value),
1191
+ index
1192
+ );
1193
+ const element = createCollectionElement({
1194
+ $id: $id.value,
1195
+ path,
1196
+ customMessages,
1197
+ rules: unwrapped$Each ?? {},
1198
+ stateValue: toRef(() => value),
1199
+ index,
1200
+ options,
1201
+ storage,
1202
+ externalErrors: toRef(externalErrors?.value ?? {}, `$each`),
1203
+ initialState: initialState?.[index],
1204
+ shortcuts,
1205
+ fieldName
1206
+ });
1207
+ if (element) {
1208
+ return element;
1209
+ }
1210
+ return null;
1211
+ }).filter((each) => !!each);
1212
+ } else {
1213
+ $eachStatus.value = [];
1214
+ }
1215
+ $fieldStatus.value = createReactiveFieldStatus({
1216
+ state,
1217
+ rulesDef,
1218
+ customMessages,
1219
+ path,
1220
+ storage,
1221
+ options,
1222
+ externalErrors: toRef(externalErrors?.value ?? {}, `$self`),
1223
+ $isArray: true,
1224
+ initialState,
1225
+ shortcuts,
1226
+ fieldName
1227
+ });
1228
+ }
1229
+ function updateStatus() {
1230
+ if (Array.isArray(state.value)) {
1231
+ const previousStatus = cloneDeep($eachStatus.value);
1232
+ $eachStatus.value = state.value.map((value, index) => {
1233
+ const currentValue = toRef(() => value);
1234
+ if (value.$id && $eachStatus.value.find((each) => each.$id === value.$id)) {
1235
+ const existingStatus = storage.getArrayStatus($id.value, value.$id);
1236
+ if (existingStatus) {
1237
+ existingStatus.$value = currentValue;
1238
+ return existingStatus;
1239
+ }
1240
+ return null;
1241
+ } else {
1242
+ const unwrapped$Each = unwrapGetter(rulesDef.value.$each, currentValue, index);
1243
+ if (unwrapped$Each) {
1244
+ const element = createCollectionElement({
1245
+ $id: $id.value,
1246
+ path,
1247
+ customMessages,
1248
+ rules: unwrapped$Each,
1249
+ stateValue: currentValue,
1250
+ index,
1251
+ options,
1252
+ storage,
1253
+ externalErrors: toRef(externalErrors?.value ?? {}, `$each`),
1254
+ initialState: initialState?.[index],
1255
+ shortcuts,
1256
+ fieldName
1257
+ });
1258
+ if (element) {
1259
+ return element;
1260
+ }
1261
+ return null;
1262
+ }
1263
+ }
1264
+ }).filter((each) => !!each);
1265
+ previousStatus.filter(($each) => !state.value.find((f) => $each.$id === f.$id)).forEach(($each, index) => {
1266
+ storage.deleteArrayStatus($id.value, index.toString());
1267
+ });
1268
+ } else {
1269
+ $eachStatus.value = [];
1270
+ }
1271
+ }
1272
+ function $watch() {
1273
+ $unwatchState = watch(
1274
+ state,
1275
+ () => {
1276
+ if (state.value != null && !Object.hasOwn(state.value, "$id")) {
1277
+ createStatus();
1278
+ } else {
1279
+ updateStatus();
1280
+ }
1281
+ },
1282
+ { deep: isVueSuperiorOrEqualTo3dotFive ? 1 : true, flush: "pre" }
1283
+ );
1284
+ scope = effectScope();
1285
+ scopeState = scope.run(() => {
1286
+ const $dirty = computed(() => {
1287
+ return $fieldStatus.value.$dirty && $eachStatus.value.every((statusOrField) => {
1288
+ return statusOrField.$dirty;
1289
+ });
1290
+ });
1291
+ const $anyDirty = computed(() => {
1292
+ return $fieldStatus.value.$anyDirty || $eachStatus.value.some((statusOrField) => {
1293
+ return statusOrField.$dirty;
1294
+ });
1295
+ });
1296
+ const $invalid = computed(() => {
1297
+ return $fieldStatus.value.$invalid || $eachStatus.value.some((statusOrField) => {
1298
+ return statusOrField.$invalid;
1299
+ });
1300
+ });
1301
+ const $valid = computed(() => {
1302
+ return (isEmpty($fieldStatus.value.$rules) ? true : $fieldStatus.value.$valid) && $eachStatus.value.every((statusOrField) => {
1303
+ return statusOrField.$valid;
1304
+ });
1305
+ });
1306
+ const $error = computed(() => {
1307
+ return $fieldStatus.value.$error || $eachStatus.value.some((statusOrField) => {
1308
+ return statusOrField.$error;
1309
+ });
1310
+ });
1311
+ const $ready = computed(() => {
1312
+ return !($invalid.value || $pending.value);
1313
+ });
1314
+ const $pending = computed(() => {
1315
+ return $fieldStatus.value.$pending || $eachStatus.value.some((statusOrField) => {
1316
+ return statusOrField.$pending;
1317
+ });
1318
+ });
1319
+ const $errors = computed(() => {
1320
+ return {
1321
+ $self: $fieldStatus.value.$errors,
1322
+ $each: $eachStatus.value.map(($each) => $each.$errors)
1323
+ };
1324
+ });
1325
+ const $silentErrors = computed(() => {
1326
+ return {
1327
+ $self: $fieldStatus.value.$silentErrors,
1328
+ $each: $eachStatus.value.map(($each) => $each.$silentErrors)
1329
+ };
1330
+ });
1331
+ const $name = computed(() => fieldName);
1332
+ function processShortcuts() {
1333
+ if (shortcuts?.collections) {
1334
+ Object.entries(shortcuts?.collections).forEach(([key, value]) => {
1335
+ const scope2 = effectScope();
1336
+ $shortcuts2[key] = scope2.run(() => {
1337
+ const result = ref();
1338
+ watchEffect(() => {
1339
+ result.value = value(
1340
+ reactive({
1341
+ $dirty,
1342
+ $error,
1343
+ $pending,
1344
+ $invalid,
1345
+ $valid,
1346
+ $errors,
1347
+ $ready,
1348
+ $silentErrors,
1349
+ $anyDirty,
1350
+ $name,
1351
+ $each: $eachStatus,
1352
+ $field: $fieldStatus,
1353
+ $value: state
1354
+ })
1355
+ );
1356
+ });
1357
+ return result;
1358
+ });
1359
+ collectionScopes.push(scope2);
1360
+ });
1361
+ }
1362
+ }
1363
+ const $shortcuts2 = {};
1364
+ processShortcuts();
1365
+ return {
1366
+ $dirty,
1367
+ $anyDirty,
1368
+ $invalid,
1369
+ $valid,
1370
+ $error,
1371
+ $pending,
1372
+ $errors,
1373
+ $silentErrors,
1374
+ $ready,
1375
+ $name,
1376
+ $shortcuts: $shortcuts2
1377
+ };
1378
+ });
1379
+ if (immediateScopeState.isPrimitiveArray.value) {
1380
+ console.warn(
1381
+ `${path} is a Array of primitives. Tracking can be lost when reassigning the Array. We advise to use an Array of objects instead`
1382
+ );
1383
+ $unwatchState();
1384
+ }
1385
+ }
1386
+ function $unwatch() {
1387
+ if ($unwatchState) {
1388
+ $unwatchState();
1389
+ }
1390
+ if ($fieldStatus.value) {
1391
+ $fieldStatus.value.$unwatch();
1392
+ }
1393
+ if ($eachStatus.value) {
1394
+ $eachStatus.value.forEach((element) => {
1395
+ if ("$dirty" in element) {
1396
+ element.$unwatch();
1397
+ }
1398
+ });
1399
+ }
1400
+ scope.stop();
1401
+ scope = effectScope();
1402
+ immediateScope.stop();
1403
+ immediateScope = effectScope(true);
1404
+ collectionScopes.forEach((s) => s.stop());
1405
+ collectionScopes = [];
1406
+ }
1407
+ function $touch(runCommit = true, withConditions = false) {
1408
+ $fieldStatus.value.$touch(runCommit, withConditions);
1409
+ $eachStatus.value.forEach(($each) => {
1410
+ $each.$touch(runCommit, withConditions);
1411
+ });
1412
+ }
1413
+ function $reset() {
1414
+ $fieldStatus.value.$reset();
1415
+ $eachStatus.value.forEach(($each) => {
1416
+ $each.$reset();
1417
+ });
1418
+ }
1419
+ async function $validate() {
1420
+ const data = state.value;
1421
+ try {
1422
+ const results = await Promise.allSettled([
1423
+ $fieldStatus.value.$validate(),
1424
+ ...$eachStatus.value.map((rule) => {
1425
+ return rule.$validate();
1426
+ })
1427
+ ]);
1428
+ const validationResults = results.every((value) => {
1429
+ if (value.status === "fulfilled") {
1430
+ return value.value.result === true;
1431
+ } else {
1432
+ return false;
1433
+ }
1434
+ });
1435
+ return { result: validationResults, data };
1436
+ } catch (e) {
1437
+ return { result: false, data };
1438
+ }
1439
+ }
1440
+ function $clearExternalErrors() {
1441
+ $fieldStatus.value.$clearExternalErrors();
1442
+ $eachStatus.value.forEach(($each) => {
1443
+ $each.$clearExternalErrors();
1444
+ });
1445
+ }
1446
+ function $extractDirtyFields(filterNullishValues = true) {
1447
+ let dirtyFields = $eachStatus.value.map(($each) => {
1448
+ if (isNestedRulesStatus($each)) {
1449
+ return $each.$extractDirtyFields(filterNullishValues);
1450
+ }
1451
+ });
1452
+ if (filterNullishValues) {
1453
+ if (dirtyFields.every((value) => {
1454
+ return isEmpty(value);
1455
+ })) {
1456
+ dirtyFields = [];
1457
+ }
1458
+ }
1459
+ return dirtyFields;
1460
+ }
1461
+ function $resetAll() {
1462
+ $unwatch();
1463
+ state.value = cloneDeep(initialState);
1464
+ $reset();
1465
+ }
1466
+ const { $shortcuts, ...restScopeState } = scopeState;
1467
+ return reactive({
1468
+ $field: $fieldStatus,
1469
+ ...restScopeState,
1470
+ ...$shortcuts,
1471
+ $each: $eachStatus,
1472
+ $value: state,
1473
+ $validate,
1474
+ $unwatch,
1475
+ $watch,
1476
+ $touch,
1477
+ $reset,
1478
+ $resetAll,
1479
+ $extractDirtyFields,
1480
+ $clearExternalErrors
1481
+ });
1482
+ }
1483
+
1484
+ // src/core/useRegle/useStateProperties/createReactiveNestedStatus.ts
1485
+ function createReactiveNestedStatus({
1486
+ rulesDef,
1487
+ state,
1488
+ path = "",
1489
+ rootRules,
1490
+ externalErrors,
1491
+ validationGroups,
1492
+ initialState,
1493
+ fieldName,
1494
+ ...commonArgs
1495
+ }) {
1496
+ let scope = effectScope();
1497
+ let scopeState;
1498
+ let nestedScopes = [];
1499
+ let $unwatchRules = null;
1500
+ let $unwatchExternalErrors = null;
1501
+ let $unwatchState = null;
1502
+ async function createReactiveFieldsStatus(watch6 = true) {
1503
+ const mapOfRulesDef = Object.entries(rulesDef.value);
1504
+ const scopedRulesStatus = Object.fromEntries(
1505
+ mapOfRulesDef.filter(([_, rule]) => !!rule).map(([statePropKey, statePropRules]) => {
1506
+ if (statePropRules) {
1507
+ const stateRef = toRef(state.value, statePropKey);
1508
+ const statePropRulesRef = toRef(() => statePropRules);
1509
+ const $externalErrors = toRef(externalErrors?.value ?? {}, statePropKey);
1510
+ return [
1511
+ statePropKey,
1512
+ createReactiveChildrenStatus({
1513
+ state: stateRef,
1514
+ rulesDef: statePropRulesRef,
1515
+ path: path ? `${path}.${statePropKey}` : statePropKey,
1516
+ externalErrors: $externalErrors,
1517
+ initialState: initialState?.[statePropKey],
1518
+ fieldName: statePropKey,
1519
+ ...commonArgs
1520
+ })
1521
+ ];
1522
+ }
1523
+ return [];
1524
+ })
1525
+ );
1526
+ const externalRulesStatus = Object.fromEntries(
1527
+ Object.entries(unref(externalErrors) ?? {}).filter(([key, errors]) => !(key in rulesDef.value) && !!errors).map(([key]) => {
1528
+ const stateRef = toRef(state.value, key);
1529
+ return [
1530
+ key,
1531
+ createReactiveChildrenStatus({
1532
+ state: stateRef,
1533
+ rulesDef: computed(() => ({})),
1534
+ path: path ? `${path}.${key}` : key,
1535
+ externalErrors: toRef(externalErrors?.value ?? {}, key),
1536
+ initialState: initialState?.[key],
1537
+ fieldName: key,
1538
+ ...commonArgs
1539
+ })
1540
+ ];
1541
+ })
1542
+ );
1543
+ const statesWithNoRules = Object.fromEntries(
1544
+ Object.entries(state.value).filter(([key]) => !(key in rulesDef.value) && !(key in (externalRulesStatus.value ?? {}))).map(([key]) => {
1545
+ const stateRef = toRef(state.value, key);
1546
+ return [
1547
+ key,
1548
+ createReactiveChildrenStatus({
1549
+ state: stateRef,
1550
+ rulesDef: computed(() => ({})),
1551
+ path: path ? `${path}.${key}` : key,
1552
+ externalErrors: toRef(externalErrors?.value ?? {}, key),
1553
+ initialState: initialState?.[key],
1554
+ fieldName: key,
1555
+ ...commonArgs
1556
+ })
1557
+ ];
1558
+ })
1559
+ );
1560
+ $fields.value = {
1561
+ ...scopedRulesStatus,
1562
+ ...externalRulesStatus,
1563
+ ...statesWithNoRules
1564
+ };
1565
+ if (watch6) {
1566
+ $watch();
1567
+ }
1568
+ }
1569
+ const $fields = commonArgs.storage.getFieldsEntry(path);
1570
+ createReactiveFieldsStatus();
1571
+ function $reset() {
1572
+ $unwatchExternalErrors?.();
1573
+ Object.values($fields.value).forEach((statusOrField) => {
1574
+ statusOrField.$reset();
1575
+ });
1576
+ define$WatchExternalErrors();
1577
+ }
1578
+ function $touch(runCommit = true, withConditions = false) {
1579
+ Object.values($fields.value).forEach((statusOrField) => {
1580
+ statusOrField.$touch(runCommit, withConditions);
1581
+ });
1582
+ }
1583
+ function define$WatchExternalErrors() {
1584
+ if (externalErrors?.value) {
1585
+ $unwatchExternalErrors = watch(
1586
+ externalErrors,
1587
+ () => {
1588
+ $unwatch();
1589
+ createReactiveFieldsStatus();
1590
+ },
1591
+ { deep: true }
1592
+ );
1593
+ }
1594
+ }
1595
+ function $watch() {
1596
+ if (rootRules) {
1597
+ $unwatchRules = watch(
1598
+ rootRules,
1599
+ () => {
1600
+ $unwatch();
1601
+ createReactiveFieldsStatus();
1602
+ },
1603
+ { deep: true, flush: "post" }
1604
+ );
1605
+ define$WatchExternalErrors();
1606
+ }
1607
+ $unwatchState = watch(
1608
+ state,
1609
+ () => {
1610
+ $unwatch();
1611
+ createReactiveFieldsStatus();
1612
+ $touch(true, true);
1613
+ },
1614
+ { flush: "sync" }
1615
+ );
1616
+ scope = effectScope();
1617
+ scopeState = scope.run(() => {
1618
+ const $dirty = computed({
1619
+ get: () => {
1620
+ return !!Object.entries($fields.value).length && Object.entries($fields.value).every(([key, statusOrField]) => {
1621
+ return statusOrField?.$dirty;
1622
+ });
1623
+ },
1624
+ set() {
1625
+ }
1626
+ });
1627
+ const $anyDirty = computed({
1628
+ get: () => {
1629
+ return Object.entries($fields.value).some(([key, statusOrField]) => {
1630
+ return statusOrField?.$dirty;
1631
+ });
1632
+ },
1633
+ set() {
1634
+ }
1635
+ });
1636
+ const $invalid = computed({
1637
+ get: () => {
1638
+ return Object.entries($fields.value).some(([key, statusOrField]) => {
1639
+ return statusOrField?.$invalid;
1640
+ });
1641
+ },
1642
+ set() {
1643
+ }
1644
+ });
1645
+ const $valid = computed({
1646
+ get: () => {
1647
+ return Object.entries($fields.value).every(([key, statusOrField]) => {
1648
+ return statusOrField?.$valid;
1649
+ });
1650
+ },
1651
+ set() {
1652
+ }
1653
+ });
1654
+ const $error = computed({
1655
+ get: () => {
1656
+ return $anyDirty.value && !$pending.value && $invalid.value;
1657
+ },
1658
+ set() {
1659
+ }
1660
+ });
1661
+ const $ready = computed({
1662
+ get: () => {
1663
+ if (!unref(commonArgs.options.autoDirty)) {
1664
+ return !($invalid.value || $pending.value);
1665
+ }
1666
+ return $anyDirty.value && !($invalid.value || $pending.value);
1667
+ },
1668
+ set() {
1669
+ }
1670
+ });
1671
+ const $pending = computed({
1672
+ get: () => {
1673
+ return Object.entries($fields.value).some(([key, statusOrField]) => {
1674
+ return statusOrField?.$pending;
1675
+ });
1676
+ },
1677
+ set() {
1678
+ }
1679
+ });
1680
+ const $errors = computed({
1681
+ get: () => {
1682
+ return Object.fromEntries(
1683
+ Object.entries($fields.value).map(([key, statusOrField]) => {
1684
+ return [key, statusOrField?.$errors];
1685
+ })
1686
+ );
1687
+ },
1688
+ set() {
1689
+ }
1690
+ });
1691
+ const $silentErrors = computed({
1692
+ get: () => {
1693
+ return Object.fromEntries(
1694
+ Object.entries($fields.value).map(([key, statusOrField]) => {
1695
+ return [key, statusOrField?.$silentErrors];
1696
+ })
1697
+ );
1698
+ },
1699
+ set() {
1700
+ }
1701
+ });
1702
+ const $name = computed({
1703
+ get: () => fieldName,
1704
+ set() {
1705
+ }
1706
+ });
1707
+ function processShortcuts() {
1708
+ if (commonArgs.shortcuts?.nested) {
1709
+ Object.entries(commonArgs.shortcuts.nested).forEach(([key, value]) => {
1710
+ const scope2 = effectScope();
1711
+ $shortcuts2[key] = scope2.run(() => {
1712
+ const result = ref();
1713
+ watchEffect(() => {
1714
+ result.value = value(
1715
+ reactive({
1716
+ $dirty,
1717
+ $value: state,
1718
+ $error,
1719
+ $pending,
1720
+ $invalid,
1721
+ $valid,
1722
+ $ready,
1723
+ $anyDirty,
1724
+ $name,
1725
+ $silentErrors,
1726
+ $errors,
1727
+ $fields
1728
+ })
1729
+ );
1730
+ });
1731
+ return result;
1732
+ });
1733
+ nestedScopes.push(scope2);
1734
+ });
1735
+ }
1736
+ }
1737
+ const $groups = computed({
1738
+ get: () => {
1739
+ if (validationGroups) {
1740
+ return Object.fromEntries(
1741
+ Object.entries(validationGroups?.($fields.value) ?? {}).map(([key, entries]) => {
1742
+ if (entries.length) {
1743
+ return [
1744
+ key,
1745
+ {
1746
+ ...Object.fromEntries(
1747
+ ["$invalid", "$error", "$pending", "$dirty", "$valid"].map((property) => [
1748
+ property,
1749
+ mergeBooleanGroupProperties(entries, property)
1750
+ ])
1751
+ ),
1752
+ ...Object.fromEntries(
1753
+ ["$errors", "$silentErrors"].map((property) => [
1754
+ property,
1755
+ mergeArrayGroupProperties(entries, property)
1756
+ ])
1757
+ )
1758
+ }
1759
+ ];
1760
+ }
1761
+ return [];
1762
+ })
1763
+ );
1764
+ }
1765
+ return {};
1766
+ },
1767
+ set() {
1768
+ }
1769
+ });
1770
+ const $shortcuts2 = {};
1771
+ processShortcuts();
1772
+ return {
1773
+ $dirty,
1774
+ $anyDirty,
1775
+ $invalid,
1776
+ $valid,
1777
+ $error,
1778
+ $pending,
1779
+ $errors,
1780
+ $silentErrors,
1781
+ $ready,
1782
+ $name,
1783
+ $shortcuts: $shortcuts2,
1784
+ $groups
1785
+ };
1786
+ });
1787
+ }
1788
+ function $unwatch() {
1789
+ $unwatchRules?.();
1790
+ $unwatchExternalErrors?.();
1791
+ $unwatchState?.();
1792
+ nestedScopes.forEach((s) => s.stop());
1793
+ nestedScopes = [];
1794
+ scope.stop();
1795
+ if ($fields.value) {
1796
+ Object.entries($fields.value).forEach(([_, field]) => {
1797
+ field.$unwatch();
1798
+ });
1799
+ }
1800
+ }
1801
+ function $clearExternalErrors() {
1802
+ Object.entries($fields.value).forEach(([_, field]) => {
1803
+ field.$clearExternalErrors();
1804
+ });
1805
+ }
1806
+ async function $resetAll() {
1807
+ $unwatch();
1808
+ state.value = cloneDeep({ ...initialState ?? {} });
1809
+ $reset();
1810
+ createReactiveFieldsStatus();
1811
+ }
1812
+ function filterNullishFields(fields) {
1813
+ return fields.filter(([key, value]) => {
1814
+ if (isObject(value)) {
1815
+ return !(value && typeof value === "object" && "_null" in value) && !isEmpty(value);
1816
+ } else if (Array.isArray(value)) {
1817
+ return value.length;
1818
+ } else {
1819
+ return true;
1820
+ }
1821
+ });
1822
+ }
1823
+ function $extractDirtyFields(filterNullishValues = true) {
1824
+ let dirtyFields = Object.entries($fields.value).map(([key, field]) => {
1825
+ return [key, field.$extractDirtyFields(filterNullishValues)];
1826
+ });
1827
+ if (filterNullishValues) {
1828
+ dirtyFields = filterNullishFields(dirtyFields);
1829
+ }
1830
+ return Object.fromEntries(dirtyFields);
1831
+ }
1832
+ async function $validate() {
1833
+ try {
1834
+ const data = state.value;
1835
+ const results = await Promise.allSettled(
1836
+ Object.values($fields.value).map((statusOrField) => {
1837
+ return statusOrField.$validate();
1838
+ })
1839
+ );
1840
+ const validationResults = results.every((value) => {
1841
+ if (value.status === "fulfilled") {
1842
+ return value.value.result === true;
1843
+ } else {
1844
+ return false;
1845
+ }
1846
+ });
1847
+ return { result: validationResults, data };
1848
+ } catch (e) {
1849
+ return { result: false, data: state.value };
1850
+ }
1851
+ }
1852
+ const { $shortcuts, ...restScopeState } = scopeState;
1853
+ return reactive({
1854
+ ...restScopeState,
1855
+ ...$shortcuts,
1856
+ $fields,
1857
+ $value: state,
1858
+ $resetAll,
1859
+ $reset,
1860
+ $touch,
1861
+ $validate,
1862
+ $unwatch,
1863
+ $watch,
1864
+ $clearExternalErrors,
1865
+ $extractDirtyFields
1866
+ });
1867
+ }
1868
+ function createReactiveChildrenStatus({
1869
+ rulesDef,
1870
+ externalErrors,
1871
+ ...properties
1872
+ }) {
1873
+ if (isCollectionRulesDef(rulesDef, properties.state)) {
1874
+ return createReactiveCollectionStatus({
1875
+ rulesDef,
1876
+ externalErrors,
1877
+ ...properties
1878
+ });
1879
+ } else if (isNestedRulesDef(properties.state, rulesDef) && isRefObject(properties.state)) {
1880
+ return createReactiveNestedStatus({
1881
+ rulesDef,
1882
+ externalErrors,
1883
+ ...properties
1884
+ });
1885
+ } else if (isValidatorRulesDef(rulesDef)) {
1886
+ return createReactiveFieldStatus({
1887
+ rulesDef,
1888
+ externalErrors,
1889
+ ...properties
1890
+ });
1891
+ }
1892
+ return null;
1893
+ }
1894
+
1895
+ // src/core/useRegle/useStateProperties/useStateProperties.ts
1896
+ function useStateProperties({
1897
+ initialState,
1898
+ options,
1899
+ scopeRules,
1900
+ state,
1901
+ customRules,
1902
+ shortcuts
1903
+ }) {
1904
+ const storage = useStorage();
1905
+ const regle = ref();
1906
+ regle.value = createReactiveNestedStatus({
1907
+ rootRules: scopeRules,
1908
+ rulesDef: scopeRules,
1909
+ state,
1910
+ customMessages: customRules?.(),
1911
+ storage,
1912
+ options,
1913
+ externalErrors: options.externalErrors,
1914
+ validationGroups: options.validationGroups,
1915
+ initialState,
1916
+ shortcuts,
1917
+ fieldName: "root",
1918
+ path: ""
1919
+ });
1920
+ onScopeDispose(() => {
1921
+ regle.value?.$unwatch();
1922
+ });
1923
+ return reactive({ regle });
1924
+ }
1925
+
1926
+ // src/core/useRegle/useRegle.ts
1927
+ function createUseRegleComposable(customRules, options, shortcuts) {
1928
+ const globalOptions = {
1929
+ autoDirty: options?.autoDirty ?? true,
1930
+ lazy: options?.lazy ?? false,
1931
+ rewardEarly: options?.rewardEarly ?? false,
1932
+ clearExternalErrorsOnChange: options?.clearExternalErrorsOnChange ?? true
1933
+ };
1934
+ function useRegle2(state, rulesFactory, options2) {
1935
+ const scopeRules = isRef(rulesFactory) ? rulesFactory : computed(typeof rulesFactory === "function" ? rulesFactory : () => rulesFactory);
1936
+ const resolvedOptions = {
1937
+ ...globalOptions,
1938
+ ...options2
1939
+ };
1940
+ const processedState = isRef(state) ? state : ref(state);
1941
+ const initialState = { ...cloneDeep(processedState.value) };
1942
+ const regle = useStateProperties({
1943
+ scopeRules,
1944
+ state: processedState,
1945
+ options: resolvedOptions,
1946
+ initialState,
1947
+ customRules,
1948
+ shortcuts
1949
+ });
1950
+ return {
1951
+ r$: regle.regle
1952
+ };
1953
+ }
1954
+ return useRegle2;
1955
+ }
1956
+ var useRegle = createUseRegleComposable();
1957
+ function createInferRuleHelper() {
1958
+ function inferRules2(state, rulesFactory) {
1959
+ return rulesFactory;
1960
+ }
1961
+ return inferRules2;
1962
+ }
1963
+ var inferRules = createInferRuleHelper();
1964
+
1965
+ // src/core/defineRegleConfig.ts
1966
+ function defineRegleConfig({
1967
+ rules,
1968
+ modifiers,
1969
+ shortcuts
1970
+ }) {
1971
+ const useRegle2 = createUseRegleComposable(rules, modifiers, shortcuts);
1972
+ const inferRules2 = createInferRuleHelper();
1973
+ return { useRegle: useRegle2, inferRules: inferRules2 };
1974
+ }
1975
+
1976
+ export { InternalRuleType, createRule, defineRegleConfig, inferRules, unwrapRuleParameters, useRegle };