@justifi/webcomponents 0.0.14 → 0.2.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.
Files changed (66) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/changelog-template.hbs +41 -0
  3. package/dist/cjs/{index-e1b45289.js → index-3947d225.js} +65 -1
  4. package/dist/cjs/justifi-bank-account-form.cjs.entry.js +59 -0
  5. package/dist/cjs/justifi-billing-form.cjs.entry.js +2150 -0
  6. package/dist/cjs/justifi-card-form.cjs.entry.js +59 -0
  7. package/dist/cjs/justifi-payment-method-form.cjs.entry.js +109 -0
  8. package/dist/cjs/{justifi-bank-account-form_4.cjs.entry.js → justifi-payments-list.cjs.entry.js} +1 -206
  9. package/dist/cjs/loader.cjs.js +3 -3
  10. package/dist/cjs/select-input_2.cjs.entry.js +59 -0
  11. package/dist/cjs/webcomponents.cjs.js +3 -3
  12. package/dist/collection/collection-manifest.json +5 -2
  13. package/dist/collection/components/bank-account-form/bank-account-form.js +5 -3
  14. package/dist/collection/components/billing-form/billing-form-schema.js +14 -0
  15. package/dist/collection/components/billing-form/billing-form.css +11 -0
  16. package/dist/collection/components/billing-form/billing-form.js +92 -0
  17. package/dist/collection/components/billing-form/state-options.js +243 -0
  18. package/dist/collection/components/card-form/card-form.js +5 -3
  19. package/dist/collection/components/payment-method-form/payment-method-form.js +4 -4
  20. package/dist/collection/components/select-input/select-input.css +7 -0
  21. package/dist/collection/components/select-input/select-input.js +144 -0
  22. package/dist/collection/components/text-input/text-input.css +7 -0
  23. package/dist/collection/components/text-input/text-input.js +126 -0
  24. package/dist/components/index.d.ts +3 -0
  25. package/dist/components/index.js +3 -0
  26. package/dist/components/justifi-bank-account-form.js +4 -2
  27. package/dist/components/justifi-billing-form.d.ts +11 -0
  28. package/dist/components/justifi-billing-form.js +2180 -0
  29. package/dist/components/justifi-card-form.js +4 -2
  30. package/dist/components/payment-method-form.js +2 -2
  31. package/dist/components/select-input.d.ts +11 -0
  32. package/dist/components/select-input.js +6 -0
  33. package/dist/components/select-input2.js +52 -0
  34. package/dist/components/text-input.d.ts +11 -0
  35. package/dist/components/text-input.js +6 -0
  36. package/dist/components/text-input2.js +48 -0
  37. package/dist/esm/{index-c1f569bd.js → index-0bcf33c4.js} +65 -1
  38. package/dist/esm/justifi-bank-account-form.entry.js +55 -0
  39. package/dist/esm/justifi-billing-form.entry.js +2146 -0
  40. package/dist/esm/justifi-card-form.entry.js +55 -0
  41. package/dist/esm/justifi-payment-method-form.entry.js +105 -0
  42. package/dist/esm/{justifi-bank-account-form_4.entry.js → justifi-payments-list.entry.js} +2 -204
  43. package/dist/esm/loader.js +4 -4
  44. package/dist/esm/select-input_2.entry.js +54 -0
  45. package/dist/esm/webcomponents.js +4 -4
  46. package/dist/types/components/billing-form/billing-form-schema.d.ts +15 -0
  47. package/dist/types/components/billing-form/billing-form.d.ts +17 -0
  48. package/dist/types/components/billing-form/state-options.d.ts +5 -0
  49. package/dist/types/components/payment-method-form/payment-method-form.d.ts +2 -2
  50. package/dist/types/components/payment-method-form/theme.d.ts +3 -1
  51. package/dist/types/components/select-input/select-input.d.ts +18 -0
  52. package/dist/types/components/text-input/text-input.d.ts +14 -0
  53. package/dist/types/components.d.ts +74 -5
  54. package/dist/webcomponents/p-0cddfd4f.entry.js +1 -0
  55. package/dist/webcomponents/p-17badb93.entry.js +1 -0
  56. package/dist/webcomponents/p-7fd07095.entry.js +1 -0
  57. package/dist/webcomponents/p-864e32fd.entry.js +1 -0
  58. package/dist/webcomponents/p-cecf0fe8.entry.js +1 -0
  59. package/dist/webcomponents/p-d3dc4e0a.entry.js +1 -0
  60. package/dist/webcomponents/p-e82c9746.js +2 -0
  61. package/dist/webcomponents/webcomponents.esm.js +1 -1
  62. package/package.json +8 -3
  63. package/readme.md +11 -72
  64. package/LICENSE +0 -21
  65. package/dist/webcomponents/p-1de39730.js +0 -2
  66. package/dist/webcomponents/p-d6caba00.entry.js +0 -1
@@ -0,0 +1,2146 @@
1
+ import { r as registerInstance, h, H as Host } from './index-0bcf33c4.js';
2
+
3
+ /**
4
+ * Based on Kendo UI Core expression code <https://github.com/telerik/kendo-ui-core#license-information>
5
+ */
6
+
7
+ function Cache(maxSize) {
8
+ this._maxSize = maxSize;
9
+ this.clear();
10
+ }
11
+ Cache.prototype.clear = function () {
12
+ this._size = 0;
13
+ this._values = Object.create(null);
14
+ };
15
+ Cache.prototype.get = function (key) {
16
+ return this._values[key]
17
+ };
18
+ Cache.prototype.set = function (key, value) {
19
+ this._size >= this._maxSize && this.clear();
20
+ if (!(key in this._values)) this._size++;
21
+
22
+ return (this._values[key] = value)
23
+ };
24
+
25
+ var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g,
26
+ DIGIT_REGEX = /^\d+$/,
27
+ LEAD_DIGIT_REGEX = /^\d/,
28
+ SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,
29
+ CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/,
30
+ MAX_CACHE_SIZE = 512;
31
+
32
+ var pathCache = new Cache(MAX_CACHE_SIZE),
33
+ setCache = new Cache(MAX_CACHE_SIZE),
34
+ getCache = new Cache(MAX_CACHE_SIZE);
35
+
36
+ var propertyExpr = {
37
+ Cache: Cache,
38
+
39
+ split: split,
40
+
41
+ normalizePath: normalizePath,
42
+
43
+ setter: function (path) {
44
+ var parts = normalizePath(path);
45
+
46
+ return (
47
+ setCache.get(path) ||
48
+ setCache.set(path, function setter(obj, value) {
49
+ var index = 0;
50
+ var len = parts.length;
51
+ var data = obj;
52
+
53
+ while (index < len - 1) {
54
+ var part = parts[index];
55
+ if (
56
+ part === '__proto__' ||
57
+ part === 'constructor' ||
58
+ part === 'prototype'
59
+ ) {
60
+ return obj
61
+ }
62
+
63
+ data = data[parts[index++]];
64
+ }
65
+ data[parts[index]] = value;
66
+ })
67
+ )
68
+ },
69
+
70
+ getter: function (path, safe) {
71
+ var parts = normalizePath(path);
72
+ return (
73
+ getCache.get(path) ||
74
+ getCache.set(path, function getter(data) {
75
+ var index = 0,
76
+ len = parts.length;
77
+ while (index < len) {
78
+ if (data != null || !safe) data = data[parts[index++]];
79
+ else return
80
+ }
81
+ return data
82
+ })
83
+ )
84
+ },
85
+
86
+ join: function (segments) {
87
+ return segments.reduce(function (path, part) {
88
+ return (
89
+ path +
90
+ (isQuoted(part) || DIGIT_REGEX.test(part)
91
+ ? '[' + part + ']'
92
+ : (path ? '.' : '') + part)
93
+ )
94
+ }, '')
95
+ },
96
+
97
+ forEach: function (path, cb, thisArg) {
98
+ forEach(Array.isArray(path) ? path : split(path), cb, thisArg);
99
+ },
100
+ };
101
+
102
+ function normalizePath(path) {
103
+ return (
104
+ pathCache.get(path) ||
105
+ pathCache.set(
106
+ path,
107
+ split(path).map(function (part) {
108
+ return part.replace(CLEAN_QUOTES_REGEX, '$2')
109
+ })
110
+ )
111
+ )
112
+ }
113
+
114
+ function split(path) {
115
+ return path.match(SPLIT_REGEX) || ['']
116
+ }
117
+
118
+ function forEach(parts, iter, thisArg) {
119
+ var len = parts.length,
120
+ part,
121
+ idx,
122
+ isArray,
123
+ isBracket;
124
+
125
+ for (idx = 0; idx < len; idx++) {
126
+ part = parts[idx];
127
+
128
+ if (part) {
129
+ if (shouldBeQuoted(part)) {
130
+ part = '"' + part + '"';
131
+ }
132
+
133
+ isBracket = isQuoted(part);
134
+ isArray = !isBracket && /^\d+$/.test(part);
135
+
136
+ iter.call(thisArg, part, isBracket, isArray, idx, parts);
137
+ }
138
+ }
139
+ }
140
+
141
+ function isQuoted(str) {
142
+ return (
143
+ typeof str === 'string' && str && ["'", '"'].indexOf(str.charAt(0)) !== -1
144
+ )
145
+ }
146
+
147
+ function hasLeadingNumber(part) {
148
+ return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)
149
+ }
150
+
151
+ function hasSpecialChars(part) {
152
+ return SPEC_CHAR_REGEX.test(part)
153
+ }
154
+
155
+ function shouldBeQuoted(part) {
156
+ return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))
157
+ }
158
+
159
+ const reWords = /[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g;
160
+
161
+ const words = (str) => str.match(reWords) || [];
162
+
163
+ const upperFirst = (str) => str[0].toUpperCase() + str.slice(1);
164
+
165
+ const join = (str, d) => words(str).join(d).toLowerCase();
166
+
167
+ const camelCase = (str) =>
168
+ words(str).reduce(
169
+ (acc, next) =>
170
+ `${acc}${
171
+ !acc
172
+ ? next.toLowerCase()
173
+ : next[0].toUpperCase() + next.slice(1).toLowerCase()
174
+ }`,
175
+ '',
176
+ );
177
+
178
+ const pascalCase = (str) => upperFirst(camelCase(str));
179
+
180
+ const snakeCase = (str) => join(str, '_');
181
+
182
+ const kebabCase = (str) => join(str, '-');
183
+
184
+ const sentenceCase = (str) => upperFirst(join(str, ' '));
185
+
186
+ const titleCase = (str) => words(str).map(upperFirst).join(' ');
187
+
188
+ var tinyCase = {
189
+ words,
190
+ upperFirst,
191
+ camelCase,
192
+ pascalCase,
193
+ snakeCase,
194
+ kebabCase,
195
+ sentenceCase,
196
+ titleCase,
197
+ };
198
+
199
+ /**
200
+ * Topological sorting function
201
+ *
202
+ * @param {Array} edges
203
+ * @returns {Array}
204
+ */
205
+
206
+ var toposort_1 = function(edges) {
207
+ return toposort(uniqueNodes(edges), edges)
208
+ };
209
+
210
+ var array$1 = toposort;
211
+
212
+ function toposort(nodes, edges) {
213
+ var cursor = nodes.length
214
+ , sorted = new Array(cursor)
215
+ , visited = {}
216
+ , i = cursor
217
+ // Better data structures make algorithm much faster.
218
+ , outgoingEdges = makeOutgoingEdges(edges)
219
+ , nodesHash = makeNodesHash(nodes);
220
+
221
+ // check for unknown nodes
222
+ edges.forEach(function(edge) {
223
+ if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {
224
+ throw new Error('Unknown node. There is an unknown node in the supplied edges.')
225
+ }
226
+ });
227
+
228
+ while (i--) {
229
+ if (!visited[i]) visit(nodes[i], i, new Set());
230
+ }
231
+
232
+ return sorted
233
+
234
+ function visit(node, i, predecessors) {
235
+ if(predecessors.has(node)) {
236
+ var nodeRep;
237
+ try {
238
+ nodeRep = ", node was:" + JSON.stringify(node);
239
+ } catch(e) {
240
+ nodeRep = "";
241
+ }
242
+ throw new Error('Cyclic dependency' + nodeRep)
243
+ }
244
+
245
+ if (!nodesHash.has(node)) {
246
+ throw new Error('Found unknown node. Make sure to provided all involved nodes. Unknown node: '+JSON.stringify(node))
247
+ }
248
+
249
+ if (visited[i]) return;
250
+ visited[i] = true;
251
+
252
+ var outgoing = outgoingEdges.get(node) || new Set();
253
+ outgoing = Array.from(outgoing);
254
+
255
+ if (i = outgoing.length) {
256
+ predecessors.add(node);
257
+ do {
258
+ var child = outgoing[--i];
259
+ visit(child, nodesHash.get(child), predecessors);
260
+ } while (i)
261
+ predecessors.delete(node);
262
+ }
263
+
264
+ sorted[--cursor] = node;
265
+ }
266
+ }
267
+
268
+ function uniqueNodes(arr){
269
+ var res = new Set();
270
+ for (var i = 0, len = arr.length; i < len; i++) {
271
+ var edge = arr[i];
272
+ res.add(edge[0]);
273
+ res.add(edge[1]);
274
+ }
275
+ return Array.from(res)
276
+ }
277
+
278
+ function makeOutgoingEdges(arr){
279
+ var edges = new Map();
280
+ for (var i = 0, len = arr.length; i < len; i++) {
281
+ var edge = arr[i];
282
+ if (!edges.has(edge[0])) edges.set(edge[0], new Set());
283
+ if (!edges.has(edge[1])) edges.set(edge[1], new Set());
284
+ edges.get(edge[0]).add(edge[1]);
285
+ }
286
+ return edges
287
+ }
288
+
289
+ function makeNodesHash(arr){
290
+ var res = new Map();
291
+ for (var i = 0, len = arr.length; i < len; i++) {
292
+ res.set(arr[i], i);
293
+ }
294
+ return res
295
+ }
296
+ toposort_1.array = array$1;
297
+
298
+ const toString = Object.prototype.toString;
299
+ const errorToString = Error.prototype.toString;
300
+ const regExpToString = RegExp.prototype.toString;
301
+ const symbolToString = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : () => '';
302
+ const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
303
+ function printNumber(val) {
304
+ if (val != +val) return 'NaN';
305
+ const isNegativeZero = val === 0 && 1 / val < 0;
306
+ return isNegativeZero ? '-0' : '' + val;
307
+ }
308
+ function printSimpleValue(val, quoteStrings = false) {
309
+ if (val == null || val === true || val === false) return '' + val;
310
+ const typeOf = typeof val;
311
+ if (typeOf === 'number') return printNumber(val);
312
+ if (typeOf === 'string') return quoteStrings ? `"${val}"` : val;
313
+ if (typeOf === 'function') return '[Function ' + (val.name || 'anonymous') + ']';
314
+ if (typeOf === 'symbol') return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');
315
+ const tag = toString.call(val).slice(8, -1);
316
+ if (tag === 'Date') return isNaN(val.getTime()) ? '' + val : val.toISOString(val);
317
+ if (tag === 'Error' || val instanceof Error) return '[' + errorToString.call(val) + ']';
318
+ if (tag === 'RegExp') return regExpToString.call(val);
319
+ return null;
320
+ }
321
+ function printValue(value, quoteStrings) {
322
+ let result = printSimpleValue(value, quoteStrings);
323
+ if (result !== null) return result;
324
+ return JSON.stringify(value, function (key, value) {
325
+ let result = printSimpleValue(this[key], quoteStrings);
326
+ if (result !== null) return result;
327
+ return value;
328
+ }, 2);
329
+ }
330
+
331
+ function toArray(value) {
332
+ return value == null ? [] : [].concat(value);
333
+ }
334
+
335
+ let strReg = /\$\{\s*(\w+)\s*\}/g;
336
+ class ValidationError extends Error {
337
+ static formatError(message, params) {
338
+ const path = params.label || params.path || 'this';
339
+ if (path !== params.path) params = Object.assign({}, params, {
340
+ path
341
+ });
342
+ if (typeof message === 'string') return message.replace(strReg, (_, key) => printValue(params[key]));
343
+ if (typeof message === 'function') return message(params);
344
+ return message;
345
+ }
346
+ static isError(err) {
347
+ return err && err.name === 'ValidationError';
348
+ }
349
+ constructor(errorOrErrors, value, field, type) {
350
+ super();
351
+ this.value = void 0;
352
+ this.path = void 0;
353
+ this.type = void 0;
354
+ this.errors = void 0;
355
+ this.params = void 0;
356
+ this.inner = void 0;
357
+ this.name = 'ValidationError';
358
+ this.value = value;
359
+ this.path = field;
360
+ this.type = type;
361
+ this.errors = [];
362
+ this.inner = [];
363
+ toArray(errorOrErrors).forEach(err => {
364
+ if (ValidationError.isError(err)) {
365
+ this.errors.push(...err.errors);
366
+ this.inner = this.inner.concat(err.inner.length ? err.inner : err);
367
+ } else {
368
+ this.errors.push(err);
369
+ }
370
+ });
371
+ this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];
372
+ if (Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);
373
+ }
374
+ }
375
+
376
+ let mixed = {
377
+ default: '${path} is invalid',
378
+ required: '${path} is a required field',
379
+ defined: '${path} must be defined',
380
+ notNull: '${path} cannot be null',
381
+ oneOf: '${path} must be one of the following values: ${values}',
382
+ notOneOf: '${path} must not be one of the following values: ${values}',
383
+ notType: ({
384
+ path,
385
+ type,
386
+ value,
387
+ originalValue
388
+ }) => {
389
+ const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : '.';
390
+ return type !== 'mixed' ? `${path} must be a \`${type}\` type, ` + `but the final value was: \`${printValue(value, true)}\`` + castMsg : `${path} must match the configured type. ` + `The validated value was: \`${printValue(value, true)}\`` + castMsg;
391
+ }
392
+ };
393
+ let string = {
394
+ length: '${path} must be exactly ${length} characters',
395
+ min: '${path} must be at least ${min} characters',
396
+ max: '${path} must be at most ${max} characters',
397
+ matches: '${path} must match the following: "${regex}"',
398
+ email: '${path} must be a valid email',
399
+ url: '${path} must be a valid URL',
400
+ uuid: '${path} must be a valid UUID',
401
+ trim: '${path} must be a trimmed string',
402
+ lowercase: '${path} must be a lowercase string',
403
+ uppercase: '${path} must be a upper case string'
404
+ };
405
+ let number = {
406
+ min: '${path} must be greater than or equal to ${min}',
407
+ max: '${path} must be less than or equal to ${max}',
408
+ lessThan: '${path} must be less than ${less}',
409
+ moreThan: '${path} must be greater than ${more}',
410
+ positive: '${path} must be a positive number',
411
+ negative: '${path} must be a negative number',
412
+ integer: '${path} must be an integer'
413
+ };
414
+ let date = {
415
+ min: '${path} field must be later than ${min}',
416
+ max: '${path} field must be at earlier than ${max}'
417
+ };
418
+ let boolean = {
419
+ isValue: '${path} field must be ${value}'
420
+ };
421
+ let object = {
422
+ noUnknown: '${path} field has unspecified keys: ${unknown}'
423
+ };
424
+ let array = {
425
+ min: '${path} field must have at least ${min} items',
426
+ max: '${path} field must have less than or equal to ${max} items',
427
+ length: '${path} must have ${length} items'
428
+ };
429
+ Object.assign(Object.create(null), {
430
+ mixed,
431
+ string,
432
+ number,
433
+ date,
434
+ object,
435
+ array,
436
+ boolean
437
+ });
438
+
439
+ const isSchema = obj => obj && obj.__isYupSchema__;
440
+
441
+ class Condition {
442
+ static fromOptions(refs, config) {
443
+ if (!config.then && !config.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');
444
+ let {
445
+ is,
446
+ then,
447
+ otherwise
448
+ } = config;
449
+ let check = typeof is === 'function' ? is : (...values) => values.every(value => value === is);
450
+ return new Condition(refs, (values, schema) => {
451
+ var _branch;
452
+ let branch = check(...values) ? then : otherwise;
453
+ return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;
454
+ });
455
+ }
456
+ constructor(refs, builder) {
457
+ this.fn = void 0;
458
+ this.refs = refs;
459
+ this.refs = refs;
460
+ this.fn = builder;
461
+ }
462
+ resolve(base, options) {
463
+ let values = this.refs.map(ref =>
464
+ // TODO: ? operator here?
465
+ ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context));
466
+ let schema = this.fn(values, base, options);
467
+ if (schema === undefined ||
468
+ // @ts-ignore this can be base
469
+ schema === base) {
470
+ return base;
471
+ }
472
+ if (!isSchema(schema)) throw new TypeError('conditions must return a schema object');
473
+ return schema.resolve(options);
474
+ }
475
+ }
476
+
477
+ const prefixes = {
478
+ context: '$',
479
+ value: '.'
480
+ };
481
+ class Reference {
482
+ constructor(key, options = {}) {
483
+ this.key = void 0;
484
+ this.isContext = void 0;
485
+ this.isValue = void 0;
486
+ this.isSibling = void 0;
487
+ this.path = void 0;
488
+ this.getter = void 0;
489
+ this.map = void 0;
490
+ if (typeof key !== 'string') throw new TypeError('ref must be a string, got: ' + key);
491
+ this.key = key.trim();
492
+ if (key === '') throw new TypeError('ref must be a non-empty string');
493
+ this.isContext = this.key[0] === prefixes.context;
494
+ this.isValue = this.key[0] === prefixes.value;
495
+ this.isSibling = !this.isContext && !this.isValue;
496
+ let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : '';
497
+ this.path = this.key.slice(prefix.length);
498
+ this.getter = this.path && propertyExpr.getter(this.path, true);
499
+ this.map = options.map;
500
+ }
501
+ getValue(value, parent, context) {
502
+ let result = this.isContext ? context : this.isValue ? value : parent;
503
+ if (this.getter) result = this.getter(result || {});
504
+ if (this.map) result = this.map(result);
505
+ return result;
506
+ }
507
+
508
+ /**
509
+ *
510
+ * @param {*} value
511
+ * @param {Object} options
512
+ * @param {Object=} options.context
513
+ * @param {Object=} options.parent
514
+ */
515
+ cast(value, options) {
516
+ return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);
517
+ }
518
+ resolve() {
519
+ return this;
520
+ }
521
+ describe() {
522
+ return {
523
+ type: 'ref',
524
+ key: this.key
525
+ };
526
+ }
527
+ toString() {
528
+ return `Ref(${this.key})`;
529
+ }
530
+ static isRef(value) {
531
+ return value && value.__isYupRef;
532
+ }
533
+ }
534
+
535
+ // @ts-ignore
536
+ Reference.prototype.__isYupRef = true;
537
+
538
+ const isAbsent = value => value == null;
539
+
540
+ function createValidation(config) {
541
+ function validate({
542
+ value,
543
+ path = '',
544
+ options,
545
+ originalValue,
546
+ schema
547
+ }, panic, next) {
548
+ const {
549
+ name,
550
+ test,
551
+ params,
552
+ message,
553
+ skipAbsent
554
+ } = config;
555
+ let {
556
+ parent,
557
+ context,
558
+ abortEarly = schema.spec.abortEarly
559
+ } = options;
560
+ function resolve(item) {
561
+ return Reference.isRef(item) ? item.getValue(value, parent, context) : item;
562
+ }
563
+ function createError(overrides = {}) {
564
+ const nextParams = Object.assign({
565
+ value,
566
+ originalValue,
567
+ label: schema.spec.label,
568
+ path: overrides.path || path,
569
+ spec: schema.spec
570
+ }, params, overrides.params);
571
+ for (const key of Object.keys(nextParams)) nextParams[key] = resolve(nextParams[key]);
572
+ const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name);
573
+ error.params = nextParams;
574
+ return error;
575
+ }
576
+ const invalid = abortEarly ? panic : next;
577
+ let ctx = {
578
+ path,
579
+ parent,
580
+ type: name,
581
+ from: options.from,
582
+ createError,
583
+ resolve,
584
+ options,
585
+ originalValue,
586
+ schema
587
+ };
588
+ const handleResult = validOrError => {
589
+ if (ValidationError.isError(validOrError)) invalid(validOrError);else if (!validOrError) invalid(createError());else next(null);
590
+ };
591
+ const handleError = err => {
592
+ if (ValidationError.isError(err)) invalid(err);else panic(err);
593
+ };
594
+ const shouldSkip = skipAbsent && isAbsent(value);
595
+ if (!options.sync) {
596
+ try {
597
+ Promise.resolve(!shouldSkip ? test.call(ctx, value, ctx) : true).then(handleResult, handleError);
598
+ } catch (err) {
599
+ handleError(err);
600
+ }
601
+ return;
602
+ }
603
+ let result;
604
+ try {
605
+ var _result;
606
+ result = !shouldSkip ? test.call(ctx, value, ctx) : true;
607
+ if (typeof ((_result = result) == null ? void 0 : _result.then) === 'function') {
608
+ throw new Error(`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. ` + `This test will finish after the validate call has returned`);
609
+ }
610
+ } catch (err) {
611
+ handleError(err);
612
+ return;
613
+ }
614
+ handleResult(result);
615
+ }
616
+ validate.OPTIONS = config;
617
+ return validate;
618
+ }
619
+
620
+ function getIn(schema, path, value, context = value) {
621
+ let parent, lastPart, lastPartDebug;
622
+
623
+ // root path: ''
624
+ if (!path) return {
625
+ parent,
626
+ parentPath: path,
627
+ schema
628
+ };
629
+ propertyExpr.forEach(path, (_part, isBracket, isArray) => {
630
+ let part = isBracket ? _part.slice(1, _part.length - 1) : _part;
631
+ schema = schema.resolve({
632
+ context,
633
+ parent,
634
+ value
635
+ });
636
+ let isTuple = schema.type === 'tuple';
637
+ let idx = isArray ? parseInt(part, 10) : 0;
638
+ if (schema.innerType || isTuple) {
639
+ if (isTuple && !isArray) throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${lastPartDebug}" must contain an index to the tuple element, e.g. "${lastPartDebug}[0]"`);
640
+ if (value && idx >= value.length) {
641
+ throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. ` + `because there is no value at that index. `);
642
+ }
643
+ parent = value;
644
+ value = value && value[idx];
645
+ schema = isTuple ? schema.spec.types[idx] : schema.innerType;
646
+ }
647
+
648
+ // sometimes the array index part of a path doesn't exist: "nested.arr.child"
649
+ // in these cases the current part is the next schema and should be processed
650
+ // in this iteration. For cases where the index signature is included this
651
+ // check will fail and we'll handle the `child` part on the next iteration like normal
652
+ if (!isArray) {
653
+ if (!schema.fields || !schema.fields[part]) throw new Error(`The schema does not contain the path: ${path}. ` + `(failed at: ${lastPartDebug} which is a type: "${schema.type}")`);
654
+ parent = value;
655
+ value = value && value[part];
656
+ schema = schema.fields[part];
657
+ }
658
+ lastPart = part;
659
+ lastPartDebug = isBracket ? '[' + _part + ']' : '.' + _part;
660
+ });
661
+ return {
662
+ schema,
663
+ parent,
664
+ parentPath: lastPart
665
+ };
666
+ }
667
+
668
+ class ReferenceSet extends Set {
669
+ describe() {
670
+ const description = [];
671
+ for (const item of this.values()) {
672
+ description.push(Reference.isRef(item) ? item.describe() : item);
673
+ }
674
+ return description;
675
+ }
676
+ resolveAll(resolve) {
677
+ let result = [];
678
+ for (const item of this.values()) {
679
+ result.push(resolve(item));
680
+ }
681
+ return result;
682
+ }
683
+ clone() {
684
+ return new ReferenceSet(this.values());
685
+ }
686
+ merge(newItems, removeItems) {
687
+ const next = this.clone();
688
+ newItems.forEach(value => next.add(value));
689
+ removeItems.forEach(value => next.delete(value));
690
+ return next;
691
+ }
692
+ }
693
+
694
+ // tweaked from https://github.com/Kelin2025/nanoclone/blob/0abeb7635bda9b68ef2277093f76dbe3bf3948e1/src/index.js
695
+ function clone(src, seen = new Map()) {
696
+ if (isSchema(src) || !src || typeof src !== 'object') return src;
697
+ if (seen.has(src)) return seen.get(src);
698
+ let copy;
699
+ if (src instanceof Date) {
700
+ // Date
701
+ copy = new Date(src.getTime());
702
+ seen.set(src, copy);
703
+ } else if (src instanceof RegExp) {
704
+ // RegExp
705
+ copy = new RegExp(src);
706
+ seen.set(src, copy);
707
+ } else if (Array.isArray(src)) {
708
+ // Array
709
+ copy = new Array(src.length);
710
+ seen.set(src, copy);
711
+ for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);
712
+ } else if (src instanceof Map) {
713
+ // Map
714
+ copy = new Map();
715
+ seen.set(src, copy);
716
+ for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));
717
+ } else if (src instanceof Set) {
718
+ // Set
719
+ copy = new Set();
720
+ seen.set(src, copy);
721
+ for (const v of src) copy.add(clone(v, seen));
722
+ } else if (src instanceof Object) {
723
+ // Object
724
+ copy = {};
725
+ seen.set(src, copy);
726
+ for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);
727
+ } else {
728
+ throw Error(`Unable to clone ${src}`);
729
+ }
730
+ return copy;
731
+ }
732
+
733
+ class Schema {
734
+ constructor(options) {
735
+ this.type = void 0;
736
+ this.deps = [];
737
+ this.tests = void 0;
738
+ this.transforms = void 0;
739
+ this.conditions = [];
740
+ this._mutate = void 0;
741
+ this.internalTests = {};
742
+ this._whitelist = new ReferenceSet();
743
+ this._blacklist = new ReferenceSet();
744
+ this.exclusiveTests = Object.create(null);
745
+ this._typeCheck = void 0;
746
+ this.spec = void 0;
747
+ this.tests = [];
748
+ this.transforms = [];
749
+ this.withMutation(() => {
750
+ this.typeError(mixed.notType);
751
+ });
752
+ this.type = options.type;
753
+ this._typeCheck = options.check;
754
+ this.spec = Object.assign({
755
+ strip: false,
756
+ strict: false,
757
+ abortEarly: true,
758
+ recursive: true,
759
+ nullable: false,
760
+ optional: true,
761
+ coerce: true
762
+ }, options == null ? void 0 : options.spec);
763
+ this.withMutation(s => {
764
+ s.nonNullable();
765
+ });
766
+ }
767
+
768
+ // TODO: remove
769
+ get _type() {
770
+ return this.type;
771
+ }
772
+ clone(spec) {
773
+ if (this._mutate) {
774
+ if (spec) Object.assign(this.spec, spec);
775
+ return this;
776
+ }
777
+
778
+ // if the nested value is a schema we can skip cloning, since
779
+ // they are already immutable
780
+ const next = Object.create(Object.getPrototypeOf(this));
781
+
782
+ // @ts-expect-error this is readonly
783
+ next.type = this.type;
784
+ next._typeCheck = this._typeCheck;
785
+ next._whitelist = this._whitelist.clone();
786
+ next._blacklist = this._blacklist.clone();
787
+ next.internalTests = Object.assign({}, this.internalTests);
788
+ next.exclusiveTests = Object.assign({}, this.exclusiveTests);
789
+
790
+ // @ts-expect-error this is readonly
791
+ next.deps = [...this.deps];
792
+ next.conditions = [...this.conditions];
793
+ next.tests = [...this.tests];
794
+ next.transforms = [...this.transforms];
795
+ next.spec = clone(Object.assign({}, this.spec, spec));
796
+ return next;
797
+ }
798
+ label(label) {
799
+ let next = this.clone();
800
+ next.spec.label = label;
801
+ return next;
802
+ }
803
+ meta(...args) {
804
+ if (args.length === 0) return this.spec.meta;
805
+ let next = this.clone();
806
+ next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);
807
+ return next;
808
+ }
809
+ withMutation(fn) {
810
+ let before = this._mutate;
811
+ this._mutate = true;
812
+ let result = fn(this);
813
+ this._mutate = before;
814
+ return result;
815
+ }
816
+ concat(schema) {
817
+ if (!schema || schema === this) return this;
818
+ if (schema.type !== this.type && this.type !== 'mixed') throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`);
819
+ let base = this;
820
+ let combined = schema.clone();
821
+ const mergedSpec = Object.assign({}, base.spec, combined.spec);
822
+ combined.spec = mergedSpec;
823
+ combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests);
824
+
825
+ // manually merge the blacklist/whitelist (the other `schema` takes
826
+ // precedence in case of conflicts)
827
+ combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);
828
+ combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist);
829
+
830
+ // start with the current tests
831
+ combined.tests = base.tests;
832
+ combined.exclusiveTests = base.exclusiveTests;
833
+
834
+ // manually add the new tests to ensure
835
+ // the deduping logic is consistent
836
+ combined.withMutation(next => {
837
+ schema.tests.forEach(fn => {
838
+ next.test(fn.OPTIONS);
839
+ });
840
+ });
841
+ combined.transforms = [...base.transforms, ...combined.transforms];
842
+ return combined;
843
+ }
844
+ isType(v) {
845
+ if (v == null) {
846
+ if (this.spec.nullable && v === null) return true;
847
+ if (this.spec.optional && v === undefined) return true;
848
+ return false;
849
+ }
850
+ return this._typeCheck(v);
851
+ }
852
+ resolve(options) {
853
+ let schema = this;
854
+ if (schema.conditions.length) {
855
+ let conditions = schema.conditions;
856
+ schema = schema.clone();
857
+ schema.conditions = [];
858
+ schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);
859
+ schema = schema.resolve(options);
860
+ }
861
+ return schema;
862
+ }
863
+ resolveOptions(options) {
864
+ var _options$strict, _options$abortEarly, _options$recursive;
865
+ return Object.assign({}, options, {
866
+ from: options.from || [],
867
+ strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,
868
+ abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,
869
+ recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive
870
+ });
871
+ }
872
+
873
+ /**
874
+ * Run the configured transform pipeline over an input value.
875
+ */
876
+
877
+ cast(value, options = {}) {
878
+ let resolvedSchema = this.resolve(Object.assign({
879
+ value
880
+ }, options));
881
+ let allowOptionality = options.assert === 'ignore-optionality';
882
+ let result = resolvedSchema._cast(value, options);
883
+ if (options.assert !== false && !resolvedSchema.isType(result)) {
884
+ if (allowOptionality && isAbsent(result)) {
885
+ return result;
886
+ }
887
+ let formattedValue = printValue(value);
888
+ let formattedResult = printValue(result);
889
+ throw new TypeError(`The value of ${options.path || 'field'} could not be cast to a value ` + `that satisfies the schema type: "${resolvedSchema.type}". \n\n` + `attempted value: ${formattedValue} \n` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ''));
890
+ }
891
+ return result;
892
+ }
893
+ _cast(rawValue, _options) {
894
+ let value = rawValue === undefined ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this), rawValue);
895
+ if (value === undefined) {
896
+ value = this.getDefault();
897
+ }
898
+ return value;
899
+ }
900
+ _validate(_value, options = {}, panic, next) {
901
+ let {
902
+ path,
903
+ originalValue = _value,
904
+ strict = this.spec.strict
905
+ } = options;
906
+ let value = _value;
907
+ if (!strict) {
908
+ value = this._cast(value, Object.assign({
909
+ assert: false
910
+ }, options));
911
+ }
912
+ let initialTests = [];
913
+ for (let test of Object.values(this.internalTests)) {
914
+ if (test) initialTests.push(test);
915
+ }
916
+ this.runTests({
917
+ path,
918
+ value,
919
+ originalValue,
920
+ options,
921
+ tests: initialTests
922
+ }, panic, initialErrors => {
923
+ // even if we aren't ending early we can't proceed further if the types aren't correct
924
+ if (initialErrors.length) {
925
+ return next(initialErrors, value);
926
+ }
927
+ this.runTests({
928
+ path,
929
+ value,
930
+ originalValue,
931
+ options,
932
+ tests: this.tests
933
+ }, panic, next);
934
+ });
935
+ }
936
+
937
+ /**
938
+ * Executes a set of validations, either schema, produced Tests or a nested
939
+ * schema validate result.
940
+ */
941
+ runTests(runOptions, panic, next) {
942
+ let fired = false;
943
+ let {
944
+ tests,
945
+ value,
946
+ originalValue,
947
+ path,
948
+ options
949
+ } = runOptions;
950
+ let panicOnce = arg => {
951
+ if (fired) return;
952
+ fired = true;
953
+ panic(arg, value);
954
+ };
955
+ let nextOnce = arg => {
956
+ if (fired) return;
957
+ fired = true;
958
+ next(arg, value);
959
+ };
960
+ let count = tests.length;
961
+ let nestedErrors = [];
962
+ if (!count) return nextOnce([]);
963
+ let args = {
964
+ value,
965
+ originalValue,
966
+ path,
967
+ options,
968
+ schema: this
969
+ };
970
+ for (let i = 0; i < tests.length; i++) {
971
+ const test = tests[i];
972
+ test(args, panicOnce, function finishTestRun(err) {
973
+ if (err) {
974
+ nestedErrors = nestedErrors.concat(err);
975
+ }
976
+ if (--count <= 0) {
977
+ nextOnce(nestedErrors);
978
+ }
979
+ });
980
+ }
981
+ }
982
+ asNestedTest({
983
+ key,
984
+ index,
985
+ parent,
986
+ parentPath,
987
+ originalParent,
988
+ options
989
+ }) {
990
+ const k = key != null ? key : index;
991
+ if (k == null) {
992
+ throw TypeError('Must include `key` or `index` for nested validations');
993
+ }
994
+ const isIndex = typeof k === 'number';
995
+ let value = parent[k];
996
+ const testOptions = Object.assign({}, options, {
997
+ // Nested validations fields are always strict:
998
+ // 1. parent isn't strict so the casting will also have cast inner values
999
+ // 2. parent is strict in which case the nested values weren't cast either
1000
+ strict: true,
1001
+ parent,
1002
+ value,
1003
+ originalValue: originalParent[k],
1004
+ // FIXME: tests depend on `index` being passed around deeply,
1005
+ // we should not let the options.key/index bleed through
1006
+ key: undefined,
1007
+ // index: undefined,
1008
+ [isIndex ? 'index' : 'key']: k,
1009
+ path: isIndex || k.includes('.') ? `${parentPath || ''}[${value ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : '') + key
1010
+ });
1011
+ return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);
1012
+ }
1013
+ validate(value, options) {
1014
+ let schema = this.resolve(Object.assign({}, options, {
1015
+ value
1016
+ }));
1017
+ return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {
1018
+ if (ValidationError.isError(error)) error.value = parsed;
1019
+ reject(error);
1020
+ }, (errors, validated) => {
1021
+ if (errors.length) reject(new ValidationError(errors, validated));else resolve(validated);
1022
+ }));
1023
+ }
1024
+ validateSync(value, options) {
1025
+ let schema = this.resolve(Object.assign({}, options, {
1026
+ value
1027
+ }));
1028
+ let result;
1029
+ schema._validate(value, Object.assign({}, options, {
1030
+ sync: true
1031
+ }), (error, parsed) => {
1032
+ if (ValidationError.isError(error)) error.value = parsed;
1033
+ throw error;
1034
+ }, (errors, validated) => {
1035
+ if (errors.length) throw new ValidationError(errors, value);
1036
+ result = validated;
1037
+ });
1038
+ return result;
1039
+ }
1040
+ isValid(value, options) {
1041
+ return this.validate(value, options).then(() => true, err => {
1042
+ if (ValidationError.isError(err)) return false;
1043
+ throw err;
1044
+ });
1045
+ }
1046
+ isValidSync(value, options) {
1047
+ try {
1048
+ this.validateSync(value, options);
1049
+ return true;
1050
+ } catch (err) {
1051
+ if (ValidationError.isError(err)) return false;
1052
+ throw err;
1053
+ }
1054
+ }
1055
+ _getDefault() {
1056
+ let defaultValue = this.spec.default;
1057
+ if (defaultValue == null) {
1058
+ return defaultValue;
1059
+ }
1060
+ return typeof defaultValue === 'function' ? defaultValue.call(this) : clone(defaultValue);
1061
+ }
1062
+ getDefault(options
1063
+ // If schema is defaulted we know it's at least not undefined
1064
+ ) {
1065
+ let schema = this.resolve(options || {});
1066
+ return schema._getDefault();
1067
+ }
1068
+ default(def) {
1069
+ if (arguments.length === 0) {
1070
+ return this._getDefault();
1071
+ }
1072
+ let next = this.clone({
1073
+ default: def
1074
+ });
1075
+ return next;
1076
+ }
1077
+ strict(isStrict = true) {
1078
+ return this.clone({
1079
+ strict: isStrict
1080
+ });
1081
+ }
1082
+ nullability(nullable, message) {
1083
+ const next = this.clone({
1084
+ nullable
1085
+ });
1086
+ next.internalTests.nullable = createValidation({
1087
+ message,
1088
+ name: 'nullable',
1089
+ test(value) {
1090
+ return value === null ? this.schema.spec.nullable : true;
1091
+ }
1092
+ });
1093
+ return next;
1094
+ }
1095
+ optionality(optional, message) {
1096
+ const next = this.clone({
1097
+ optional
1098
+ });
1099
+ next.internalTests.optionality = createValidation({
1100
+ message,
1101
+ name: 'optionality',
1102
+ test(value) {
1103
+ return value === undefined ? this.schema.spec.optional : true;
1104
+ }
1105
+ });
1106
+ return next;
1107
+ }
1108
+ optional() {
1109
+ return this.optionality(true);
1110
+ }
1111
+ defined(message = mixed.defined) {
1112
+ return this.optionality(false, message);
1113
+ }
1114
+ nullable() {
1115
+ return this.nullability(true);
1116
+ }
1117
+ nonNullable(message = mixed.notNull) {
1118
+ return this.nullability(false, message);
1119
+ }
1120
+ required(message = mixed.required) {
1121
+ return this.clone().withMutation(next => next.nonNullable(message).defined(message));
1122
+ }
1123
+ notRequired() {
1124
+ return this.clone().withMutation(next => next.nullable().optional());
1125
+ }
1126
+ transform(fn) {
1127
+ let next = this.clone();
1128
+ next.transforms.push(fn);
1129
+ return next;
1130
+ }
1131
+
1132
+ /**
1133
+ * Adds a test function to the schema's queue of tests.
1134
+ * tests can be exclusive or non-exclusive.
1135
+ *
1136
+ * - exclusive tests, will replace any existing tests of the same name.
1137
+ * - non-exclusive: can be stacked
1138
+ *
1139
+ * If a non-exclusive test is added to a schema with an exclusive test of the same name
1140
+ * the exclusive test is removed and further tests of the same name will be stacked.
1141
+ *
1142
+ * If an exclusive test is added to a schema with non-exclusive tests of the same name
1143
+ * the previous tests are removed and further tests of the same name will replace each other.
1144
+ */
1145
+
1146
+ test(...args) {
1147
+ let opts;
1148
+ if (args.length === 1) {
1149
+ if (typeof args[0] === 'function') {
1150
+ opts = {
1151
+ test: args[0]
1152
+ };
1153
+ } else {
1154
+ opts = args[0];
1155
+ }
1156
+ } else if (args.length === 2) {
1157
+ opts = {
1158
+ name: args[0],
1159
+ test: args[1]
1160
+ };
1161
+ } else {
1162
+ opts = {
1163
+ name: args[0],
1164
+ message: args[1],
1165
+ test: args[2]
1166
+ };
1167
+ }
1168
+ if (opts.message === undefined) opts.message = mixed.default;
1169
+ if (typeof opts.test !== 'function') throw new TypeError('`test` is a required parameters');
1170
+ let next = this.clone();
1171
+ let validate = createValidation(opts);
1172
+ let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;
1173
+ if (opts.exclusive) {
1174
+ if (!opts.name) throw new TypeError('Exclusive tests must provide a unique `name` identifying the test');
1175
+ }
1176
+ if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;
1177
+ next.tests = next.tests.filter(fn => {
1178
+ if (fn.OPTIONS.name === opts.name) {
1179
+ if (isExclusive) return false;
1180
+ if (fn.OPTIONS.test === validate.OPTIONS.test) return false;
1181
+ }
1182
+ return true;
1183
+ });
1184
+ next.tests.push(validate);
1185
+ return next;
1186
+ }
1187
+ when(keys, options) {
1188
+ if (!Array.isArray(keys) && typeof keys !== 'string') {
1189
+ options = keys;
1190
+ keys = '.';
1191
+ }
1192
+ let next = this.clone();
1193
+ let deps = toArray(keys).map(key => new Reference(key));
1194
+ deps.forEach(dep => {
1195
+ // @ts-ignore readonly array
1196
+ if (dep.isSibling) next.deps.push(dep.key);
1197
+ });
1198
+ next.conditions.push(typeof options === 'function' ? new Condition(deps, options) : Condition.fromOptions(deps, options));
1199
+ return next;
1200
+ }
1201
+ typeError(message) {
1202
+ let next = this.clone();
1203
+ next.internalTests.typeError = createValidation({
1204
+ message,
1205
+ name: 'typeError',
1206
+ test(value) {
1207
+ if (!isAbsent(value) && !this.schema._typeCheck(value)) return this.createError({
1208
+ params: {
1209
+ type: this.schema.type
1210
+ }
1211
+ });
1212
+ return true;
1213
+ }
1214
+ });
1215
+ return next;
1216
+ }
1217
+ oneOf(enums, message = mixed.oneOf) {
1218
+ let next = this.clone();
1219
+ enums.forEach(val => {
1220
+ next._whitelist.add(val);
1221
+ next._blacklist.delete(val);
1222
+ });
1223
+ next.internalTests.whiteList = createValidation({
1224
+ message,
1225
+ name: 'oneOf',
1226
+ skipAbsent: true,
1227
+ test(value) {
1228
+ let valids = this.schema._whitelist;
1229
+ let resolved = valids.resolveAll(this.resolve);
1230
+ return resolved.includes(value) ? true : this.createError({
1231
+ params: {
1232
+ values: Array.from(valids).join(', '),
1233
+ resolved
1234
+ }
1235
+ });
1236
+ }
1237
+ });
1238
+ return next;
1239
+ }
1240
+ notOneOf(enums, message = mixed.notOneOf) {
1241
+ let next = this.clone();
1242
+ enums.forEach(val => {
1243
+ next._blacklist.add(val);
1244
+ next._whitelist.delete(val);
1245
+ });
1246
+ next.internalTests.blacklist = createValidation({
1247
+ message,
1248
+ name: 'notOneOf',
1249
+ test(value) {
1250
+ let invalids = this.schema._blacklist;
1251
+ let resolved = invalids.resolveAll(this.resolve);
1252
+ if (resolved.includes(value)) return this.createError({
1253
+ params: {
1254
+ values: Array.from(invalids).join(', '),
1255
+ resolved
1256
+ }
1257
+ });
1258
+ return true;
1259
+ }
1260
+ });
1261
+ return next;
1262
+ }
1263
+ strip(strip = true) {
1264
+ let next = this.clone();
1265
+ next.spec.strip = strip;
1266
+ return next;
1267
+ }
1268
+
1269
+ /**
1270
+ * Return a serialized description of the schema including validations, flags, types etc.
1271
+ *
1272
+ * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).
1273
+ */
1274
+ describe(options) {
1275
+ const next = (options ? this.resolve(options) : this).clone();
1276
+ const {
1277
+ label,
1278
+ meta,
1279
+ optional,
1280
+ nullable
1281
+ } = next.spec;
1282
+ const description = {
1283
+ meta,
1284
+ label,
1285
+ optional,
1286
+ nullable,
1287
+ default: next.getDefault(options),
1288
+ type: next.type,
1289
+ oneOf: next._whitelist.describe(),
1290
+ notOneOf: next._blacklist.describe(),
1291
+ tests: next.tests.map(fn => ({
1292
+ name: fn.OPTIONS.name,
1293
+ params: fn.OPTIONS.params
1294
+ })).filter((n, idx, list) => list.findIndex(c => c.name === n.name) === idx)
1295
+ };
1296
+ return description;
1297
+ }
1298
+ }
1299
+ // @ts-expect-error
1300
+ Schema.prototype.__isYupSchema__ = true;
1301
+ for (const method of ['validate', 'validateSync']) Schema.prototype[`${method}At`] = function (path, value, options = {}) {
1302
+ const {
1303
+ parent,
1304
+ parentPath,
1305
+ schema
1306
+ } = getIn(this, path, value, options.context);
1307
+ return schema[method](parent && parent[parentPath], Object.assign({}, options, {
1308
+ parent,
1309
+ path
1310
+ }));
1311
+ };
1312
+ for (const alias of ['equals', 'is']) Schema.prototype[alias] = Schema.prototype.oneOf;
1313
+ for (const alias of ['not', 'nope']) Schema.prototype[alias] = Schema.prototype.notOneOf;
1314
+
1315
+ // Taken from HTML spec: https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
1316
+ let rEmail =
1317
+ // eslint-disable-next-line
1318
+ /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1319
+ let rUrl =
1320
+ // eslint-disable-next-line
1321
+ /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
1322
+
1323
+ // eslint-disable-next-line
1324
+ let rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
1325
+ let isTrimmed = value => isAbsent(value) || value === value.trim();
1326
+ let objStringTag = {}.toString();
1327
+ function create$6() {
1328
+ return new StringSchema();
1329
+ }
1330
+ class StringSchema extends Schema {
1331
+ constructor() {
1332
+ super({
1333
+ type: 'string',
1334
+ check(value) {
1335
+ if (value instanceof String) value = value.valueOf();
1336
+ return typeof value === 'string';
1337
+ }
1338
+ });
1339
+ this.withMutation(() => {
1340
+ this.transform((value, _raw, ctx) => {
1341
+ if (!ctx.spec.coerce || ctx.isType(value)) return value;
1342
+
1343
+ // don't ever convert arrays
1344
+ if (Array.isArray(value)) return value;
1345
+ const strValue = value != null && value.toString ? value.toString() : value;
1346
+
1347
+ // no one wants plain objects converted to [Object object]
1348
+ if (strValue === objStringTag) return value;
1349
+ return strValue;
1350
+ });
1351
+ });
1352
+ }
1353
+ required(message) {
1354
+ return super.required(message).withMutation(schema => schema.test({
1355
+ message: message || mixed.required,
1356
+ name: 'required',
1357
+ skipAbsent: true,
1358
+ test: value => !!value.length
1359
+ }));
1360
+ }
1361
+ notRequired() {
1362
+ return super.notRequired().withMutation(schema => {
1363
+ schema.tests = schema.tests.filter(t => t.OPTIONS.name !== 'required');
1364
+ return schema;
1365
+ });
1366
+ }
1367
+ length(length, message = string.length) {
1368
+ return this.test({
1369
+ message,
1370
+ name: 'length',
1371
+ exclusive: true,
1372
+ params: {
1373
+ length
1374
+ },
1375
+ skipAbsent: true,
1376
+ test(value) {
1377
+ return value.length === this.resolve(length);
1378
+ }
1379
+ });
1380
+ }
1381
+ min(min, message = string.min) {
1382
+ return this.test({
1383
+ message,
1384
+ name: 'min',
1385
+ exclusive: true,
1386
+ params: {
1387
+ min
1388
+ },
1389
+ skipAbsent: true,
1390
+ test(value) {
1391
+ return value.length >= this.resolve(min);
1392
+ }
1393
+ });
1394
+ }
1395
+ max(max, message = string.max) {
1396
+ return this.test({
1397
+ name: 'max',
1398
+ exclusive: true,
1399
+ message,
1400
+ params: {
1401
+ max
1402
+ },
1403
+ skipAbsent: true,
1404
+ test(value) {
1405
+ return value.length <= this.resolve(max);
1406
+ }
1407
+ });
1408
+ }
1409
+ matches(regex, options) {
1410
+ let excludeEmptyString = false;
1411
+ let message;
1412
+ let name;
1413
+ if (options) {
1414
+ if (typeof options === 'object') {
1415
+ ({
1416
+ excludeEmptyString = false,
1417
+ message,
1418
+ name
1419
+ } = options);
1420
+ } else {
1421
+ message = options;
1422
+ }
1423
+ }
1424
+ return this.test({
1425
+ name: name || 'matches',
1426
+ message: message || string.matches,
1427
+ params: {
1428
+ regex
1429
+ },
1430
+ skipAbsent: true,
1431
+ test: value => value === '' && excludeEmptyString || value.search(regex) !== -1
1432
+ });
1433
+ }
1434
+ email(message = string.email) {
1435
+ return this.matches(rEmail, {
1436
+ name: 'email',
1437
+ message,
1438
+ excludeEmptyString: true
1439
+ });
1440
+ }
1441
+ url(message = string.url) {
1442
+ return this.matches(rUrl, {
1443
+ name: 'url',
1444
+ message,
1445
+ excludeEmptyString: true
1446
+ });
1447
+ }
1448
+ uuid(message = string.uuid) {
1449
+ return this.matches(rUUID, {
1450
+ name: 'uuid',
1451
+ message,
1452
+ excludeEmptyString: false
1453
+ });
1454
+ }
1455
+
1456
+ //-- transforms --
1457
+ ensure() {
1458
+ return this.default('').transform(val => val === null ? '' : val);
1459
+ }
1460
+ trim(message = string.trim) {
1461
+ return this.transform(val => val != null ? val.trim() : val).test({
1462
+ message,
1463
+ name: 'trim',
1464
+ test: isTrimmed
1465
+ });
1466
+ }
1467
+ lowercase(message = string.lowercase) {
1468
+ return this.transform(value => !isAbsent(value) ? value.toLowerCase() : value).test({
1469
+ message,
1470
+ name: 'string_case',
1471
+ exclusive: true,
1472
+ skipAbsent: true,
1473
+ test: value => isAbsent(value) || value === value.toLowerCase()
1474
+ });
1475
+ }
1476
+ uppercase(message = string.uppercase) {
1477
+ return this.transform(value => !isAbsent(value) ? value.toUpperCase() : value).test({
1478
+ message,
1479
+ name: 'string_case',
1480
+ exclusive: true,
1481
+ skipAbsent: true,
1482
+ test: value => isAbsent(value) || value === value.toUpperCase()
1483
+ });
1484
+ }
1485
+ }
1486
+ create$6.prototype = StringSchema.prototype;
1487
+
1488
+ // @ts-expect-error
1489
+ function sortFields(fields, excludedEdges = []) {
1490
+ let edges = [];
1491
+ let nodes = new Set();
1492
+ let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));
1493
+ function addNode(depPath, key) {
1494
+ let node = propertyExpr.split(depPath)[0];
1495
+ nodes.add(node);
1496
+ if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);
1497
+ }
1498
+ for (const key of Object.keys(fields)) {
1499
+ let value = fields[key];
1500
+ nodes.add(key);
1501
+ if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);else if (isSchema(value) && 'deps' in value) value.deps.forEach(path => addNode(path, key));
1502
+ }
1503
+ return toposort_1.array(Array.from(nodes), edges).reverse();
1504
+ }
1505
+
1506
+ function findIndex(arr, err) {
1507
+ let idx = Infinity;
1508
+ arr.some((key, ii) => {
1509
+ var _err$path;
1510
+ if ((_err$path = err.path) != null && _err$path.includes(key)) {
1511
+ idx = ii;
1512
+ return true;
1513
+ }
1514
+ });
1515
+ return idx;
1516
+ }
1517
+ function sortByKeyOrder(keys) {
1518
+ return (a, b) => {
1519
+ return findIndex(keys, a) - findIndex(keys, b);
1520
+ };
1521
+ }
1522
+
1523
+ const parseJson = (value, _, ctx) => {
1524
+ if (typeof value !== 'string') {
1525
+ return value;
1526
+ }
1527
+ let parsed = value;
1528
+ try {
1529
+ parsed = JSON.parse(value);
1530
+ } catch (err) {
1531
+ /* */
1532
+ }
1533
+ return ctx.isType(parsed) ? parsed : value;
1534
+ };
1535
+
1536
+ // @ts-ignore
1537
+ function deepPartial(schema) {
1538
+ if ('fields' in schema) {
1539
+ const partial = {};
1540
+ for (const [key, fieldSchema] of Object.entries(schema.fields)) {
1541
+ partial[key] = deepPartial(fieldSchema);
1542
+ }
1543
+ return schema.setFields(partial);
1544
+ }
1545
+ if (schema.type === 'array') {
1546
+ const nextArray = schema.optional();
1547
+ if (nextArray.innerType) nextArray.innerType = deepPartial(nextArray.innerType);
1548
+ return nextArray;
1549
+ }
1550
+ if (schema.type === 'tuple') {
1551
+ return schema.optional().clone({
1552
+ types: schema.spec.types.map(deepPartial)
1553
+ });
1554
+ }
1555
+ if ('optional' in schema) {
1556
+ return schema.optional();
1557
+ }
1558
+ return schema;
1559
+ }
1560
+ const deepHas = (obj, p) => {
1561
+ const path = [...propertyExpr.normalizePath(p)];
1562
+ if (path.length === 1) return path[0] in obj;
1563
+ let last = path.pop();
1564
+ let parent = propertyExpr.getter(propertyExpr.join(path), true)(obj);
1565
+ return !!(parent && last in parent);
1566
+ };
1567
+ let isObject = obj => Object.prototype.toString.call(obj) === '[object Object]';
1568
+ function unknown(ctx, value) {
1569
+ let known = Object.keys(ctx.fields);
1570
+ return Object.keys(value).filter(key => known.indexOf(key) === -1);
1571
+ }
1572
+ const defaultSort = sortByKeyOrder([]);
1573
+ function create$3(spec) {
1574
+ return new ObjectSchema(spec);
1575
+ }
1576
+ class ObjectSchema extends Schema {
1577
+ constructor(spec) {
1578
+ super({
1579
+ type: 'object',
1580
+ check(value) {
1581
+ return isObject(value) || typeof value === 'function';
1582
+ }
1583
+ });
1584
+ this.fields = Object.create(null);
1585
+ this._sortErrors = defaultSort;
1586
+ this._nodes = [];
1587
+ this._excludedEdges = [];
1588
+ this.withMutation(() => {
1589
+ if (spec) {
1590
+ this.shape(spec);
1591
+ }
1592
+ });
1593
+ }
1594
+ _cast(_value, options = {}) {
1595
+ var _options$stripUnknown;
1596
+ let value = super._cast(_value, options);
1597
+
1598
+ //should ignore nulls here
1599
+ if (value === undefined) return this.getDefault();
1600
+ if (!this._typeCheck(value)) return value;
1601
+ let fields = this.fields;
1602
+ let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;
1603
+ let props = [].concat(this._nodes, Object.keys(value).filter(v => !this._nodes.includes(v)));
1604
+ let intermediateValue = {}; // is filled during the transform below
1605
+ let innerOptions = Object.assign({}, options, {
1606
+ parent: intermediateValue,
1607
+ __validating: options.__validating || false
1608
+ });
1609
+ let isChanged = false;
1610
+ for (const prop of props) {
1611
+ let field = fields[prop];
1612
+ let exists = (prop in value);
1613
+ if (field) {
1614
+ let fieldValue;
1615
+ let inputValue = value[prop];
1616
+
1617
+ // safe to mutate since this is fired in sequence
1618
+ innerOptions.path = (options.path ? `${options.path}.` : '') + prop;
1619
+ field = field.resolve({
1620
+ value: inputValue,
1621
+ context: options.context,
1622
+ parent: intermediateValue
1623
+ });
1624
+ let fieldSpec = field instanceof Schema ? field.spec : undefined;
1625
+ let strict = fieldSpec == null ? void 0 : fieldSpec.strict;
1626
+ if (fieldSpec != null && fieldSpec.strip) {
1627
+ isChanged = isChanged || prop in value;
1628
+ continue;
1629
+ }
1630
+ fieldValue = !options.__validating || !strict ?
1631
+ // TODO: use _cast, this is double resolving
1632
+ field.cast(value[prop], innerOptions) : value[prop];
1633
+ if (fieldValue !== undefined) {
1634
+ intermediateValue[prop] = fieldValue;
1635
+ }
1636
+ } else if (exists && !strip) {
1637
+ intermediateValue[prop] = value[prop];
1638
+ }
1639
+ if (exists !== prop in intermediateValue || intermediateValue[prop] !== value[prop]) {
1640
+ isChanged = true;
1641
+ }
1642
+ }
1643
+ return isChanged ? intermediateValue : value;
1644
+ }
1645
+ _validate(_value, options = {}, panic, next) {
1646
+ let {
1647
+ from = [],
1648
+ originalValue = _value,
1649
+ recursive = this.spec.recursive
1650
+ } = options;
1651
+ options.from = [{
1652
+ schema: this,
1653
+ value: originalValue
1654
+ }, ...from];
1655
+ // this flag is needed for handling `strict` correctly in the context of
1656
+ // validation vs just casting. e.g strict() on a field is only used when validating
1657
+ options.__validating = true;
1658
+ options.originalValue = originalValue;
1659
+ super._validate(_value, options, panic, (objectErrors, value) => {
1660
+ if (!recursive || !isObject(value)) {
1661
+ next(objectErrors, value);
1662
+ return;
1663
+ }
1664
+ originalValue = originalValue || value;
1665
+ let tests = [];
1666
+ for (let key of this._nodes) {
1667
+ let field = this.fields[key];
1668
+ if (!field || Reference.isRef(field)) {
1669
+ continue;
1670
+ }
1671
+ tests.push(field.asNestedTest({
1672
+ options,
1673
+ key,
1674
+ parent: value,
1675
+ parentPath: options.path,
1676
+ originalParent: originalValue
1677
+ }));
1678
+ }
1679
+ this.runTests({
1680
+ tests,
1681
+ value,
1682
+ originalValue,
1683
+ options
1684
+ }, panic, fieldErrors => {
1685
+ next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);
1686
+ });
1687
+ });
1688
+ }
1689
+ clone(spec) {
1690
+ const next = super.clone(spec);
1691
+ next.fields = Object.assign({}, this.fields);
1692
+ next._nodes = this._nodes;
1693
+ next._excludedEdges = this._excludedEdges;
1694
+ next._sortErrors = this._sortErrors;
1695
+ return next;
1696
+ }
1697
+ concat(schema) {
1698
+ let next = super.concat(schema);
1699
+ let nextFields = next.fields;
1700
+ for (let [field, schemaOrRef] of Object.entries(this.fields)) {
1701
+ const target = nextFields[field];
1702
+ nextFields[field] = target === undefined ? schemaOrRef : target;
1703
+ }
1704
+ return next.withMutation(s => s.setFields(nextFields, this._excludedEdges));
1705
+ }
1706
+ _getDefault() {
1707
+ if ('default' in this.spec) {
1708
+ return super._getDefault();
1709
+ }
1710
+
1711
+ // if there is no default set invent one
1712
+ if (!this._nodes.length) {
1713
+ return undefined;
1714
+ }
1715
+ let dft = {};
1716
+ this._nodes.forEach(key => {
1717
+ const field = this.fields[key];
1718
+ dft[key] = field && 'getDefault' in field ? field.getDefault() : undefined;
1719
+ });
1720
+ return dft;
1721
+ }
1722
+ setFields(shape, excludedEdges) {
1723
+ let next = this.clone();
1724
+ next.fields = shape;
1725
+ next._nodes = sortFields(shape, excludedEdges);
1726
+ next._sortErrors = sortByKeyOrder(Object.keys(shape));
1727
+ // XXX: this carries over edges which may not be what you want
1728
+ if (excludedEdges) next._excludedEdges = excludedEdges;
1729
+ return next;
1730
+ }
1731
+ shape(additions, excludes = []) {
1732
+ return this.clone().withMutation(next => {
1733
+ let edges = next._excludedEdges;
1734
+ if (excludes.length) {
1735
+ if (!Array.isArray(excludes[0])) excludes = [excludes];
1736
+ edges = [...next._excludedEdges, ...excludes];
1737
+ }
1738
+
1739
+ // XXX: excludes here is wrong
1740
+ return next.setFields(Object.assign(next.fields, additions), edges);
1741
+ });
1742
+ }
1743
+ partial() {
1744
+ const partial = {};
1745
+ for (const [key, schema] of Object.entries(this.fields)) {
1746
+ partial[key] = 'optional' in schema && schema.optional instanceof Function ? schema.optional() : schema;
1747
+ }
1748
+ return this.setFields(partial);
1749
+ }
1750
+ deepPartial() {
1751
+ const next = deepPartial(this);
1752
+ return next;
1753
+ }
1754
+ pick(keys) {
1755
+ const picked = {};
1756
+ for (const key of keys) {
1757
+ if (this.fields[key]) picked[key] = this.fields[key];
1758
+ }
1759
+ return this.setFields(picked);
1760
+ }
1761
+ omit(keys) {
1762
+ const fields = Object.assign({}, this.fields);
1763
+ for (const key of keys) {
1764
+ delete fields[key];
1765
+ }
1766
+ return this.setFields(fields);
1767
+ }
1768
+ from(from, to, alias) {
1769
+ let fromGetter = propertyExpr.getter(from, true);
1770
+ return this.transform(obj => {
1771
+ if (!obj) return obj;
1772
+ let newObj = obj;
1773
+ if (deepHas(obj, from)) {
1774
+ newObj = Object.assign({}, obj);
1775
+ if (!alias) delete newObj[from];
1776
+ newObj[to] = fromGetter(obj);
1777
+ }
1778
+ return newObj;
1779
+ });
1780
+ }
1781
+
1782
+ /** Parse an input JSON string to an object */
1783
+ json() {
1784
+ return this.transform(parseJson);
1785
+ }
1786
+ noUnknown(noAllow = true, message = object.noUnknown) {
1787
+ if (typeof noAllow !== 'boolean') {
1788
+ message = noAllow;
1789
+ noAllow = true;
1790
+ }
1791
+ let next = this.test({
1792
+ name: 'noUnknown',
1793
+ exclusive: true,
1794
+ message: message,
1795
+ test(value) {
1796
+ if (value == null) return true;
1797
+ const unknownKeys = unknown(this.schema, value);
1798
+ return !noAllow || unknownKeys.length === 0 || this.createError({
1799
+ params: {
1800
+ unknown: unknownKeys.join(', ')
1801
+ }
1802
+ });
1803
+ }
1804
+ });
1805
+ next.spec.noUnknown = noAllow;
1806
+ return next;
1807
+ }
1808
+ unknown(allow = true, message = object.noUnknown) {
1809
+ return this.noUnknown(!allow, message);
1810
+ }
1811
+ transformKeys(fn) {
1812
+ return this.transform(obj => {
1813
+ if (!obj) return obj;
1814
+ const result = {};
1815
+ for (const key of Object.keys(obj)) result[fn(key)] = obj[key];
1816
+ return result;
1817
+ });
1818
+ }
1819
+ camelCase() {
1820
+ return this.transformKeys(tinyCase.camelCase);
1821
+ }
1822
+ snakeCase() {
1823
+ return this.transformKeys(tinyCase.snakeCase);
1824
+ }
1825
+ constantCase() {
1826
+ return this.transformKeys(key => tinyCase.snakeCase(key).toUpperCase());
1827
+ }
1828
+ describe(options) {
1829
+ let base = super.describe(options);
1830
+ base.fields = {};
1831
+ for (const [key, value] of Object.entries(this.fields)) {
1832
+ var _innerOptions;
1833
+ let innerOptions = options;
1834
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
1835
+ innerOptions = Object.assign({}, innerOptions, {
1836
+ parent: innerOptions.value,
1837
+ value: innerOptions.value[key]
1838
+ });
1839
+ }
1840
+ base.fields[key] = value.describe(innerOptions);
1841
+ }
1842
+ return base;
1843
+ }
1844
+ }
1845
+ create$3.prototype = ObjectSchema.prototype;
1846
+
1847
+ const RegExZip = /^\d{5}/;
1848
+ const BillingFormSchema = create$3({
1849
+ // name: string().required('Enter name'),
1850
+ address_line1: create$6().required('Enter street address'),
1851
+ address_line2: create$6(),
1852
+ address_city: create$6().required('Enter city'),
1853
+ address_state: create$6().required('Choose state'),
1854
+ address_postal_code: create$6()
1855
+ .required('Enter ZIP')
1856
+ .matches(RegExZip, 'Enter a valid ZIP')
1857
+ .min(5, 'Enter a valid ZIP')
1858
+ });
1859
+
1860
+ const StateOptions = [
1861
+ {
1862
+ label: 'Choose state',
1863
+ value: ''
1864
+ },
1865
+ {
1866
+ label: 'Alabama',
1867
+ value: 'AL'
1868
+ },
1869
+ {
1870
+ label: 'Alaska',
1871
+ value: 'AK'
1872
+ },
1873
+ {
1874
+ label: 'American Samoa',
1875
+ value: 'AS'
1876
+ },
1877
+ {
1878
+ label: 'Arizona',
1879
+ value: 'AZ'
1880
+ },
1881
+ {
1882
+ label: 'Arkansas',
1883
+ value: 'AR'
1884
+ },
1885
+ {
1886
+ label: 'California',
1887
+ value: 'CA'
1888
+ },
1889
+ {
1890
+ label: 'Colorado',
1891
+ value: 'CO'
1892
+ },
1893
+ {
1894
+ label: 'Connecticut',
1895
+ value: 'CT'
1896
+ },
1897
+ {
1898
+ label: 'Delaware',
1899
+ value: 'DE'
1900
+ },
1901
+ {
1902
+ label: 'District Of Columbia',
1903
+ value: 'DC'
1904
+ },
1905
+ {
1906
+ label: 'Federated States Of Micronesia',
1907
+ value: 'FM'
1908
+ },
1909
+ {
1910
+ label: 'Florida',
1911
+ value: 'FL'
1912
+ },
1913
+ {
1914
+ label: 'Georgia',
1915
+ value: 'GA'
1916
+ },
1917
+ {
1918
+ label: 'Guam',
1919
+ value: 'GU'
1920
+ },
1921
+ {
1922
+ label: 'Hawaii',
1923
+ value: 'HI'
1924
+ },
1925
+ {
1926
+ label: 'Idaho',
1927
+ value: 'ID'
1928
+ },
1929
+ {
1930
+ label: 'Illinois',
1931
+ value: 'IL'
1932
+ },
1933
+ {
1934
+ label: 'Indiana',
1935
+ value: 'IN'
1936
+ },
1937
+ {
1938
+ label: 'Iowa',
1939
+ value: 'IA'
1940
+ },
1941
+ {
1942
+ label: 'Kansas',
1943
+ value: 'KS'
1944
+ },
1945
+ {
1946
+ label: 'Kentucky',
1947
+ value: 'KY'
1948
+ },
1949
+ {
1950
+ label: 'Louisiana',
1951
+ value: 'LA'
1952
+ },
1953
+ {
1954
+ label: 'Maine',
1955
+ value: 'ME'
1956
+ },
1957
+ {
1958
+ label: 'Marshall Islands',
1959
+ value: 'MH'
1960
+ },
1961
+ {
1962
+ label: 'Maryland',
1963
+ value: 'MD'
1964
+ },
1965
+ {
1966
+ label: 'Massachusetts',
1967
+ value: 'MA'
1968
+ },
1969
+ {
1970
+ label: 'Michigan',
1971
+ value: 'MI'
1972
+ },
1973
+ {
1974
+ label: 'Minnesota',
1975
+ value: 'MN'
1976
+ },
1977
+ {
1978
+ label: 'Mississippi',
1979
+ value: 'MS'
1980
+ },
1981
+ {
1982
+ label: 'Missouri',
1983
+ value: 'MO'
1984
+ },
1985
+ {
1986
+ label: 'Montana',
1987
+ value: 'MT'
1988
+ },
1989
+ {
1990
+ label: 'Nebraska',
1991
+ value: 'NE'
1992
+ },
1993
+ {
1994
+ label: 'Nevada',
1995
+ value: 'NV'
1996
+ },
1997
+ {
1998
+ label: 'New Hampshire',
1999
+ value: 'NH'
2000
+ },
2001
+ {
2002
+ label: 'New Jersey',
2003
+ value: 'NJ'
2004
+ },
2005
+ {
2006
+ label: 'New Mexico',
2007
+ value: 'NM'
2008
+ },
2009
+ {
2010
+ label: 'New York',
2011
+ value: 'NY'
2012
+ },
2013
+ {
2014
+ label: 'North Carolina',
2015
+ value: 'NC'
2016
+ },
2017
+ {
2018
+ label: 'North Dakota',
2019
+ value: 'ND'
2020
+ },
2021
+ {
2022
+ label: 'Northern Mariana Islands',
2023
+ value: 'MP'
2024
+ },
2025
+ {
2026
+ label: 'Ohio',
2027
+ value: 'OH'
2028
+ },
2029
+ {
2030
+ label: 'Oklahoma',
2031
+ value: 'OK'
2032
+ },
2033
+ {
2034
+ label: 'Oregon',
2035
+ value: 'OR'
2036
+ },
2037
+ {
2038
+ label: 'Palau',
2039
+ value: 'PW'
2040
+ },
2041
+ {
2042
+ label: 'Pennsylvania',
2043
+ value: 'PA'
2044
+ },
2045
+ {
2046
+ label: 'Puerto Rico',
2047
+ value: 'PR'
2048
+ },
2049
+ {
2050
+ label: 'Rhode Island',
2051
+ value: 'RI'
2052
+ },
2053
+ {
2054
+ label: 'South Carolina',
2055
+ value: 'SC'
2056
+ },
2057
+ {
2058
+ label: 'South Dakota',
2059
+ value: 'SD'
2060
+ },
2061
+ {
2062
+ label: 'Tennessee',
2063
+ value: 'TN'
2064
+ },
2065
+ {
2066
+ label: 'Texas',
2067
+ value: 'TX'
2068
+ },
2069
+ {
2070
+ label: 'Utah',
2071
+ value: 'UT'
2072
+ },
2073
+ {
2074
+ label: 'Vermont',
2075
+ value: 'VT'
2076
+ },
2077
+ {
2078
+ label: 'Virgin Islands',
2079
+ value: 'VI'
2080
+ },
2081
+ {
2082
+ label: 'Virginia',
2083
+ value: 'VA'
2084
+ },
2085
+ {
2086
+ label: 'Washington',
2087
+ value: 'WA'
2088
+ },
2089
+ {
2090
+ label: 'West Virginia',
2091
+ value: 'WV'
2092
+ },
2093
+ {
2094
+ label: 'Wisconsin',
2095
+ value: 'WI'
2096
+ },
2097
+ {
2098
+ label: 'Wyoming',
2099
+ value: 'WY'
2100
+ }
2101
+ ];
2102
+
2103
+ const billingFormCss = ":host{display:block}label{display:block}input{margin-bottom:8px}";
2104
+
2105
+ const BillingForm = class {
2106
+ constructor(hostRef) {
2107
+ registerInstance(this, hostRef);
2108
+ this.billingFields = {
2109
+ address_line1: '',
2110
+ address_line2: '',
2111
+ address_city: '',
2112
+ address_state: '',
2113
+ address_postal_code: ''
2114
+ };
2115
+ this.billingFieldsErrors = {};
2116
+ }
2117
+ setFormValue(event) {
2118
+ const data = event.detail;
2119
+ const billingFieldsClone = Object.assign({}, this.billingFields);
2120
+ if (data.name) {
2121
+ billingFieldsClone[data.name] = data.value;
2122
+ this.billingFields = billingFieldsClone;
2123
+ }
2124
+ }
2125
+ async validate() {
2126
+ const newErrors = {};
2127
+ let isValid = true;
2128
+ try {
2129
+ await BillingFormSchema.validate(this.billingFields, { abortEarly: false });
2130
+ }
2131
+ catch (err) {
2132
+ isValid = false;
2133
+ err.inner.map((item) => {
2134
+ newErrors[item.path] = item.message;
2135
+ });
2136
+ }
2137
+ this.billingFieldsErrors = newErrors;
2138
+ return { isValid: isValid };
2139
+ }
2140
+ render() {
2141
+ return (h(Host, null, h("fieldset", null, h("text-input", { name: "address_line1", label: "Street Address", defaultValue: this.billingFields.address_line1, error: this.billingFieldsErrors.address_line1 }), h("text-input", { name: "address_line2", label: "Apartment, Suite, etc. (optional)", defaultValue: this.billingFields.address_line2, error: this.billingFieldsErrors.address_line2 }), h("text-input", { name: "address_city", label: "City", defaultValue: this.billingFields.address_city, error: this.billingFieldsErrors.address_city }), h("select-input", { name: "address_state", label: "State", options: StateOptions, defaultValue: this.billingFields.address_state, error: this.billingFieldsErrors.address_state }), h("text-input", { name: "address_postal_code", label: "ZIP", defaultValue: this.billingFields.address_postal_code, error: this.billingFieldsErrors.address_postal_code }))));
2142
+ }
2143
+ };
2144
+ BillingForm.style = billingFormCss;
2145
+
2146
+ export { BillingForm as justifi_billing_form };