object.js
20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
// Load modules
var Hoek = require('hoek');
var Topo = require('topo');
var Any = require('./any');
var Cast = require('./cast');
var Errors = require('./errors');
// Declare internals
var internals = {};
internals.Object = function () {
Any.call(this);
this._type = 'object';
this._inner.children = null;
this._inner.renames = [];
this._inner.dependencies = [];
this._inner.patterns = [];
};
Hoek.inherits(internals.Object, Any);
internals.Object.prototype._base = function (value, state, options) {
var item, key, localState, result;
var target = value;
var errors = [];
var finish = function () {
return {
value: target,
errors: errors.length ? errors : null
};
};
if (typeof value === 'string' &&
options.convert) {
try {
value = JSON.parse(value);
}
catch (parseErr) { }
}
var type = this._flags.func ? 'function' : 'object';
if (!value ||
typeof value !== type ||
Array.isArray(value)) {
errors.push(Errors.create(type + '.base', null, state, options));
return finish();
}
// Skip if there are no other rules to test
if (!this._inner.renames.length &&
!this._inner.dependencies.length &&
!this._inner.children && // null allows any keys
!this._inner.patterns.length) {
target = value;
return finish();
}
// Ensure target is a local copy (parsed) or shallow copy
if (target === value) {
if (type === 'object') {
target = Object.create(Object.getPrototypeOf(value));
}
else {
target = function () {
return value.apply(this, arguments);
};
target.prototype = Hoek.clone(value.prototype);
}
var valueKeys = Object.keys(value);
for (var t = 0, tl = valueKeys.length; t < tl; ++t) {
target[valueKeys[t]] = value[valueKeys[t]];
}
}
else {
target = value;
}
// Rename keys
var renamed = {};
for (var r = 0, rl = this._inner.renames.length; r < rl; ++r) {
item = this._inner.renames[r];
if (item.options.ignoreUndefined && target[item.from] === undefined) {
continue;
}
if (!item.options.multiple &&
renamed[item.to]) {
errors.push(Errors.create('object.rename.multiple', { from: item.from, to: item.to }, state, options));
if (options.abortEarly) {
return finish();
}
}
if (Object.prototype.hasOwnProperty.call(target, item.to) &&
!item.options.override &&
!renamed[item.to]) {
errors.push(Errors.create('object.rename.override', { from: item.from, to: item.to }, state, options));
if (options.abortEarly) {
return finish();
}
}
if (target[item.from] === undefined) {
delete target[item.to];
}
else {
target[item.to] = target[item.from];
}
renamed[item.to] = true;
if (!item.options.alias) {
delete target[item.from];
}
}
// Validate schema
if (!this._inner.children && // null allows any keys
!this._inner.patterns.length &&
!this._inner.dependencies.length) {
return finish();
}
var unprocessed = Hoek.mapToObject(Object.keys(target));
if (this._inner.children) {
for (var i = 0, il = this._inner.children.length; i < il; ++i) {
var child = this._inner.children[i];
key = child.key;
item = target[key];
delete unprocessed[key];
localState = { key: key, path: (state.path || '') + (state.path && key ? '.' : '') + key, parent: target, reference: state.reference };
result = child.schema._validate(item, localState, options);
if (result.errors) {
errors.push(Errors.create('object.child', { key: key, reason: result.errors }, localState, options));
if (options.abortEarly) {
return finish();
}
}
if (child.schema._flags.strip || (result.value === undefined && result.value !== item)) {
delete target[key];
}
else if (result.value !== undefined) {
target[key] = result.value;
}
}
}
// Unknown keys
var unprocessedKeys = Object.keys(unprocessed);
if (unprocessedKeys.length &&
this._inner.patterns.length) {
for (i = 0, il = unprocessedKeys.length; i < il; ++i) {
key = unprocessedKeys[i];
for (var p = 0, pl = this._inner.patterns.length; p < pl; ++p) {
var pattern = this._inner.patterns[p];
if (pattern.regex.test(key)) {
delete unprocessed[key];
item = target[key];
localState = { key: key, path: (state.path ? state.path + '.' : '') + key, parent: target, reference: state.reference };
result = pattern.rule._validate(item, localState, options);
if (result.errors) {
errors.push(Errors.create('object.child', { key: key, reason: result.errors }, localState, options));
if (options.abortEarly) {
return finish();
}
}
if (result.value !== undefined) {
target[key] = result.value;
}
}
}
}
unprocessedKeys = Object.keys(unprocessed);
}
if ((this._inner.children || this._inner.patterns.length) && unprocessedKeys.length) {
if (options.stripUnknown ||
options.skipFunctions) {
for (var k = 0, kl = unprocessedKeys.length; k < kl; ++k) {
key = unprocessedKeys[k];
if (options.stripUnknown) {
delete target[key];
delete unprocessed[key];
}
else if (typeof target[key] === 'function') {
delete unprocessed[key];
}
}
unprocessedKeys = Object.keys(unprocessed);
}
if (unprocessedKeys.length &&
(this._flags.allowUnknown !== undefined ? !this._flags.allowUnknown : !options.allowUnknown)) {
for (var e = 0, el = unprocessedKeys.length; e < el; ++e) {
errors.push(Errors.create('object.allowUnknown', null, { key: unprocessedKeys[e], path: state.path + (state.path ? '.' : '') + unprocessedKeys[e] }, options));
}
}
}
// Validate dependencies
for (var d = 0, dl = this._inner.dependencies.length; d < dl; ++d) {
var dep = this._inner.dependencies[d];
var err = internals[dep.type](dep.key !== null && value[dep.key], dep.peers, target, { key: dep.key, path: (state.path || '') + (dep.key ? '.' + dep.key : '') }, options);
if (err) {
errors.push(err);
if (options.abortEarly) {
return finish();
}
}
}
return finish();
};
internals.Object.prototype._func = function () {
var obj = this.clone();
obj._flags.func = true;
return obj;
};
internals.Object.prototype.keys = function (schema) {
Hoek.assert(schema === null || schema === undefined || typeof schema === 'object', 'Object schema must be a valid object');
Hoek.assert(!schema || !schema.isJoi, 'Object schema cannot be a joi schema');
var obj = this.clone();
if (!schema) {
obj._inner.children = null;
return obj;
}
var children = Object.keys(schema);
if (!children.length) {
obj._inner.children = [];
return obj;
}
var topo = new Topo();
var child;
if (obj._inner.children) {
for (var i = 0, il = obj._inner.children.length; i < il; ++i) {
child = obj._inner.children[i];
// Only add the key if we are not going to replace it later
if (children.indexOf(child.key) === -1) {
topo.add(child, { after: child._refs, group: child.key });
}
}
}
for (var c = 0, cl = children.length; c < cl; ++c) {
var key = children[c];
child = schema[key];
try {
var cast = Cast.schema(child);
topo.add({ key: key, schema: cast }, { after: cast._refs, group: key });
}
catch (castErr) {
if (castErr.hasOwnProperty('path')) {
castErr.path = key + '.' + castErr.path;
}
else {
castErr.path = key;
}
throw castErr;
}
}
obj._inner.children = topo.nodes;
return obj;
};
internals.Object.prototype.unknown = function (allow) {
var obj = this.clone();
obj._flags.allowUnknown = (allow !== false);
return obj;
};
internals.Object.prototype.length = function (limit) {
Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('length', limit, function (value, state, options) {
if (Object.keys(value).length === limit) {
return null;
}
return Errors.create('object.length', { limit: limit }, state, options);
});
};
internals.Object.prototype.min = function (limit) {
Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('min', limit, function (value, state, options) {
if (Object.keys(value).length >= limit) {
return null;
}
return Errors.create('object.min', { limit: limit }, state, options);
});
};
internals.Object.prototype.max = function (limit) {
Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('max', limit, function (value, state, options) {
if (Object.keys(value).length <= limit) {
return null;
}
return Errors.create('object.max', { limit: limit }, state, options);
});
};
internals.Object.prototype.pattern = function (pattern, schema) {
Hoek.assert(pattern instanceof RegExp, 'Invalid regular expression');
Hoek.assert(schema !== undefined, 'Invalid rule');
pattern = new RegExp(pattern.source, pattern.ignoreCase ? 'i' : undefined); // Future version should break this and forbid unsupported regex flags
try {
schema = Cast.schema(schema);
}
catch (castErr) {
if (castErr.hasOwnProperty('path')) {
castErr.message += '(' + castErr.path + ')';
}
throw castErr;
}
var obj = this.clone();
obj._inner.patterns.push({ regex: pattern, rule: schema });
return obj;
};
internals.Object.prototype.with = function (key, peers) {
return this._dependency('with', key, peers);
};
internals.Object.prototype.without = function (key, peers) {
return this._dependency('without', key, peers);
};
internals.Object.prototype.xor = function () {
var peers = Hoek.flatten(Array.prototype.slice.call(arguments));
return this._dependency('xor', null, peers);
};
internals.Object.prototype.or = function () {
var peers = Hoek.flatten(Array.prototype.slice.call(arguments));
return this._dependency('or', null, peers);
};
internals.Object.prototype.and = function () {
var peers = Hoek.flatten(Array.prototype.slice.call(arguments));
return this._dependency('and', null, peers);
};
internals.Object.prototype.nand = function () {
var peers = Hoek.flatten(Array.prototype.slice.call(arguments));
return this._dependency('nand', null, peers);
};
internals.Object.prototype.requiredKeys = function (children) {
children = Hoek.flatten(Array.prototype.slice.call(arguments));
return this.applyFunctionToChildren(children, 'required');
};
internals.Object.prototype.optionalKeys = function (children) {
children = Hoek.flatten(Array.prototype.slice.call(arguments));
return this.applyFunctionToChildren(children, 'optional');
};
internals.renameDefaults = {
alias: false, // Keep old value in place
multiple: false, // Allow renaming multiple keys into the same target
override: false // Overrides an existing key
};
internals.Object.prototype.rename = function (from, to, options) {
Hoek.assert(typeof from === 'string', 'Rename missing the from argument');
Hoek.assert(typeof to === 'string', 'Rename missing the to argument');
Hoek.assert(to !== from, 'Cannot rename key to same name:', from);
for (var i = 0, il = this._inner.renames.length; i < il; ++i) {
Hoek.assert(this._inner.renames[i].from !== from, 'Cannot rename the same key multiple times');
}
var obj = this.clone();
obj._inner.renames.push({
from: from,
to: to,
options: Hoek.applyToDefaults(internals.renameDefaults, options || {})
});
return obj;
};
internals.groupChildren = function (children) {
children.sort();
var grouped = {};
for (var c = 0, lc = children.length; c < lc; c++) {
var child = children[c];
Hoek.assert(typeof child === 'string', 'children must be strings');
var group = child.split('.')[0];
var childGroup = grouped[group] = (grouped[group] || []);
childGroup.push(child.substring(group.length + 1));
}
return grouped;
};
internals.Object.prototype.applyFunctionToChildren = function (children, fn, args, root) {
children = [].concat(children);
Hoek.assert(children.length > 0, 'expected at least one children');
var groupedChildren = internals.groupChildren(children);
var obj;
if ('' in groupedChildren) {
obj = this[fn].apply(this, args);
delete groupedChildren[''];
}
else {
obj = this.clone();
}
if (obj._inner.children) {
root = root ? (root + '.') : '';
for (var i = 0, il = obj._inner.children.length; i < il; ++i) {
var child = obj._inner.children[i];
var group = groupedChildren[child.key];
if (group) {
obj._inner.children[i] = {
key: child.key,
_refs: child._refs,
schema: child.schema.applyFunctionToChildren(group, fn, args, root + child.key)
};
delete groupedChildren[child.key];
}
}
}
var remaining = Object.keys(groupedChildren);
Hoek.assert(remaining.length === 0, 'unknown key(s)', remaining.join(', '));
return obj;
};
internals.Object.prototype._dependency = function (type, key, peers) {
peers = [].concat(peers);
for (var i = 0, li = peers.length; i < li; i++) {
Hoek.assert(typeof peers[i] === 'string', type, 'peers must be a string or array of strings');
}
var obj = this.clone();
obj._inner.dependencies.push({ type: type, key: key, peers: peers });
return obj;
};
internals.with = function (value, peers, parent, state, options) {
if (value === undefined) {
return null;
}
for (var i = 0, il = peers.length; i < il; ++i) {
var peer = peers[i];
if (!Object.prototype.hasOwnProperty.call(parent, peer) ||
parent[peer] === undefined) {
return Errors.create('object.with', { peer: peer }, state, options);
}
}
return null;
};
internals.without = function (value, peers, parent, state, options) {
if (value === undefined) {
return null;
}
for (var i = 0, il = peers.length; i < il; ++i) {
var peer = peers[i];
if (Object.prototype.hasOwnProperty.call(parent, peer) &&
parent[peer] !== undefined) {
return Errors.create('object.without', { peer: peer }, state, options);
}
}
return null;
};
internals.xor = function (value, peers, parent, state, options) {
var present = [];
for (var i = 0, il = peers.length; i < il; ++i) {
var peer = peers[i];
if (Object.prototype.hasOwnProperty.call(parent, peer) &&
parent[peer] !== undefined) {
present.push(peer);
}
}
if (present.length === 1) {
return null;
}
if (present.length === 0) {
return Errors.create('object.missing', { peers: peers }, state, options);
}
return Errors.create('object.xor', { peers: peers }, state, options);
};
internals.or = function (value, peers, parent, state, options) {
for (var i = 0, il = peers.length; i < il; ++i) {
var peer = peers[i];
if (Object.prototype.hasOwnProperty.call(parent, peer) &&
parent[peer] !== undefined) {
return null;
}
}
return Errors.create('object.missing', { peers: peers }, state, options);
};
internals.and = function (value, peers, parent, state, options) {
var missing = [];
var present = [];
var count = peers.length;
for (var i = 0; i < count; ++i) {
var peer = peers[i];
if (!Object.prototype.hasOwnProperty.call(parent, peer) ||
parent[peer] === undefined) {
missing.push(peer);
}
else {
present.push(peer);
}
}
var aon = (missing.length === count || present.length === count);
return !aon ? Errors.create('object.and', { present: present, missing: missing }, state, options) : null;
};
internals.nand = function (value, peers, parent, state, options) {
var present = [];
for (var i = 0, il = peers.length; i < il; ++i) {
var peer = peers[i];
if (Object.prototype.hasOwnProperty.call(parent, peer) &&
parent[peer] !== undefined) {
present.push(peer);
}
}
var values = Hoek.clone(peers);
var main = values.splice(0, 1)[0];
var allPresent = (present.length === peers.length);
return allPresent ? Errors.create('object.nand', { main: main, peers: values }, state, options) : null;
};
internals.Object.prototype.describe = function (shallow) {
var description = Any.prototype.describe.call(this);
if (this._inner.children &&
!shallow) {
description.children = {};
for (var i = 0, il = this._inner.children.length; i < il; ++i) {
var child = this._inner.children[i];
description.children[child.key] = child.schema.describe();
}
}
if (this._inner.dependencies.length) {
description.dependencies = Hoek.clone(this._inner.dependencies);
}
if (this._inner.patterns.length) {
description.patterns = [];
for (var p = 0, pl = this._inner.patterns.length; p < pl; ++p) {
var pattern = this._inner.patterns[p];
description.patterns.push({ regex: pattern.regex.toString(), rule: pattern.rule.describe() });
}
}
return description;
};
internals.Object.prototype.assert = function (ref, schema, message) {
ref = Cast.ref(ref);
Hoek.assert(ref.isContext || ref.depth > 1, 'Cannot use assertions for root level references - use direct key rules instead');
message = message || 'pass the assertion test';
var cast;
try {
cast = Cast.schema(schema);
}
catch (castErr) {
if (castErr.hasOwnProperty('path')) {
castErr.message += '(' + castErr.path + ')';
}
throw castErr;
}
var key = ref.path[ref.path.length - 1];
var path = ref.path.join('.');
return this._test('assert', { cast: cast, ref: ref }, function (value, state, options) {
var result = cast._validate(ref(value), null, options, value);
if (!result.errors) {
return null;
}
var localState = Hoek.merge({}, state);
localState.key = key;
localState.path = path;
return Errors.create('object.assert', { ref: localState.path, message: message }, localState, options);
});
};
internals.Object.prototype.type = function (constructor, name) {
Hoek.assert(typeof constructor === 'function', 'type must be a constructor function');
name = name || constructor.name;
return this._test('type', name, function (value, state, options) {
if (value instanceof constructor) {
return null;
}
return Errors.create('object.type', { type: name }, state, options);
});
};
module.exports = new internals.Object();