@regle/core 1.2.3 → 1.3.0

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