@leaflink/stash 44.6.0 → 44.7.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,201 +1,246 @@
1
1
  import O from "lodash-es/debounce";
2
- import E from "lodash-es/get";
3
- import { toValue as f, computed as c, ref as T, watch as A, reactive as S, nextTick as w, readonly as N } from "vue";
4
- import { DECIMAL_PRECISION as D, DEBOUNCE as j } from "./constants.js";
5
- import { t as d } from "./locale.js";
6
- import { i as v } from "./isDefined-2ce6cde4.js";
7
- import C from "lodash-es/round";
8
- function q(t) {
9
- return t && t.constructor && typeof t.constructor.isBuffer == "function" && t.constructor.isBuffer(t);
2
+ import S from "lodash-es/get";
3
+ import { toValue as u, computed as c, ref as w, watch as L, reactive as T, nextTick as I, readonly as V } from "vue";
4
+ import { DECIMAL_PRECISION as A, DEBOUNCE as q } from "./constants.js";
5
+ import { t as f } from "./locale.js";
6
+ import { i as l } from "./isDefined-2ce6cde4.js";
7
+ import D from "lodash-es/round";
8
+ function j(e) {
9
+ return e && e.constructor && typeof e.constructor.isBuffer == "function" && e.constructor.isBuffer(e);
10
10
  }
11
- function B(t) {
12
- return t;
11
+ function C(e) {
12
+ return e;
13
13
  }
14
- function F(t, e) {
15
- e = e || {};
16
- const a = e.delimiter || ".", i = e.maxDepth, o = e.transformKey || B, u = {};
17
- function g(h, y, m) {
18
- m = m || 1, Object.keys(h).forEach(function(b) {
19
- const r = h[b], V = e.safe && Array.isArray(r), n = Object.prototype.toString.call(r), s = q(r), p = n === "[object Object]" || n === "[object Array]", l = y ? y + a + o(b) : o(b);
20
- if (!V && !s && p && Object.keys(r).length && (!e.maxDepth || m < i))
21
- return g(r, l, m + 1);
22
- u[l] = r;
14
+ function F(e, t) {
15
+ t = t || {};
16
+ const i = t.delimiter || ".", o = t.maxDepth, s = t.transformKey || C, m = {};
17
+ function v(h, y, g) {
18
+ g = g || 1, Object.keys(h).forEach(function(p) {
19
+ const r = h[p], x = t.safe && Array.isArray(r), n = Object.prototype.toString.call(r), a = j(r), b = n === "[object Object]" || n === "[object Array]", d = y ? y + i + s(p) : s(p);
20
+ if (!x && !a && b && Object.keys(r).length && (!t.maxDepth || g < o))
21
+ return v(r, d, g + 1);
22
+ m[d] = r;
23
23
  });
24
24
  }
25
- return g(t), u;
25
+ return v(e), m;
26
26
  }
27
- function P(t = {}) {
27
+ function P(e = {}) {
28
28
  return {
29
29
  name: "email",
30
- validator(e) {
31
- return !v(e) || typeof e == "string" && /^\S+@\S+\.\S+$/.test(e);
30
+ validator(t) {
31
+ return !l(t) || typeof t == "string" && /^\S+@\S+\.\S+$/.test(t);
32
32
  },
33
- message: t.message || d("ll.validation.email")
33
+ message: e.message || f("ll.validation.email")
34
34
  };
35
35
  }
36
- function Y(t) {
36
+ function Y(e) {
37
+ return {
38
+ name: "maxLength",
39
+ validator(t) {
40
+ const i = u(e.max), o = u(t);
41
+ if (!l(o))
42
+ return !0;
43
+ let s = String(o);
44
+ return e.trim && (s = s.trim()), s.length <= i;
45
+ },
46
+ message: e.message || (() => f("ll.validation.maxLength", { max: String(u(e.max)) }))
47
+ };
48
+ }
49
+ function z(e) {
37
50
  return {
38
51
  name: "maxValue",
39
- validator(e) {
40
- const a = f(t.max);
41
- return !v(e) || Number(e) <= a;
52
+ validator(t) {
53
+ const i = u(e.max);
54
+ return !l(t) || Number(t) <= i;
55
+ },
56
+ message: e.message || (() => f("ll.validation.maxValue", { max: String(u(e.max)) }))
57
+ };
58
+ }
59
+ function G(e) {
60
+ return {
61
+ name: "minLength",
62
+ validator(t) {
63
+ const i = u(e.min), o = u(t);
64
+ if (!l(o))
65
+ return !0;
66
+ let s = String(o);
67
+ return e.trim && (s = s.trim()), s.length >= i;
42
68
  },
43
- message: t.message || (() => d("ll.validation.maxValue", { max: String(f(t.max)) }))
69
+ message: e.message || (() => f("ll.validation.minLength", { min: String(u(e.min)) }))
44
70
  };
45
71
  }
46
- function z(t) {
72
+ function H(e) {
47
73
  return {
48
74
  name: "minValue",
49
- validator(e) {
50
- const a = f(t.min);
51
- return !v(e) || Number(e) >= a;
75
+ validator(t) {
76
+ const i = u(e.min);
77
+ return !l(t) || Number(t) >= i;
78
+ },
79
+ message: e.message || (() => f("ll.validation.minValue", { min: String(u(e.min)) }))
80
+ };
81
+ }
82
+ function J(e) {
83
+ return {
84
+ name: "pattern",
85
+ validator(t) {
86
+ const i = u(t);
87
+ return !l(i) || e.regex.test(String(i));
52
88
  },
53
- message: t.message || (() => d("ll.validation.minValue", { min: String(f(t.min)) }))
89
+ message: () => {
90
+ if (typeof e.message != "string" || !e.message.trim())
91
+ throw new Error(
92
+ 'The "pattern" ruleFactory requires a custom message informing the user of the required pattern.'
93
+ );
94
+ return e.message;
95
+ }
54
96
  };
55
97
  }
56
- function G(t = {}) {
98
+ function Q(e = {}) {
57
99
  return {
58
100
  name: "positiveNumber",
59
- validator(e) {
60
- return !v(e) || Number(e) > 0;
101
+ validator(t) {
102
+ return !l(t) || Number(t) > 0;
61
103
  },
62
- message: t.message || d("ll.validation.positiveNumber")
104
+ message: e.message || f("ll.validation.positiveNumber")
63
105
  };
64
106
  }
65
- function H(t = {}) {
107
+ function X(e = {}) {
66
108
  return {
67
109
  name: "price",
68
- validator(e) {
69
- const a = Number(e);
70
- return !v(e) || a !== 1 / 0 && a >= 0 && a === C(a, D.CURRENCY);
110
+ validator(t) {
111
+ const i = Number(t);
112
+ return !l(t) || i !== 1 / 0 && i >= 0 && i === D(i, A.CURRENCY);
71
113
  },
72
- message: t.message || d("ll.validation.price")
114
+ message: e.message || f("ll.validation.price")
73
115
  };
74
116
  }
75
- function J(t = {}) {
117
+ function Z(e = {}) {
76
118
  return {
77
119
  name: "required",
78
- validator(e) {
79
- return v(typeof e == "string" ? e.trim() : e);
120
+ validator(t) {
121
+ return l(typeof t == "string" ? t.trim() : t);
80
122
  },
81
- message: t.message || d("ll.validation.required")
123
+ message: e.message || f("ll.validation.required")
82
124
  };
83
125
  }
84
- function Q(t = {}) {
126
+ function W(e = {}) {
85
127
  return {
86
128
  name: "wholeNumber",
87
- validator(e) {
88
- return !v(e) || Number.isInteger(Number(e)) && Number(e) >= 0;
129
+ validator(t) {
130
+ return !l(t) || Number.isInteger(Number(t)) && Number(t) >= 0;
89
131
  },
90
- message: t.message || d("ll.validation.wholeNumber")
132
+ message: e.message || f("ll.validation.wholeNumber")
91
133
  };
92
134
  }
93
- function X({
94
- rules: t,
95
- values: e
135
+ function ee({
136
+ rules: e,
137
+ values: t
96
138
  }) {
97
- const i = c(() => Object.keys(F(t, { safe: !0 }))).value.reduce((n, s) => {
98
- const p = T(E(f(e), s)), l = (I) => {
99
- p.value = E(f(e), I);
100
- }, x = O(() => {
101
- l(s);
102
- }, j.FAST);
103
- return A(
104
- () => E(f(e), s),
139
+ const o = c(() => Object.keys(F(e, { safe: !0 }))).value.reduce((n, a) => {
140
+ const b = w(S(u(t), a)), d = (N) => {
141
+ b.value = S(u(t), N);
142
+ }, E = O(() => {
143
+ d(a);
144
+ }, q.FAST);
145
+ return L(
146
+ () => S(u(t), a),
105
147
  () => {
106
- x();
148
+ E();
107
149
  }
108
- ), n[s] = M({
109
- fieldName: s,
110
- fieldValue: p,
150
+ ), n[a] = B({
151
+ fieldName: a,
152
+ fieldValue: b,
111
153
  flush: () => {
112
- x.cancel(), l(s);
154
+ E.cancel(), d(a);
113
155
  },
114
- rules: E(t, s)
156
+ rules: S(e, a)
115
157
  }), n;
116
- }, {}), o = c(() => Object.values(i)), u = c(() => o.value.some((n) => n.errors.length > 0)), g = c(() => o.value.some((n) => n.isTouched)), h = c(() => o.value.filter((n) => n.isDirty));
117
- return S({
158
+ }, {}), s = c(() => Object.values(o)), m = c(() => s.value.some((n) => n.errors.length > 0)), v = c(() => s.value.some((n) => n.isTouched)), h = c(() => s.value.filter((n) => n.isDirty));
159
+ return T({
118
160
  validate: async function({ preventScroll: n } = {}) {
119
- if (o.value.forEach((s) => {
120
- s.setTouched(!1), s.setTouched(!0);
121
- }), await w(), u.value && !n) {
122
- const s = Object.entries(i).find(([x, I]) => I.errorMessage), p = (s == null ? void 0 : s[0]) || "", l = document == null ? void 0 : document.querySelector(`[name=${p}]`);
123
- l && l.scrollIntoView({ behavior: "smooth" });
161
+ if (s.value.forEach((a) => {
162
+ a.setTouched(!1), a.setTouched(!0);
163
+ }), await I(), m.value && !n) {
164
+ const a = Object.entries(o).find(([E, N]) => N.errorMessage), b = (a == null ? void 0 : a[0]) || "", d = document == null ? void 0 : document.querySelector(`[name=${b}]`);
165
+ d && d.scrollIntoView({ behavior: "smooth" });
124
166
  }
125
- return !u.value;
167
+ return !m.value;
126
168
  },
127
169
  getError: function(n) {
128
- var s;
129
- return ((s = i[n]) == null ? void 0 : s.errorMessage) || "";
170
+ var a;
171
+ return ((a = o[n]) == null ? void 0 : a.errorMessage) || "";
130
172
  },
131
173
  touch: function(n) {
132
- if (!i[n])
174
+ if (!o[n])
133
175
  throw new Error(`In touch: fieldName "${n}" does not exist in the validation fields.`);
134
- i[n].setTouched();
176
+ o[n].setTouched();
135
177
  },
136
178
  setAllUntouched: async function() {
137
- await w(), o.value.forEach((n) => {
179
+ await I(), s.value.forEach((n) => {
138
180
  n.setTouched(!1);
139
181
  });
140
182
  },
141
183
  setInitialValues: function(n) {
142
- o.value.forEach((s) => {
143
- s.setInitialValue(n[s.name]);
184
+ s.value.forEach((a) => {
185
+ a.setInitialValue(n[a.name]);
144
186
  });
145
187
  },
146
- fields: i,
188
+ fields: o,
147
189
  dirtyFields: h,
148
- hasErrors: u,
149
- someTouched: g
190
+ hasErrors: m,
191
+ someTouched: v
150
192
  });
151
193
  }
152
- function M({
153
- fieldName: t,
154
- fieldValue: e,
155
- rules: a,
156
- flush: i
194
+ function B({
195
+ fieldName: e,
196
+ fieldValue: t,
197
+ rules: i,
198
+ flush: o
157
199
  }) {
158
- const o = T(e.value), u = T(!1), g = c(() => (e.value ?? "") !== (o.value ?? "")), h = c(() => u.value ? a.map((r) => ({
159
- fieldName: t,
200
+ const s = w(t.value), m = w(!1), v = c(() => (t.value ?? "") !== (s.value ?? "")), h = c(() => m.value ? i.map((r) => ({
201
+ fieldName: e,
160
202
  ruleName: r.name,
161
- isValid: r.validator(e.value),
162
- message: typeof r.message == "function" ? r.message(e.value) : r.message
203
+ isValid: r.validator(t.value),
204
+ message: typeof r.message == "function" ? r.message(t.value) : r.message
163
205
  })) : []), y = c(
164
206
  () => h.value.filter((r) => !r.isValid).map((r) => ({
165
207
  ruleName: r.ruleName,
166
208
  message: r.message
167
209
  }))
168
210
  );
169
- function m(r = !0) {
170
- i(), u.value = r;
211
+ function g(r = !0) {
212
+ o(), m.value = r;
171
213
  }
172
- function b(r) {
173
- o.value = r;
214
+ function p(r) {
215
+ s.value = r;
174
216
  }
175
- return S({
176
- name: t,
177
- currentValue: N(e),
178
- initialValue: N(o),
179
- isTouched: N(u),
180
- isDirty: N(g),
217
+ return T({
218
+ name: e,
219
+ currentValue: V(t),
220
+ initialValue: V(s),
221
+ isTouched: V(m),
222
+ isDirty: V(v),
181
223
  errorMessage: c(() => {
182
- var r, V;
183
- return ((V = (r = y.value) == null ? void 0 : r[0]) == null ? void 0 : V.message) || "";
224
+ var r, x;
225
+ return ((x = (r = y.value) == null ? void 0 : r[0]) == null ? void 0 : x.message) || "";
184
226
  }),
185
227
  errors: y,
186
- setInitialValue: b,
187
- setTouched: m
228
+ setInitialValue: p,
229
+ setTouched: g
188
230
  });
189
231
  }
190
232
  export {
191
- X as default,
233
+ ee as default,
192
234
  P as email,
193
- v as isDefined,
194
- Y as maxValue,
195
- z as minValue,
196
- G as positiveNumber,
197
- H as price,
198
- J as required,
199
- Q as wholeNumber
235
+ l as isDefined,
236
+ Y as maxLength,
237
+ z as maxValue,
238
+ G as minLength,
239
+ H as minValue,
240
+ J as pattern,
241
+ Q as positiveNumber,
242
+ X as price,
243
+ Z as required,
244
+ W as wholeNumber
200
245
  };
201
246
  //# sourceMappingURL=useValidation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useValidation.js","sources":["../node_modules/flat/index.js","../src/composables/useValidation/ruleFactories/email.ts","../src/composables/useValidation/ruleFactories/maxValue.ts","../src/composables/useValidation/ruleFactories/minValue.ts","../src/composables/useValidation/ruleFactories/positiveNumber.ts","../src/composables/useValidation/ruleFactories/price.ts","../src/composables/useValidation/ruleFactories/required.ts","../src/composables/useValidation/ruleFactories/wholeNumber.ts","../src/composables/useValidation/useValidation.ts"],"sourcesContent":["function isBuffer (obj) {\n return obj &&\n obj.constructor &&\n (typeof obj.constructor.isBuffer === 'function') &&\n obj.constructor.isBuffer(obj)\n}\n\nfunction keyIdentity (key) {\n return key\n}\n\nexport function flatten (target, opts) {\n opts = opts || {}\n\n const delimiter = opts.delimiter || '.'\n const maxDepth = opts.maxDepth\n const transformKey = opts.transformKey || keyIdentity\n const output = {}\n\n function step (object, prev, currentDepth) {\n currentDepth = currentDepth || 1\n Object.keys(object).forEach(function (key) {\n const value = object[key]\n const isarray = opts.safe && Array.isArray(value)\n const type = Object.prototype.toString.call(value)\n const isbuffer = isBuffer(value)\n const isobject = (\n type === '[object Object]' ||\n type === '[object Array]'\n )\n\n const newKey = prev\n ? prev + delimiter + transformKey(key)\n : transformKey(key)\n\n if (!isarray && !isbuffer && isobject && Object.keys(value).length &&\n (!opts.maxDepth || currentDepth < maxDepth)) {\n return step(value, newKey, currentDepth + 1)\n }\n\n output[newKey] = value\n })\n }\n\n step(target)\n\n return output\n}\n\nexport function unflatten (target, opts) {\n opts = opts || {}\n\n const delimiter = opts.delimiter || '.'\n const overwrite = opts.overwrite || false\n const transformKey = opts.transformKey || keyIdentity\n const result = {}\n\n const isbuffer = isBuffer(target)\n if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') {\n return target\n }\n\n // safely ensure that the key is\n // an integer.\n function getkey (key) {\n const parsedKey = Number(key)\n\n return (\n isNaN(parsedKey) ||\n key.indexOf('.') !== -1 ||\n opts.object\n )\n ? key\n : parsedKey\n }\n\n function addKeys (keyPrefix, recipient, target) {\n return Object.keys(target).reduce(function (result, key) {\n result[keyPrefix + delimiter + key] = target[key]\n\n return result\n }, recipient)\n }\n\n function isEmpty (val) {\n const type = Object.prototype.toString.call(val)\n const isArray = type === '[object Array]'\n const isObject = type === '[object Object]'\n\n if (!val) {\n return true\n } else if (isArray) {\n return !val.length\n } else if (isObject) {\n return !Object.keys(val).length\n }\n }\n\n target = Object.keys(target).reduce(function (result, key) {\n const type = Object.prototype.toString.call(target[key])\n const isObject = (type === '[object Object]' || type === '[object Array]')\n if (!isObject || isEmpty(target[key])) {\n result[key] = target[key]\n return result\n } else {\n return addKeys(\n key,\n result,\n flatten(target[key], opts)\n )\n }\n }, {})\n\n Object.keys(target).forEach(function (key) {\n const split = key.split(delimiter).map(transformKey)\n let key1 = getkey(split.shift())\n let key2 = getkey(split[0])\n let recipient = result\n\n while (key2 !== undefined) {\n if (key1 === '__proto__') {\n return\n }\n\n const type = Object.prototype.toString.call(recipient[key1])\n const isobject = (\n type === '[object Object]' ||\n type === '[object Array]'\n )\n\n // do not write over falsey, non-undefined values if overwrite is false\n if (!overwrite && !isobject && typeof recipient[key1] !== 'undefined') {\n return\n }\n\n if ((overwrite && !isobject) || (!overwrite && recipient[key1] == null)) {\n recipient[key1] = (\n typeof key2 === 'number' &&\n !opts.object\n ? []\n : {}\n )\n }\n\n recipient = recipient[key1]\n if (split.length > 0) {\n key1 = getkey(split.shift())\n key2 = getkey(split[0])\n }\n }\n\n // unflatten again for 'messy objects'\n recipient[key1] = unflatten(target[key], opts)\n })\n\n return result\n}\n","import { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function email(config: Config = {}): ValidationRule {\n return {\n name: 'email',\n validator(value) {\n return !isDefined(value) || (typeof value === 'string' && /^\\S+@\\S+\\.\\S+$/.test(value));\n },\n message: config.message || t('ll.validation.email'),\n };\n}\n","import { MaybeRefOrGetter, toValue } from 'vue';\n\nimport { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n max: MaybeRefOrGetter<number>;\n message?: ValidationMessage;\n}\n\nexport default function maxValue(config: Config): ValidationRule {\n return {\n name: 'maxValue',\n validator(value) {\n const max = toValue(config.max);\n\n return !isDefined(value) || Number(value) <= max;\n },\n message: config.message || (() => t('ll.validation.maxValue', { max: String(toValue(config.max)) })),\n };\n}\n","import { MaybeRefOrGetter, toValue } from 'vue';\n\nimport { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n min: MaybeRefOrGetter<number>;\n message?: ValidationMessage;\n}\n\nexport default function minValue(config: Config): ValidationRule {\n return {\n name: 'minValue',\n validator(value) {\n const min = toValue(config.min);\n\n return !isDefined(value) || Number(value) >= min;\n },\n message: config.message || (() => t('ll.validation.minValue', { min: String(toValue(config.min)) })),\n };\n}\n","import { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function positiveNumber(config: Config = {}): ValidationRule {\n return {\n name: 'positiveNumber',\n validator(value) {\n return !isDefined(value) || Number(value) > 0;\n },\n message: config.message || t('ll.validation.positiveNumber'),\n };\n}\n","import round from 'lodash-es/round';\n\nimport { DECIMAL_PRECISION } from '../../../constants';\nimport { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function price(config: Config = {}): ValidationRule {\n return {\n name: 'price',\n validator(value) {\n const price = Number(value);\n\n return (\n !isDefined(value) || (price !== Infinity && price >= 0 && price === round(price, DECIMAL_PRECISION.CURRENCY))\n );\n },\n message: config.message || t('ll.validation.price'),\n };\n}\n","import { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function required(config: Config = {}): ValidationRule {\n return {\n name: 'required',\n validator(value) {\n return isDefined(typeof value === 'string' ? value.trim() : value);\n },\n message: config.message || t('ll.validation.required'),\n };\n}\n","import { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function wholeNumber(config: Config = {}): ValidationRule {\n return {\n name: 'wholeNumber',\n validator(value) {\n return !isDefined(value) || (Number.isInteger(Number(value)) && Number(value) >= 0);\n },\n message: config.message || t('ll.validation.wholeNumber'),\n };\n}\n","import { flatten } from 'flat';\nimport debounce from 'lodash-es/debounce';\nimport get from 'lodash-es/get';\nimport { computed, ComputedRef, nextTick, reactive, readonly, Ref, ref, toValue, UnwrapRef, watch } from 'vue';\n\nimport { DEBOUNCE } from '../../constants';\nimport {\n UseValidationArgs,\n ValidationError,\n ValidationField,\n ValidationGroup,\n ValidationRule,\n} from './useValidation.types';\n\nexport default function useValidation<Values extends object>({\n rules,\n values,\n}: UseValidationArgs<Values>): ValidationGroup<Values> {\n const fieldNames = computed(() => Object.keys(flatten(rules, { safe: true })));\n\n const fields = fieldNames.value.reduce((map, fieldName) => {\n const fieldValue = ref(get(toValue(values), fieldName));\n\n // Having this function here allows us to update the fieldValue when the value of the field changes.\n // Also, passing `fieldValue` outside the `.reduce()` loop will cause a racing condition on `fieldValue` updates\n const updateFieldValue = (fieldName: string) => {\n fieldValue.value = get(toValue(values), fieldName);\n };\n\n const debouncedSetFieldValue = debounce(() => {\n updateFieldValue(fieldName);\n }, DEBOUNCE.FAST);\n\n watch(\n () => get(toValue(values), fieldName),\n () => {\n debouncedSetFieldValue();\n },\n );\n\n map[fieldName] = buildField<UnwrapRef<typeof fieldValue>>({\n fieldName,\n fieldValue,\n flush: () => {\n debouncedSetFieldValue.cancel();\n updateFieldValue(fieldName);\n },\n rules: get(rules, fieldName),\n });\n\n return map;\n }, {} as Record<string, ValidationField>);\n\n const fieldList = computed(() => Object.values(fields));\n\n const hasErrors = computed(() => fieldList.value.some((field) => field.errors.length > 0));\n\n const someTouched = computed(() => fieldList.value.some((field) => field.isTouched));\n\n const dirtyFields = computed(() => fieldList.value.filter((field) => field.isDirty));\n\n const validate: ValidationGroup<Values>['validate'] = async function ({ preventScroll } = {}) {\n fieldList.value.forEach((field) => {\n // Doing setTouched(true) on a field that already has isTouched as `true` will not trigger reactivity for that field. Therefore, setting isTouched to `false` for all fields ensures that setTouched(true) will trigger reactivity for every field, which will cause all validations to run and display any error messages.\n field.setTouched(false);\n field.setTouched(true);\n });\n await nextTick();\n\n if (hasErrors.value && !preventScroll) {\n const firstFieldWithError = Object.entries(fields).find(([_, field]) => field.errorMessage);\n const fieldName = firstFieldWithError?.[0] || '';\n const firstErrorElement = document?.querySelector(`[name=${fieldName}]`);\n\n if (firstErrorElement) {\n firstErrorElement.scrollIntoView({ behavior: 'smooth' });\n }\n }\n\n return !hasErrors.value;\n };\n\n const getError: ValidationGroup<Values>['getError'] = function (fieldName: string) {\n return fields[fieldName]?.errorMessage || '';\n };\n\n const touch: ValidationGroup<Values>['touch'] = function (fieldName: string) {\n if (!fields[fieldName]) {\n throw new Error(`In touch: fieldName \"${fieldName}\" does not exist in the validation fields.`);\n }\n\n fields[fieldName].setTouched();\n };\n\n const setAllUntouched: ValidationGroup<Values>['setAllUntouched'] = async function () {\n await nextTick(); // wait for field values to be reset\n fieldList.value.forEach((field) => {\n field.setTouched(false);\n });\n };\n\n const setInitialValues: ValidationGroup<Values>['setInitialValues'] = function (intialValues: Values) {\n fieldList.value.forEach((field) => {\n field.setInitialValue(intialValues[field.name]);\n });\n };\n\n return reactive({\n validate,\n getError,\n touch,\n setAllUntouched,\n setInitialValues,\n fields,\n dirtyFields,\n hasErrors,\n someTouched,\n });\n}\n\ninterface BuildFieldArgs<Value = unknown> {\n fieldName: string;\n fieldValue: ComputedRef<Value>;\n rules: ValidationRule[];\n flush: () => void;\n}\n\nfunction buildField<Value = unknown>({\n fieldName,\n fieldValue,\n rules,\n flush,\n}: BuildFieldArgs<Value>): ValidationField<Value> {\n /**\n * In order for `initialValue` to work properly, the `buildField` function must not be reactive; `buildField` should be called only once for each field when `useValidation` is called.\n */\n const initialValue = ref(fieldValue.value) as Ref<Value>;\n const isTouched = ref(false);\n const isDirty = computed(() => (fieldValue.value ?? '') !== (initialValue.value ?? ''));\n\n const results = computed(() => {\n // Adding a check for `isTouched` to avoid running the validation rules on the initial load, when the field is not touched.\n // if receives a fieldValue with some value as default or not, rule validation should also be triggered only via `touch()` or `validate()` methods.\n if (!isTouched.value) {\n return [];\n }\n\n return rules.map((rule) => ({\n fieldName,\n ruleName: rule.name,\n isValid: rule.validator(fieldValue.value),\n message: typeof rule.message === 'function' ? rule.message(fieldValue.value) : rule.message,\n }));\n });\n\n const errors = computed<ValidationError[]>(() =>\n results.value\n .filter((result) => !result.isValid)\n .map((result) => {\n return {\n ruleName: result.ruleName,\n message: result.message,\n };\n }),\n );\n\n function setTouched(value = true) {\n // Flushing the debounced value to be updated right away.\n // So that, we can have reactivity for `rules` validation, `isTouched`, `isDirty`, among other values\n flush();\n\n isTouched.value = value;\n }\n\n function setInitialValue(value: Value) {\n initialValue.value = value;\n }\n\n return reactive({\n name: fieldName,\n currentValue: readonly(fieldValue),\n initialValue: readonly(initialValue),\n isTouched: readonly(isTouched),\n isDirty: readonly(isDirty),\n errorMessage: computed(() => errors.value?.[0]?.message || ''),\n errors,\n setInitialValue,\n setTouched,\n });\n}\n\n// The ruleFactories are excluded from the main entrypoint in vite.config.ts, so they are exported here instead. This allows one import statement to be used for useValidation, its types, and all of the ruleFactories.\nexport { default as email } from './ruleFactories/email';\nexport { default as maxValue } from './ruleFactories/maxValue';\nexport { default as minValue } from './ruleFactories/minValue';\nexport { default as positiveNumber } from './ruleFactories/positiveNumber';\nexport { default as price } from './ruleFactories/price';\nexport { default as required } from './ruleFactories/required';\nexport { default as wholeNumber } from './ruleFactories/wholeNumber';\nexport * from './useValidation.types';\nexport { default as isDefined } from './utils/isDefined';\n"],"names":["isBuffer","obj","keyIdentity","key","flatten","target","opts","delimiter","maxDepth","transformKey","output","step","object","prev","currentDepth","value","isarray","type","isbuffer","isobject","newKey","email","config","isDefined","t","maxValue","max","toValue","minValue","min","positiveNumber","price","round","DECIMAL_PRECISION","required","wholeNumber","useValidation","rules","values","fields","computed","map","fieldName","fieldValue","ref","get","updateFieldValue","debouncedSetFieldValue","debounce","DEBOUNCE","watch","buildField","fieldList","hasErrors","field","someTouched","dirtyFields","reactive","preventScroll","nextTick","firstFieldWithError","_","firstErrorElement","_a","intialValues","flush","initialValue","isTouched","isDirty","results","rule","errors","result","setTouched","setInitialValue","readonly","_b"],"mappings":";;;;;;;AAAA,SAASA,EAAUC,GAAK;AACtB,SAAOA,KACLA,EAAI,eACH,OAAOA,EAAI,YAAY,YAAa,cACrCA,EAAI,YAAY,SAASA,CAAG;AAChC;AAEA,SAASC,EAAaC,GAAK;AACzB,SAAOA;AACT;AAEO,SAASC,EAASC,GAAQC,GAAM;AACrC,EAAAA,IAAOA,KAAQ,CAAE;AAEjB,QAAMC,IAAYD,EAAK,aAAa,KAC9BE,IAAWF,EAAK,UAChBG,IAAeH,EAAK,gBAAgBJ,GACpCQ,IAAS,CAAE;AAEjB,WAASC,EAAMC,GAAQC,GAAMC,GAAc;AACzC,IAAAA,IAAeA,KAAgB,GAC/B,OAAO,KAAKF,CAAM,EAAE,QAAQ,SAAUT,GAAK;AACzC,YAAMY,IAAQH,EAAOT,CAAG,GAClBa,IAAUV,EAAK,QAAQ,MAAM,QAAQS,CAAK,GAC1CE,IAAO,OAAO,UAAU,SAAS,KAAKF,CAAK,GAC3CG,IAAWlB,EAASe,CAAK,GACzBI,IACJF,MAAS,qBACTA,MAAS,kBAGLG,IAASP,IACXA,IAAON,IAAYE,EAAaN,CAAG,IACnCM,EAAaN,CAAG;AAEpB,UAAI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AA,IACxC,SAAS,OAAO2B,EAAK,WAAY,aAAaA,EAAK,QAAQ3B,EAAW,KAAK,IAAI2B,EAAK;AAAA,EACpF,EAAA,IARO,EASV,GAEKC,IAAS/B;AAAA,IAA4B,MACzC6B,EAAQ,MACL,OAAO,CAACG,MAAW,CAACA,EAAO,OAAO,EAClC,IAAI,CAACA,OACG;AAAA,MACL,UAAUA,EAAO;AAAA,MACjB,SAASA,EAAO;AAAA,IAAA,EAEnB;AAAA,EAAA;AAGI,WAAAC,EAAW1D,IAAQ,IAAM;AAG1B,IAAAkD,KAENE,EAAU,QAAQpD;AAAA,EACpB;AAEA,WAAS2D,EAAgB3D,GAAc;AACrC,IAAAmD,EAAa,QAAQnD;AAAA,EACvB;AAEA,SAAO0C,EAAS;AAAA,IACd,MAAMf;AAAA,IACN,cAAciC,EAAShC,CAAU;AAAA,IACjC,cAAcgC,EAAST,CAAY;AAAA,IACnC,WAAWS,EAASR,CAAS;AAAA,IAC7B,SAASQ,EAASP,CAAO;AAAA,IACzB,cAAc5B,EAAS;;AAAM,eAAAoC,KAAAb,IAAAQ,EAAO,UAAP,gBAAAR,EAAe,OAAf,gBAAAa,EAAmB,YAAW;AAAA,KAAE;AAAA,IAC7D,QAAAL;AAAA,IACA,iBAAAG;AAAA,IACA,YAAAD;AAAA,EAAA,CACD;AACH;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"useValidation.js","sources":["../node_modules/flat/index.js","../src/composables/useValidation/ruleFactories/email.ts","../src/composables/useValidation/ruleFactories/maxLength.ts","../src/composables/useValidation/ruleFactories/maxValue.ts","../src/composables/useValidation/ruleFactories/minLength.ts","../src/composables/useValidation/ruleFactories/minValue.ts","../src/composables/useValidation/ruleFactories/pattern.ts","../src/composables/useValidation/ruleFactories/positiveNumber.ts","../src/composables/useValidation/ruleFactories/price.ts","../src/composables/useValidation/ruleFactories/required.ts","../src/composables/useValidation/ruleFactories/wholeNumber.ts","../src/composables/useValidation/useValidation.ts"],"sourcesContent":["function isBuffer (obj) {\n return obj &&\n obj.constructor &&\n (typeof obj.constructor.isBuffer === 'function') &&\n obj.constructor.isBuffer(obj)\n}\n\nfunction keyIdentity (key) {\n return key\n}\n\nexport function flatten (target, opts) {\n opts = opts || {}\n\n const delimiter = opts.delimiter || '.'\n const maxDepth = opts.maxDepth\n const transformKey = opts.transformKey || keyIdentity\n const output = {}\n\n function step (object, prev, currentDepth) {\n currentDepth = currentDepth || 1\n Object.keys(object).forEach(function (key) {\n const value = object[key]\n const isarray = opts.safe && Array.isArray(value)\n const type = Object.prototype.toString.call(value)\n const isbuffer = isBuffer(value)\n const isobject = (\n type === '[object Object]' ||\n type === '[object Array]'\n )\n\n const newKey = prev\n ? prev + delimiter + transformKey(key)\n : transformKey(key)\n\n if (!isarray && !isbuffer && isobject && Object.keys(value).length &&\n (!opts.maxDepth || currentDepth < maxDepth)) {\n return step(value, newKey, currentDepth + 1)\n }\n\n output[newKey] = value\n })\n }\n\n step(target)\n\n return output\n}\n\nexport function unflatten (target, opts) {\n opts = opts || {}\n\n const delimiter = opts.delimiter || '.'\n const overwrite = opts.overwrite || false\n const transformKey = opts.transformKey || keyIdentity\n const result = {}\n\n const isbuffer = isBuffer(target)\n if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') {\n return target\n }\n\n // safely ensure that the key is\n // an integer.\n function getkey (key) {\n const parsedKey = Number(key)\n\n return (\n isNaN(parsedKey) ||\n key.indexOf('.') !== -1 ||\n opts.object\n )\n ? key\n : parsedKey\n }\n\n function addKeys (keyPrefix, recipient, target) {\n return Object.keys(target).reduce(function (result, key) {\n result[keyPrefix + delimiter + key] = target[key]\n\n return result\n }, recipient)\n }\n\n function isEmpty (val) {\n const type = Object.prototype.toString.call(val)\n const isArray = type === '[object Array]'\n const isObject = type === '[object Object]'\n\n if (!val) {\n return true\n } else if (isArray) {\n return !val.length\n } else if (isObject) {\n return !Object.keys(val).length\n }\n }\n\n target = Object.keys(target).reduce(function (result, key) {\n const type = Object.prototype.toString.call(target[key])\n const isObject = (type === '[object Object]' || type === '[object Array]')\n if (!isObject || isEmpty(target[key])) {\n result[key] = target[key]\n return result\n } else {\n return addKeys(\n key,\n result,\n flatten(target[key], opts)\n )\n }\n }, {})\n\n Object.keys(target).forEach(function (key) {\n const split = key.split(delimiter).map(transformKey)\n let key1 = getkey(split.shift())\n let key2 = getkey(split[0])\n let recipient = result\n\n while (key2 !== undefined) {\n if (key1 === '__proto__') {\n return\n }\n\n const type = Object.prototype.toString.call(recipient[key1])\n const isobject = (\n type === '[object Object]' ||\n type === '[object Array]'\n )\n\n // do not write over falsey, non-undefined values if overwrite is false\n if (!overwrite && !isobject && typeof recipient[key1] !== 'undefined') {\n return\n }\n\n if ((overwrite && !isobject) || (!overwrite && recipient[key1] == null)) {\n recipient[key1] = (\n typeof key2 === 'number' &&\n !opts.object\n ? []\n : {}\n )\n }\n\n recipient = recipient[key1]\n if (split.length > 0) {\n key1 = getkey(split.shift())\n key2 = getkey(split[0])\n }\n }\n\n // unflatten again for 'messy objects'\n recipient[key1] = unflatten(target[key], opts)\n })\n\n return result\n}\n","import { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function email(config: Config = {}): ValidationRule {\n return {\n name: 'email',\n validator(value) {\n return !isDefined(value) || (typeof value === 'string' && /^\\S+@\\S+\\.\\S+$/.test(value));\n },\n message: config.message || t('ll.validation.email'),\n };\n}\n","import { MaybeRefOrGetter, toValue } from 'vue';\n\nimport { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n max: MaybeRefOrGetter<number>;\n message?: ValidationMessage;\n trim?: boolean;\n}\n\nexport default function maxLength(config: Config): ValidationRule {\n return {\n name: 'maxLength',\n validator(_value) {\n const max = toValue(config.max);\n const value = toValue(_value);\n\n if (!isDefined(value)) {\n return true;\n }\n\n let valueString = String(value);\n\n if (config.trim) {\n valueString = valueString.trim();\n }\n\n return valueString.length <= max;\n },\n message: config.message || (() => t('ll.validation.maxLength', { max: String(toValue(config.max)) })),\n };\n}\n","import { MaybeRefOrGetter, toValue } from 'vue';\n\nimport { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n max: MaybeRefOrGetter<number>;\n message?: ValidationMessage;\n}\n\nexport default function maxValue(config: Config): ValidationRule {\n return {\n name: 'maxValue',\n validator(value) {\n const max = toValue(config.max);\n\n return !isDefined(value) || Number(value) <= max;\n },\n message: config.message || (() => t('ll.validation.maxValue', { max: String(toValue(config.max)) })),\n };\n}\n","import { MaybeRefOrGetter, toValue } from 'vue';\n\nimport { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n min: MaybeRefOrGetter<number>;\n message?: ValidationMessage;\n trim?: boolean;\n}\n\nexport default function minLength(config: Config): ValidationRule {\n return {\n name: 'minLength',\n validator(_value) {\n const min = toValue(config.min);\n const value = toValue(_value);\n\n if (!isDefined(value)) {\n return true;\n }\n\n let valueString = String(value);\n\n if (config.trim) {\n valueString = valueString.trim();\n }\n\n return valueString.length >= min;\n },\n message: config.message || (() => t('ll.validation.minLength', { min: String(toValue(config.min)) })),\n };\n}\n","import { MaybeRefOrGetter, toValue } from 'vue';\n\nimport { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n min: MaybeRefOrGetter<number>;\n message?: ValidationMessage;\n}\n\nexport default function minValue(config: Config): ValidationRule {\n return {\n name: 'minValue',\n validator(value) {\n const min = toValue(config.min);\n\n return !isDefined(value) || Number(value) >= min;\n },\n message: config.message || (() => t('ll.validation.minValue', { min: String(toValue(config.min)) })),\n };\n}\n","import { toValue } from 'vue';\n\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n regex: RegExp;\n /** A custom message is required in order to inform the user of the required pattern. */\n message: ValidationMessage;\n}\n\nexport default function pattern(config: Config): ValidationRule {\n return {\n name: 'pattern',\n validator(_value) {\n const value = toValue(_value);\n\n return !isDefined(value) || config.regex.test(String(value));\n },\n message: () => {\n if (typeof config.message !== 'string' || !config.message.trim()) {\n throw new Error(\n 'The \"pattern\" ruleFactory requires a custom message informing the user of the required pattern.',\n );\n }\n\n return config.message;\n },\n };\n}\n","import { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function positiveNumber(config: Config = {}): ValidationRule {\n return {\n name: 'positiveNumber',\n validator(value) {\n return !isDefined(value) || Number(value) > 0;\n },\n message: config.message || t('ll.validation.positiveNumber'),\n };\n}\n","import round from 'lodash-es/round';\n\nimport { DECIMAL_PRECISION } from '../../../constants';\nimport { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function price(config: Config = {}): ValidationRule {\n return {\n name: 'price',\n validator(value) {\n const price = Number(value);\n\n return (\n !isDefined(value) || (price !== Infinity && price >= 0 && price === round(price, DECIMAL_PRECISION.CURRENCY))\n );\n },\n message: config.message || t('ll.validation.price'),\n };\n}\n","import { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function required(config: Config = {}): ValidationRule {\n return {\n name: 'required',\n validator(value) {\n return isDefined(typeof value === 'string' ? value.trim() : value);\n },\n message: config.message || t('ll.validation.required'),\n };\n}\n","import { t } from '../../../locale';\nimport { ValidationMessage, ValidationRule } from '../useValidation.types';\nimport isDefined from '../utils/isDefined';\n\ninterface Config {\n message?: ValidationMessage;\n}\n\nexport default function wholeNumber(config: Config = {}): ValidationRule {\n return {\n name: 'wholeNumber',\n validator(value) {\n return !isDefined(value) || (Number.isInteger(Number(value)) && Number(value) >= 0);\n },\n message: config.message || t('ll.validation.wholeNumber'),\n };\n}\n","import { flatten } from 'flat';\nimport debounce from 'lodash-es/debounce';\nimport get from 'lodash-es/get';\nimport { computed, ComputedRef, nextTick, reactive, readonly, Ref, ref, toValue, UnwrapRef, watch } from 'vue';\n\nimport { DEBOUNCE } from '../../constants';\nimport {\n UseValidationArgs,\n ValidationError,\n ValidationField,\n ValidationGroup,\n ValidationRule,\n} from './useValidation.types';\n\nexport default function useValidation<Values extends object>({\n rules,\n values,\n}: UseValidationArgs<Values>): ValidationGroup<Values> {\n const fieldNames = computed(() => Object.keys(flatten(rules, { safe: true })));\n\n const fields = fieldNames.value.reduce((map, fieldName) => {\n const fieldValue = ref(get(toValue(values), fieldName));\n\n // Having this function here allows us to update the fieldValue when the value of the field changes.\n // Also, passing `fieldValue` outside the `.reduce()` loop will cause a racing condition on `fieldValue` updates\n const updateFieldValue = (fieldName: string) => {\n fieldValue.value = get(toValue(values), fieldName);\n };\n\n const debouncedSetFieldValue = debounce(() => {\n updateFieldValue(fieldName);\n }, DEBOUNCE.FAST);\n\n watch(\n () => get(toValue(values), fieldName),\n () => {\n debouncedSetFieldValue();\n },\n );\n\n map[fieldName] = buildField<UnwrapRef<typeof fieldValue>>({\n fieldName,\n fieldValue,\n flush: () => {\n debouncedSetFieldValue.cancel();\n updateFieldValue(fieldName);\n },\n rules: get(rules, fieldName),\n });\n\n return map;\n }, {} as Record<string, ValidationField>);\n\n const fieldList = computed(() => Object.values(fields));\n\n const hasErrors = computed(() => fieldList.value.some((field) => field.errors.length > 0));\n\n const someTouched = computed(() => fieldList.value.some((field) => field.isTouched));\n\n const dirtyFields = computed(() => fieldList.value.filter((field) => field.isDirty));\n\n const validate: ValidationGroup<Values>['validate'] = async function ({ preventScroll } = {}) {\n fieldList.value.forEach((field) => {\n // Doing setTouched(true) on a field that already has isTouched as `true` will not trigger reactivity for that field. Therefore, setting isTouched to `false` for all fields ensures that setTouched(true) will trigger reactivity for every field, which will cause all validations to run and display any error messages.\n field.setTouched(false);\n field.setTouched(true);\n });\n await nextTick();\n\n if (hasErrors.value && !preventScroll) {\n const firstFieldWithError = Object.entries(fields).find(([_, field]) => field.errorMessage);\n const fieldName = firstFieldWithError?.[0] || '';\n const firstErrorElement = document?.querySelector(`[name=${fieldName}]`);\n\n if (firstErrorElement) {\n firstErrorElement.scrollIntoView({ behavior: 'smooth' });\n }\n }\n\n return !hasErrors.value;\n };\n\n const getError: ValidationGroup<Values>['getError'] = function (fieldName: string) {\n return fields[fieldName]?.errorMessage || '';\n };\n\n const touch: ValidationGroup<Values>['touch'] = function (fieldName: string) {\n if (!fields[fieldName]) {\n throw new Error(`In touch: fieldName \"${fieldName}\" does not exist in the validation fields.`);\n }\n\n fields[fieldName].setTouched();\n };\n\n const setAllUntouched: ValidationGroup<Values>['setAllUntouched'] = async function () {\n await nextTick(); // wait for field values to be reset\n fieldList.value.forEach((field) => {\n field.setTouched(false);\n });\n };\n\n const setInitialValues: ValidationGroup<Values>['setInitialValues'] = function (intialValues: Values) {\n fieldList.value.forEach((field) => {\n field.setInitialValue(intialValues[field.name]);\n });\n };\n\n return reactive({\n validate,\n getError,\n touch,\n setAllUntouched,\n setInitialValues,\n fields,\n dirtyFields,\n hasErrors,\n someTouched,\n });\n}\n\ninterface BuildFieldArgs<Value = unknown> {\n fieldName: string;\n fieldValue: ComputedRef<Value>;\n rules: ValidationRule[];\n flush: () => void;\n}\n\nfunction buildField<Value = unknown>({\n fieldName,\n fieldValue,\n rules,\n flush,\n}: BuildFieldArgs<Value>): ValidationField<Value> {\n /**\n * In order for `initialValue` to work properly, the `buildField` function must not be reactive; `buildField` should be called only once for each field when `useValidation` is called.\n */\n const initialValue = ref(fieldValue.value) as Ref<Value>;\n const isTouched = ref(false);\n const isDirty = computed(() => (fieldValue.value ?? '') !== (initialValue.value ?? ''));\n\n const results = computed(() => {\n // Adding a check for `isTouched` to avoid running the validation rules on the initial load, when the field is not touched.\n // if receives a fieldValue with some value as default or not, rule validation should also be triggered only via `touch()` or `validate()` methods.\n if (!isTouched.value) {\n return [];\n }\n\n return rules.map((rule) => ({\n fieldName,\n ruleName: rule.name,\n isValid: rule.validator(fieldValue.value),\n message: typeof rule.message === 'function' ? rule.message(fieldValue.value) : rule.message,\n }));\n });\n\n const errors = computed<ValidationError[]>(() =>\n results.value\n .filter((result) => !result.isValid)\n .map((result) => {\n return {\n ruleName: result.ruleName,\n message: result.message,\n };\n }),\n );\n\n function setTouched(value = true) {\n // Flushing the debounced value to be updated right away.\n // So that, we can have reactivity for `rules` validation, `isTouched`, `isDirty`, among other values\n flush();\n\n isTouched.value = value;\n }\n\n function setInitialValue(value: Value) {\n initialValue.value = value;\n }\n\n return reactive({\n name: fieldName,\n currentValue: readonly(fieldValue),\n initialValue: readonly(initialValue),\n isTouched: readonly(isTouched),\n isDirty: readonly(isDirty),\n errorMessage: computed(() => errors.value?.[0]?.message || ''),\n errors,\n setInitialValue,\n setTouched,\n });\n}\n\n// The ruleFactories are excluded from the main entrypoint in vite.config.ts, so they are exported here instead. This allows one import statement to be used for useValidation, its types, and all of the ruleFactories.\nexport { default as email } from './ruleFactories/email';\nexport { default as maxLength } from './ruleFactories/maxLength';\nexport { default as maxValue } from './ruleFactories/maxValue';\nexport { default as minLength } from './ruleFactories/minLength';\nexport { default as minValue } from './ruleFactories/minValue';\nexport { default as pattern } from './ruleFactories/pattern';\nexport { default as positiveNumber } from './ruleFactories/positiveNumber';\nexport { default as price } from './ruleFactories/price';\nexport { default as required } from './ruleFactories/required';\nexport { default as wholeNumber } from './ruleFactories/wholeNumber';\nexport * from './useValidation.types';\nexport { default as isDefined } from './utils/isDefined';\n"],"names":["isBuffer","obj","keyIdentity","key","flatten","target","opts","delimiter","maxDepth","transformKey","output","step","object","prev","currentDepth","value","isarray","type","isbuffer","isobject","newKey","email","config","isDefined","t","maxLength","_value","max","toValue","valueString","maxValue","minLength","min","minValue","pattern","positiveNumber","price","round","DECIMAL_PRECISION","required","wholeNumber","useValidation","rules","values","fields","computed","map","fieldName","fieldValue","ref","get","updateFieldValue","debouncedSetFieldValue","debounce","DEBOUNCE","watch","buildField","fieldList","hasErrors","field","someTouched","dirtyFields","reactive","preventScroll","nextTick","firstFieldWithError","_","firstErrorElement","_a","intialValues","flush","initialValue","isTouched","isDirty","results","rule","errors","result","setTouched","setInitialValue","readonly","_b"],"mappings":";;;;;;;AAAA,SAASA,EAAUC,GAAK;AACtB,SAAOA,KACLA,EAAI,eACH,OAAOA,EAAI,YAAY,YAAa,cACrCA,EAAI,YAAY,SAASA,CAAG;AAChC;AAEA,SAASC,EAAaC,GAAK;AACzB,SAAOA;AACT;AAEO,SAASC,EAASC,GAAQC,GAAM;AACrC,EAAAA,IAAOA,KAAQ,CAAE;AAEjB,QAAMC,IAAYD,EAAK,aAAa,KAC9BE,IAAWF,EAAK,UAChBG,IAAeH,EAAK,gBAAgBJ,GACpCQ,IAAS,CAAE;AAEjB,WAASC,EAAMC,GAAQC,GAAMC,GAAc;AACzC,IAAAA,IAAeA,KAAgB,GAC/B,OAAO,KAAKF,CAAM,EAAE,QAAQ,SAAUT,GAAK;AACzC,YAAMY,IAAQH,EAAOT,CAAG,GAClBa,IAAUV,EAAK,QAAQ,MAAM,QAAQS,CAAK,GAC1CE,IAAO,OAAO,UAAU,SAAS,KAAKF,CAAK,GAC3CG,IAAWlB,EAASe,CAAK,GACzBI,IACJF,MAAS,qBACTA,MAAS,kBAGLG,IAASP,IACXA,IAAON,IAAYE,EAAaN,CAAG,IACnCM,EAAaN,CAAG;AAEpB,UAAI,CAACa,KAAW,CAACE,KAAYC,KAAY,OAAO,KAAKJ,CAAK,EAAE,WACzD,CAACT,EAAK,YAAYQ,IAAeN;AAClC,eAAOG,EAAKI,GAAOK,GAAQN,IAAe,CAAC;AAG7C,MAAAJ,EAAOU,CAAM,IA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ACG,MAAW,CAACA,EAAO,OAAO,EAClC,IAAI,CAACA,OACG;AAAA,MACL,UAAUA,EAAO;AAAA,MACjB,SAASA,EAAO;AAAA,IAAA,EAEnB;AAAA,EAAA;AAGI,WAAAC,EAAW/D,IAAQ,IAAM;AAG1B,IAAAuD,KAENE,EAAU,QAAQzD;AAAA,EACpB;AAEA,WAASgE,EAAgBhE,GAAc;AACrC,IAAAwD,EAAa,QAAQxD;AAAA,EACvB;AAEA,SAAO+C,EAAS;AAAA,IACd,MAAMf;AAAA,IACN,cAAciC,EAAShC,CAAU;AAAA,IACjC,cAAcgC,EAAST,CAAY;AAAA,IACnC,WAAWS,EAASR,CAAS;AAAA,IAC7B,SAASQ,EAASP,CAAO;AAAA,IACzB,cAAc5B,EAAS;;AAAM,eAAAoC,KAAAb,IAAAQ,EAAO,UAAP,gBAAAR,EAAe,OAAf,gBAAAa,EAAmB,YAAW;AAAA,KAAE;AAAA,IAC7D,QAAAL;AAAA,IACA,iBAAAG;AAAA,IACA,YAAAD;AAAA,EAAA,CACD;AACH;","x_google_ignoreList":[0]}
@@ -5,27 +5,27 @@ import "lodash-es/get";
5
5
  import "lodash-es/isFinite";
6
6
  import "lodash-es/isPlainObject";
7
7
  import "../constants.js";
8
- const n = "ll";
9
- function m(t, o, a = {}) {
10
- const e = a.global ? "" : `-${location.pathname}`, r = `${n}-${t}${e}`, s = JSON.stringify(o);
8
+ const c = "ll";
9
+ function m(o, r, a = {}) {
10
+ const e = a.global ? "" : `-${location.pathname}`, t = `${c}-${o}${e}`, s = JSON.stringify(r);
11
11
  try {
12
- localStorage.setItem(r, s);
13
- } catch (c) {
14
- c && c.name === "QuotaExceededError" ? l.log(`Your localStorage is full. Failed to save item for key: ${r}`) : l.log(`Failed to save value to localStorage for key: ${r}`);
12
+ localStorage.setItem(t, s);
13
+ } catch (n) {
14
+ (n == null ? void 0 : n.name) === "QuotaExceededError" ? l.log(`Your localStorage is full. Failed to save item for key: ${t}`) : l.log(`Failed to save value to localStorage for key: ${t}`);
15
15
  }
16
16
  }
17
- function g(t, o = {}) {
18
- const a = o.global ? "" : `-${location.pathname}`, e = localStorage.getItem(`${n}-${t}${a}`);
17
+ function g(o, r = {}) {
18
+ const a = r.global ? "" : `-${location.pathname}`, e = localStorage.getItem(`${c}-${o}${a}`);
19
19
  if (e === null || e === "undefined")
20
20
  return null;
21
21
  try {
22
22
  return JSON.parse(e);
23
- } catch (r) {
24
- return l.error(r.message, { error: r }), null;
23
+ } catch (t) {
24
+ return l.error(t == null ? void 0 : t.message, { error: t }), null;
25
25
  }
26
26
  }
27
- function u(t, o = {}) {
28
- const a = o.global ? "" : `-${location.pathname}`, e = `${n}-${t}${a}`;
27
+ function u(o, r = {}) {
28
+ const a = r.global ? "" : `-${location.pathname}`, e = `${c}-${o}${a}`;
29
29
  if (localStorage.getItem(e) !== null)
30
30
  try {
31
31
  localStorage.removeItem(e);
@@ -33,22 +33,22 @@ function u(t, o = {}) {
33
33
  l.error(s.message, { error: s });
34
34
  }
35
35
  }
36
- function y(t, o) {
37
- const a = JSON.parse(localStorage.getItem(t) || "{}");
36
+ function y(o, r) {
37
+ const a = JSON.parse(localStorage.getItem(o) || "{}");
38
38
  try {
39
- return (a[o] || {})[i(location.pathname)];
39
+ return (a[r] || {})[i(location.pathname)];
40
40
  } catch (e) {
41
- l.error(e.message, { error: e });
41
+ l.error(e == null ? void 0 : e.message, { error: e });
42
42
  return;
43
43
  }
44
44
  }
45
- function v(t, o) {
46
- const e = { ...JSON.parse(localStorage.getItem(t) || "{}") };
47
- e[o] && delete e[o][i(location.pathname)];
45
+ function v(o, r) {
46
+ const e = { ...JSON.parse(localStorage.getItem(o) || "{}") };
47
+ e[r] && delete e[r][i(location.pathname)];
48
48
  try {
49
- localStorage.setItem(t, JSON.stringify(e));
50
- } catch (r) {
51
- r && r.name === "QuotaExceededError" ? l.log("Your localStorage is full. Failed to set item.") : l.log("Failed to set item to localStorage.");
49
+ localStorage.setItem(o, JSON.stringify(e));
50
+ } catch (t) {
51
+ (t == null ? void 0 : t.name) === "QuotaExceededError" ? l.log("Your localStorage is full. Failed to set item.") : l.log("Failed to set item to localStorage.");
52
52
  }
53
53
  }
54
54
  const P = {
@@ -1 +1 @@
1
- {"version":3,"file":"storage.js","sources":["../../src/utils/storage.ts"],"sourcesContent":["import logger from '@leaflink/snitch';\n\nimport { hashCode } from './helpers';\n\nconst PREFIX = 'll';\n\n/**\n * Persist an item to localStorage, unique to each url pathname unless [options.global] is set to true\n *\n * If global is set to false (the default):\n * name: 'foo'\n * data: { a: 'a' }\n *\n * localStorage key: 'll-foo-/c/the-leaf-shop/customers/'\n * localStorage value: { a: 'a' }\n *\n * If global is set to true:\n * name: 'bar'\n * data: { b: 'b' }\n *\n * localStorage key: 'll-bar'\n * localStorage value: { b: 'b' }\n *\n * @param {string} name - the storage key name, often a component name\n * @param {object} data - the data to persist\n * @param {object} [options] - an optional options object\n * @param {boolean} [options.global] - does not add url to the key when true\n */\nexport function setPersistentItem(name, data, options: { global?: boolean } = {}) {\n const scope = options.global ? '' : `-${location.pathname}`;\n const storageKey = `${PREFIX}-${name}${scope}`;\n const storageValue = JSON.stringify(data);\n\n try {\n localStorage.setItem(storageKey, storageValue);\n } catch (error: any) {\n if (error && error.name === 'QuotaExceededError') {\n logger.log(`Your localStorage is full. Failed to save item for key: ${storageKey}`);\n } else {\n logger.log(`Failed to save value to localStorage for key: ${storageKey}`);\n }\n }\n}\n\n/**\n * Retrieve an item from localStorage, previously saved by `setPersistentItem`.\n * @param {string} name The storage key name, often a component name\n * @param {object} [options] - an optional options object\n * @param {boolean} [options.global] - does not add url to the key when true\n * @returns {any | undefined}\n */\nexport function getPersistentItem(name, options: { global?: boolean } = {}) {\n const scope = options.global ? '' : `-${location.pathname}`;\n const item = localStorage.getItem(`${PREFIX}-${name}${scope}`);\n\n // localStorage.getItem always returns a string or null. When it's a string,\n // it usually contains an object or a boolean. If the value is 'false', we\n // need to ensure we return false instead of null.\n if (item === null || item === 'undefined') {\n return null;\n }\n\n try {\n return JSON.parse(item);\n } catch (err) {\n logger.error((err as Error).message, { error: err });\n\n return null;\n }\n}\n\n/**\n * Remove an item from localStorage, previously saved by `setPersistentItem`.\n * @param {string} name The storage key name, often a component name\n * @param {object} [options] - an optional options object\n * @param {boolean} [options.global] - does not add url to the key when true\n */\nexport function removePersistentItem(name, options: { global?: boolean } = {}) {\n const scope = options.global ? '' : `-${location.pathname}`;\n const storageKey = `${PREFIX}-${name}${scope}`;\n const item = localStorage.getItem(storageKey);\n\n if (item === null) {\n return;\n }\n\n try {\n localStorage.removeItem(storageKey);\n } catch (err) {\n logger.error((err as Error).message, { error: err });\n }\n}\n\n/**\n ***************** DEPRECATED *****************\n */\nexport function getPersistentItem__deprecated(itemKey: string, name) {\n const item = JSON.parse(localStorage.getItem(itemKey) || '{}');\n\n try {\n return (item[name] || {})[hashCode(location.pathname)];\n } catch (err) {\n logger.error((err as Error).message, { error: err });\n\n return undefined;\n }\n}\n\nexport function removePersistentItem__deprecated(itemKey, name) {\n const item = JSON.parse(localStorage.getItem(itemKey) || '{}');\n const itemValue = { ...item };\n\n if (itemValue[name]) {\n delete itemValue[name][hashCode(location.pathname)];\n }\n\n try {\n localStorage.setItem(itemKey, JSON.stringify(itemValue));\n } catch (error: any) {\n if (error && error.name === 'QuotaExceededError') {\n logger.log(`Your localStorage is full. Failed to set item.`);\n } else {\n logger.log(`Failed to set item to localStorage.`);\n }\n }\n}\n// END DEPRECATED\n\nexport const persistentStorage = {\n setItem: setPersistentItem,\n getItem: getPersistentItem,\n removeItem: removePersistentItem,\n};\n"],"names":["PREFIX","setPersistentItem","name","data","options","scope","storageKey","storageValue","error","logger","getPersistentItem","item","err","removePersistentItem","getPersistentItem__deprecated","itemKey","hashCode","removePersistentItem__deprecated","itemValue","persistentStorage"],"mappings":";;;;;;;AAIA,MAAMA,IAAS;AAwBR,SAASC,EAAkBC,GAAMC,GAAMC,IAAgC,CAAA,GAAI;AAChF,QAAMC,IAAQD,EAAQ,SAA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SAAS,EAAE,OAAOA,GAAK;AAE5C;AAAA,EACT;AACF;AAEgB,SAAAK,EAAiCF,GAASb,GAAM;AAExD,QAAAgB,IAAY,EAAE,GADP,KAAK,MAAM,aAAa,QAAQH,CAAO,KAAK,IAAI;AAGzD,EAAAG,EAAUhB,CAAI,KAChB,OAAOgB,EAAUhB,CAAI,EAAEc,EAAS,SAAS,QAAQ,CAAC;AAGhD,MAAA;AACF,iBAAa,QAAQD,GAAS,KAAK,UAAUG,CAAS,CAAC;AAAA,WAChDV,GAAY;AACf,IAAAA,KAASA,EAAM,SAAS,uBAC1BC,EAAO,IAAI,gDAAgD,IAE3DA,EAAO,IAAI,qCAAqC;AAAA,EAEpD;AACF;AAGO,MAAMU,IAAoB;AAAA,EAC/B,SAASlB;AAAA,EACT,SAASS;AAAA,EACT,YAAYG;AACd;"}
1
+ {"version":3,"file":"storage.js","sources":["../../src/utils/storage.ts"],"sourcesContent":["import logger from '@leaflink/snitch';\n\nimport { hashCode } from './helpers';\n\nconst PREFIX = 'll';\n\n/**\n * Persist an item to localStorage, unique to each url pathname unless [options.global] is set to true\n *\n * If global is set to false (the default):\n * name: 'foo'\n * data: { a: 'a' }\n *\n * localStorage key: 'll-foo-/c/the-leaf-shop/customers/'\n * localStorage value: { a: 'a' }\n *\n * If global is set to true:\n * name: 'bar'\n * data: { b: 'b' }\n *\n * localStorage key: 'll-bar'\n * localStorage value: { b: 'b' }\n *\n * @param {string} name - the storage key name, often a component name\n * @param {object} data - the data to persist\n * @param {object} [options] - an optional options object\n * @param {boolean} [options.global] - does not add url to the key when true\n */\nexport function setPersistentItem(name, data, options: { global?: boolean } = {}) {\n const scope = options.global ? '' : `-${location.pathname}`;\n const storageKey = `${PREFIX}-${name}${scope}`;\n const storageValue = JSON.stringify(data);\n\n try {\n localStorage.setItem(storageKey, storageValue);\n } catch (error) {\n if ((error as Error)?.name === 'QuotaExceededError') {\n logger.log(`Your localStorage is full. Failed to save item for key: ${storageKey}`);\n } else {\n logger.log(`Failed to save value to localStorage for key: ${storageKey}`);\n }\n }\n}\n\n/**\n * Retrieve an item from localStorage, previously saved by `setPersistentItem`.\n * @param {string} name The storage key name, often a component name\n * @param {object} [options] - an optional options object\n * @param {boolean} [options.global] - does not add url to the key when true\n * @returns {any | undefined}\n */\nexport function getPersistentItem(name, options: { global?: boolean } = {}) {\n const scope = options.global ? '' : `-${location.pathname}`;\n const item = localStorage.getItem(`${PREFIX}-${name}${scope}`);\n\n // localStorage.getItem always returns a string or null. When it's a string,\n // it usually contains an object or a boolean. If the value is 'false', we\n // need to ensure we return false instead of null.\n if (item === null || item === 'undefined') {\n return null;\n }\n\n try {\n return JSON.parse(item);\n } catch (err) {\n logger.error((err as Error)?.message, { error: err });\n\n return null;\n }\n}\n\n/**\n * Remove an item from localStorage, previously saved by `setPersistentItem`.\n * @param {string} name The storage key name, often a component name\n * @param {object} [options] - an optional options object\n * @param {boolean} [options.global] - does not add url to the key when true\n */\nexport function removePersistentItem(name, options: { global?: boolean } = {}) {\n const scope = options.global ? '' : `-${location.pathname}`;\n const storageKey = `${PREFIX}-${name}${scope}`;\n const item = localStorage.getItem(storageKey);\n\n if (item === null) {\n return;\n }\n\n try {\n localStorage.removeItem(storageKey);\n } catch (err) {\n logger.error((err as Error).message, { error: err });\n }\n}\n\n/**\n ***************** DEPRECATED *****************\n */\nexport function getPersistentItem__deprecated(itemKey: string, name) {\n const item = JSON.parse(localStorage.getItem(itemKey) || '{}');\n\n try {\n return (item[name] || {})[hashCode(location.pathname)];\n } catch (err) {\n logger.error((err as Error)?.message, { error: err });\n\n return undefined;\n }\n}\n\nexport function removePersistentItem__deprecated(itemKey, name) {\n const item = JSON.parse(localStorage.getItem(itemKey) || '{}');\n const itemValue = { ...item };\n\n if (itemValue[name]) {\n delete itemValue[name][hashCode(location.pathname)];\n }\n\n try {\n localStorage.setItem(itemKey, JSON.stringify(itemValue));\n } catch (error) {\n if ((error as Error)?.name === 'QuotaExceededError') {\n logger.log(`Your localStorage is full. Failed to set item.`);\n } else {\n logger.log(`Failed to set item to localStorage.`);\n }\n }\n}\n// END DEPRECATED\n\nexport const persistentStorage = {\n setItem: setPersistentItem,\n getItem: getPersistentItem,\n removeItem: removePersistentItem,\n};\n"],"names":["PREFIX","setPersistentItem","name","data","options","scope","storageKey","storageValue","error","logger","getPersistentItem","item","err","removePersistentItem","getPersistentItem__deprecated","itemKey","hashCode","removePersistentItem__deprecated","itemValue","persistentStorage"],"mappings":";;;;;;;AAIA,MAAMA,IAAS;AAwBR,SAASC,EAAkBC,GAAMC,GAAMC,IAAgC,CAAA,GAAI;AAChF,QAAMC,IAAQD,EAAQ,SAAS,KAAK,IAAI,SAAS,QAAQ,IACnDE,IAAa,GAAGN,CAAM,IAAIE,CAAI,GAAGG,CAAK,IACtCE,IAAe,KAAK,UAAUJ,CAAI;AAEpC,MAAA;AACW,iBAAA,QAAQG,GAAYC,CAAY;AAAA,WACtCC,GAAO;AACT,KAAAA,KAAA,gBAAAA,EAAiB,UAAS,uBACtBC,EAAA,IAAI,2DAA2DH,CAAU,EAAE,IAE3EG,EAAA,IAAI,iDAAiDH,CAAU,EAAE;AAAA,EAE5E;AACF;AASO,SAASI,EAAkBR,GAAME,IAAgC,IAAI;AAC1E,QAAMC,IAAQD,EAAQ,SAAS,KAAK,IAAI,SAAS,QAAQ,IACnDO,IAAO,aAAa,QAAQ,GAAGX,CAAM,IAAIE,CAAI,GAAGG,CAAK,EAAE;AAKzD,MAAAM,MAAS,QAAQA,MAAS;AACrB,WAAA;AAGL,MAAA;AACK,WAAA,KAAK,MAAMA,CAAI;AAAA,WACfC,GAAK;AACZ,WAAAH,EAAO,MAAOG,KAAA,gBAAAA,EAAe,SAAS,EAAE,OAAOA,GAAK,GAE7C;AAAA,EACT;AACF;AAQO,SAASC,EAAqBX,GAAME,IAAgC,IAAI;AAC7E,QAAMC,IAAQD,EAAQ,SAAS,KAAK,IAAI,SAAS,QAAQ,IACnDE,IAAa,GAAGN,CAAM,IAAIE,CAAI,GAA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