forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrtts_assert.ts
More file actions
369 lines (289 loc) · 8.57 KB
/
rtts_assert.ts
File metadata and controls
369 lines (289 loc) · 8.57 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
var _global = typeof window === 'object' ? window : global;
// TODO(vojta):
// - extract into multiple files
// - different error types
// - simplify/humanize error messages
// - throw when invalid input (such as odd number of args into assert.argumentTypes)
var POSITION_NAME = ['', '1st', '2nd', '3rd'];
function argPositionName(i) {
var position = (i / 2) + 1;
return POSITION_NAME[position] || (position + 'th');
}
var primitives;
var genericType;
if (typeof _global['$traceurRuntime'] === 'object') {
primitives = _global['$traceurRuntime'].type;
genericType = _global['$traceurRuntime'].genericType;
} else {
// Allow to work without traceur runtime as well!
primitives = {
any: {name: 'any'},
boolean: {name: 'boolean'},
number: {name: 'number'},
string: {name: 'string'},
symbol: {name: 'symbol'}, void: {name: 'void'}
};
genericType = function(type, args) {
return { type: type, args: args }
}
}
Object.keys(primitives).forEach(function(name) { primitives[name].__assertName = name; });
export function proxy() {}
function assertArgumentTypes(...params) {
var actual, type;
var currentArgErrors;
var errors = [];
var msg;
for (var i = 0, l = params.length; i < l; i = i + 2) {
actual = params[i];
type = params[i + 1];
currentArgErrors = [];
// currentStack = [];
//
if (!isType(actual, type, currentArgErrors)) {
// console.log(JSON.stringify(errors, null, ' '));
// TODO(vojta): print "an instance of" only if T starts with uppercase.
errors.push(argPositionName(i) + ' argument has to be an instance of ' + prettyPrint(type) +
', got ' + prettyPrint(actual));
if (currentArgErrors.length) {
errors.push(currentArgErrors);
}
}
}
if (errors.length) {
throw new Error('Invalid arguments given!\n' + formatErrors(errors));
}
}
function prettyPrint(value, depth?) {
if (typeof(depth) === 'undefined') {
depth = 0;
}
if (depth++ > 3) {
return '[...]';
}
if (typeof value === 'undefined') {
return 'undefined';
}
if (typeof value === 'string') {
return '"' + value + '"';
}
if (typeof value === 'boolean') {
return value.toString();
}
if (value === null) {
return 'null';
}
if (typeof value === 'object') {
if (value.__assertName) {
return value.__assertName;
}
if (value.map && typeof value.map === 'function') {
return '[' + value.map((v) => prettyPrint(v, depth)).join(', ') + ']';
}
var properties = Object.keys(value);
var suffix = '}';
if (properties.length > 20) {
properties.length = 20;
suffix = ', ... }';
}
return '{' + properties.map((p) => p + ': ' + prettyPrint(value[p], depth)).join(', ') + suffix;
}
return value.__assertName || value.name || value.toString();
}
function isType(value, T, errors) {
if (T && T.type) {
// needed for generics.
// TODO(tbosch): read out T.args and do assertions based on them as well!
T = T.type;
}
if (T === primitives.void) {
return typeof value === 'undefined';
}
if (_isProxy(value)) {
return true;
}
if (T === primitives.any || value === null) {
return true;
}
if (T === primitives.string) {
return typeof value === 'string';
}
if (T === primitives.number) {
return typeof value === 'number';
}
if (T === primitives.boolean) {
return typeof value === 'boolean';
}
// var parentStack = currentStack;
// currentStack = [];
// shouldnt this create new stack?
if (typeof T.assert === 'function') {
var parentStack = currentStack;
var isValid;
currentStack = errors;
try {
isValid = T.assert(value);
} catch (e) {
fail(e.message);
isValid = false;
}
currentStack = parentStack;
if (typeof isValid === 'undefined') {
isValid = errors.length === 0;
}
return isValid;
// if (!currentStack.length) {
// currentStack = parentStack;
// return [];
// }
// var res = currentStack;
// currentStack = parentStack;
// return ['not instance of ' + prettyPrint(T), res];
}
return value instanceof T;
// if (!(value instanceof T)) {
// fail('not instance of ' + prettyPrint(T));
// }
// var res = currentStack;
// currentStack = parentStack;
// return res;
}
function _isProxy(obj) {
if (!obj || !obj.constructor || !obj.constructor.annotations) return false;
return obj.constructor.annotations.filter((a) => a instanceof proxy).length > 0;
}
function formatErrors(errors, indent = ' ') {
return errors.map((e) => {
if (typeof e === 'string') return indent + '- ' + e;
return formatErrors(e, indent + ' ');
})
.join('\n');
}
// assert a type of given value and throw if does not pass
var type: any =
function(actual, T) {
var errors = [];
// currentStack = [];
if (!isType(actual, T, errors)) {
// console.log(JSON.stringify(errors, null, ' '));
// TODO(vojta): print "an instance of" only if T starts with uppercase.
var msg = 'Expected an instance of ' + prettyPrint(T) + ', got ' + prettyPrint(actual) + '!';
if (errors.length) {
msg += '\n' + formatErrors(errors);
}
throw new Error(msg);
}
return actual;
}
function returnType(actual, T) {
var errors = [];
// currentStack = [];
if (!isType(actual, T, errors)) {
// console.log(JSON.stringify(errors, null, ' '));
// TODO(vojta): print "an instance of" only if T starts with uppercase.
var msg = 'Expected to return an instance of ' + prettyPrint(T) + ', got ' +
prettyPrint(actual) + '!';
if (errors.length) {
msg += '\n' + formatErrors(errors);
}
throw new Error(msg);
}
return actual;
}
// TODO(vojta): define these with DSL?
var string = type.string = define('string', function(value) { return typeof value === 'string'; });
var boolean = type.boolean =
define('boolean', function(value) { return typeof value === 'boolean'; });
var number = type.number = define('number', function(value) { return typeof value === 'number'; });
function arrayOf(...types) {
return assert.define('array of ' + types.map(prettyPrint).join('/'), function(value) {
if (assert(value).is(Array)) {
for (var i = 0; i < value.length; i++) {
assert(value[i]).is(...types);
}
}
});
}
function structure(definition) {
var properties = Object.keys(definition);
return assert.define('object with properties ' + properties.join(', '), function(value) {
if (assert(value).is(Object)) {
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
assert(value[property]).is(definition[property]);
}
}
})
}
// I'm sorry, bad global state... to make the API nice ;-)
var currentStack = [];
function fail(message) {
currentStack.push(message);
}
function define(classOrName, check) {
var cls = classOrName;
if (typeof classOrName === 'string') {
cls = function() {};
cls.__assertName = classOrName;
}
cls.assert = function(value) {
// var parentStack = currentStack;
// currentStack = [];
return check(value);
// if (currentStack.length) {
// parentStack.push(currentStack)
// }
// currentStack = parentStack;
};
return cls;
}
var assert: any = function(value) {
return {
is: function is(...types) {
// var errors = []
var allErrors = [];
var errors;
for (var i = 0; i < types.length; i++) {
var type = types[i];
errors = [];
if (isType(value, type, errors)) {
return true;
}
// if no errors, merge multiple "is not instance of " into x/y/z ?
allErrors.push(prettyPrint(value) + ' is not instance of ' + prettyPrint(type));
if (errors.length) {
allErrors.push(errors);
}
}
// if (types.length > 1) {
// currentStack.push(['has to be ' + types.map(prettyPrint).join(' or '),
// ...allErrors]);
// } else {
currentStack.push(...allErrors);
// }
return false;
}
};
};
// PUBLIC API
// asserting API
// throw if no type provided
assert.type = type;
for (var prop in primitives) {
assert.type[prop] = primitives[prop];
}
assert.genericType = genericType;
// throw if odd number of args
assert.argumentTypes = assertArgumentTypes;
assert.returnType = returnType;
// define AP;
assert.define = define;
assert.fail = fail;
// primitive value type;
assert.string = string;
assert.number = number;
assert.boolean = boolean;
// custom types
assert.arrayOf = arrayOf;
assert.structure = structure;
export {assert}