-
Notifications
You must be signed in to change notification settings - Fork 4
/
breeze.base.debug.js
15840 lines (13911 loc) · 542 KB
/
breeze.base.debug.js
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014 IdeaBlade, Inc. All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the IdeaBlade Breeze license, available at http://www.breezejs.com/license
*
* Author: Jay Traband
*/
(function (global, definition) {
var def = function(){ return definition(global); };
// CommonJS
if (typeof exports === "object" && typeof module === "object") {
module.exports = def();
// RequireJS
} else if (typeof define === "function" && define["amd"]) {
define(def);
// <script>
} else {
breeze = def();
}
})(this, function (global) {
"use strict";
var breeze = {
version: "1.5.2",
metadataVersion: "1.0.5"
};
;/**
@module core
**/
var __hasOwnProperty = uncurry(Object.prototype.hasOwnProperty);
var __arraySlice = uncurry(Array.prototype.slice);
var __isES5Supported = function () {
try {
return !!Object.getPrototypeOf && Object.defineProperty({}, 'x', {});
} catch (e) {
return false;
}
}();
// iterate over object
function __objectForEach(obj, kvFn) {
for (var key in obj) {
if (__hasOwnProperty(obj, key)) {
kvFn(key, obj[key]);
}
}
}
function __objectMap(obj, kvFn) {
var results = [];
for (var key in obj) {
if (__hasOwnProperty(obj, key)) {
var result = kvFn ? kvFn(key, obj[key]) : obj[key];
if (result !== undefined) {
results.push(result);
}
}
}
return results;
}
function __objectFirst(obj, kvPredicate) {
for (var key in obj) {
if (__hasOwnProperty(obj, key)) {
var value = obj[key];
if (kvPredicate(key, value)) {
return { key: key, value: value };
}
}
}
return null;
}
function __isSettable(entity, propertyName) {
var pd = __getPropDescriptor(entity, propertyName);
if (pd == null) return true;
return !!(pd.writable || pd.set);
}
function __getPropDescriptor(obj, propertyName) {
if (!__isES5Supported) return null;
if (obj.hasOwnProperty(propertyName)) {
return Object.getOwnPropertyDescriptor(obj, propertyName);
} else {
var nextObj = Object.getPrototypeOf(obj);
if (nextObj == null) return null;
return __getPropDescriptor(nextObj, propertyName);
}
}
// Functional extensions
// can be used like: persons.filter(propEq("firstName", "John"))
function __propEq(propertyName, value) {
return function (obj) {
return obj[propertyName] === value;
};
}
// can be used like persons.map(pluck("firstName"))
function __pluck(propertyName) {
return function (obj) {
return obj[propertyName];
};
}
// end functional extensions
function __getOwnPropertyValues(source) {
var result = [];
for (var name in source) {
if (__hasOwnProperty(source, name)) {
result.push(source[name]);
}
}
return result;
}
function __extend(target, source, propNames) {
if (!source) return target;
if (propNames) {
propNames.forEach(function (propName) {
target[propName] = source[propName];
});
} else {
for (var propName in source) {
if (__hasOwnProperty(source, propName)) {
target[propName] = source[propName];
}
}
}
return target;
}
function __updateWithDefaults(target, defaults) {
for (var name in defaults) {
if (target[name] === undefined) {
target[name] = defaults[name];
}
}
return target;
}
function __setAsDefault(target, ctor) {
// we want to insure that the object returned by ctor.defaultInstance is always immutable
// Use 'target' as the primary template for the ctor.defaultInstance;
// Use current 'ctor.defaultInstance' as the template for any missing properties
// creates a new instance for ctor.defaultInstance
// returns target unchanged
ctor.defaultInstance = __updateWithDefaults(new ctor(target), ctor.defaultInstance);
return target;
}
// 'source' is an object that will be transformed into another
// 'template' is a map where the
// keys: are the keys to return
// if a key contains ','s then the key is treated as a delimited string with first of the
// keys being the key to return and the others all valid aliases for this key
// 'values' are either
// 1) the 'default' value of the key
// 2) a function that takes in the source value and should return the value to set
// The value from the source is then set on the target,
// after first passing thru the fn, if provided, UNLESS:
// 1) it is the default value
// 2) it is undefined ( nulls WILL be set)
// 'target' is optional
// - if it exists then properties of the target will be set ( overwritten if the exist)
// - if it does not exist then a new object will be created as filled.
// 'target is returned.
function __toJson(source, template, target) {
target = target || {};
for (var key in template) {
var aliases = key.split(",");
var defaultValue = template[key];
// using some as a forEach with a 'break'
aliases.some(function(propName) {
if (!(propName in source)) return false;
var value = source[propName];
// there is a functional property defined with this alias ( not what we want to replace).
if (typeof value == 'function') return false;
// '==' is deliberate here - idea is that null or undefined values will never get serialized
// if default value is set to null.
if (value == defaultValue) return true;
if (Array.isArray(value) && value.length === 0) return true;
if (typeof(defaultValue) === "function") {
value = defaultValue(value);
} else if (typeof (value) === "object") {
if (value && value.parentEnum) {
value = value.name;
}
}
if (value === undefined) return true;
target[aliases[0]] = value;
return true;
});
}
return target;
}
// safely perform toJSON logic on objects with cycles.
function __toJSONSafe(obj, replacer) {
if (obj !== Object(obj)) return obj; // primitive value
if (obj._$visited) return undefined;
if (obj.toJSON) {
var newObj = obj.toJSON();
if (newObj !== Object(newObj)) return newObj; // primitive value
if (newObj !== obj) return __toJSONSafe(newObj);
// toJSON returned the object unchanged.
obj = newObj;
}
obj._$visited = true;
var result;
if (obj instanceof Array) {
result = obj.map(function (o) {
return __toJSONSafe(o, replacer);
});
} else if (typeof (obj) === "function") {
result = undefined;
} else {
result = {};
for (var prop in obj) {
if (prop === "_$visited") continue;
var val = obj[prop];
if (replacer) {
val = replacer(prop, val);
if (val === undefined) continue;
}
val = __toJSONSafe(val);
if (val === undefined) continue;
result[prop] = val;
}
}
delete obj._$visited;
return result;
}
// resolves the values of a list of properties by checking each property in multiple sources until a value is found.
function __resolveProperties(sources, propertyNames) {
var r = {};
var length = sources.length;
propertyNames.forEach(function (pn) {
for (var i = 0; i < length; i++) {
var src = sources[i];
if (src) {
var val = src[pn];
if (val !== undefined) {
r[pn] = val;
break;
}
}
}
});
return r;
}
// array functions
function __toArray(item) {
if (item == null) {
return [];
} else if (Array.isArray(item)) {
return item;
} else {
return [item];
}
}
// a version of Array.map that doesn't require an array, i.e. works on arrays and scalars.
function __map(items, fn, includeNull) {
// whether to return nulls in array of results; default = true;
includeNull = includeNull == null ? true : includeNull;
if (items == null) return items;
var result;
if (Array.isArray(items)) {
result = [];
items.forEach(function (v, ix) {
var r = fn(v, ix);
if (r != null || includeNull) {
result[ix] = r;
}
});
} else {
result = fn(items);
}
return result;
}
function __arrayFirst(array, predicate) {
for (var i = 0, j = array.length; i < j; i++) {
if (predicate(array[i])) {
return array[i];
}
}
return null;
}
function __arrayIndexOf(array, predicate) {
for (var i = 0, j = array.length; i < j; i++) {
if (predicate(array[i])) return i;
}
return -1;
}
function __arrayAddItemUnique(array, item) {
var ix = array.indexOf(item);
if (ix === -1) array.push(item);
}
function __arrayRemoveItem(array, predicateOrItem, shouldRemoveMultiple) {
var predicate = __isFunction(predicateOrItem) ? predicateOrItem : undefined;
var lastIx = array.length - 1;
var removed = false;
for (var i = lastIx; i >= 0; i--) {
if (predicate ? predicate(array[i]) : (array[i] === predicateOrItem)) {
array.splice(i, 1);
removed = true;
if (!shouldRemoveMultiple) {
return true;
}
}
}
return removed;
}
function __arrayZip(a1, a2, callback) {
var result = [];
var n = Math.min(a1.length, a2.length);
for (var i = 0; i < n; ++i) {
result.push(callback(a1[i], a2[i]));
}
return result;
}
//function __arrayDistinct(array) {
// array = array || [];
// var result = [];
// for (var i = 0, j = array.length; i < j; i++) {
// if (result.indexOf(array[i]) < 0)
// result.push(array[i]);
// }
// return result;
//}
// Not yet needed
//// much faster but only works on array items with a toString method that
//// returns distinct string for distinct objects. So this is safe for arrays with primitive
//// types but not for arrays with object types, unless toString() has been implemented.
//function arrayDistinctUnsafe(array) {
// var o = {}, i, l = array.length, r = [];
// for (i = 0; i < l; i += 1) {
// var v = array[i];
// o[v] = v;
// }
// for (i in o) r.push(o[i]);
// return r;
//}
function __arrayEquals(a1, a2, equalsFn) {
//Check if the arrays are undefined/null
if (!a1 || !a2) return false;
if (a1.length !== a2.length) return false;
//go thru all the vars
for (var i = 0; i < a1.length; i++) {
//if the var is an array, we need to make a recursive check
//otherwise we'll just compare the values
if (Array.isArray(a1[i])) {
if (!__arrayEquals(a1[i], a2[i])) return false;
} else {
if (equalsFn) {
if (!equalsFn(a1[i], a2[i])) return false;
} else {
if (a1[i] !== a2[i]) return false;
}
}
}
return true;
}
// end of array functions
// returns and array for a source and a prop, and creates the prop if needed.
function __getArray(source, propName) {
var arr = source[propName];
if (!arr) {
arr = [];
source[propName] = arr;
}
return arr;
}
function __requireLib(libNames, errMessage) {
var arrNames = libNames.split(";");
for (var i = 0, j = arrNames.length; i < j; i++) {
var lib = __requireLibCore(arrNames[i]);
if (lib) return lib;
}
if (errMessage) {
throw new Error("Unable to initialize " + libNames + ". " + errMessage);
}
}
// Returns the 'libName' module if loaded or else returns undefined
function __requireLibCore(libName) {
var window = global.window;
if (!window) return; // Must run in a browser. Todo: add commonjs support
// get library from browser globals if we can
var lib = window[libName];
if (lib) return lib;
// if require exists, maybe require can get it.
// This method is synchronous so it can't load modules with AMD.
// It can only obtain modules from require that have already been loaded.
// Developer should bootstrap such that the breeze module
// loads after all other libraries that breeze should find with this method
// See documentation
var r = window.require;
if (r) { // if require exists
if (r.defined) { // require.defined is not standard and may not exist
// require.defined returns true if module has been loaded
return r.defined(libName) ? r(libName) : undefined;
} else {
// require.defined does not exist so we have to call require('libName') directly.
// The require('libName') overload is synchronous and does not load modules.
// It throws an exception if the module isn't already loaded.
try {
return r(libName);
} catch (e) {
// require('libName') threw because module not loaded
return;
}
}
}
}
function __using(obj, property, tempValue, fn) {
var originalValue = obj[property];
if (tempValue === originalValue) {
return fn();
}
obj[property] = tempValue;
try {
return fn();
} finally {
if (originalValue === undefined) {
delete obj[property];
} else {
obj[property] = originalValue;
}
}
}
function __wrapExecution(startFn, endFn, fn) {
var state;
try {
state = startFn();
return fn();
} catch (e) {
if (typeof(state) === 'object') {
state.error = e;
}
throw e;
} finally {
endFn(state);
}
}
function __memoize(fn) {
return function () {
var args = __arraySlice(arguments),
hash = "",
i = args.length,
currentArg = null;
while (i--) {
currentArg = args[i];
hash += (currentArg === Object(currentArg)) ? JSON.stringify(currentArg) : currentArg;
fn.memoize || (fn.memoize = {});
}
return (hash in fn.memoize) ?
fn.memoize[hash] :
fn.memoize[hash] = fn.apply(this, args);
};
}
function __getUuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
//noinspection NonShortCircuitBooleanExpressionJS
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function __durationToSeconds(duration) {
// basic algorithm from https://github.com/nezasa/iso8601-js-period
if (typeof duration !== "string") throw new Error("Invalid ISO8601 duration '" + duration + "'");
// regex splits as follows - grp0, grp1, y, m, d, grp2, h, m, s
// 0 1 2 3 4 5 6 7 8
var struct = /^P((\d+Y)?(\d+M)?(\d+D)?)?(T(\d+H)?(\d+M)?(\d+S)?)?$/.exec(duration);
if (!struct) throw new Error("Invalid ISO8601 duration '" + duration + "'");
var ymdhmsIndexes = [2, 3, 4, 6, 7, 8]; // -> grp1,y,m,d,grp2,h,m,s
var factors = [31104000, // year (360*24*60*60)
2592000, // month (30*24*60*60)
86400, // day (24*60*60)
3600, // hour (60*60)
60, // minute (60)
1]; // second (1)
var seconds = 0;
for (var i = 0; i < 6; i++) {
var digit = struct[ymdhmsIndexes[i]];
// remove letters, replace by 0 if not defined
digit = digit ? +digit.replace(/[A-Za-z]+/g, '') : 0;
seconds += digit * factors[i];
}
return seconds;
}
// is functions
function __noop() {
// does nothing
}
function __identity(x) {
return x;
}
function __classof(o) {
if (o === null) {
return "null";
}
if (o === undefined) {
return "undefined";
}
return Object.prototype.toString.call(o).slice(8, -1).toLowerCase();
}
function __isDate(o) {
return __classof(o) === "date" && !isNaN(o.getTime());
}
function __isDateString(s) {
// var rx = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/;
var rx = /^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/;
return (typeof s === "string") && rx.test(s);
}
function __isFunction(o) {
return __classof(o) === "function";
}
function __isString(o) {
return (typeof o === "string");
}
function __isObject(o) {
return (typeof o === "object");
}
function __isGuid(value) {
return (typeof value === "string") && /[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}/.test(value);
}
function __isDuration(value) {
return (typeof value === "string") && /^(-|)?P[T]?[\d\.,\-]+[YMDTHS]/.test(value);
}
function __isEmpty(obj) {
if (obj === null || obj === undefined) {
return true;
}
for (var key in obj) {
if (__hasOwnProperty(obj, key)) {
return false;
}
}
return true;
}
function __isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
// returns true for booleans, numbers, strings and dates
// false for null, and non-date objects, functions, and arrays
function __isPrimitive(obj) {
if (obj == null) return false;
// true for numbers, strings, booleans and null, false for objects
if (obj != Object(obj)) return true;
return _isDate(obj);
}
// end of is Functions
// string functions
function __stringStartsWith(str, prefix) {
// returns true for empty string or null prefix
if ((!str)) return false;
if (prefix == "" || prefix == null) return true;
return str.indexOf(prefix, 0) === 0;
}
function __stringEndsWith(str, suffix) {
// returns true for empty string or null suffix
if ((!str)) return false;
if (suffix == "" || suffix == null) return true;
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
// Based on fragment from Dean Edwards' Base 2 library
// format("a %1 and a %2", "cat", "dog") -> "a cat and a dog"
function __formatString(string) {
var args = arguments;
var pattern = RegExp("%([1-" + (arguments.length - 1) + "])", "g");
return string.replace(pattern, function (match, index) {
return args[index];
});
}
// end of string functions
// See Mark Miller’s explanation of what this does.
// http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
function uncurry(f) {
var call = Function.call;
return function () {
return call.apply(f, arguments);
};
}
// shims
if (!Object.create) {
Object.create = function (parent) {
var F = function () {
};
F.prototype = parent;
return new F();
};
}
var core = {};
// not all methods above are exported
core.__isES5Supported = __isES5Supported;
core.objectForEach = __objectForEach;
core.extend = __extend;
core.propEq = __propEq;
core.pluck = __pluck;
core.arrayEquals = __arrayEquals;
core.arrayFirst = __arrayFirst;
core.arrayIndexOf = __arrayIndexOf;
core.arrayRemoveItem = __arrayRemoveItem;
core.arrayZip = __arrayZip;
core.requireLib = __requireLib;
core.using = __using;
core.memoize = __memoize;
core.getUuid = __getUuid;
core.durationToSeconds = __durationToSeconds;
core.isDate = __isDate;
core.isGuid = __isGuid;
core.isDuration = __isDuration;
core.isFunction = __isFunction;
core.isEmpty = __isEmpty;
core.isNumeric = __isNumeric;
core.stringStartsWith = __stringStartsWith;
core.stringEndsWith = __stringEndsWith;
core.formatString = __formatString;
core.getPropertyDescriptor = __getPropDescriptor;
core.toJSONSafe = __toJSONSafe;
core.parent = breeze;
breeze.core = core;
;/**
@module core
**/
var Param = (function () {
// The %1 parameter
// is required
// must be a %2
// must be an instance of %2
// must be an instance of the %2 enumeration
// must have a %2 property
// must be an array where each element
// is optional or
var ctor = function (v, name) {
this.v = v;
this.name = name;
this._contexts = [null];
};
var proto = ctor.prototype;
proto.isObject = function () {
return this.isTypeOf("object");
};
proto.isBoolean = function () {
return this.isTypeOf('boolean');
};
proto.isString = function () {
return this.isTypeOf('string');
};
proto.isNonEmptyString = function () {
return addContext(this, {
fn: isNonEmptyString,
msg: "must be a nonEmpty string"
});
};
function isNonEmptyString(context, v) {
if (v == null) return false;
return (typeof(v) === 'string') && v.length > 0;
}
proto.isNumber = function () {
return this.isTypeOf('number');
};
proto.isFunction = function () {
return this.isTypeOf('function');
};
proto.isTypeOf = function (typeName) {
return addContext(this, {
fn: isTypeOf,
typeName: typeName,
msg: __formatString("must be a '%1'", typeName)
});
};
function isTypeOf(context, v) {
if (v == null) return false;
if (typeof(v) === context.typeName) return true;
return false;
}
proto.isInstanceOf = function (type, typeName) {
typeName = typeName || type.prototype._$typeName;
return addContext(this, {
fn: isInstanceOf,
type: type,
typeName: typeName,
msg: __formatString("must be an instance of '%1'", typeName)
});
};
function isInstanceOf(context, v) {
if (v == null) return false;
return (v instanceof context.type);
}
proto.hasProperty = function (propertyName) {
return addContext(this, {
fn: hasProperty,
propertyName: propertyName,
msg: __formatString("must have a '%1' property ", propertyName)
});
};
function hasProperty(context, v) {
if (v == null) return false;
return (v[context.propertyName] !== undefined);
}
proto.isEnumOf = function (enumType) {
return addContext(this, {
fn: isEnumOf,
enumType: enumType,
msg: __formatString("must be an instance of the '%1' enumeration", enumType.name)
});
};
function isEnumOf(context, v) {
if (v == null) return false;
return context.enumType.contains(v);
}
proto.isRequired = function (allowNull) {
return addContext(this, {
fn: isRequired,
allowNull: allowNull,
msg: "is required"
});
};
function isRequired(context, v) {
if (context.allowNull) {
return v !== undefined;
} else {
return v != null;
}
}
// combinable methods.
proto.isOptional = function () {
var context = {
fn: isOptional,
prevContext: null,
msg: isOptionalMessage
};
return addContext(this, context);
};
function isOptional(context, v) {
if (v == null) return true;
var prevContext = context.prevContext;
if (prevContext) {
return prevContext.fn(prevContext, v);
} else {
return true;
}
}
function isOptionalMessage(context, v) {
var prevContext = context.prevContext;
var element = prevContext ? " or it " + getMessage(prevContext, v) : "";
return "is optional" + element;
}
proto.isNonEmptyArray = function () {
return this.isArray(true);
};
proto.isArray = function (mustNotBeEmpty) {
var context = {
fn: isArray,
mustNotBeEmpty: mustNotBeEmpty,
prevContext: null,
msg: isArrayMessage
};
return addContext(this, context);
};
function isArray(context, v) {
if (!Array.isArray(v)) {
return false;
}
if (context.mustNotBeEmpty) {
if (v.length === 0) return false;
}
// allow standalone is array call.
var prevContext = context.prevContext;
if (!prevContext) return true;
return v.every(function (v1) {
return prevContext.fn(prevContext, v1);
});
}
function isArrayMessage(context, v) {
var arrayDescr = context.mustNotBeEmpty ? "a nonEmpty array" : "an array";
var prevContext = context.prevContext;
var element = prevContext ? " where each element " + getMessage(prevContext, v) : "";
return " must be " + arrayDescr + element;
}
function getMessage(context, v) {
var msg = context.msg;
if (typeof(msg) === "function") {
msg = msg(context, v);
}
return msg;
}
proto.or = function () {
this._contexts.push(null);
this._context = null;
return this;
};
proto.check = function (defaultValue) {
var ok = exec(this);
if (ok === undefined) return;
if (!ok) {
throw new Error(this.getMessage());
}
if (this.v !== undefined) {
return this.v;
} else {
return defaultValue;
}
};
// called from outside this file.
proto._addContext = function (context) {
return addContext(this, context);
};
function addContext(that, context) {
if (that._context) {
var curContext = that._context;
while (curContext.prevContext != null) {
curContext = curContext.prevContext;
}
if (curContext.prevContext === null) {
curContext.prevContext = context;
// just update the prevContext but don't change the curContext.
return that;
} else if (context.prevContext == null) {
context.prevContext = that._context;
} else {
throw new Error("Illegal construction - use 'or' to combine checks");
}
}
return setContext(that, context);
}
function setContext(that, context) {
that._contexts[that._contexts.length - 1] = context;
that._context = context;
return that;
}
function exec(self) {
// clear off last one if null
var contexts = self._contexts;
if (contexts[contexts.length - 1] == null) {
contexts.pop();
}
if (contexts.length === 0) {
return undefined;
}
return contexts.some(function (context) {
return context.fn(context, self.v);
});
}
proto.getMessage = function () {
var that = this;
var message = this._contexts.map(function (context) {
return getMessage(context, that.v);
}).join(", or it ");
return __formatString(this.MESSAGE_PREFIX, this.name) + " " + message;
};
proto.withDefault = function (defaultValue) {
this.defaultValue = defaultValue;
return this;
};
proto.whereParam = function (propName) {
return this.parent.whereParam(propName);
};
proto.applyAll = function (instance, checkOnly) {
var parentTypeName = instance._$typeName;
var allowUnknownProperty = (parentTypeName && this.parent.config._$typeName === parentTypeName);
var clone = __extend({}, this.parent.config);
this.parent.params.forEach(function (p) {
if (!allowUnknownProperty) delete clone[p.name];
try {
p.check();
} catch (e) {
throwConfigError(instance, e.message);
}
(!checkOnly) && p._applyOne(instance);
});
// should be no properties left in the clone