vest 3.2.4-dev-c9788a → 3.2.7

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 (70) hide show
  1. package/README.md +115 -0
  2. package/any.d.ts +3 -0
  3. package/any.js +1 -0
  4. package/classNames.d.ts +14 -0
  5. package/classNames.js +1 -0
  6. package/docs/.nojekyll +0 -0
  7. package/docs/README.md +115 -0
  8. package/docs/_assets/favicon.ico +0 -0
  9. package/docs/_assets/vest-logo.png +0 -0
  10. package/docs/_sidebar.md +19 -0
  11. package/docs/_sidebar.md.bak +14 -0
  12. package/docs/cross_field_validations.md +79 -0
  13. package/docs/enforce.md +18 -0
  14. package/docs/enforce.md.bak +13 -0
  15. package/docs/exclusion.md +128 -0
  16. package/docs/getting_started.md +79 -0
  17. package/docs/group.md +142 -0
  18. package/docs/index.html +41 -0
  19. package/docs/migration.md +107 -0
  20. package/docs/n4s/compound.md +187 -0
  21. package/docs/n4s/custom.md +52 -0
  22. package/docs/n4s/external.md +54 -0
  23. package/docs/n4s/rules.md +1282 -0
  24. package/docs/n4s/template.md +53 -0
  25. package/docs/node.md +43 -0
  26. package/docs/optional.md +51 -0
  27. package/docs/result.md +238 -0
  28. package/docs/state.md +102 -0
  29. package/docs/test.md +172 -0
  30. package/docs/utilities.md +105 -0
  31. package/docs/warn.md +82 -0
  32. package/enforce.d.ts +230 -0
  33. package/esm/package.json +1 -0
  34. package/esm/vest.es.development.js +2493 -0
  35. package/esm/vest.es.production.js +2490 -0
  36. package/esm/vest.es.production.min.js +1 -0
  37. package/package.json +65 -12
  38. package/promisify.d.ts +7 -0
  39. package/{dist/umd/promisify.production.js → promisify.js} +1 -1
  40. package/schema.d.ts +26 -0
  41. package/schema.js +1 -0
  42. package/vest.cjs.development.js +2494 -0
  43. package/vest.cjs.production.js +2491 -0
  44. package/vest.cjs.production.min.js +1 -0
  45. package/vest.d.ts +249 -0
  46. package/vest.js +7 -0
  47. package/vest.umd.development.js +2711 -0
  48. package/vest.umd.production.js +2708 -0
  49. package/vest.umd.production.min.js +1 -0
  50. package/vestResult.d.ts +105 -0
  51. package/CHANGELOG.md +0 -52
  52. package/LICENSE +0 -21
  53. package/dist/cjs/classnames.development.js +0 -67
  54. package/dist/cjs/classnames.production.js +0 -1
  55. package/dist/cjs/promisify.development.js +0 -20
  56. package/dist/cjs/promisify.production.js +0 -1
  57. package/dist/cjs/vest.development.js +0 -1616
  58. package/dist/cjs/vest.production.js +0 -1
  59. package/dist/es/classnames.development.js +0 -65
  60. package/dist/es/classnames.production.js +0 -1
  61. package/dist/es/promisify.development.js +0 -18
  62. package/dist/es/promisify.production.js +0 -1
  63. package/dist/es/vest.development.js +0 -1604
  64. package/dist/es/vest.production.js +0 -1
  65. package/dist/umd/classnames.development.js +0 -73
  66. package/dist/umd/classnames.production.js +0 -1
  67. package/dist/umd/promisify.development.js +0 -26
  68. package/dist/umd/vest.development.js +0 -1622
  69. package/dist/umd/vest.production.js +0 -1
  70. package/index.js +0 -7
@@ -0,0 +1,2490 @@
1
+ function createState(onStateChange) {
2
+ var state = {
3
+ references: []
4
+ };
5
+ var registrations = [];
6
+ return {
7
+ registerStateKey: registerStateKey,
8
+ reset: reset
9
+ };
10
+ /**
11
+ * Registers a new key in the state, takes the initial value (may be a function that returns the initial value), returns a function.
12
+ *
13
+ * @example
14
+ *
15
+ * const useColor = state.registerStateKey("blue");
16
+ *
17
+ * let [color, setColor] = useColor(); // -> ["blue", Function]
18
+ *
19
+ * setColor("green");
20
+ *
21
+ * useColor()[0]; -> "green"
22
+ */
23
+
24
+ function registerStateKey(initialState, onUpdate) {
25
+ var key = registrations.length;
26
+ registrations.push([initialState, onUpdate]);
27
+ return initKey(key, initialState);
28
+ }
29
+
30
+ function reset() {
31
+ state.references = [];
32
+ registrations.forEach(function (_ref, index) {
33
+ var initialValue = _ref[0];
34
+ return initKey(index, initialValue);
35
+ });
36
+ }
37
+
38
+ function initKey(key, initialState) {
39
+ current().push();
40
+ set(key, optionalFunctionValue$1(initialState));
41
+ return function useStateKey() {
42
+ return [current()[key], function (nextState) {
43
+ return set(key, optionalFunctionValue$1(nextState, [current()[key]]));
44
+ }];
45
+ };
46
+ }
47
+
48
+ function current() {
49
+ return state.references;
50
+ }
51
+
52
+ function set(key, value) {
53
+ var prevValue = state.references[key];
54
+ state.references[key] = value;
55
+ var _registrations$key = registrations[key],
56
+ onUpdate = _registrations$key[1];
57
+
58
+ if (isFunction$1(onUpdate)) {
59
+ onUpdate(value, prevValue);
60
+ }
61
+
62
+ if (isFunction$1(onStateChange)) {
63
+ onStateChange();
64
+ }
65
+ }
66
+ }
67
+
68
+ function isFunction$1(f) {
69
+ return typeof f === 'function';
70
+ }
71
+
72
+ function optionalFunctionValue$1(value, args) {
73
+ return isFunction$1(value) ? value.apply(null, args) : value;
74
+ }
75
+
76
+ function asArray(possibleArg) {
77
+ return [].concat(possibleArg);
78
+ }
79
+
80
+ function createStateRef(state, {
81
+ suiteId,
82
+ name
83
+ }) {
84
+ return {
85
+ carryOverTests: state.registerStateKey(() => []),
86
+ optionalFields: state.registerStateKey(() => ({})),
87
+ pending: state.registerStateKey(() => ({
88
+ pending: [],
89
+ lagging: []
90
+ })),
91
+ skippedTests: state.registerStateKey(() => []),
92
+ suiteId: state.registerStateKey(() => ({
93
+ id: suiteId,
94
+ name
95
+ })),
96
+ testCallbacks: state.registerStateKey(() => ({
97
+ fieldCallbacks: {},
98
+ doneCallbacks: []
99
+ })),
100
+ testObjects: state.registerStateKey(() => [])
101
+ };
102
+ }
103
+
104
+ function _extends() {
105
+ _extends = Object.assign || function (target) {
106
+ for (var i = 1; i < arguments.length; i++) {
107
+ var source = arguments[i];
108
+
109
+ for (var key in source) {
110
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
111
+ target[key] = source[key];
112
+ }
113
+ }
114
+ }
115
+
116
+ return target;
117
+ };
118
+
119
+ return _extends.apply(this, arguments);
120
+ }
121
+
122
+ function createContext(init) {
123
+ var storage = {
124
+ ancestry: []
125
+ };
126
+ return {
127
+ run: run,
128
+ bind: bind,
129
+ use: use
130
+ };
131
+
132
+ function run(ctxRef, fn) {
133
+ var _init;
134
+
135
+ var parentContext = use();
136
+
137
+ var out = _extends({}, parentContext ? parentContext : {}, (_init = init === null || init === void 0 ? void 0 : init(ctxRef, parentContext)) !== null && _init !== void 0 ? _init : ctxRef);
138
+
139
+ var ctx = set(Object.freeze(out));
140
+ storage.ancestry.unshift(ctx);
141
+ var res = fn(ctx);
142
+ clear();
143
+ return res;
144
+ }
145
+
146
+ function bind(ctxRef, fn) {
147
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
148
+ args[_key - 2] = arguments[_key];
149
+ }
150
+
151
+ return function () {
152
+ for (var _len2 = arguments.length, runTimeArgs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
153
+ runTimeArgs[_key2] = arguments[_key2];
154
+ }
155
+
156
+ return run(ctxRef, function () {
157
+ return fn.apply(void 0, args.concat(runTimeArgs));
158
+ });
159
+ };
160
+ }
161
+
162
+ function use() {
163
+ return storage.ctx;
164
+ }
165
+
166
+ function set(value) {
167
+ return storage.ctx = value;
168
+ }
169
+
170
+ function clear() {
171
+ var _storage$ancestry$;
172
+
173
+ storage.ancestry.shift();
174
+ set((_storage$ancestry$ = storage.ancestry[0]) !== null && _storage$ancestry$ !== void 0 ? _storage$ancestry$ : null);
175
+ }
176
+ }
177
+
178
+ var assign = Object.assign;
179
+
180
+ const EXCLUSION_ITEM_TYPE_TESTS = 'tests';
181
+ const EXCLUSION_ITEM_TYPE_GROUPS = 'groups';
182
+
183
+ const context = createContext((ctxRef, parentContext) => parentContext ? null : assign({}, {
184
+ exclusion: {
185
+ [EXCLUSION_ITEM_TYPE_TESTS]: {},
186
+ [EXCLUSION_ITEM_TYPE_GROUPS]: {}
187
+ }
188
+ }, ctxRef));
189
+
190
+ /**
191
+ * @returns a unique numeric id.
192
+ */
193
+ const id = (n => () => `${n++}`)(0);
194
+
195
+ function isFunction (v) {
196
+ return typeof v === 'function';
197
+ }
198
+
199
+ function bindNot(fn) {
200
+ return function () {
201
+ return !fn.apply(this, arguments);
202
+ };
203
+ }
204
+
205
+ function isNull(value) {
206
+ return value === null;
207
+ }
208
+ const isNotNull = bindNot(isNull);
209
+
210
+ function lengthEquals(value, arg1) {
211
+ return value.length === Number(arg1);
212
+ }
213
+ const lengthNotEquals = bindNot(lengthEquals);
214
+
215
+ /**
216
+ * Creates a cache function
217
+ * @param {number} [maxSize] Max cache size
218
+ * @return {Function} cache function
219
+ */
220
+
221
+ const createCache = (maxSize = 10) => {
222
+ const cacheStorage = [];
223
+ /**
224
+ * @param {Any[]} deps dependency array.
225
+ * @param {Function} cache action function.
226
+ */
227
+
228
+ const cache = (deps, cacheAction) => {
229
+ const cacheHit = cache.get(deps);
230
+
231
+ if (isNotNull(cacheHit)) {
232
+ return cacheHit[1];
233
+ }
234
+
235
+ const result = cacheAction();
236
+ cacheStorage.unshift([deps.concat(), result]);
237
+
238
+ if (cacheStorage.length > maxSize) {
239
+ cacheStorage.length = maxSize;
240
+ }
241
+
242
+ return result;
243
+ };
244
+ /**
245
+ * Retrieves an item from the cache.
246
+ * @param {deps} deps Dependency array
247
+ */
248
+
249
+
250
+ cache.get = deps => cacheStorage[cacheStorage.findIndex(([cachedDeps]) => lengthEquals(deps, cachedDeps.length) && deps.every((dep, i) => dep === cachedDeps[i]))] || null;
251
+
252
+ return cache;
253
+ };
254
+
255
+ const SEVERITY_GROUP_WARN = 'warnings';
256
+ const SEVERITY_COUNT_WARN = 'warnCount';
257
+ const SEVERITY_GROUP_ERROR = 'errors';
258
+ const SEVERITY_COUNT_ERROR = 'errorCount';
259
+ const TEST_COUNT = 'testCount';
260
+
261
+ const getStateRef = () => context.use().stateRef;
262
+
263
+ function useCarryOverTests() {
264
+ return getStateRef().carryOverTests();
265
+ }
266
+ function usePending() {
267
+ return getStateRef().pending();
268
+ }
269
+ function useSuiteId() {
270
+ return getStateRef().suiteId();
271
+ }
272
+ function useTestCallbacks() {
273
+ return getStateRef().testCallbacks();
274
+ }
275
+ function useTestObjects() {
276
+ return getStateRef().testObjects();
277
+ }
278
+ function useSkippedTests() {
279
+ return getStateRef().skippedTests();
280
+ }
281
+ function useOptionalFields() {
282
+ return getStateRef().optionalFields();
283
+ }
284
+
285
+ /**
286
+ * Reads the testObjects list and gets full validation result from it.
287
+ */
288
+
289
+ const genTestsSummary = () => {
290
+ const [testObjects] = useTestObjects();
291
+ const [suiteIdState] = useSuiteId();
292
+ const [skippedTests] = useSkippedTests();
293
+ const summary = {
294
+ [SEVERITY_COUNT_ERROR]: 0,
295
+ [SEVERITY_COUNT_WARN]: 0,
296
+ [TEST_COUNT]: 0,
297
+ groups: {},
298
+ name: suiteIdState.name,
299
+ tests: {}
300
+ };
301
+ appendSummary(testObjects);
302
+ appendSummary(skippedTests, true);
303
+ return countFailures(summary);
304
+
305
+ function appendSummary(testObject, skipped) {
306
+ testObject.forEach(testObject => {
307
+ const {
308
+ fieldName,
309
+ groupName
310
+ } = testObject;
311
+ summary.tests[fieldName] = genTestObject(summary.tests, testObject, skipped);
312
+
313
+ if (groupName) {
314
+ summary.groups[groupName] = summary.groups[groupName] || {};
315
+ summary.groups[groupName][fieldName] = genTestObject(summary.groups[groupName], testObject, skipped);
316
+ }
317
+ });
318
+ }
319
+ };
320
+ /**
321
+ * Counts the failed tests and adds global counters
322
+ * @param {Object} summary (generated by genTestsSummary)
323
+ */
324
+
325
+
326
+ const countFailures = summary => {
327
+ for (const test in summary.tests) {
328
+ summary[SEVERITY_COUNT_ERROR] += summary.tests[test][SEVERITY_COUNT_ERROR];
329
+ summary[SEVERITY_COUNT_WARN] += summary.tests[test][SEVERITY_COUNT_WARN];
330
+ summary[TEST_COUNT] += summary.tests[test][TEST_COUNT];
331
+ }
332
+
333
+ return summary;
334
+ };
335
+ /**
336
+ *
337
+ * @param {Object} summaryKey The container for the test result data
338
+ * @param {VestTest} testObject
339
+ * @returns {Object} Test result summary
340
+ */
341
+
342
+ const genTestObject = (summaryKey, testObject, skipped) => {
343
+ const {
344
+ fieldName,
345
+ isWarning,
346
+ failed,
347
+ statement
348
+ } = testObject;
349
+ summaryKey[fieldName] = summaryKey[fieldName] || {
350
+ [SEVERITY_COUNT_ERROR]: 0,
351
+ [SEVERITY_COUNT_WARN]: 0,
352
+ [TEST_COUNT]: 0
353
+ };
354
+ const testKey = summaryKey[fieldName];
355
+
356
+ if (skipped) {
357
+ return testKey;
358
+ }
359
+
360
+ summaryKey[fieldName][TEST_COUNT]++; // Adds to severity group
361
+
362
+ const addTo = (count, group) => {
363
+ testKey[count]++;
364
+
365
+ if (statement) {
366
+ testKey[group] = (testKey[group] || []).concat(statement);
367
+ }
368
+ };
369
+
370
+ if (failed) {
371
+ if (isWarning) {
372
+ addTo(SEVERITY_COUNT_WARN, SEVERITY_GROUP_WARN);
373
+ } else {
374
+ addTo(SEVERITY_COUNT_ERROR, SEVERITY_GROUP_ERROR);
375
+ }
376
+ }
377
+
378
+ return testKey;
379
+ };
380
+
381
+ /**
382
+ * Checks that a given test object matches the currently specified severity level
383
+ * @param {string} severity Represents severity level
384
+ * @param {VestTest} testObject VestTest instance
385
+ * @returns {boolean}
386
+ */
387
+
388
+ function isMatchingSeverityProfile(severity, testObject) {
389
+ return severity !== SEVERITY_GROUP_WARN && testObject.isWarning || severity === SEVERITY_GROUP_WARN && !testObject.isWarning;
390
+ }
391
+
392
+ /**
393
+ * @param {'warn'|'error'} severity Filter by severity.
394
+ * @param {Object} options
395
+ * @param {String} [options.group] Group name for error lookup.
396
+ * @param {String} [options.fieldName] Field name for error lookup.
397
+ * @returns all messages for given criteria.
398
+ */
399
+
400
+ const collectFailureMessages = (severity, options) => {
401
+ const [testObjects] = useTestObjects();
402
+ const {
403
+ group,
404
+ fieldName
405
+ } = options || {};
406
+ const res = testObjects.reduce((collector, testObject) => {
407
+ if (group && testObject.groupName !== group) {
408
+ return collector;
409
+ }
410
+
411
+ if (fieldName && testObject.fieldName !== fieldName) {
412
+ return collector;
413
+ }
414
+
415
+ if (!testObject.failed) {
416
+ return collector;
417
+ }
418
+
419
+ if (isMatchingSeverityProfile(severity, testObject)) {
420
+ return collector;
421
+ }
422
+
423
+ collector[testObject.fieldName] = (collector[testObject.fieldName] || []).concat(testObject.statement);
424
+ return collector;
425
+ }, {});
426
+
427
+ if (fieldName) {
428
+ return res[fieldName] || [];
429
+ } else {
430
+ return res;
431
+ }
432
+ };
433
+
434
+ /**
435
+ * @param {'errors'|'warnings'} severityKey lookup severity
436
+ * @param {string} [fieldName]
437
+ * @returns suite or field's errors or warnings.
438
+ */
439
+
440
+ function getFailures(severityKey, fieldName) {
441
+ return collectFailureMessages(severityKey, {
442
+ fieldName
443
+ });
444
+ }
445
+
446
+ /**
447
+ * Throws a timed out error.
448
+ * @param {String} message Error message to display.
449
+ * @param {Error} [type] Alternative Error type.
450
+ */
451
+ const throwError = (message, type = Error) => {
452
+ throw new type(`[${"vest"}]: ${message}`);
453
+ };
454
+
455
+ /**
456
+ * Gets failure messages by group.
457
+ * @param {'errors'|'warnings'} severityKey lookup severity
458
+ * @param {string} group Group name.
459
+ * @param {string} [fieldName] Field name.
460
+ */
461
+
462
+ const getByGroup = (severityKey, group, fieldName) => {
463
+ if (!group) {
464
+ throwError(`get${severityKey[0].toUpperCase()}${severityKey.slice(1)}ByGroup requires a group name. Received \`${group}\` instead.`);
465
+ }
466
+
467
+ return collectFailureMessages(severityKey, {
468
+ group,
469
+ fieldName
470
+ });
471
+ };
472
+
473
+ /**
474
+ * Determines whether a certain test profile has failures.
475
+ * @param {VestTest} testObject
476
+ * @param {'warnings'|'errors'} severityKey lookup severity
477
+ * @param {string} [fieldName]
478
+ * @returns {Boolean}
479
+ */
480
+
481
+ const hasLogic = (testObject, severityKey, fieldName) => {
482
+ if (!testObject.failed) {
483
+ return false;
484
+ }
485
+
486
+ if (fieldName && fieldName !== testObject.fieldName) {
487
+ return false;
488
+ }
489
+
490
+ if (isMatchingSeverityProfile(severityKey, testObject)) {
491
+ return false;
492
+ }
493
+
494
+ return true;
495
+ };
496
+ /**
497
+ * @param {'warnings'|'errors'} severityKey lookup severity
498
+ * @param {string} [fieldName]
499
+ * @returns {Boolean} whether a suite or field have errors or warnings.
500
+ */
501
+
502
+ const has = (severityKey, fieldName) => {
503
+ const [testObjects] = useTestObjects();
504
+ return testObjects.some(testObject => hasLogic(testObject, severityKey, fieldName));
505
+ };
506
+
507
+ /**
508
+ * Checks whether there are failures in a given group.
509
+ * @param {'errors'|'warnings'} severityKey lookup severity
510
+ * @param {string} group Group name.
511
+ * @param {string} [fieldName] Field name.
512
+ * @return {boolean}
513
+ */
514
+
515
+ const hasByGroup = (severityKey, group, fieldName) => {
516
+ const [testObjects] = useTestObjects();
517
+ return testObjects.some(testObject => {
518
+ if (group !== testObject.groupName) {
519
+ return false;
520
+ }
521
+
522
+ return hasLogic(testObject, severityKey, fieldName);
523
+ });
524
+ };
525
+
526
+ /**
527
+ * A safe hasOwnProperty access
528
+ */
529
+ function hasOwnProperty(obj, key) {
530
+ return Object.prototype.hasOwnProperty.call(obj, key);
531
+ }
532
+
533
+ function isNumeric(value) {
534
+ const result = !isNaN(parseFloat(value)) && !isNaN(Number(value)) && isFinite(value);
535
+ return Boolean(result);
536
+ }
537
+ const isNotNumeric = bindNot(isNumeric);
538
+
539
+ function isEmpty(value) {
540
+ if (!value) {
541
+ return true;
542
+ } else if (isNumeric(value)) {
543
+ return value === 0;
544
+ } else if (hasOwnProperty(value, 'length')) {
545
+ return lengthEquals(value, 0);
546
+ } else if (typeof value === 'object') {
547
+ return lengthEquals(Object.keys(value), 0);
548
+ }
549
+
550
+ return true;
551
+ }
552
+ const isNotEmpty = bindNot(isEmpty);
553
+
554
+ /**
555
+ * Checks if a given tests, or the suite as a whole still have remaining tests.
556
+ * @param {string} [fieldName]
557
+ * @returns {Boolean}
558
+ */
559
+
560
+ const hasRemainingTests = fieldName => {
561
+ const [{
562
+ pending,
563
+ lagging
564
+ }] = usePending();
565
+ const allIncomplete = pending.concat(lagging);
566
+
567
+ if (isEmpty(allIncomplete)) {
568
+ return false;
569
+ }
570
+
571
+ if (fieldName) {
572
+ return allIncomplete.some(testObject => testObject.fieldName === fieldName);
573
+ }
574
+
575
+ return isNotEmpty(allIncomplete);
576
+ };
577
+
578
+ const HAS_WARNINGS = 'hasWarnings';
579
+ const HAS_ERRORS = 'hasErrors';
580
+
581
+ function setFnName(fn, value) {
582
+ var _Object$getOwnPropert;
583
+
584
+ // Pre ES2015 non standard implementation, "Function.name" is non configurable field
585
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
586
+ return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(fn, 'name')) !== null && _Object$getOwnPropert !== void 0 && _Object$getOwnPropert.configurable ? Object.defineProperty(fn, 'name', {
587
+ value
588
+ }) : fn;
589
+ }
590
+
591
+ /**
592
+ * ES5 Transpilation increases the size of spread arguments by a lot.
593
+ * Wraps a function and passes its spread params as an array.
594
+ *
595
+ * @param {Function} cb
596
+ * @param {String} [fnName]
597
+ * @return {Function}
598
+ */
599
+
600
+ function withArgs(cb, fnName) {
601
+ return setFnName(function () {
602
+ const args = Array.from(arguments);
603
+ const right = args.splice(cb.length - 1);
604
+ return cb.apply(null, args.concat([right]));
605
+ }, fnName || cb.name);
606
+ }
607
+
608
+ const cache = createCache(20);
609
+ /**
610
+ * @param {boolean} [isDraft]
611
+ * @returns Vest output object.
612
+ */
613
+
614
+ const produce = isDraft => {
615
+ const {
616
+ stateRef
617
+ } = context.use();
618
+ const [testObjects] = useTestObjects();
619
+ const ctxRef = {
620
+ stateRef
621
+ };
622
+ return cache([testObjects, isDraft], context.bind(ctxRef, () => [[HAS_ERRORS, has, SEVERITY_GROUP_ERROR], [HAS_WARNINGS, has, SEVERITY_GROUP_WARN], ['getErrors', getFailures, SEVERITY_GROUP_ERROR], ['getWarnings', getFailures, SEVERITY_GROUP_WARN], ['hasErrorsByGroup', hasByGroup, SEVERITY_GROUP_ERROR], ['hasWarningsByGroup', hasByGroup, SEVERITY_GROUP_WARN], ['getErrorsByGroup', getByGroup, SEVERITY_GROUP_ERROR], ['getWarningsByGroup', getByGroup, SEVERITY_GROUP_WARN]].concat([['isValid', isValid]], isDraft ? [] : [['done', withArgs(done)]]).reduce((properties, [name, fn, severityKey]) => {
623
+ properties[name] = context.bind(ctxRef, fn, severityKey);
624
+ return properties;
625
+ }, genTestsSummary())));
626
+ };
627
+ /**
628
+ * Registers done callbacks.
629
+ * @param {string} [fieldName]
630
+ * @param {Function} doneCallback
631
+ * @register {Object} Vest output object.
632
+ */
633
+
634
+ function done(args) {
635
+ const [callback, fieldName] = args.reverse();
636
+ const {
637
+ stateRef
638
+ } = context.use();
639
+ const output = produce(); // If we do not have any test runs for the current field
640
+
641
+ const shouldSkipRegistration = fieldName && (!output.tests[fieldName] || output.tests[fieldName].testCount === 0);
642
+
643
+ if (!isFunction(callback) || shouldSkipRegistration) {
644
+ return output;
645
+ }
646
+
647
+ const cb = context.bind({
648
+ stateRef
649
+ }, () => callback(produce(
650
+ /*isDraft:*/
651
+ true))); // is suite finished || field name exists, and test is finished
652
+
653
+ const shouldRunCallback = !hasRemainingTests() || fieldName && !hasRemainingTests(fieldName);
654
+
655
+ if (shouldRunCallback) {
656
+ cb();
657
+ return output;
658
+ }
659
+
660
+ const [, setTestCallbacks] = useTestCallbacks();
661
+ setTestCallbacks(current => {
662
+ if (fieldName) {
663
+ current.fieldCallbacks[fieldName] = (current.fieldCallbacks[fieldName] || []).concat(cb);
664
+ } else {
665
+ current.doneCallbacks.push(cb);
666
+ }
667
+
668
+ return current;
669
+ });
670
+ return output;
671
+ }
672
+
673
+ function isValid() {
674
+ const result = produce();
675
+
676
+ if (result.hasErrors()) {
677
+ return false;
678
+ }
679
+
680
+ const [testObjects] = useTestObjects();
681
+
682
+ if (testObjects.length === 0) {
683
+ return false;
684
+ }
685
+
686
+ const [optionalFields] = useOptionalFields();
687
+ const [{
688
+ pending,
689
+ lagging
690
+ }] = usePending();
691
+
692
+ if (isNotEmpty(pending.concat(lagging).filter(testObject => !testObject.isWarning))) {
693
+ return false;
694
+ }
695
+
696
+ for (const test in result.tests) {
697
+ if (!optionalFields[test] && result.tests[test].testCount === 0) {
698
+ return false;
699
+ }
700
+ }
701
+
702
+ return true;
703
+ }
704
+
705
+ /**
706
+ * Initializes a validation suite, creates a validation context.
707
+ * @param {String} [name] Identifier for validation suite.
708
+ * @param {Function} tests Validation suite body.
709
+ * @returns {Function} validator function.
710
+ */
711
+
712
+ const createSuite = withArgs(args => {
713
+ const [tests, name] = args.reverse();
714
+
715
+ if (!isFunction(tests)) {
716
+ throwError('Suite initialization error. Expected `tests` to be a function.');
717
+ }
718
+
719
+ const handlers = [];
720
+ const state = createState(() => {
721
+ handlers.forEach(fn => fn({
722
+ suiteState: stateRef,
723
+ type: 'suiteStateUpdate'
724
+ }));
725
+ });
726
+ const stateRef = createStateRef(state, {
727
+ suiteId: id(),
728
+ name
729
+ });
730
+ /*
731
+ context.bind returns our `validate` function
732
+ We then wrap it with defineProperties to add
733
+ the `get`, and `reset` functions.
734
+ */
735
+
736
+ const suite = context.bind({
737
+ stateRef
738
+ }, function () {
739
+ const [previousTestObjects] = useTestObjects();
740
+ const [, setCarryOverTests] = useCarryOverTests();
741
+ const [{
742
+ pending
743
+ }, setPending] = usePending();
744
+ state.reset();
745
+ setCarryOverTests(() => previousTestObjects); // Move all the active pending tests to the lagging array
746
+
747
+ setPending({
748
+ lagging: pending,
749
+ pending: []
750
+ }); // Run the consumer's callback
751
+
752
+ tests.apply(null, arguments);
753
+ return produce();
754
+ });
755
+ suite.get = context.bind({
756
+ stateRef
757
+ }, produce,
758
+ /*isDraft:*/
759
+ true);
760
+ suite.reset = state.reset;
761
+ suite.remove = context.bind({
762
+ stateRef
763
+ }, name => {
764
+ const [testObjects] = useTestObjects(); // We're mutating the array in `cancel`, so we have to first copy it.
765
+
766
+ asArray(testObjects).forEach(testObject => {
767
+ if (testObject.fieldName === name) {
768
+ testObject.cancel();
769
+ }
770
+ });
771
+ });
772
+
773
+ suite.subscribe = function (handler) {
774
+ if (!isFunction(handler)) return;
775
+ handlers.push(handler);
776
+ handler({
777
+ type: 'suiteSubscribeInit',
778
+ suiteState: stateRef
779
+ });
780
+ };
781
+
782
+ return suite;
783
+ });
784
+
785
+ /**
786
+ * Stores values and configuration passed down to compound rules.
787
+ *
788
+ * @param {Object} content
789
+ */
790
+
791
+ function EnforceContext(content) {
792
+ assign(this, content);
793
+ }
794
+ /**
795
+ * Sets an EnforceContext config `failFast`
796
+ *
797
+ * @param {Boolean} failFast
798
+ * @return {EnforceContext}
799
+ */
800
+
801
+ EnforceContext.prototype.setFailFast = function (failFast) {
802
+ this.failFast = !!failFast;
803
+ return this;
804
+ };
805
+ /**
806
+ * Extracts the literal value from an EnforceContext object
807
+ * @param {*} value
808
+ * @return {*}
809
+ */
810
+
811
+
812
+ EnforceContext.unwrap = function unwrap(value) {
813
+ return EnforceContext.is(value) ? value.value : value;
814
+ };
815
+ /**
816
+ * Wraps a literal value within a context.
817
+ * @param {*} value
818
+ * @return {EnforceContext}
819
+ */
820
+
821
+
822
+ EnforceContext.wrap = function wrap(value) {
823
+ return EnforceContext.is(value) ? value : new EnforceContext({
824
+ value
825
+ });
826
+ };
827
+ /**
828
+ * Checks whether a given value is an EnforceContext instance
829
+ *
830
+ * @param {*} value
831
+ * @returns {boolean}
832
+ */
833
+
834
+
835
+ EnforceContext.is = function is(value) {
836
+ return value instanceof EnforceContext;
837
+ };
838
+
839
+ function isBoolean(value) {
840
+ return !!value === value;
841
+ }
842
+
843
+ const isNotBoolean = bindNot(isBoolean);
844
+
845
+ function isUndefined(value) {
846
+ return value === undefined;
847
+ }
848
+ const isNotUndefined = bindNot(isUndefined);
849
+
850
+ /**
851
+ * Stores a rule result in an easy to inspect and manipulate structure.
852
+ *
853
+ * @param {boolean|RuleResult} ruleRunResult
854
+ */
855
+
856
+ function RuleResult(ruleRunResult) {
857
+ if (isUndefined(ruleRunResult)) {
858
+ return;
859
+ }
860
+
861
+ if (isBoolean(ruleRunResult)) {
862
+ this.setFailed(!ruleRunResult);
863
+ } else {
864
+ this.extend(ruleRunResult);
865
+ }
866
+ }
867
+ /**
868
+ * Determines whether a given value is a RuleResult instance
869
+ * @param {*} res
870
+ * @return {boolean}
871
+ */
872
+
873
+ RuleResult.is = function (res) {
874
+ return res instanceof RuleResult;
875
+ };
876
+ /**
877
+ * Marks the current result object as an array
878
+ */
879
+
880
+
881
+ RuleResult.prototype.asArray = function () {
882
+ this.isArray = true;
883
+ return this;
884
+ };
885
+ /**
886
+ * @param {string} key
887
+ * @param {value} value
888
+ * @return {RuleResult} current instance
889
+ */
890
+
891
+
892
+ RuleResult.prototype.setAttribute = function (key, value) {
893
+ this[key] = value;
894
+ return this;
895
+ };
896
+ /**
897
+ * @param {boolean} failed
898
+ * @return {RuleResult} current instance
899
+ */
900
+
901
+
902
+ RuleResult.prototype.setFailed = function (failed) {
903
+ this.setAttribute(this.warn ? HAS_WARNINGS : HAS_ERRORS, failed);
904
+ return this.setAttribute('failed', failed);
905
+ };
906
+ /**
907
+ * Adds a nested result object
908
+ *
909
+ * @param {string} key
910
+ * @param {RuleResult} child
911
+ */
912
+
913
+
914
+ RuleResult.prototype.setChild = function (key, child) {
915
+ if (isNull(child)) {
916
+ return null;
917
+ }
918
+
919
+ const isWarning = this[HAS_WARNINGS] || child[HAS_WARNINGS] || child.warn || this.warn;
920
+ this.setAttribute(HAS_WARNINGS, isWarning && child.failed || false);
921
+ this.setAttribute(HAS_ERRORS, this[HAS_ERRORS] || child[HAS_ERRORS] || !isWarning && child.failed || false);
922
+ this.setFailed(this.failed || child.failed);
923
+ this.children = this.children || {};
924
+ this.children[key] = child;
925
+ return child;
926
+ };
927
+ /**
928
+ * Retrieves a child by its key
929
+ *
930
+ * @param {string} key
931
+ * @return {RuleResult|undefined}
932
+ */
933
+
934
+
935
+ RuleResult.prototype.getChild = function (key) {
936
+ return (this.children || {})[key];
937
+ };
938
+ /**
939
+ * Extends current instance with a new provided result
940
+ * @param {Boolean|RuleResult} newRes
941
+ */
942
+
943
+
944
+ RuleResult.prototype.extend = function (newRes) {
945
+ if (isNull(newRes)) {
946
+ return this;
947
+ }
948
+
949
+ const res = RuleResult.is(newRes) ? newRes : new RuleResult().setAttribute('warn', !!this.warn).setFailed(!newRes);
950
+ const failed = this.failed || res.failed;
951
+ const children = mergeChildren(res, this).children;
952
+ assign(this, res);
953
+
954
+ if (!isEmpty(children)) {
955
+ this.children = children;
956
+ }
957
+
958
+ this.setFailed(failed);
959
+ this.setAttribute(HAS_WARNINGS, !!(this[HAS_WARNINGS] || res[HAS_WARNINGS]));
960
+ this.setAttribute(HAS_ERRORS, !!(this[HAS_ERRORS] || res[HAS_ERRORS]));
961
+ };
962
+
963
+ Object.defineProperty(RuleResult.prototype, 'pass', {
964
+ get() {
965
+ return !this.failed;
966
+ }
967
+
968
+ });
969
+ /**
970
+ * Deeply merge the nested children of compound rules
971
+ *
972
+ * @param {?RuleResult} base
973
+ * @param {?RuleResult} add
974
+ * @return {RuleResult}
975
+ */
976
+
977
+ function mergeChildren(base, add) {
978
+ const isRuleResultBase = RuleResult.is(base);
979
+ const isRuleResultAdd = RuleResult.is(add); // If both base and add are result objects
980
+
981
+ if (isRuleResultBase && isRuleResultAdd) {
982
+ // Use failed if either is failing
983
+ base.setFailed(base.failed || add.failed); // If neither has a children object, or the children object is
984
+
985
+ if (isEmpty(base.children) && isEmpty(add.children)) {
986
+ return base;
987
+ } // If both have a children object
988
+
989
+
990
+ if (base.children && add.children) {
991
+ // Merge all the "right side" children back to base
992
+ for (const key in base.children) {
993
+ mergeChildren(base.children[key], add.children[key]);
994
+ } // If a child exists in "add" but not in "base", just copy the child as is
995
+
996
+
997
+ for (const key in add.children) {
998
+ if (!hasOwnProperty(base.children, key)) {
999
+ base.setChild(key, add.children[key]);
1000
+ }
1001
+ } // Return the modified base object
1002
+
1003
+
1004
+ return base; // If base has no children (but add does)
1005
+ } else if (!base.children) {
1006
+ // Use add's children
1007
+ base.children = add.children; // If add has no children
1008
+ } else if (!add.children) {
1009
+ // return base as is
1010
+ return base;
1011
+ } // If only base is `RuleResult`
1012
+
1013
+ } else if (isRuleResultBase) {
1014
+ // Return base as is
1015
+ return base; // If only add is RuleResult
1016
+ } else if (isRuleResultAdd) {
1017
+ // Return add as is
1018
+ return add;
1019
+ } // That's a weird case. Let's fail. Very unlikely.
1020
+
1021
+
1022
+ return new RuleResult(false);
1023
+ }
1024
+
1025
+ const RUN_RULE = 'run';
1026
+ const TEST_RULE = 'test';
1027
+ const MODE_ALL = 'all';
1028
+ const MODE_ONE = 'one';
1029
+ const MODE_ANY = 'any';
1030
+
1031
+ /**
1032
+ * Determines whether we should bail out of an enforcement.
1033
+ *
1034
+ * @param {EnforceContext} ctx
1035
+ * @param {RuleResult} result
1036
+ */
1037
+
1038
+ function shouldFailFast(ctx, result) {
1039
+ if (result.pass || result.warn) {
1040
+ return false;
1041
+ }
1042
+
1043
+ return !!EnforceContext.is(ctx) && ctx.failFast;
1044
+ }
1045
+
1046
+ /**
1047
+ * Runs multiple enforce rules that are passed to compounds.
1048
+ * Example: enforce.allOf(enforce.ruleOne(), enforce.ruleTwo().ruleThree())
1049
+ *
1050
+ * @param {{run: Function}[]} ruleGroups
1051
+ * @param {*} value
1052
+ * @return {RuleResult}
1053
+ */
1054
+
1055
+ function runLazyRules(ruleGroups, value) {
1056
+ const result = new RuleResult(true);
1057
+
1058
+ for (const chain of asArray(ruleGroups)) {
1059
+ if (shouldFailFast(value, result)) {
1060
+ break;
1061
+ }
1062
+
1063
+ result.extend(runLazyRule(chain, value));
1064
+ }
1065
+
1066
+ return result;
1067
+ }
1068
+ /**
1069
+ * Runs a single lazy rule
1070
+ *
1071
+ * @param {{run: Function}} ruleGroup
1072
+ * @param {*} value
1073
+ * @return {boolean|RuleResult}
1074
+ */
1075
+
1076
+ function runLazyRule(ruleGroup, value) {
1077
+ return ruleGroup[RUN_RULE](value);
1078
+ }
1079
+
1080
+ /**
1081
+ * Runs chains of rules
1082
+ *
1083
+ * @param {EnforceContext} value
1084
+ * @param {[{test: Function, run: Function}]} rules
1085
+ * @param {RuleResult} options
1086
+ */
1087
+
1088
+ function runCompoundChain(value, rules, options) {
1089
+ const result = new RuleResult(true);
1090
+
1091
+ if (isEmpty(rules)) {
1092
+ result.setFailed(true);
1093
+ }
1094
+
1095
+ const failedResults = [];
1096
+ let count = 0;
1097
+
1098
+ for (const chain of rules) {
1099
+ // Inner result for each iteration
1100
+ const currentResult = runLazyRule(chain, value);
1101
+
1102
+ if (isNull(currentResult)) {
1103
+ return null;
1104
+ }
1105
+
1106
+ const pass = currentResult.pass;
1107
+
1108
+ if (pass) {
1109
+ count++;
1110
+ } else {
1111
+ failedResults.push(currentResult);
1112
+ }
1113
+
1114
+ if (options) {
1115
+ // "anyOf" is a special case.
1116
+ // It shouldn't extend with failed results,
1117
+ // that's why we continue
1118
+ if (options.mode === MODE_ANY) {
1119
+ if (pass) {
1120
+ result.extend(currentResult);
1121
+ break;
1122
+ }
1123
+
1124
+ continue;
1125
+ }
1126
+
1127
+ result.extend(currentResult); // MODE_ALL: All must pass.
1128
+ // If one failed, exit.
1129
+
1130
+ if (options.mode === MODE_ALL) {
1131
+ if (!pass) {
1132
+ break;
1133
+ }
1134
+ } // MODE_ONE: only one must pass.
1135
+ // If more than one passed, exit.
1136
+
1137
+
1138
+ if (options.mode === MODE_ONE) {
1139
+ result.setFailed(count !== 1);
1140
+
1141
+ if (count > 1) {
1142
+ break;
1143
+ }
1144
+ }
1145
+ } else {
1146
+ result.extend(currentResult);
1147
+
1148
+ if (pass) {
1149
+ break;
1150
+ }
1151
+ }
1152
+ }
1153
+
1154
+ if (result.pass && count === 0) {
1155
+ result.setFailed(true); // In some cases we do not want to extend failures, for example - in ANY
1156
+ // when there is a valid response, so we do it before returning
1157
+
1158
+ failedResults.forEach(failedResult => result.extend(failedResult));
1159
+ }
1160
+
1161
+ return result;
1162
+ }
1163
+
1164
+ /**
1165
+ * Runs a chain of rules, making sure that all assertions pass
1166
+ *
1167
+ * @param {EnforceContext} value
1168
+ * @param {[{test: Function, run: Function}]} ruleChains
1169
+ * @return {RuleResult}
1170
+ */
1171
+
1172
+ function allOf(value, rules) {
1173
+ return runCompoundChain(value, rules, {
1174
+ mode: MODE_ALL
1175
+ });
1176
+ }
1177
+
1178
+ var allOf$1 = withArgs(allOf);
1179
+
1180
+ /**
1181
+ * Runs chains of rules, making sure
1182
+ * that at least one assertion passes
1183
+ *
1184
+ * @param {EnforceContext} value
1185
+ * @param {[{test: Function, run: Function}]} ruleChains
1186
+ * @return {RuleResult}
1187
+ */
1188
+
1189
+ function anyOf(value, ruleChains) {
1190
+ return runCompoundChain(value, ruleChains, {
1191
+ mode: MODE_ANY
1192
+ });
1193
+ }
1194
+
1195
+ var anyOf$1 = withArgs(anyOf);
1196
+
1197
+ function isArray(value) {
1198
+ return Boolean(Array.isArray(value));
1199
+ }
1200
+ const isNotArray = bindNot(isArray);
1201
+
1202
+ /**
1203
+ * Asserts that each element in an array passes
1204
+ * at least one of the provided rule chain
1205
+ *
1206
+ * @param {EnforceContext} value
1207
+ * @param {[{test: Function, run: Function}]} ruleChains
1208
+ * @return {RuleResult}
1209
+ */
1210
+
1211
+ function isArrayOf(value, ruleChains) {
1212
+ const plainValue = EnforceContext.unwrap(value);
1213
+ const result = new RuleResult(true).asArray(); // Fails if current value is not an array
1214
+
1215
+ if (isNotArray(plainValue)) {
1216
+ return result.setFailed(true);
1217
+ }
1218
+
1219
+ for (let i = 0; i < plainValue.length; i++) {
1220
+ // Set result per each item in the array
1221
+ result.setChild(i, runCompoundChain(new EnforceContext({
1222
+ value: plainValue[i],
1223
+ obj: plainValue,
1224
+ key: i
1225
+ }).setFailFast(value.failFast), ruleChains, {
1226
+ mode: MODE_ANY
1227
+ }));
1228
+ }
1229
+
1230
+ return result;
1231
+ }
1232
+
1233
+ var isArrayOf$1 = withArgs(isArrayOf);
1234
+
1235
+ /**
1236
+ * @param {EnforceContext} value
1237
+ * @param {[{test: Function, run: Function}]} ruleChains
1238
+ * @return {RuleResult}
1239
+ */
1240
+
1241
+ function oneOf(value, rules) {
1242
+ return runCompoundChain(value, rules, {
1243
+ mode: MODE_ONE
1244
+ });
1245
+ }
1246
+
1247
+ var oneOf$1 = withArgs(oneOf);
1248
+
1249
+ /**
1250
+ * @param {Array} ObjectEntry Object and key leading to current value
1251
+ * @param {Function[]} rules Rules to validate the value with
1252
+ */
1253
+
1254
+ function optional$1(inputObject, ruleGroups) {
1255
+ const {
1256
+ obj,
1257
+ key
1258
+ } = inputObject; // If current value is not defined, undefined or null
1259
+ // Pass without further assertions
1260
+
1261
+ if (!hasOwnProperty(obj, key) || isUndefined(obj[key] || isNull(obj[key]))) {
1262
+ return true;
1263
+ } // Pass if exists but no assertions
1264
+
1265
+
1266
+ if (isEmpty(ruleGroups)) {
1267
+ return true;
1268
+ } // Run chain with `all` mode
1269
+
1270
+
1271
+ return runCompoundChain(obj[key], ruleGroups, {
1272
+ mode: MODE_ALL
1273
+ });
1274
+ }
1275
+
1276
+ var optional$2 = withArgs(optional$1);
1277
+
1278
+ /**
1279
+ * @param {EnforceContext} inputObject Data object that gets validated
1280
+ * @param {Object} shapeObj Shape definition
1281
+ * @param {Object} options
1282
+ * @param {boolean} options.loose Ignore extra keys not defined in shapeObj
1283
+ */
1284
+
1285
+ function shape(inputObject, shapeObj, options) {
1286
+ // Extract the object from context
1287
+ const obj = EnforceContext.unwrap(inputObject); // Create a new result object
1288
+
1289
+ const result = new RuleResult(true); // Iterate over the shape keys
1290
+
1291
+ for (const key in shapeObj) {
1292
+ const current = shapeObj[key];
1293
+ const value = obj[key];
1294
+
1295
+ if (shouldFailFast(value, result)) {
1296
+ break;
1297
+ } // Set each key in the result object
1298
+
1299
+
1300
+ result.setChild(key, runLazyRule(current, new EnforceContext({
1301
+ value,
1302
+ obj,
1303
+ key
1304
+ }).setFailFast(inputObject.failFast)));
1305
+ } // If mode is not loose
1306
+
1307
+
1308
+ if (!(options || {}).loose) {
1309
+ // Check that each key in the input object exists in the shape
1310
+ for (const key in obj) {
1311
+ if (!hasOwnProperty(shapeObj, key)) {
1312
+ return result.setFailed(true);
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ return result;
1318
+ }
1319
+ const loose = (obj, shapeObj) => shape(obj, shapeObj, {
1320
+ loose: true
1321
+ });
1322
+
1323
+ var compounds = {
1324
+ allOf: allOf$1,
1325
+ anyOf: anyOf$1,
1326
+ isArrayOf: isArrayOf$1,
1327
+ loose,
1328
+ oneOf: oneOf$1,
1329
+ optional: optional$2,
1330
+ shape
1331
+ };
1332
+
1333
+ /**
1334
+ * Takes a value. If it is a function, runs it and returns the result.
1335
+ * Otherwise, returns the value as is.
1336
+ *
1337
+ * @param {Function|*} value Value to return. Run it if a function.
1338
+ * @param {Any[]} [args] Arguments to pass if a function
1339
+ * @return {Any}
1340
+ */
1341
+
1342
+ function optionalFunctionValue(value, args) {
1343
+ return isFunction(value) ? value.apply(null, args) : value;
1344
+ }
1345
+
1346
+ function message(value, msg) {
1347
+ return optionalFunctionValue(msg, [EnforceContext.unwrap(value)]);
1348
+ }
1349
+
1350
+ function warn$1(_, isWarn = true) {
1351
+ return isWarn;
1352
+ }
1353
+
1354
+ function when(value, condition, bail) {
1355
+ const shouldBail = !optionalFunctionValue(condition, [EnforceContext.unwrap(value)].concat(EnforceContext.is(value) ? [value.key, value.obj] : []));
1356
+ return bail(shouldBail);
1357
+ }
1358
+
1359
+ var ruleMeta = {
1360
+ warn: warn$1,
1361
+ message,
1362
+ when
1363
+ };
1364
+
1365
+ function isStringValue (v) {
1366
+ return String(v) === v;
1367
+ }
1368
+
1369
+ function endsWith(value, arg1) {
1370
+ return isStringValue(value) && isStringValue(arg1) && value.endsWith(arg1);
1371
+ }
1372
+ const doesNotEndWith = bindNot(endsWith);
1373
+
1374
+ function equals(value, arg1) {
1375
+ return value === arg1;
1376
+ }
1377
+ const notEquals = bindNot(equals);
1378
+
1379
+ function greaterThan(value, arg1) {
1380
+ return isNumeric(value) && isNumeric(arg1) && Number(value) > Number(arg1);
1381
+ }
1382
+
1383
+ function greaterThanOrEquals(value, arg1) {
1384
+ return isNumeric(value) && isNumeric(arg1) && Number(value) >= Number(arg1);
1385
+ }
1386
+
1387
+ function inside(value, arg1) {
1388
+ if (Array.isArray(arg1) && /^[s|n|b]/.test(typeof value)) {
1389
+ return arg1.indexOf(value) !== -1;
1390
+ } // both value and arg1 are strings
1391
+
1392
+
1393
+ if (isStringValue(arg1) && isStringValue(value)) {
1394
+ return arg1.indexOf(value) !== -1;
1395
+ }
1396
+
1397
+ return false;
1398
+ }
1399
+ const notInside = bindNot(inside);
1400
+
1401
+ function lessThanOrEquals(value, arg1) {
1402
+ return isNumeric(value) && isNumeric(arg1) && Number(value) <= Number(arg1);
1403
+ }
1404
+
1405
+ function isBetween(value, min, max) {
1406
+ return greaterThanOrEquals(value, min) && lessThanOrEquals(value, max);
1407
+ }
1408
+ const isNotBetween = bindNot(isBetween);
1409
+
1410
+ function isBlank(value) {
1411
+ return typeof value === 'string' && value.trim() === '';
1412
+ }
1413
+ const isNotBlank = bindNot(isBlank);
1414
+
1415
+ /**
1416
+ * Validates that a given value is an even number
1417
+ * @param {Number|String} value Value to be validated
1418
+ * @return {Boolean}
1419
+ */
1420
+
1421
+ const isEven = value => {
1422
+ if (isNumeric(value)) {
1423
+ return value % 2 === 0;
1424
+ }
1425
+
1426
+ return false;
1427
+ };
1428
+
1429
+ function isNaN$1(value) {
1430
+ return Number.isNaN(value);
1431
+ }
1432
+ const isNotNaN = bindNot(isNaN$1);
1433
+
1434
+ function isNegative(value) {
1435
+ if (isNumeric(value)) {
1436
+ return Number(value) < 0;
1437
+ }
1438
+
1439
+ return false;
1440
+ }
1441
+ const isPositive = bindNot(isNegative);
1442
+
1443
+ function isNumber(value) {
1444
+ return Boolean(typeof value === 'number');
1445
+ }
1446
+ const isNotNumber = bindNot(isNumber);
1447
+
1448
+ /**
1449
+ * Validates that a given value is an odd number
1450
+ * @param {Number|String} value Value to be validated
1451
+ * @return {Boolean}
1452
+ */
1453
+
1454
+ const isOdd = value => {
1455
+ if (isNumeric(value)) {
1456
+ return value % 2 !== 0;
1457
+ }
1458
+
1459
+ return false;
1460
+ };
1461
+
1462
+ const isNotString = bindNot(isStringValue);
1463
+
1464
+ function isTruthy(value) {
1465
+ return !!value;
1466
+ }
1467
+ const isFalsy = bindNot(isTruthy);
1468
+
1469
+ function lessThan(value, arg1) {
1470
+ return isNumeric(value) && isNumeric(arg1) && Number(value) < Number(arg1);
1471
+ }
1472
+
1473
+ function longerThan(value, arg1) {
1474
+ return value.length > Number(arg1);
1475
+ }
1476
+
1477
+ function longerThanOrEquals(value, arg1) {
1478
+ return value.length >= Number(arg1);
1479
+ }
1480
+
1481
+ function matches(value, regex) {
1482
+ if (regex instanceof RegExp) {
1483
+ return regex.test(value);
1484
+ } else if (isStringValue(regex)) {
1485
+ return new RegExp(regex).test(value);
1486
+ } else {
1487
+ return false;
1488
+ }
1489
+ }
1490
+ const notMatches = bindNot(matches);
1491
+
1492
+ function numberEquals(value, arg1) {
1493
+ return isNumeric(value) && isNumeric(arg1) && Number(value) === Number(arg1);
1494
+ }
1495
+ const numberNotEquals = bindNot(numberEquals);
1496
+
1497
+ function shorterThan(value, arg1) {
1498
+ return value.length < Number(arg1);
1499
+ }
1500
+
1501
+ function shorterThanOrEquals(value, arg1) {
1502
+ return value.length <= Number(arg1);
1503
+ }
1504
+
1505
+ function startsWith(value, arg1) {
1506
+ return isStringValue(value) && isStringValue(arg1) && value.startsWith(arg1);
1507
+ }
1508
+ const doesNotStartWith = bindNot(startsWith);
1509
+
1510
+ function rules() {
1511
+ return {
1512
+ doesNotEndWith,
1513
+ doesNotStartWith,
1514
+ endsWith,
1515
+ equals,
1516
+ greaterThan,
1517
+ greaterThanOrEquals,
1518
+ gt: greaterThan,
1519
+ gte: greaterThanOrEquals,
1520
+ inside,
1521
+ isArray,
1522
+ isBetween,
1523
+ isBoolean,
1524
+ isBlank,
1525
+ isEmpty,
1526
+ isEven,
1527
+ isFalsy,
1528
+ isNaN: isNaN$1,
1529
+ isNegative,
1530
+ isNotArray,
1531
+ isNotBetween,
1532
+ isNotBlank,
1533
+ isNotBoolean,
1534
+ isNotEmpty,
1535
+ isNotNaN,
1536
+ isNotNull,
1537
+ isNotNumber,
1538
+ isNotNumeric,
1539
+ isNotString,
1540
+ isNotUndefined,
1541
+ isNull,
1542
+ isNumber,
1543
+ isNumeric,
1544
+ isOdd,
1545
+ isPositive,
1546
+ isString: isStringValue,
1547
+ isTruthy,
1548
+ isUndefined,
1549
+ lengthEquals,
1550
+ lengthNotEquals,
1551
+ lessThan,
1552
+ lessThanOrEquals,
1553
+ longerThan,
1554
+ longerThanOrEquals,
1555
+ lt: lessThan,
1556
+ lte: lessThanOrEquals,
1557
+ matches,
1558
+ notEquals,
1559
+ notInside,
1560
+ notMatches,
1561
+ numberEquals,
1562
+ numberNotEquals,
1563
+ shorterThan,
1564
+ shorterThanOrEquals,
1565
+ startsWith
1566
+ };
1567
+ }
1568
+
1569
+ var runtimeRules = assign(rules(), compounds, ruleMeta);
1570
+
1571
+ /**
1572
+ * Determines whether a given string is a name of a rule
1573
+ *
1574
+ * @param {string} name
1575
+ * @return {boolean}
1576
+ */
1577
+
1578
+ const isRule = name => hasOwnProperty(runtimeRules, name) && isFunction(runtimeRules[name]);
1579
+
1580
+ const GLOBAL_OBJECT = Function('return this')();
1581
+
1582
+ const proxySupported = () => isFunction(GLOBAL_OBJECT.Proxy);
1583
+
1584
+ function genRuleProxy(target, output) {
1585
+ if (proxySupported()) {
1586
+ return new Proxy(target, {
1587
+ get: (target, fnName) => {
1588
+ // A faster bailout when we access `run` and `test`
1589
+ if (hasOwnProperty(target, fnName)) {
1590
+ return target[fnName];
1591
+ }
1592
+
1593
+ if (isRule(fnName)) {
1594
+ return output(fnName);
1595
+ }
1596
+
1597
+ return target[fnName];
1598
+ }
1599
+ });
1600
+ } else {
1601
+ /**
1602
+ * This method is REALLY not recommended as it is slow and iterates over
1603
+ * all the rules for each direct enforce reference. We only use it as a
1604
+ * lightweight alternative for the much faster proxy interface
1605
+ */
1606
+ for (const fnName in runtimeRules) {
1607
+ if (!isFunction(target[fnName])) {
1608
+ Object.defineProperties(target, {
1609
+ [fnName]: {
1610
+ get: () => output(fnName)
1611
+ }
1612
+ });
1613
+ }
1614
+ }
1615
+
1616
+ return target;
1617
+ }
1618
+ }
1619
+
1620
+ /**
1621
+ * Determines whether a given rule is a compound.
1622
+ *
1623
+ * @param {Function} rule
1624
+ * @return {boolean}
1625
+ */
1626
+
1627
+ function isCompound(rule) {
1628
+ return hasOwnProperty(compounds, rule.name);
1629
+ }
1630
+
1631
+ /**
1632
+ * Creates a rule of lazily called rules.
1633
+ * Each rule gets added a `.run()` property
1634
+ * which runs all the accumulated rules in
1635
+ * the chain against the supplied value
1636
+ *
1637
+ * @param {string} ruleName
1638
+ * @return {{run: Function}}
1639
+ */
1640
+
1641
+ function bindLazyRule(ruleName) {
1642
+ const registeredRules = []; // Chained rules
1643
+
1644
+ const meta = []; // Meta properties to add onto the rule context
1645
+ // Appends a function to the registeredRules array.
1646
+ // It gets called every time the consumer usess chaining
1647
+ // so, for example - enforce.isArray() <- this calles addFn
1648
+
1649
+ const addFn = ruleName => {
1650
+ return withArgs(args => {
1651
+ const rule = runtimeRules[ruleName]; // Add a meta function
1652
+
1653
+ if (ruleMeta[rule.name] === rule) {
1654
+ meta.push((value, ruleResult, bail) => {
1655
+ ruleResult.setAttribute(rule.name, rule(value, args[0], bail));
1656
+ });
1657
+ } else {
1658
+ // Register a rule
1659
+ registeredRules.push(setFnName(value => {
1660
+ return rule.apply(null, [// If the rule is compound - wraps the value with context
1661
+ // Otherwise - unwraps it
1662
+ isCompound(rule) ? EnforceContext.wrap(value) : EnforceContext.unwrap(value)].concat(args));
1663
+ }, ruleName));
1664
+ } // set addFn as the proxy handler
1665
+
1666
+
1667
+ const returnvalue = genRuleProxy({}, addFn);
1668
+
1669
+ returnvalue[RUN_RULE] = value => {
1670
+ const result = new RuleResult(true);
1671
+ let bailed = false; // Run meta chains
1672
+
1673
+ meta.forEach(fn => {
1674
+ fn(value, result, shouldBail => bailed = shouldBail);
1675
+ });
1676
+
1677
+ if (bailed) {
1678
+ return null;
1679
+ } // Iterate over all the registered rules
1680
+ // This runs the function that's inside `addFn`
1681
+
1682
+
1683
+ for (const fn of registeredRules) {
1684
+ try {
1685
+ result.extend(fn(value)); // If a chained rule fails, exit. We failed.
1686
+
1687
+ if (!result.pass) {
1688
+ break;
1689
+ }
1690
+ } catch (e) {
1691
+ result.setFailed(true);
1692
+ break;
1693
+ }
1694
+ }
1695
+
1696
+ return result;
1697
+ };
1698
+
1699
+ returnvalue[TEST_RULE] = value => returnvalue[RUN_RULE](EnforceContext.wrap(value).setFailFast(true)).pass;
1700
+
1701
+ return returnvalue;
1702
+ }, ruleName);
1703
+ }; // Returns the initial rule in the chain
1704
+
1705
+
1706
+ return addFn(ruleName);
1707
+ }
1708
+
1709
+ function bindExtend(enforce, Enforce) {
1710
+ enforce.extend = customRules => {
1711
+ assign(runtimeRules, customRules);
1712
+
1713
+ if (!proxySupported()) {
1714
+ genRuleProxy(Enforce, bindLazyRule);
1715
+ }
1716
+
1717
+ return enforce;
1718
+ };
1719
+ }
1720
+
1721
+ function validateResult(result, rule) {
1722
+ // if result is boolean, or if result.pass is boolean
1723
+ if (isBoolean(result) || result && isBoolean(result.pass)) {
1724
+ return;
1725
+ }
1726
+
1727
+ throwError(rule.name + 'wrong return value');
1728
+ } // for easier testing and mocking
1729
+
1730
+ function getDefaultResult(value) {
1731
+ return {
1732
+ message: new Error(`invalid ${typeof value} value`)
1733
+ };
1734
+ }
1735
+ /**
1736
+ * Transform the result of a rule into a standard format
1737
+ * @param {string} interfaceName to be used in the messages
1738
+ * @param {*} result of the rule
1739
+ * @param {Object} options
1740
+ * @param {function} options.rule
1741
+ * @param {*} options.value
1742
+ * @returns {Object} result
1743
+ * @returns {string} result.message
1744
+ * @returns {boolean} result.pass indicates if the test passes or not
1745
+ */
1746
+
1747
+ function transformResult(result, {
1748
+ rule,
1749
+ value
1750
+ }) {
1751
+ const defaultResult = getDefaultResult(value);
1752
+ validateResult(result, rule); // if result is boolean
1753
+
1754
+ if (isBoolean(result)) {
1755
+ return defaultResult.pass = result, defaultResult;
1756
+ } else {
1757
+ defaultResult.pass = result.pass;
1758
+
1759
+ if (result.message) {
1760
+ defaultResult.message = optionalFunctionValue(result.message);
1761
+ }
1762
+
1763
+ return defaultResult;
1764
+ }
1765
+ }
1766
+
1767
+ /**
1768
+ * Run a single rule against enforced value (e.g. `isNumber()`)
1769
+ *
1770
+ * @param {Function} rule - rule to run
1771
+ * @param {Any} value
1772
+ * @param {Array} args list of arguments sent from consumer
1773
+ * @throws
1774
+ */
1775
+
1776
+ function runner(rule, value, args = []) {
1777
+ let result;
1778
+ const isCompoundRule = isCompound(rule);
1779
+ const ruleValue = isCompoundRule ? EnforceContext.wrap(value).setFailFast(true) : EnforceContext.unwrap(value);
1780
+ result = rule.apply(null, [ruleValue].concat(args));
1781
+
1782
+ if (!isCompoundRule) {
1783
+ result = transformResult(result, {
1784
+ rule,
1785
+ value
1786
+ });
1787
+ }
1788
+
1789
+ if (!result.pass) {
1790
+ throw result.message;
1791
+ }
1792
+ }
1793
+
1794
+ /**
1795
+ * Adds `template` property to enforce.
1796
+ *
1797
+ * @param {Function} enforce
1798
+ */
1799
+
1800
+ function bindTemplate(enforce) {
1801
+ enforce.template = withArgs(rules => {
1802
+ const template = value => {
1803
+ runner(runLazyRules.bind(null, rules), value);
1804
+ const proxy = genRuleProxy({}, ruleName => withArgs(args => {
1805
+ runner(runtimeRules[ruleName], value, args);
1806
+ return proxy;
1807
+ }));
1808
+ return proxy;
1809
+ }; // `run` returns a deep ResultObject
1810
+
1811
+
1812
+ template[RUN_RULE] = value => runLazyRules(rules, value); // `test` returns a boolean
1813
+
1814
+
1815
+ template[TEST_RULE] = value => runLazyRules(rules, EnforceContext.wrap(value).setFailFast(true)).pass;
1816
+
1817
+ return template;
1818
+ });
1819
+ }
1820
+
1821
+ const Enforce = value => {
1822
+ const proxy = genRuleProxy({}, ruleName => withArgs(args => {
1823
+ runner(runtimeRules[ruleName], value, args);
1824
+ return proxy;
1825
+ }));
1826
+ return proxy;
1827
+ };
1828
+
1829
+ const enforce = genRuleProxy(Enforce, bindLazyRule);
1830
+ bindExtend(enforce, Enforce);
1831
+ bindTemplate(enforce);
1832
+
1833
+ /**
1834
+ * @type {String} Error message to display when a hook was called outside of context.
1835
+ */
1836
+ const ERROR_HOOK_CALLED_OUTSIDE = 'hook called outside of a running suite.';
1837
+
1838
+ /**
1839
+ * Adds a field or multiple fields to inclusion group.
1840
+ * @param {String[]|String} item Item to be added to inclusion group.
1841
+ */
1842
+
1843
+ function only(item) {
1844
+ return addTo(EXCLUSION_GROUP_NAME_ONLY, EXCLUSION_ITEM_TYPE_TESTS, item);
1845
+ }
1846
+
1847
+ only.group = item => addTo(EXCLUSION_GROUP_NAME_ONLY, EXCLUSION_ITEM_TYPE_GROUPS, item);
1848
+ /**
1849
+ * Adds a field or multiple fields to exclusion group.
1850
+ * @param {String[]|String} item Item to be added to exclusion group.
1851
+ */
1852
+
1853
+
1854
+ function skip(item) {
1855
+ return addTo(EXCLUSION_GROUP_NAME_SKIP, EXCLUSION_ITEM_TYPE_TESTS, item);
1856
+ }
1857
+
1858
+ skip.group = item => addTo(EXCLUSION_GROUP_NAME_SKIP, EXCLUSION_ITEM_TYPE_GROUPS, item);
1859
+ /**
1860
+ * Checks whether a certain test profile excluded by any of the exclusion groups.
1861
+ * @param {String} fieldName Field name to test.
1862
+ * @param {VestTest} Test Object reference.
1863
+ * @returns {Boolean}
1864
+ */
1865
+
1866
+
1867
+ function isExcluded(testObject) {
1868
+ const {
1869
+ fieldName,
1870
+ groupName
1871
+ } = testObject;
1872
+ const {
1873
+ exclusion
1874
+ } = context.use();
1875
+ const keyTests = exclusion[EXCLUSION_ITEM_TYPE_TESTS];
1876
+ const testValue = keyTests[fieldName]; // if test is skipped
1877
+ // no need to proceed
1878
+
1879
+ if (testValue === false) {
1880
+ return true;
1881
+ }
1882
+
1883
+ const isTestIncluded = testValue === true; // If inside a group
1884
+
1885
+ if (groupName) {
1886
+ if (isGroupExcluded(groupName)) {
1887
+ return true; // field excluded by group
1888
+ // if group is `only`ed
1889
+ } else if (exclusion[EXCLUSION_ITEM_TYPE_GROUPS][groupName] === true) {
1890
+ if (isTestIncluded) {
1891
+ return false;
1892
+ } // If there is _ANY_ `only`ed test (and we already know this one isn't)
1893
+
1894
+
1895
+ if (hasIncludedTests(keyTests)) {
1896
+ return true; // Excluded implicitly
1897
+ }
1898
+
1899
+ return keyTests[fieldName] === false;
1900
+ }
1901
+ } // if field is only'ed
1902
+
1903
+
1904
+ if (isTestIncluded) {
1905
+ return false;
1906
+ } // If there is _ANY_ `only`ed test (and we already know this one isn't) return true
1907
+ // Otherwise return false
1908
+
1909
+
1910
+ return hasIncludedTests(keyTests);
1911
+ }
1912
+ /**
1913
+ * Checks whether a given group is excluded from running.
1914
+ * @param {String} groupName
1915
+ * @return {Boolean}
1916
+ */
1917
+
1918
+ function isGroupExcluded(groupName) {
1919
+ const {
1920
+ exclusion
1921
+ } = context.use();
1922
+ const keyGroups = exclusion[EXCLUSION_ITEM_TYPE_GROUPS];
1923
+ const groupPresent = hasOwnProperty(keyGroups, groupName); // When group is either only'ed or skipped
1924
+
1925
+ if (groupPresent) {
1926
+ // Return true if group is skipped and false if only'ed
1927
+ return keyGroups[groupName] === false;
1928
+ } // Group is not present
1929
+
1930
+
1931
+ for (const group in keyGroups) {
1932
+ // If any other group is only'ed
1933
+ if (keyGroups[group] === true) {
1934
+ return true;
1935
+ }
1936
+ }
1937
+
1938
+ return false;
1939
+ }
1940
+ /**
1941
+ * @type {String} Exclusion group name: only.
1942
+ */
1943
+
1944
+ const EXCLUSION_GROUP_NAME_ONLY = 'only';
1945
+ /**
1946
+ * @type {String} Exclusion group name: skip.
1947
+ */
1948
+
1949
+ const EXCLUSION_GROUP_NAME_SKIP = 'skip';
1950
+ /**
1951
+ * Adds fields to a specified exclusion group.
1952
+ * @param {String} exclusionGroup To add the fields to.
1953
+ * @param {String} itemType Whether the item is a group or a test.
1954
+ * @param {String[]|String} item A field name or a list of field names.
1955
+ */
1956
+
1957
+ const addTo = (exclusionGroup, itemType, item) => {
1958
+ const ctx = context.use();
1959
+
1960
+ if (!item) {
1961
+ return;
1962
+ }
1963
+
1964
+ if (!ctx) {
1965
+ throwError(`${exclusionGroup} ${ERROR_HOOK_CALLED_OUTSIDE}`);
1966
+ return;
1967
+ }
1968
+
1969
+ asArray(item).forEach(itemName => {
1970
+ if (!isStringValue(itemName)) {
1971
+ return null;
1972
+ }
1973
+
1974
+ ctx.exclusion[itemType][itemName] = exclusionGroup === EXCLUSION_GROUP_NAME_ONLY;
1975
+ });
1976
+ };
1977
+ /**
1978
+ * Checks if context has included tests
1979
+ * @param {Object} keyTests Object containing included and excluded tests
1980
+ * @returns {boolean}
1981
+ */
1982
+
1983
+
1984
+ const hasIncludedTests = keyTests => {
1985
+ for (const test in keyTests) {
1986
+ if (keyTests[test] === true) {
1987
+ return true; // excluded implicitly
1988
+ }
1989
+ }
1990
+
1991
+ return false;
1992
+ };
1993
+
1994
+ // an if statement. The reason for it is to support version 4 api in version 3
1995
+ // so that someone reading the latest docs can still run the code.
1996
+
1997
+ function skipWhen(conditional, callback) {
1998
+ if (isFalsy(optionalFunctionValue(conditional))) {
1999
+ if (isFunction(callback)) {
2000
+ callback();
2001
+ }
2002
+ }
2003
+ }
2004
+
2005
+ /**
2006
+ * @type {String} Error message to display when `warn` gets called outside of a test.
2007
+ */
2008
+
2009
+ const ERROR_OUTSIDE_OF_TEST = 'warn called outside of a test.';
2010
+ /**
2011
+ * Sets a running test to warn only mode.
2012
+ */
2013
+
2014
+ const warn = () => {
2015
+ const ctx = context.use();
2016
+
2017
+ if (!ctx) {
2018
+ throwError('warn ' + ERROR_HOOK_CALLED_OUTSIDE);
2019
+ return;
2020
+ }
2021
+
2022
+ if (!ctx.currentTest) {
2023
+ throwError(ERROR_OUTSIDE_OF_TEST);
2024
+ return;
2025
+ }
2026
+
2027
+ ctx.currentTest.warn();
2028
+ };
2029
+
2030
+ const throwGroupError = () => throwError("group initialization error. Incompatible argument passed to group.");
2031
+ /**
2032
+ * Runs a group callback.
2033
+ * @param {string} groupName
2034
+ * @param {Function} tests
2035
+ */
2036
+
2037
+
2038
+ const group = (groupName, tests) => {
2039
+ if (!isStringValue(groupName)) {
2040
+ throwGroupError();
2041
+ }
2042
+
2043
+ if (!isFunction(tests)) {
2044
+ throwGroupError();
2045
+ } // Running with the context applied
2046
+
2047
+
2048
+ context.bind({
2049
+ groupName
2050
+ }, tests)();
2051
+ };
2052
+
2053
+ function optional(optionals) {
2054
+ const [, setOptionalFields] = useOptionalFields();
2055
+ setOptionalFields(state => {
2056
+ asArray(optionals).forEach(optionalField => {
2057
+ state[optionalField] = true;
2058
+ });
2059
+ return state;
2060
+ });
2061
+ }
2062
+
2063
+ function isSameProfileTest(testObject1, testObject2) {
2064
+ return testObject1.fieldName === testObject2.fieldName && testObject1.groupName === testObject2.groupName;
2065
+ }
2066
+
2067
+ /**
2068
+ * Removes first found element from array
2069
+ * WARNING: Mutates array
2070
+ *
2071
+ * @param {any[]} array
2072
+ * @param {any} element
2073
+ */
2074
+ const removeElementFromArray = (array, element) => {
2075
+ const index = array.indexOf(element);
2076
+
2077
+ if (index !== -1) {
2078
+ array.splice(index, 1);
2079
+ }
2080
+
2081
+ return array;
2082
+ };
2083
+
2084
+ /**
2085
+ * Sets a test as pending in the state.
2086
+ * @param {VestTest} testObject
2087
+ */
2088
+
2089
+ const setPending = testObject => {
2090
+ const [pendingState, setPending] = usePending();
2091
+ const lagging = asArray(pendingState.lagging).reduce((lagging, laggingTestObject) => {
2092
+ /**
2093
+ * If the test is of the same profile
2094
+ * (same name + same group) we cancel
2095
+ * it. Otherwise, it is lagging.
2096
+ */
2097
+ if (isSameProfileTest(testObject, laggingTestObject) && // This last case handles memoized tests
2098
+ // because that retain their od across runs
2099
+ laggingTestObject.id !== testObject.id) {
2100
+ laggingTestObject.cancel();
2101
+ } else {
2102
+ lagging.push(laggingTestObject);
2103
+ }
2104
+
2105
+ return lagging;
2106
+ }, []);
2107
+ setPending(state => ({
2108
+ lagging,
2109
+ pending: state.pending.concat(testObject)
2110
+ }));
2111
+ };
2112
+ /**
2113
+ * Removes a tests from the pending and lagging arrays.
2114
+ * @param {VestTest} testObject
2115
+ */
2116
+
2117
+ const removePending = testObject => {
2118
+ const [, setPending] = usePending();
2119
+ setPending(state => ({
2120
+ pending: removeElementFromArray(state.pending, testObject),
2121
+ lagging: removeElementFromArray(state.lagging, testObject)
2122
+ }));
2123
+ };
2124
+
2125
+ /**
2126
+ * Removes test object from suite state
2127
+ * @param {VestTest} testObject
2128
+ */
2129
+
2130
+ var removeTestFromState = (testObject => {
2131
+ const [, setTestObjects] = useTestObjects();
2132
+ setTestObjects(testObjects => // using asArray to clear the cache.
2133
+ asArray(removeElementFromArray(testObjects, testObject)));
2134
+ });
2135
+
2136
+ /**
2137
+ * Describes a test call inside a Vest suite.
2138
+ * @param {String} fieldName Name of the field being tested.
2139
+ * @param {String} statement The message returned when failing.
2140
+ * @param {Promise|Function} testFn The actual test callback or promise.
2141
+ * @param {string} [group] The group in which the test runs.
2142
+ */
2143
+
2144
+ function VestTest({
2145
+ fieldName,
2146
+ statement,
2147
+ testFn,
2148
+ group
2149
+ }) {
2150
+ const testObject = {
2151
+ cancel,
2152
+ fail,
2153
+ failed: false,
2154
+ fieldName,
2155
+ id: id(),
2156
+ isWarning: false,
2157
+ statement,
2158
+ testFn,
2159
+ valueOf,
2160
+ warn
2161
+ };
2162
+
2163
+ if (group) {
2164
+ testObject.groupName = group;
2165
+ }
2166
+
2167
+ return testObject;
2168
+ /**
2169
+ * @returns {Boolean} Current validity status of a test.
2170
+ */
2171
+
2172
+ function valueOf() {
2173
+ return testObject.failed !== true;
2174
+ }
2175
+ /**
2176
+ * Sets a test to failed.
2177
+ */
2178
+
2179
+
2180
+ function fail() {
2181
+ testObject.failed = true;
2182
+ }
2183
+ /**
2184
+ * Sets a current test's `isWarning` to true.
2185
+ */
2186
+
2187
+
2188
+ function warn() {
2189
+ testObject.isWarning = true;
2190
+ }
2191
+ /**
2192
+ * Marks a test as canceled, removes it from the state.
2193
+ * This function needs to be called within a stateRef context.
2194
+ */
2195
+
2196
+
2197
+ function cancel() {
2198
+ testObject.canceled = true;
2199
+ removePending(this);
2200
+ removeTestFromState(this);
2201
+ }
2202
+ }
2203
+
2204
+ /**
2205
+ *
2206
+ * @param {any[]} array
2207
+ * @param {() => boolean} predicate
2208
+ * @returns {[any[], any[]]}
2209
+ */
2210
+ function partition(array, predicate) {
2211
+ return array.reduce((partitions, value, index) => {
2212
+ partitions[predicate(value, index, array) ? 0 : 1].push(value);
2213
+ return partitions;
2214
+ }, [[], []]);
2215
+ }
2216
+
2217
+ function mergeCarryOverTests(testObject) {
2218
+ const [carryOverTests, setCarryOverTests] = useCarryOverTests();
2219
+ const [, setTestObjects] = useTestObjects();
2220
+ const [moveToTestObjects, keepInCarryOvers] = partition(carryOverTests, carryOverTest => isSameProfileTest(carryOverTest, testObject));
2221
+ setCarryOverTests(() => keepInCarryOvers);
2222
+ setTestObjects(testObjects => testObjects.concat(moveToTestObjects));
2223
+ }
2224
+
2225
+ /**
2226
+ * Stores test object inside suite state.
2227
+ * @param {VestTest} testObject
2228
+ */
2229
+
2230
+ var addTestToState = (testObject => {
2231
+ const [, setTestObjects] = useTestObjects();
2232
+ setTestObjects(testObjects => testObjects.concat(testObject));
2233
+ });
2234
+
2235
+ function isPromise(value) {
2236
+ return value && isFunction(value.then);
2237
+ }
2238
+
2239
+ function callEach(arr) {
2240
+ return arr.forEach(fn => fn());
2241
+ }
2242
+
2243
+ /**
2244
+ * Runs async test.
2245
+ * @param {VestTest} testObject A VestTest instance.
2246
+ */
2247
+
2248
+ const runAsyncTest = testObject => {
2249
+ const {
2250
+ asyncTest,
2251
+ statement
2252
+ } = testObject;
2253
+ const {
2254
+ stateRef
2255
+ } = context.use();
2256
+ const done = context.bind({
2257
+ stateRef
2258
+ }, () => {
2259
+ removePending(testObject); // This is for cases in which the suite state was already reset
2260
+
2261
+ if (testObject.canceled) {
2262
+ return;
2263
+ } // Perform required done callback calls and cleanups after the test is finished
2264
+
2265
+
2266
+ runDoneCallbacks(testObject.fieldName);
2267
+ });
2268
+ const fail = context.bind({
2269
+ stateRef
2270
+ }, rejectionMessage => {
2271
+ testObject.statement = isStringValue(rejectionMessage) ? rejectionMessage : statement;
2272
+ testObject.fail(); // Spreading the array to invalidate the cache
2273
+
2274
+ const [, setTestObjects] = useTestObjects();
2275
+ setTestObjects(testObjects => testObjects.slice());
2276
+ done();
2277
+ });
2278
+
2279
+ try {
2280
+ asyncTest.then(done, fail);
2281
+ } catch (e) {
2282
+ fail();
2283
+ }
2284
+ };
2285
+ /**
2286
+ * Runs done callback when async tests are finished running.
2287
+ * @param {string} [fieldName] Field name with associated callbacks.
2288
+ */
2289
+
2290
+
2291
+ const runDoneCallbacks = fieldName => {
2292
+ const [{
2293
+ fieldCallbacks,
2294
+ doneCallbacks
2295
+ }] = useTestCallbacks();
2296
+
2297
+ if (fieldName) {
2298
+ if (!hasRemainingTests(fieldName) && Array.isArray(fieldCallbacks[fieldName])) {
2299
+ callEach(fieldCallbacks[fieldName]);
2300
+ }
2301
+ }
2302
+
2303
+ if (!hasRemainingTests()) {
2304
+ callEach(doneCallbacks);
2305
+ }
2306
+ };
2307
+
2308
+ /**
2309
+ * Runs sync tests - or extracts promise.
2310
+ * @param {VestTest} testObject VestTest instance.
2311
+ * @returns {*} Result from test callback.
2312
+ */
2313
+
2314
+ function runSyncTest(testObject) {
2315
+ return context.run({
2316
+ currentTest: testObject
2317
+ }, () => {
2318
+ let result;
2319
+
2320
+ try {
2321
+ result = testObject.testFn();
2322
+ } catch (e) {
2323
+ if (isUndefined(testObject.statement) && isStringValue(e)) {
2324
+ testObject.statement = e;
2325
+ }
2326
+
2327
+ result = false;
2328
+ }
2329
+
2330
+ if (result === false) {
2331
+ testObject.fail();
2332
+ }
2333
+
2334
+ return result;
2335
+ });
2336
+ }
2337
+
2338
+ /**
2339
+ * Registers test, if async - adds to pending array
2340
+ * @param {VestTest} testObject A VestTest Instance.
2341
+ */
2342
+
2343
+ function registerTest(testObject) {
2344
+ addTestToState(testObject); // Run test callback.
2345
+ // If a promise is returned, set as async and
2346
+ // Move to pending list.
2347
+
2348
+ const result = runSyncTest(testObject);
2349
+
2350
+ try {
2351
+ // try catch for safe property access
2352
+ // in case object is an enforce chain
2353
+ if (isPromise(result)) {
2354
+ testObject.asyncTest = result;
2355
+ setPending(testObject);
2356
+ runAsyncTest(testObject);
2357
+ }
2358
+ } catch (_unused) {
2359
+ }
2360
+ }
2361
+
2362
+ /* eslint-disable jest/no-export */
2363
+
2364
+ function bindTestEach(test) {
2365
+ /**
2366
+ * Run multiple tests using a parameter table
2367
+ * @param {any[]} table Array of arrays with params for each run (will accept 1d-array and treat every item as size one array)
2368
+ * @param {String} fieldName Name of the field to test.
2369
+ * @param {String|function} [statement] The message returned in case of a failure. Follows printf syntax.
2370
+ * @param {function} testFn The actual test callback.
2371
+ * @return {VestTest[]} An array of VestTest instances.
2372
+ */
2373
+ function each(table) {
2374
+ if (!Array.isArray(table)) {
2375
+ throwError('test.each: Expected table to be an array.');
2376
+ }
2377
+
2378
+ return withArgs((fieldName, args) => {
2379
+ const [testFn, statement] = args.reverse();
2380
+ return table.map(item => {
2381
+ item = asArray(item);
2382
+ return test(optionalFunctionValue(fieldName, item), optionalFunctionValue(statement, item), () => testFn.apply(null, item));
2383
+ });
2384
+ });
2385
+ }
2386
+
2387
+ test.each = each;
2388
+ }
2389
+
2390
+ /* eslint-disable jest/no-export */
2391
+
2392
+ function bindTestMemo(test) {
2393
+ const cache = createCache(100); // arbitrary cache size
2394
+
2395
+ /**
2396
+ * Caches, or returns an already cached test call
2397
+ * @param {String} fieldName Name of the field to test.
2398
+ * @param {String} [statement] The message returned in case of a failure.
2399
+ * @param {function} testFn The actual test callback.
2400
+ * @param {any[]} deps Dependency array.
2401
+ * @return {VestTest} A VestTest instance.
2402
+ */
2403
+
2404
+ function memo(fieldName, args) {
2405
+ const [suiteId] = useSuiteId();
2406
+ const [deps, testFn, msg] = args.reverse(); // Implicit dependency for more specificity
2407
+
2408
+ const dependencies = [suiteId.id, fieldName].concat(deps);
2409
+ const cached = cache.get(dependencies);
2410
+
2411
+ if (isNull(cached)) {
2412
+ // Cache miss. Start fresh
2413
+ return cache(dependencies, test.bind(null, fieldName, msg, testFn));
2414
+ }
2415
+
2416
+ const [, testObject] = cached;
2417
+
2418
+ if (isExcluded(testObject)) {
2419
+ return testObject;
2420
+ }
2421
+
2422
+ addTestToState(testObject);
2423
+
2424
+ if (testObject && isPromise(testObject.asyncTest)) {
2425
+ setPending(testObject);
2426
+ runAsyncTest(testObject);
2427
+ }
2428
+
2429
+ return testObject;
2430
+ }
2431
+
2432
+ test.memo = withArgs(memo);
2433
+ }
2434
+
2435
+ /**
2436
+ * Test function used by consumer to provide their own validations.
2437
+ * @param {String} fieldName Name of the field to test.
2438
+ * @param {String} [statement] The message returned in case of a failure.
2439
+ * @param {function} testFn The actual test callback.
2440
+ * @return {VestTest} A VestTest instance.
2441
+ *
2442
+ * **IMPORTANT**
2443
+ * Changes to this function need to reflect in test.memo as well
2444
+ */
2445
+
2446
+ const test = withArgs(function (fieldName, args) {
2447
+ const [testFn, statement] = args.reverse();
2448
+ const [, setSkippedTests] = useSkippedTests();
2449
+ const {
2450
+ groupName
2451
+ } = context.use();
2452
+ const testObject = VestTest({
2453
+ fieldName,
2454
+ group: groupName,
2455
+ statement,
2456
+ testFn
2457
+ });
2458
+
2459
+ if (isExcluded(testObject)) {
2460
+ setSkippedTests(skippedTests => skippedTests.concat(testObject));
2461
+ mergeCarryOverTests(testObject);
2462
+ return testObject;
2463
+ }
2464
+
2465
+ if (!isFunction(testFn)) {
2466
+ return testObject;
2467
+ }
2468
+
2469
+ registerTest(testObject);
2470
+ return testObject;
2471
+ });
2472
+ bindTestEach(test);
2473
+ bindTestMemo(test);
2474
+
2475
+ const VERSION = "3.2.7";
2476
+ var vest_mjs = {
2477
+ VERSION,
2478
+ create: createSuite,
2479
+ enforce,
2480
+ group,
2481
+ only,
2482
+ optional,
2483
+ skip,
2484
+ skipWhen,
2485
+ test,
2486
+ warn
2487
+ };
2488
+
2489
+ export default vest_mjs;
2490
+ export { VERSION, createSuite as create, enforce, group, only, optional, skip, skipWhen, test, warn };