@regle/core 0.4.5 → 0.4.6-beta.1

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