n4s 3.1.0 → 4.0.0-dev-e266d9

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 (63) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/LICENSE +1 -2
  3. package/README.md +2 -5
  4. package/compose/package.json +7 -0
  5. package/compounds/package.json +7 -0
  6. package/dist/cjs/compose.development.js +139 -0
  7. package/dist/cjs/compose.js +7 -0
  8. package/dist/cjs/compose.production.js +1 -0
  9. package/dist/cjs/compounds.development.js +132 -0
  10. package/dist/cjs/compounds.js +7 -0
  11. package/dist/cjs/compounds.production.js +1 -0
  12. package/dist/cjs/n4s.development.js +602 -0
  13. package/dist/cjs/n4s.js +7 -0
  14. package/dist/cjs/n4s.production.js +1 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/schema.development.js +144 -0
  17. package/dist/cjs/schema.js +7 -0
  18. package/dist/cjs/schema.production.js +1 -0
  19. package/dist/es/compose.development.js +137 -0
  20. package/dist/es/compose.production.js +1 -0
  21. package/dist/es/compounds.development.js +130 -0
  22. package/dist/es/compounds.production.js +1 -0
  23. package/dist/es/n4s.development.js +597 -0
  24. package/dist/es/n4s.production.js +1 -0
  25. package/dist/es/package.json +1 -0
  26. package/dist/es/schema.development.js +140 -0
  27. package/dist/es/schema.production.js +1 -0
  28. package/dist/umd/compose.development.js +143 -0
  29. package/dist/umd/compose.production.js +1 -0
  30. package/dist/umd/compounds.development.js +136 -0
  31. package/dist/umd/compounds.production.js +1 -0
  32. package/dist/umd/n4s.development.js +606 -0
  33. package/dist/umd/n4s.production.js +1 -0
  34. package/dist/umd/schema.development.js +148 -0
  35. package/dist/umd/schema.production.js +1 -0
  36. package/docs/README.md +2 -5
  37. package/docs/_sidebar.md +0 -1
  38. package/docs/external.md +1 -28
  39. package/package.json +129 -53
  40. package/schema/package.json +7 -0
  41. package/tsconfig.json +8 -0
  42. package/types/compose.d.ts +134 -0
  43. package/types/compounds.d.ts +146 -0
  44. package/types/n4s.d.ts +167 -0
  45. package/types/schema.d.ts +151 -0
  46. package/config/jest/jest.setup.js +0 -14
  47. package/config/rollup/enforce.js +0 -8
  48. package/config/rollup/rollup.config.js +0 -3
  49. package/docs/compound.md +0 -187
  50. package/docs/custom.md +0 -52
  51. package/docs/template.md +0 -53
  52. package/esm/n4s.es.development.js +0 -1142
  53. package/esm/n4s.es.production.js +0 -1142
  54. package/esm/n4s.es.production.min.js +0 -1
  55. package/esm/package.json +0 -1
  56. package/jest.config.js +0 -3
  57. package/n4s.cjs.development.js +0 -1144
  58. package/n4s.cjs.production.js +0 -1144
  59. package/n4s.cjs.production.min.js +0 -1
  60. package/n4s.js +0 -7
  61. package/n4s.umd.development.js +0 -1231
  62. package/n4s.umd.production.js +0 -1231
  63. package/n4s.umd.production.min.js +0 -1
@@ -1,1142 +0,0 @@
1
- var assign = Object.assign;
2
-
3
- /**
4
- * Stores values and configuration passed down to compound rules.
5
- *
6
- * @param {Object} content
7
- */
8
-
9
- function EnforceContext(content) {
10
- assign(this, content);
11
- }
12
- /**
13
- * Sets an EnforceContext config `failFast`
14
- *
15
- * @param {Boolean} failFast
16
- * @return {EnforceContext}
17
- */
18
-
19
- EnforceContext.prototype.setFailFast = function (failFast) {
20
- this.failFast = !!failFast;
21
- return this;
22
- };
23
- /**
24
- * Extracts the literal value from an EnforceContext object
25
- * @param {*} value
26
- * @return {*}
27
- */
28
-
29
-
30
- EnforceContext.unwrap = function unwrap(value) {
31
- return EnforceContext.is(value) ? value.value : value;
32
- };
33
- /**
34
- * Wraps a literal value within a context.
35
- * @param {*} value
36
- * @return {EnforceContext}
37
- */
38
-
39
-
40
- EnforceContext.wrap = function wrap(value) {
41
- return EnforceContext.is(value) ? value : new EnforceContext({
42
- value
43
- });
44
- };
45
- /**
46
- * Checks whether a given value is an EnforceContext instance
47
- *
48
- * @param {*} value
49
- * @returns {boolean}
50
- */
51
-
52
-
53
- EnforceContext.is = function is(value) {
54
- return value instanceof EnforceContext;
55
- };
56
-
57
- /**
58
- * A safe hasOwnProperty access
59
- */
60
- function hasOwnProperty(obj, key) {
61
- return Object.prototype.hasOwnProperty.call(obj, key);
62
- }
63
-
64
- function bindNot(fn) {
65
- return function () {
66
- return !fn.apply(this, arguments);
67
- };
68
- }
69
-
70
- function isBoolean(value) {
71
- return !!value === value;
72
- }
73
-
74
- const isNotBoolean = bindNot(isBoolean);
75
-
76
- function isNumeric(value) {
77
- const result = !isNaN(parseFloat(value)) && !isNaN(Number(value)) && isFinite(value);
78
- return Boolean(result);
79
- }
80
- const isNotNumeric = bindNot(isNumeric);
81
-
82
- function lengthEquals(value, arg1) {
83
- return value.length === Number(arg1);
84
- }
85
- const lengthNotEquals = bindNot(lengthEquals);
86
-
87
- function isEmpty(value) {
88
- if (!value) {
89
- return true;
90
- } else if (isNumeric(value)) {
91
- return value === 0;
92
- } else if (hasOwnProperty(value, 'length')) {
93
- return lengthEquals(value, 0);
94
- } else if (typeof value === 'object') {
95
- return lengthEquals(Object.keys(value), 0);
96
- }
97
-
98
- return true;
99
- }
100
- const isNotEmpty = bindNot(isEmpty);
101
-
102
- function isNull(value) {
103
- return value === null;
104
- }
105
- const isNotNull = bindNot(isNull);
106
-
107
- function isUndefined(value) {
108
- return value === undefined;
109
- }
110
- const isNotUndefined = bindNot(isUndefined);
111
-
112
- const HAS_WARNINGS = 'hasWarnings';
113
- const HAS_ERRORS = 'hasErrors';
114
-
115
- /**
116
- * Stores a rule result in an easy to inspect and manipulate structure.
117
- *
118
- * @param {boolean|RuleResult} ruleRunResult
119
- */
120
-
121
- function RuleResult(ruleRunResult) {
122
- if (isUndefined(ruleRunResult)) {
123
- return;
124
- }
125
-
126
- if (isBoolean(ruleRunResult)) {
127
- this.setFailed(!ruleRunResult);
128
- } else {
129
- this.extend(ruleRunResult);
130
- }
131
- }
132
- /**
133
- * Determines whether a given value is a RuleResult instance
134
- * @param {*} res
135
- * @return {boolean}
136
- */
137
-
138
- RuleResult.is = function (res) {
139
- return res instanceof RuleResult;
140
- };
141
- /**
142
- * Marks the current result object as an array
143
- */
144
-
145
-
146
- RuleResult.prototype.asArray = function () {
147
- this.isArray = true;
148
- return this;
149
- };
150
- /**
151
- * @param {string} key
152
- * @param {value} value
153
- * @return {RuleResult} current instance
154
- */
155
-
156
-
157
- RuleResult.prototype.setAttribute = function (key, value) {
158
- this[key] = value;
159
- return this;
160
- };
161
- /**
162
- * @param {boolean} failed
163
- * @return {RuleResult} current instance
164
- */
165
-
166
-
167
- RuleResult.prototype.setFailed = function (failed) {
168
- this.setAttribute(this.warn ? HAS_WARNINGS : HAS_ERRORS, failed);
169
- return this.setAttribute('failed', failed);
170
- };
171
- /**
172
- * Adds a nested result object
173
- *
174
- * @param {string} key
175
- * @param {RuleResult} child
176
- */
177
-
178
-
179
- RuleResult.prototype.setChild = function (key, child) {
180
- if (isNull(child)) {
181
- return null;
182
- }
183
-
184
- const isWarning = this[HAS_WARNINGS] || child[HAS_WARNINGS] || child.warn || this.warn;
185
- this.setAttribute(HAS_WARNINGS, isWarning && child.failed || false);
186
- this.setAttribute(HAS_ERRORS, this[HAS_ERRORS] || child[HAS_ERRORS] || !isWarning && child.failed || false);
187
- this.setFailed(this.failed || child.failed);
188
- this.children = this.children || {};
189
- this.children[key] = child;
190
- return child;
191
- };
192
- /**
193
- * Retrieves a child by its key
194
- *
195
- * @param {string} key
196
- * @return {RuleResult|undefined}
197
- */
198
-
199
-
200
- RuleResult.prototype.getChild = function (key) {
201
- return (this.children || {})[key];
202
- };
203
- /**
204
- * Extends current instance with a new provided result
205
- * @param {Boolean|RuleResult} newRes
206
- */
207
-
208
-
209
- RuleResult.prototype.extend = function (newRes) {
210
- if (isNull(newRes)) {
211
- return this;
212
- }
213
-
214
- const res = RuleResult.is(newRes) ? newRes : new RuleResult().setAttribute('warn', !!this.warn).setFailed(!newRes);
215
- const failed = this.failed || res.failed;
216
- const children = mergeChildren(res, this).children;
217
- assign(this, res);
218
-
219
- if (!isEmpty(children)) {
220
- this.children = children;
221
- }
222
-
223
- this.setFailed(failed);
224
- this.setAttribute(HAS_WARNINGS, !!(this[HAS_WARNINGS] || res[HAS_WARNINGS]));
225
- this.setAttribute(HAS_ERRORS, !!(this[HAS_ERRORS] || res[HAS_ERRORS]));
226
- };
227
-
228
- Object.defineProperty(RuleResult.prototype, 'pass', {
229
- get() {
230
- return !this.failed;
231
- }
232
-
233
- });
234
- /**
235
- * Deeply merge the nested children of compound rules
236
- *
237
- * @param {?RuleResult} base
238
- * @param {?RuleResult} add
239
- * @return {RuleResult}
240
- */
241
-
242
- function mergeChildren(base, add) {
243
- const isRuleResultBase = RuleResult.is(base);
244
- const isRuleResultAdd = RuleResult.is(add); // If both base and add are result objects
245
-
246
- if (isRuleResultBase && isRuleResultAdd) {
247
- // Use failed if either is failing
248
- base.setFailed(base.failed || add.failed); // If neither has a children object, or the children object is
249
-
250
- if (isEmpty(base.children) && isEmpty(add.children)) {
251
- return base;
252
- } // If both have a children object
253
-
254
-
255
- if (base.children && add.children) {
256
- // Merge all the "right side" children back to base
257
- for (const key in base.children) {
258
- mergeChildren(base.children[key], add.children[key]);
259
- } // If a child exists in "add" but not in "base", just copy the child as is
260
-
261
-
262
- for (const key in add.children) {
263
- if (!hasOwnProperty(base.children, key)) {
264
- base.setChild(key, add.children[key]);
265
- }
266
- } // Return the modified base object
267
-
268
-
269
- return base; // If base has no children (but add does)
270
- } else if (!base.children) {
271
- // Use add's children
272
- base.children = add.children; // If add has no children
273
- } else if (!add.children) {
274
- // return base as is
275
- return base;
276
- } // If only base is `RuleResult`
277
-
278
- } else if (isRuleResultBase) {
279
- // Return base as is
280
- return base; // If only add is RuleResult
281
- } else if (isRuleResultAdd) {
282
- // Return add as is
283
- return add;
284
- } // That's a weird case. Let's fail. Very unlikely.
285
-
286
-
287
- return new RuleResult(false);
288
- }
289
-
290
- const RUN_RULE = 'run';
291
- const TEST_RULE = 'test';
292
- const MODE_ALL = 'all';
293
- const MODE_ONE = 'one';
294
- const MODE_ANY = 'any';
295
-
296
- function isFunction (v) {
297
- return typeof v === 'function';
298
- }
299
-
300
- function asArray(possibleArg) {
301
- return [].concat(possibleArg);
302
- }
303
-
304
- /**
305
- * Determines whether we should bail out of an enforcement.
306
- *
307
- * @param {EnforceContext} ctx
308
- * @param {RuleResult} result
309
- */
310
-
311
- function shouldFailFast(ctx, result) {
312
- if (result.pass || result.warn) {
313
- return false;
314
- }
315
-
316
- return !!EnforceContext.is(ctx) && ctx.failFast;
317
- }
318
-
319
- /**
320
- * Runs multiple enforce rules that are passed to compounds.
321
- * Example: enforce.allOf(enforce.ruleOne(), enforce.ruleTwo().ruleThree())
322
- *
323
- * @param {{run: Function}[]} ruleGroups
324
- * @param {*} value
325
- * @return {RuleResult}
326
- */
327
-
328
- function runLazyRules(ruleGroups, value) {
329
- const result = new RuleResult(true);
330
-
331
- for (const chain of asArray(ruleGroups)) {
332
- if (shouldFailFast(value, result)) {
333
- break;
334
- }
335
-
336
- result.extend(runLazyRule(chain, value));
337
- }
338
-
339
- return result;
340
- }
341
- /**
342
- * Runs a single lazy rule
343
- *
344
- * @param {{run: Function}} ruleGroup
345
- * @param {*} value
346
- * @return {boolean|RuleResult}
347
- */
348
-
349
- function runLazyRule(ruleGroup, value) {
350
- return ruleGroup[RUN_RULE](value);
351
- }
352
-
353
- /**
354
- * Runs chains of rules
355
- *
356
- * @param {EnforceContext} value
357
- * @param {[{test: Function, run: Function}]} rules
358
- * @param {RuleResult} options
359
- */
360
-
361
- function runCompoundChain(value, rules, options) {
362
- const result = new RuleResult(true);
363
-
364
- if (isEmpty(rules)) {
365
- result.setFailed(true);
366
- }
367
-
368
- const failedResults = [];
369
- let count = 0;
370
-
371
- for (const chain of rules) {
372
- // Inner result for each iteration
373
- const currentResult = runLazyRule(chain, value);
374
-
375
- if (isNull(currentResult)) {
376
- return null;
377
- }
378
-
379
- const pass = currentResult.pass;
380
-
381
- if (pass) {
382
- count++;
383
- } else {
384
- failedResults.push(currentResult);
385
- }
386
-
387
- if (options) {
388
- // "anyOf" is a special case.
389
- // It shouldn't extend with failed results,
390
- // that's why we continue
391
- if (options.mode === MODE_ANY) {
392
- if (pass) {
393
- result.extend(currentResult);
394
- break;
395
- }
396
-
397
- continue;
398
- }
399
-
400
- result.extend(currentResult); // MODE_ALL: All must pass.
401
- // If one failed, exit.
402
-
403
- if (options.mode === MODE_ALL) {
404
- if (!pass) {
405
- break;
406
- }
407
- } // MODE_ONE: only one must pass.
408
- // If more than one passed, exit.
409
-
410
-
411
- if (options.mode === MODE_ONE) {
412
- result.setFailed(count !== 1);
413
-
414
- if (count > 1) {
415
- break;
416
- }
417
- }
418
- } else {
419
- result.extend(currentResult);
420
-
421
- if (pass) {
422
- break;
423
- }
424
- }
425
- }
426
-
427
- if (result.pass && count === 0) {
428
- result.setFailed(true); // In some cases we do not want to extend failures, for example - in ANY
429
- // when there is a valid response, so we do it before returning
430
-
431
- failedResults.forEach(failedResult => result.extend(failedResult));
432
- }
433
-
434
- return result;
435
- }
436
-
437
- function setFnName(fn, value) {
438
- var _Object$getOwnPropert;
439
-
440
- // Pre ES2015 non standard implementation, "Function.name" is non configurable field
441
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
442
- return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(fn, 'name')) !== null && _Object$getOwnPropert !== void 0 && _Object$getOwnPropert.configurable ? Object.defineProperty(fn, 'name', {
443
- value
444
- }) : fn;
445
- }
446
-
447
- /**
448
- * ES5 Transpilation increases the size of spread arguments by a lot.
449
- * Wraps a function and passes its spread params as an array.
450
- *
451
- * @param {Function} cb
452
- * @param {String} [fnName]
453
- * @return {Function}
454
- */
455
-
456
- function withArgs(cb, fnName) {
457
- return setFnName(function () {
458
- const args = Array.from(arguments);
459
- const right = args.splice(cb.length - 1);
460
- return cb.apply(null, args.concat([right]));
461
- }, fnName || cb.name);
462
- }
463
-
464
- /**
465
- * Runs a chain of rules, making sure that all assertions pass
466
- *
467
- * @param {EnforceContext} value
468
- * @param {[{test: Function, run: Function}]} ruleChains
469
- * @return {RuleResult}
470
- */
471
-
472
- function allOf(value, rules) {
473
- return runCompoundChain(value, rules, {
474
- mode: MODE_ALL
475
- });
476
- }
477
-
478
- var allOf$1 = withArgs(allOf);
479
-
480
- /**
481
- * Runs chains of rules, making sure
482
- * that at least one assertion passes
483
- *
484
- * @param {EnforceContext} value
485
- * @param {[{test: Function, run: Function}]} ruleChains
486
- * @return {RuleResult}
487
- */
488
-
489
- function anyOf(value, ruleChains) {
490
- return runCompoundChain(value, ruleChains, {
491
- mode: MODE_ANY
492
- });
493
- }
494
-
495
- var anyOf$1 = withArgs(anyOf);
496
-
497
- function isArray(value) {
498
- return Boolean(Array.isArray(value));
499
- }
500
- const isNotArray = bindNot(isArray);
501
-
502
- /**
503
- * Asserts that each element in an array passes
504
- * at least one of the provided rule chain
505
- *
506
- * @param {EnforceContext} value
507
- * @param {[{test: Function, run: Function}]} ruleChains
508
- * @return {RuleResult}
509
- */
510
-
511
- function isArrayOf(value, ruleChains) {
512
- const plainValue = EnforceContext.unwrap(value);
513
- const result = new RuleResult(true).asArray(); // Fails if current value is not an array
514
-
515
- if (isNotArray(plainValue)) {
516
- return result.setFailed(true);
517
- }
518
-
519
- for (let i = 0; i < plainValue.length; i++) {
520
- // Set result per each item in the array
521
- result.setChild(i, runCompoundChain(new EnforceContext({
522
- value: plainValue[i],
523
- obj: plainValue,
524
- key: i
525
- }).setFailFast(value.failFast), ruleChains, {
526
- mode: MODE_ANY
527
- }));
528
- }
529
-
530
- return result;
531
- }
532
-
533
- var isArrayOf$1 = withArgs(isArrayOf);
534
-
535
- /**
536
- * @param {EnforceContext} value
537
- * @param {[{test: Function, run: Function}]} ruleChains
538
- * @return {RuleResult}
539
- */
540
-
541
- function oneOf(value, rules) {
542
- return runCompoundChain(value, rules, {
543
- mode: MODE_ONE
544
- });
545
- }
546
-
547
- var oneOf$1 = withArgs(oneOf);
548
-
549
- /**
550
- * @param {Array} ObjectEntry Object and key leading to current value
551
- * @param {Function[]} rules Rules to validate the value with
552
- */
553
-
554
- function optional(inputObject, ruleGroups) {
555
- const {
556
- obj,
557
- key
558
- } = inputObject; // If current value is not defined, undefined or null
559
- // Pass without further assertions
560
-
561
- if (!hasOwnProperty(obj, key) || isUndefined(obj[key] || isNull(obj[key]))) {
562
- return true;
563
- } // Pass if exists but no assertions
564
-
565
-
566
- if (isEmpty(ruleGroups)) {
567
- return true;
568
- } // Run chain with `all` mode
569
-
570
-
571
- return runCompoundChain(obj[key], ruleGroups, {
572
- mode: MODE_ALL
573
- });
574
- }
575
-
576
- var optional$1 = withArgs(optional);
577
-
578
- /**
579
- * @param {EnforceContext} inputObject Data object that gets validated
580
- * @param {Object} shapeObj Shape definition
581
- * @param {Object} options
582
- * @param {boolean} options.loose Ignore extra keys not defined in shapeObj
583
- */
584
-
585
- function shape(inputObject, shapeObj, options) {
586
- // Extract the object from context
587
- const obj = EnforceContext.unwrap(inputObject); // Create a new result object
588
-
589
- const result = new RuleResult(true); // Iterate over the shape keys
590
-
591
- for (const key in shapeObj) {
592
- const current = shapeObj[key];
593
- const value = obj[key];
594
-
595
- if (shouldFailFast(value, result)) {
596
- break;
597
- } // Set each key in the result object
598
-
599
-
600
- result.setChild(key, runLazyRule(current, new EnforceContext({
601
- value,
602
- obj,
603
- key
604
- }).setFailFast(inputObject.failFast)));
605
- } // If mode is not loose
606
-
607
-
608
- if (!(options || {}).loose) {
609
- // Check that each key in the input object exists in the shape
610
- for (const key in obj) {
611
- if (!hasOwnProperty(shapeObj, key)) {
612
- return result.setFailed(true);
613
- }
614
- }
615
- }
616
-
617
- return result;
618
- }
619
- const loose = (obj, shapeObj) => shape(obj, shapeObj, {
620
- loose: true
621
- });
622
-
623
- var compounds = {
624
- allOf: allOf$1,
625
- anyOf: anyOf$1,
626
- isArrayOf: isArrayOf$1,
627
- loose,
628
- oneOf: oneOf$1,
629
- optional: optional$1,
630
- shape
631
- };
632
-
633
- /**
634
- * Takes a value. If it is a function, runs it and returns the result.
635
- * Otherwise, returns the value as is.
636
- *
637
- * @param {Function|*} value Value to return. Run it if a function.
638
- * @param {Any[]} [args] Arguments to pass if a function
639
- * @return {Any}
640
- */
641
-
642
- function optionalFunctionValue(value, args) {
643
- return isFunction(value) ? value.apply(null, args) : value;
644
- }
645
-
646
- function message(value, msg) {
647
- return optionalFunctionValue(msg, [EnforceContext.unwrap(value)]);
648
- }
649
-
650
- function warn(_, isWarn = true) {
651
- return isWarn;
652
- }
653
-
654
- function when(value, condition, bail) {
655
- const shouldBail = !optionalFunctionValue(condition, [EnforceContext.unwrap(value)].concat(EnforceContext.is(value) ? [value.key, value.obj] : []));
656
- return bail(shouldBail);
657
- }
658
-
659
- var ruleMeta = {
660
- warn,
661
- message,
662
- when
663
- };
664
-
665
- function isString (v) {
666
- return String(v) === v;
667
- }
668
-
669
- function endsWith(value, arg1) {
670
- return isString(value) && isString(arg1) && value.endsWith(arg1);
671
- }
672
- const doesNotEndWith = bindNot(endsWith);
673
-
674
- function equals(value, arg1) {
675
- return value === arg1;
676
- }
677
- const notEquals = bindNot(equals);
678
-
679
- function greaterThan(value, arg1) {
680
- return isNumeric(value) && isNumeric(arg1) && Number(value) > Number(arg1);
681
- }
682
-
683
- function greaterThanOrEquals(value, arg1) {
684
- return isNumeric(value) && isNumeric(arg1) && Number(value) >= Number(arg1);
685
- }
686
-
687
- function inside(value, arg1) {
688
- if (Array.isArray(arg1) && /^[s|n|b]/.test(typeof value)) {
689
- return arg1.indexOf(value) !== -1;
690
- } // both value and arg1 are strings
691
-
692
-
693
- if (isString(arg1) && isString(value)) {
694
- return arg1.indexOf(value) !== -1;
695
- }
696
-
697
- return false;
698
- }
699
- const notInside = bindNot(inside);
700
-
701
- function lessThanOrEquals(value, arg1) {
702
- return isNumeric(value) && isNumeric(arg1) && Number(value) <= Number(arg1);
703
- }
704
-
705
- function isBetween(value, min, max) {
706
- return greaterThanOrEquals(value, min) && lessThanOrEquals(value, max);
707
- }
708
- const isNotBetween = bindNot(isBetween);
709
-
710
- function isBlank(value) {
711
- return typeof value === 'string' && value.trim() === '';
712
- }
713
- const isNotBlank = bindNot(isBlank);
714
-
715
- /**
716
- * Validates that a given value is an even number
717
- * @param {Number|String} value Value to be validated
718
- * @return {Boolean}
719
- */
720
-
721
- const isEven = value => {
722
- if (isNumeric(value)) {
723
- return value % 2 === 0;
724
- }
725
-
726
- return false;
727
- };
728
-
729
- function isNaN$1(value) {
730
- return Number.isNaN(value);
731
- }
732
- const isNotNaN = bindNot(isNaN$1);
733
-
734
- function isNegative(value) {
735
- if (isNumeric(value)) {
736
- return Number(value) < 0;
737
- }
738
-
739
- return false;
740
- }
741
- const isPositive = bindNot(isNegative);
742
-
743
- function isNumber(value) {
744
- return Boolean(typeof value === 'number');
745
- }
746
- const isNotNumber = bindNot(isNumber);
747
-
748
- /**
749
- * Validates that a given value is an odd number
750
- * @param {Number|String} value Value to be validated
751
- * @return {Boolean}
752
- */
753
-
754
- const isOdd = value => {
755
- if (isNumeric(value)) {
756
- return value % 2 !== 0;
757
- }
758
-
759
- return false;
760
- };
761
-
762
- const isNotString = bindNot(isString);
763
-
764
- function isTruthy(value) {
765
- return !!value;
766
- }
767
- const isFalsy = bindNot(isTruthy);
768
-
769
- function lessThan(value, arg1) {
770
- return isNumeric(value) && isNumeric(arg1) && Number(value) < Number(arg1);
771
- }
772
-
773
- function longerThan(value, arg1) {
774
- return value.length > Number(arg1);
775
- }
776
-
777
- function longerThanOrEquals(value, arg1) {
778
- return value.length >= Number(arg1);
779
- }
780
-
781
- function matches(value, regex) {
782
- if (regex instanceof RegExp) {
783
- return regex.test(value);
784
- } else if (isString(regex)) {
785
- return new RegExp(regex).test(value);
786
- } else {
787
- return false;
788
- }
789
- }
790
- const notMatches = bindNot(matches);
791
-
792
- function numberEquals(value, arg1) {
793
- return isNumeric(value) && isNumeric(arg1) && Number(value) === Number(arg1);
794
- }
795
- const numberNotEquals = bindNot(numberEquals);
796
-
797
- function shorterThan(value, arg1) {
798
- return value.length < Number(arg1);
799
- }
800
-
801
- function shorterThanOrEquals(value, arg1) {
802
- return value.length <= Number(arg1);
803
- }
804
-
805
- function startsWith(value, arg1) {
806
- return isString(value) && isString(arg1) && value.startsWith(arg1);
807
- }
808
- const doesNotStartWith = bindNot(startsWith);
809
-
810
- function rules() {
811
- return {
812
- doesNotEndWith,
813
- doesNotStartWith,
814
- endsWith,
815
- equals,
816
- greaterThan,
817
- greaterThanOrEquals,
818
- gt: greaterThan,
819
- gte: greaterThanOrEquals,
820
- inside,
821
- isArray,
822
- isBetween,
823
- isBoolean,
824
- isBlank,
825
- isEmpty,
826
- isEven,
827
- isFalsy,
828
- isNaN: isNaN$1,
829
- isNegative,
830
- isNotArray,
831
- isNotBetween,
832
- isNotBlank,
833
- isNotBoolean,
834
- isNotEmpty,
835
- isNotNaN,
836
- isNotNull,
837
- isNotNumber,
838
- isNotNumeric,
839
- isNotString,
840
- isNotUndefined,
841
- isNull,
842
- isNumber,
843
- isNumeric,
844
- isOdd,
845
- isPositive,
846
- isString,
847
- isTruthy,
848
- isUndefined,
849
- lengthEquals,
850
- lengthNotEquals,
851
- lessThan,
852
- lessThanOrEquals,
853
- longerThan,
854
- longerThanOrEquals,
855
- lt: lessThan,
856
- lte: lessThanOrEquals,
857
- matches,
858
- notEquals,
859
- notInside,
860
- notMatches,
861
- numberEquals,
862
- numberNotEquals,
863
- shorterThan,
864
- shorterThanOrEquals,
865
- startsWith
866
- };
867
- }
868
-
869
- var runtimeRules = assign(rules(), compounds, ruleMeta);
870
-
871
- /**
872
- * Determines whether a given string is a name of a rule
873
- *
874
- * @param {string} name
875
- * @return {boolean}
876
- */
877
-
878
- const isRule = name => hasOwnProperty(runtimeRules, name) && isFunction(runtimeRules[name]);
879
-
880
- const GLOBAL_OBJECT = Function('return this')();
881
-
882
- const proxySupported = () => isFunction(GLOBAL_OBJECT.Proxy);
883
-
884
- function genRuleProxy(target, output) {
885
- if (proxySupported()) {
886
- return new Proxy(target, {
887
- get: (target, fnName) => {
888
- // A faster bailout when we access `run` and `test`
889
- if (hasOwnProperty(target, fnName)) {
890
- return target[fnName];
891
- }
892
-
893
- if (isRule(fnName)) {
894
- return output(fnName);
895
- }
896
-
897
- return target[fnName];
898
- }
899
- });
900
- } else {
901
- /**
902
- * This method is REALLY not recommended as it is slow and iterates over
903
- * all the rules for each direct enforce reference. We only use it as a
904
- * lightweight alternative for the much faster proxy interface
905
- */
906
- for (const fnName in runtimeRules) {
907
- if (!isFunction(target[fnName])) {
908
- Object.defineProperties(target, {
909
- [fnName]: {
910
- get: () => output(fnName)
911
- }
912
- });
913
- }
914
- }
915
-
916
- return target;
917
- }
918
- }
919
-
920
- /**
921
- * Determines whether a given rule is a compound.
922
- *
923
- * @param {Function} rule
924
- * @return {boolean}
925
- */
926
-
927
- function isCompound(rule) {
928
- return hasOwnProperty(compounds, rule.name);
929
- }
930
-
931
- /**
932
- * Creates a rule of lazily called rules.
933
- * Each rule gets added a `.run()` property
934
- * which runs all the accumulated rules in
935
- * the chain against the supplied value
936
- *
937
- * @param {string} ruleName
938
- * @return {{run: Function}}
939
- */
940
-
941
- function bindLazyRule(ruleName) {
942
- const registeredRules = []; // Chained rules
943
-
944
- const meta = []; // Meta properties to add onto the rule context
945
- // Appends a function to the registeredRules array.
946
- // It gets called every time the consumer usess chaining
947
- // so, for example - enforce.isArray() <- this calles addFn
948
-
949
- const addFn = ruleName => {
950
- return withArgs(args => {
951
- const rule = runtimeRules[ruleName]; // Add a meta function
952
-
953
- if (ruleMeta[rule.name] === rule) {
954
- meta.push((value, ruleResult, bail) => {
955
- ruleResult.setAttribute(rule.name, rule(value, args[0], bail));
956
- });
957
- } else {
958
- // Register a rule
959
- registeredRules.push(setFnName(value => {
960
- return rule.apply(null, [// If the rule is compound - wraps the value with context
961
- // Otherwise - unwraps it
962
- isCompound(rule) ? EnforceContext.wrap(value) : EnforceContext.unwrap(value)].concat(args));
963
- }, ruleName));
964
- } // set addFn as the proxy handler
965
-
966
-
967
- const returnvalue = genRuleProxy({}, addFn);
968
-
969
- returnvalue[RUN_RULE] = value => {
970
- const result = new RuleResult(true);
971
- let bailed = false; // Run meta chains
972
-
973
- meta.forEach(fn => {
974
- fn(value, result, shouldBail => bailed = shouldBail);
975
- });
976
-
977
- if (bailed) {
978
- return null;
979
- } // Iterate over all the registered rules
980
- // This runs the function that's inside `addFn`
981
-
982
-
983
- for (const fn of registeredRules) {
984
- try {
985
- result.extend(fn(value)); // If a chained rule fails, exit. We failed.
986
-
987
- if (!result.pass) {
988
- break;
989
- }
990
- } catch (e) {
991
- result.setFailed(true);
992
- break;
993
- }
994
- }
995
-
996
- return result;
997
- };
998
-
999
- returnvalue[TEST_RULE] = value => returnvalue[RUN_RULE](EnforceContext.wrap(value).setFailFast(true)).pass;
1000
-
1001
- return returnvalue;
1002
- }, ruleName);
1003
- }; // Returns the initial rule in the chain
1004
-
1005
-
1006
- return addFn(ruleName);
1007
- }
1008
-
1009
- function bindExtend(enforce, Enforce) {
1010
- enforce.extend = customRules => {
1011
- assign(runtimeRules, customRules);
1012
-
1013
- if (!proxySupported()) {
1014
- genRuleProxy(Enforce, bindLazyRule);
1015
- }
1016
-
1017
- return enforce;
1018
- };
1019
- }
1020
-
1021
- /**
1022
- * Throws a timed out error.
1023
- * @param {String} message Error message to display.
1024
- * @param {Error} [type] Alternative Error type.
1025
- */
1026
- const throwError = (message, type = Error) => {
1027
- throw new type(`[${"n4s"}]: ${message}`);
1028
- };
1029
-
1030
- function validateResult(result, rule) {
1031
- // if result is boolean, or if result.pass is boolean
1032
- if (isBoolean(result) || result && isBoolean(result.pass)) {
1033
- return;
1034
- }
1035
-
1036
- throwError(rule.name + 'wrong return value');
1037
- } // for easier testing and mocking
1038
-
1039
- function getDefaultResult(value) {
1040
- return {
1041
- message: new Error(`invalid ${typeof value} value`)
1042
- };
1043
- }
1044
- /**
1045
- * Transform the result of a rule into a standard format
1046
- * @param {string} interfaceName to be used in the messages
1047
- * @param {*} result of the rule
1048
- * @param {Object} options
1049
- * @param {function} options.rule
1050
- * @param {*} options.value
1051
- * @returns {Object} result
1052
- * @returns {string} result.message
1053
- * @returns {boolean} result.pass indicates if the test passes or not
1054
- */
1055
-
1056
- function transformResult(result, {
1057
- rule,
1058
- value
1059
- }) {
1060
- const defaultResult = getDefaultResult(value);
1061
- validateResult(result, rule); // if result is boolean
1062
-
1063
- if (isBoolean(result)) {
1064
- return defaultResult.pass = result, defaultResult;
1065
- } else {
1066
- defaultResult.pass = result.pass;
1067
-
1068
- if (result.message) {
1069
- defaultResult.message = optionalFunctionValue(result.message);
1070
- }
1071
-
1072
- return defaultResult;
1073
- }
1074
- }
1075
-
1076
- /**
1077
- * Run a single rule against enforced value (e.g. `isNumber()`)
1078
- *
1079
- * @param {Function} rule - rule to run
1080
- * @param {Any} value
1081
- * @param {Array} args list of arguments sent from consumer
1082
- * @throws
1083
- */
1084
-
1085
- function runner(rule, value, args = []) {
1086
- let result;
1087
- const isCompoundRule = isCompound(rule);
1088
- const ruleValue = isCompoundRule ? EnforceContext.wrap(value).setFailFast(true) : EnforceContext.unwrap(value);
1089
- result = rule.apply(null, [ruleValue].concat(args));
1090
-
1091
- if (!isCompoundRule) {
1092
- result = transformResult(result, {
1093
- rule,
1094
- value
1095
- });
1096
- }
1097
-
1098
- if (!result.pass) {
1099
- throw result.message;
1100
- }
1101
- }
1102
-
1103
- /**
1104
- * Adds `template` property to enforce.
1105
- *
1106
- * @param {Function} enforce
1107
- */
1108
-
1109
- function bindTemplate(enforce) {
1110
- enforce.template = withArgs(rules => {
1111
- const template = value => {
1112
- runner(runLazyRules.bind(null, rules), value);
1113
- const proxy = genRuleProxy({}, ruleName => withArgs(args => {
1114
- runner(runtimeRules[ruleName], value, args);
1115
- return proxy;
1116
- }));
1117
- return proxy;
1118
- }; // `run` returns a deep ResultObject
1119
-
1120
-
1121
- template[RUN_RULE] = value => runLazyRules(rules, value); // `test` returns a boolean
1122
-
1123
-
1124
- template[TEST_RULE] = value => runLazyRules(rules, EnforceContext.wrap(value).setFailFast(true)).pass;
1125
-
1126
- return template;
1127
- });
1128
- }
1129
-
1130
- const Enforce = value => {
1131
- const proxy = genRuleProxy({}, ruleName => withArgs(args => {
1132
- runner(runtimeRules[ruleName], value, args);
1133
- return proxy;
1134
- }));
1135
- return proxy;
1136
- };
1137
-
1138
- const enforce = genRuleProxy(Enforce, bindLazyRule);
1139
- bindExtend(enforce, Enforce);
1140
- bindTemplate(enforce);
1141
-
1142
- export default enforce;