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