-
Notifications
You must be signed in to change notification settings - Fork 906
/
mixed.js
448 lines (354 loc) · 10.5 KB
/
mixed.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
import has from 'lodash/has';
import { mixed as locale } from './locale';
import Condition from './Condition';
import runValidations from './util/runValidations';
import merge from './util/merge';
import isAbsent from './util/isAbsent';
import cloneDeep from './util/clone';
import createValidation from './util/createValidation';
import BadSet from './util/set';
import Ref from './Reference';
let notEmpty = value => !isAbsent(value);
function extractTestParams(name, message, test, useCallback) {
var opts = name;
if (typeof message === 'function')
test = message, message = locale.default, name = null;
if (typeof name === 'function')
test = name, message = locale.default, name = null;
if (typeof name === 'string' || name === null)
opts = { name, test, message, useCallback, exclusive: false }
if (typeof opts.test !== 'function')
throw new TypeError('`test` is a required parameters')
return opts
}
module.exports = SchemaType
function SchemaType(options = {}){
if ( !(this instanceof SchemaType))
return new SchemaType()
this._deps = []
this._conditions = []
this._options = { abortEarly: true, recursive: true }
this._exclusive = Object.create(null)
this._whitelist = new BadSet()
this._blacklist = new BadSet()
this.tests = []
this.transforms = []
this.withMutation(() => {
this.typeError(locale.notType)
})
if (has(options, 'default'))
this._defaultDefault = options.default
this._type = options.type || 'mixed'
}
SchemaType.prototype = {
__isYupSchema__: true,
constructor: SchemaType,
clone() {
if (this._mutate)
return this;
return cloneDeep(this);
},
label(label) {
var next = this.clone();
next._label = label;
return next;
},
meta(obj) {
if (arguments.length === 0)
return this._meta;
var next = this.clone();
next._meta = Object.assign(next._meta || {}, obj)
return next;
},
withMutation(fn) {
this._mutate = true
let result = fn(this)
this._mutate = false
return result
},
concat(schema){
if (!schema)
return this
if (schema._type !== this._type && this._type !== 'mixed')
throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this._type} and ${schema._type}`)
var cloned = this.clone()
var next = merge(this.clone(), schema.clone())
// undefined isn't merged over, but is a valid value for default
if (schema._default === undefined && has(this, '_default'))
next._default = schema._default
next.tests = cloned.tests;
next._exclusive = cloned._exclusive;
// manually add the new tests to ensure
// the deduping logic is consistent
schema.tests.forEach((fn) => {
next = next.test(fn.TEST)
});
next._type = schema._type;
return next
},
isType(v) {
if( this._nullable && v === null) return true
return !this._typeCheck || this._typeCheck(v)
},
resolve({ context, parent }) {
if (this._conditions.length) {
return this._conditions.reduce((schema, match) =>
match.resolve(schema, match.getValue(parent, context)), this)
}
return this
},
cast(value, options = {}) {
let resolvedSchema = this.resolve(options)
let result = resolvedSchema._cast(value, options);
if (
value !== undefined &&
options.assert !== false &&
resolvedSchema.isType(result) !== true
) {
let formattedValue = JSON.stringify(value);
let formattedResult = JSON.stringify(result);
throw new TypeError(
`The value of ${options.path || 'field'} could not be cast to a value ` +
`that satisfies the schema type: "${resolvedSchema._type}". \n\n` +
`attempted value: ${JSON.stringify(value)} \n` +
((formattedResult !== formattedValue)
? `result of cast: ${JSON.stringify(result)}` : '')
);
}
return result;
},
_cast(_value) {
let value = _value === undefined ? _value
: this.transforms.reduce(
(value, transform) => transform.call(this, value, _value), _value)
if (value === undefined && (has(this, '_default'))) {
value = this.default()
}
return value
},
validate(value, options = {}, cb) {
if (typeof options === 'function')
cb = options, options = {}
let schema = this.resolve(options)
return nodeify(schema._validate(value, options), cb)
},
//-- tests
_validate(_value, options = {}) {
let value = _value
, schema, endEarly, isStrict;
schema = this
isStrict = this._option('strict', options)
endEarly = this._option('abortEarly', options)
let path = options.path
let label = this._label
if (!isStrict) {
value = this._cast(value, { assert: false, ...options })
}
// value is cast, we can check if it meets type requirements
let validationParams = { value, path, schema: this, options, label }
let initialTests = []
if (schema._typeError)
initialTests.push(this._typeError(validationParams));
if (this._whitelistError)
initialTests.push(this._whitelistError(validationParams));
if (this._blacklistError)
initialTests.push(this._blacklistError(validationParams));
return runValidations({ validations: initialTests, endEarly, value, path })
.then(value => runValidations({
path,
value,
endEarly,
validations: this.tests.map(fn => fn(validationParams)),
}))
},
isValid(value, options, cb) {
if (typeof options === 'function')
cb = options, options = {}
return nodeify(this
.validate(value, options)
.then(() => true)
.catch(err => {
if ( err.name === 'ValidationError')
return false
throw err
}), cb)
},
getDefault({ context, parent }) {
return this._resolve(context, parent).default()
},
default(def) {
if (arguments.length === 0) {
var dflt = has(this, '_default') ? this._default : this._defaultDefault
return typeof dflt === 'function'
? dflt.call(this) : cloneDeep(dflt)
}
var next = this.clone()
next._default = def
return next
},
strict() {
var next = this.clone()
next._options.strict = true
return next
},
required(msg) {
return this.test(
'required',
msg || locale.required,
notEmpty
)
},
nullable(value) {
var next = this.clone()
next._nullable = value === false ? false : true
return next
},
transform(fn) {
var next = this.clone();
next.transforms.push(fn)
return next
},
/**
* Adds a test function to the schema's queue of tests.
* tests can be exclusive or non-exclusive.
*
* - exclusive tests, will replace any existing tests of the same name.
* - non-exclusive: can be stacked
*
* If a non-exclusive test is added to a schema with an exclusive test of the same name
* the exclusive test is removed and further tests of the same name will be stacked.
*
* If an exclusive test is added to a schema with non-exclusive tests of the same name
* the previous tests are removed and further tests of the same name will replace each other.
*/
test(name, message, test, useCallback) {
var opts = extractTestParams(name, message, test, useCallback)
, next = this.clone();
var validate = createValidation(opts);
var isExclusive = (
opts.exclusive ||
(opts.name && next._exclusive[opts.name] === true)
)
if (opts.exclusive && !opts.name) {
throw new TypeError('You cannot have an exclusive validation without a `name`')
}
next._exclusive[opts.name] = !!opts.exclusive
next.tests = next.tests
.filter(fn => {
if (fn.TEST_NAME === opts.name) {
if (isExclusive) return false
if (fn.TEST.test === validate.TEST.test) return false
}
return true
})
next.tests.push(validate)
return next
},
when(keys, options) {
var next = this.clone()
, deps = [].concat(keys).map(key => new Ref(key));
deps.forEach(dep => {
if (!dep.isContext)
next._deps.push(dep.key)
})
next._conditions.push(new Condition(deps, options))
return next
},
typeError(message) {
var next = this.clone()
next._typeError = createValidation({
message,
name: 'typeError',
test(value) {
if (value !== undefined && !this.schema.isType(value))
return this.createError({
params: {
type: this.schema._type
}
})
return true
}
})
return next
},
oneOf(enums, message = locale.oneOf) {
var next = this.clone();
if (next.tests.length)
throw new TypeError('Cannot specify values when there are validation rules specified')
enums.forEach(val => {
next._blacklist.delete(val)
next._whitelist.add(val)
})
next._whitelistError = createValidation({
message,
name: 'oneOf',
test(value) {
let valids = this.schema._whitelist
if (valids.length && !(value === undefined || valids.has(value)))
return this.createError({
params: {
values: valids.values().join(', ')
}
})
return true
}
})
return next
},
notOneOf(enums, message = locale.notOneOf) {
var next = this.clone();
enums.forEach( val => {
next._whitelist.delete(val)
next._blacklist.add(val)
})
next._blacklistError = createValidation({
message,
name: 'notOneOf',
test(value) {
let invalids = this.schema._blacklist
if (invalids.length && invalids.has(value))
return this.createError({
params: {
values: invalids.values().join(', ')
}
})
return true
}
})
return next
},
strip(strip = true) {
let next = this.clone()
next._strip = strip
return next
},
_option(key, overrides){
return has(overrides, key)
? overrides[key] : this._options[key]
},
describe() {
let next = this.clone();
return {
type: next._type,
meta: next._meta,
label: next._label,
tests: next.tests.map((fn) => fn.TEST_NAME, {})
}
}
}
let aliases = {
oneOf: ['equals', 'is'],
notOneOf: ['not', 'nope']
}
Object.keys(aliases).forEach(method => {
aliases[method].forEach(alias =>
SchemaType.prototype[alias] = SchemaType.prototype[method]
)
})
function nodeify(promise, cb){
if(typeof cb !== 'function') return promise
promise.then(
val => cb(null, val),
err => cb(err)
)
}