All files / validator/yupSource mixed.js

55.86% Statements 162/290
61.36% Branches 108/176
54.43% Functions 43/79
58% Lines 145/250

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                            330x 330x                           4x     9x     9x     8x     5x 5x 2x   4x     184x 184x 184x 184x                         74x 1x       73x 73x 73x 73x   73x 73x   73x 73x   73x 73x     73x   73x   73x     3x           248x       92x 1567x     1563x 184x           17x 17x 17x                       145x 145x 145x 145x 145x                                                                                   349x 349x 347x       357x   357x                         357x                   66x             66x   66x                                     66x         172x     170x       172x       172x                     128x   128x 128x 106x 106x 106x     128x                     128x   128x 128x 128x   128x                   128x   120x                               30x 30x     30x     18x 18x 8x           98x 98x     98x 98x 53x     53x                                                                                                                     55x       33x         55x                                   1x 1x 1x       72x 72x 72x                                     63x 1x 62x 3x     63x 61x 61x     61x                 63x   63x     63x 63x     63x   63x           63x   63x 13x       13x     63x   63x                                           73x   73x       128x 4x         124x     73x       5x 2x     5x   5x 9x 9x     5x       8x 8x   8x                   5x                                                                     25x                                                                     4x         2x 2x     72x   72x     29x   43x         3x 6x 55x 55x           55x             9x 6x 3x  
import { cloneDeepWith, has, toArray, values } from '../../utils'
 
import Condition from './Condition'
import Ref from './Reference'
import { mixed as locale } from './locale'
import createValidation from './util/createValidation'
import isSchema from './util/isSchema'
import prependDeep from './util/prependDeep'
import printValue from './util/printValue'
import { getIn } from './util/reach'
import runTests from './util/runTests'
 
class RefSet {
  constructor() {
    this.list = new Set()
    this.refs = new Map()
  }
  get size() {
    return this.list.size + this.refs.size
  }
  describe() {
    const description = []
 
    for (const item of this.list) description.push(item)
    for (const [, ref] of this.refs) description.push(ref.describe())
 
    return description
  }
  toArray() {
    return toArray(this.list).concat(toArray(this.refs.values()))
  }
  add(value) {
    Ref.isRef(value) ? this.refs.set(value.key, value) : this.list.add(value)
  }
  delete(value) {
    Ref.isRef(value) ? this.refs.delete(value.key) : this.list.delete(value)
  }
  has(value, resolve) {
    if (this.list.has(value)) return true
 
    let item,
      values = this.refs.values()
    while (((item = values.next()), !item.done))
      if (resolve(item.value) === value) return true
 
    return false
  }
  clone() {
    const next = new RefSet()
    next.list = new Set(this.list)
    next.refs = new Map(this.refs)
    return next
  }
  merge(newItems, removeItems) {
    const next = this.clone()
    newItems.list.forEach(value => next.add(value))
    newItems.refs.forEach(value => next.add(value))
    removeItems.list.forEach(value => next.delete(value))
    removeItems.refs.forEach(value => next.delete(value))
    return next
  }
}
 
export default function SchemaType(options = {}) {
  if (!(this instanceof SchemaType))
    return typeof options === 'function'
      ? options(new SchemaType())
      : new SchemaType()
 
  this._deps = []
  this._conditions = []
  this._options = { abortEarly: true, recursive: true }
  this._exclusive = Object.create(null)
 
  this._whitelist = new RefSet()
  this._blacklist = new RefSet()
 
  this.tests = []
  this.transforms = []
 
  this.withMutation(() => {
    this.typeError(locale.notType)
  })
 
  if (has(options, 'default')) this._defaultDefault = options.default
 
  this.type = options.type || 'mixed'
  // TODO: remove
  this._type = options.type || 'mixed'
}
 
const proto = (SchemaType.prototype = {
  __isYupSchema__: true,
 
  constructor: SchemaType,
 
  clone() {
    if (this._mutate) return this
 
    // if the nested value is a schema we can skip cloning, since
    // they are already immutable
    return cloneDeepWith(this, (value, key) => {
      if (isSchema(value) && value !== this) return value
 
      // fix for ie11 when cloning Set and Map
      if (key === '_whitelist' || key === '_blacklist') {
        return value.clone()
      }
    })
  },
 
  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) {
    let before = this._mutate
    this._mutate = true
    let result = fn(this)
    this._mutate = before
    return result
  },
 
  concat(schema) {
    if (!schema || schema === this) 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 next = prependDeep(schema.clone(), this)
 
    // new undefined default is overridden by old non-undefined one, revert
    if (has(schema, '_default')) next._default = schema._default
 
    next.tests = this.tests
    next._exclusive = this._exclusive
 
    // manually merge the blacklist/whitelist (the other `schema` takes
    // precedence in case of conflicts)
    next._whitelist = this._whitelist.merge(
      schema._whitelist,
      schema._blacklist,
    )
    next._blacklist = this._blacklist.merge(
      schema._blacklist,
      schema._whitelist,
    )
 
    // manually add the new tests to ensure
    // the deduping logic is consistent
    next.withMutation(next => {
      schema.tests.forEach(fn => {
        next.test(fn.OPTIONS)
      })
    })
 
    return next
  },
 
  isType(v) {
    Iif (this._nullable && v === null) return true
    if (this._allowEmptyString && v === '') return true
    return !this._typeCheck || this._typeCheck(v)
  },
 
  resolve(options) {
    let schema = this
 
    Iif (schema._conditions.length) {
      let conditions = schema._conditions
 
      schema = schema.clone()
      schema._conditions = []
      schema = conditions.reduce(
        (schema, condition) => condition.resolve(schema, options),
        schema,
      )
 
      schema = schema.resolve(options)
    }
 
    return schema
  },
  /**
   *
   * @param {*} value
   * @param {Object} options
   * @param {*=} options.parent
   * @param {*=} options.context
   */
  cast(value, options = {}) {
    let resolvedSchema = this.resolve({
      value,
      ...options,
      // parent: options.parent,
      // context: options.context,
    })
 
    let result = resolvedSchema._cast(value, options)
 
    Iif (
      value !== undefined &&
      options.assert !== false &&
      resolvedSchema.isType(result) !== true
    ) {
      let formattedValue = printValue(value)
      let formattedResult = printValue(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: ${formattedValue} \n` +
          (formattedResult !== formattedValue
            ? `result of cast: ${formattedResult}`
            : ''),
      )
    }
 
    return result
  },
 
  _cast(rawValue) {
    let value =
      rawValue === undefined
        ? rawValue
        : this.transforms.reduce(
            (value, fn) => fn.call(this, value, rawValue),
            rawValue,
          )
 
    Iif (value === undefined && has(this, '_default')) {
      value = this.getDefault()
    }
 
    return value
  },
 
  _validate(_value, options = {}, cb) {
    let {
      sync,
      path,
      from = [],
      originalValue = _value,
      strict = this._options.strict,
      abortEarly = this._options.abortEarly,
    } = options
 
    let value = _value
    if (!strict) {
      this._validating = true
      value = this._cast(value, { assert: false, ...options })
      this._validating = false
    }
    // value is cast, we can check if it meets type requirements
    let args = {
      value,
      path,
      options,
      originalValue,
      schema: this,
      label: this._label,
      sync,
      from,
    }
 
    let initialTests = []
 
    if (this._typeError) initialTests.push(this._typeError)
    if (this._whitelistError) initialTests.push(this._whitelistError)
    Iif (this._blacklistError) initialTests.push(this._blacklistError)
 
    return runTests(
      {
        args,
        value,
        path,
        sync,
        tests: initialTests,
        endEarly: abortEarly,
      },
      err => {
        if (err) return void cb(err)
 
        runTests(
          {
            tests: this.tests,
            args,
            path,
            sync,
            value,
            endEarly: abortEarly,
          },
          cb,
        )
      },
    )
  },
 
  validate(value, options = {}, maybeCb) {
    if (!options.rootValue) options.rootValue = value
    let schema = this.resolve({ ...options, value })
 
    // callback case is for nested validations
    return typeof maybeCb === 'function'
      ? schema._validate(value, options, maybeCb)
      : new Promise((resolve, reject) =>
          schema._validate(value, options, (err, value) => {
            if (err) reject(err)
            else resolve(value)
          }),
        )
  },
 
  validateSync(value, options = {}) {
    if (!options.rootValue) options.rootValue = value
    let schema = this.resolve({ ...options, value })
    let result
 
    schema._validate(value, { ...options, sync: true }, (err, value) => {
      if (err) throw err
      result = value
    })
 
    return result
  },
 
  isValid(value, options) {
    return this.validate(value, options)
      .then(() => true)
      .catch(err => {
        if (err.name === 'ValidationError') return false
        throw err
      })
  },
 
  isValidSync(value, options) {
    try {
      this.validateSync(value, options)
      return true
    } catch (err) {
      if (err.name === 'ValidationError') return false
      throw err
    }
  },
 
  _getDefault() {
    var defaultValue = has(this, '_default')
      ? this._default
      : this._defaultDefault
 
    return typeof defaultValue === 'function'
      ? defaultValue.call(this)
      : cloneDeepWith(defaultValue)
  },
 
  getDefault(options = {}) {
    let schema = this.resolve(options)
    return schema._getDefault()
  },
 
  default(def) {
    if (arguments.length === 0) {
      console.warn(
        'Calling `schema.default()` as a getter to retrieve a default is deprecated and will be removed in the next version. \n' +
          'Use `schema.getDefault()` instead.',
      )
 
      return this._getDefault()
    }
 
    var next = this.clone()
    next._default = def
    return next
  },
 
  strict(isStrict = true) {
    var next = this.clone()
    next._options.strict = isStrict
    return next
  },
 
  _isPresent(value) {
    return value != null
  },
 
  required(message = locale.required) {
    return this.test({
      message,
      name: 'required',
      exclusive: true,
      test(value) {
        return this.schema._isPresent(value)
      },
    })
  },
 
  notRequired() {
    var next = this.clone()
    next.tests = next.tests.filter(test => test.OPTIONS.name !== 'required')
    return next
  },
 
  nullable(isNullable = true) {
    var next = this.clone()
    next._nullable = isNullable
    return next
  },
 
  allowEmptyString() {
    var next = this.clone()
    next._allowEmptyString = 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(...args) {
    let opts
 
    if (typeof args[0] === 'function') {
      opts = { test: args[0], message: args[1] }
    } else if (args[0] instanceof RegExp) {
      opts = { test: value => args[0].test(value), message: args[1] }
    }
 
    if (!opts) {
      if (args.length === 1) {
        Iif (typeof args[0] === 'function') {
          opts = { test: args[0] }
        } else {
          opts = args[0]
        }
      } else Eif (args.length === 2) {
        opts = { name: args[0], test: args[1] }
      } else {
        opts = { name: args[0], message: args[1], test: args[2] }
      }
    }
 
    Iif (opts.message === undefined) opts.message = locale.default
 
    Iif (typeof opts.test !== 'function')
      throw new TypeError('`test` is a required parameters')
 
    let next = this.clone()
    let validate = createValidation(opts)
 
    let isExclusive =
      opts.exclusive || (opts.name && next._exclusive[opts.name] === true)
 
    Iif (opts.exclusive && !opts.name) {
      throw new TypeError(
        'Exclusive tests must provide a unique `name` identifying the test',
      )
    }
 
    next._exclusive[opts.name] = !!opts.exclusive
 
    next.tests = next.tests.filter(fn => {
      Iif (fn.OPTIONS.name === opts.name) {
        if (isExclusive) return false
        if (fn.OPTIONS.test === validate.OPTIONS.test) return false
      }
      return true
    })
 
    next.tests.push(validate)
 
    return next
  },
 
  when(keys, options) {
    if (arguments.length === 1) {
      options = keys
      keys = '.'
    }
 
    var next = this.clone(),
      deps = [].concat(keys).map(key => new Ref(key))
 
    deps.forEach(dep => {
      if (dep.isSibling) 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) {
    if (!Array.isArray(enums)) {
      enums = values(enums)
    }
 
    var next = this.clone()
 
    enums.forEach(val => {
      next._whitelist.add(val)
      next._blacklist.delete(val)
    })
 
    next._whitelistError = createValidation({
      message,
      name: 'oneOf',
      test(value) {
        Iif (value === undefined) return true
        let valids = this.schema._whitelist
 
        return valids.has(value, this.resolve)
          ? true
          : this.createError({
              params: {
                values: valids.toArray().join(', '),
              },
            })
      },
    })
 
    return next
  },
 
  notOneOf(enums, message = locale.notOneOf) {
    var next = this.clone()
    enums.forEach(val => {
      next._blacklist.add(val)
      next._whitelist.delete(val)
    })
 
    next._blacklistError = createValidation({
      message,
      name: 'notOneOf',
      test(value) {
        let invalids = this.schema._blacklist
        if (invalids.has(value, this.resolve))
          return this.createError({
            params: {
              values: invalids.toArray().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() {
    const next = this.clone()
    const description = {
      type: next._type,
      meta: next._meta,
      label: next._label,
      tests: next.tests
        .map(fn => ({ name: fn.OPTIONS.name, params: fn.OPTIONS.params }))
        .filter(
          (n, idx, list) => list.findIndex(c => c.name === n.name) === idx,
        ),
    }
 
    if (next._whitelist.size) description.oneOf = next._whitelist.describe()
    if (next._blacklist.size) description.notOneOf = next._blacklist.describe()
 
    return description
  },
 
  defined(message = locale.defined) {
    return this.test({
      message,
      name: 'defined',
      exclusive: true,
      test(value) {
        return value !== undefined
      },
    })
  },
 
  // 新增
  validatePlus(data, options) {
    return (
      this.type === 'object'
        ? this.validateInOrder(data, options)
        : this.validate(data, options)
    )
      .then(data => ({ data }))
      .catch(error => ({ error, data }))
  },
  validatePlusSync(data, options) {
    try {
      const _data =
        this.type === 'object'
          ? this.validateInOrderSync(data, options)
          : this.validateSync(data, options)
      return { data: _data }
    } catch (error) {
      return { error, data }
    }
  },
})
 
for (const method of ['validate', 'validateSync'])
  proto[`${method}At`] = function (path, value, options = {}) {
    if (!options.rootValue) options.rootValue = value
    const { parent, parentPath, schema } = getIn(
      this,
      path,
      value,
      options.context,
    )
    return schema[method](parent && parent[parentPath], {
      ...options,
      parent,
      path,
    })
  }
 
for (const alias of ['equals', 'is', 'enum']) proto[alias] = proto.oneOf
for (const alias of ['not', 'nope']) proto[alias] = proto.notOneOf
proto.optional = proto.notRequired