• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict'
2module.exports = validate
3
4function isArguments (thingy) {
5  return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee')
6}
7
8const types = {
9  '*': {label: 'any', check: () => true},
10  A: {label: 'array', check: _ => Array.isArray(_) || isArguments(_)},
11  S: {label: 'string', check: _ => typeof _ === 'string'},
12  N: {label: 'number', check: _ => typeof _ === 'number'},
13  F: {label: 'function', check: _ => typeof _ === 'function'},
14  O: {label: 'object', check: _ => typeof _ === 'object' && _ != null && !types.A.check(_) && !types.E.check(_)},
15  B: {label: 'boolean', check: _ => typeof _ === 'boolean'},
16  E: {label: 'error', check: _ => _ instanceof Error},
17  Z: {label: 'null', check: _ => _ == null}
18}
19
20function addSchema (schema, arity) {
21  const group = arity[schema.length] = arity[schema.length] || []
22  if (group.indexOf(schema) === -1) group.push(schema)
23}
24
25function validate (rawSchemas, args) {
26  if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length)
27  if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas')
28  if (!args) throw missingRequiredArg(1, 'args')
29  if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas)
30  if (!types.A.check(args)) throw invalidType(1, ['array'], args)
31  const schemas = rawSchemas.split('|')
32  const arity = {}
33
34  schemas.forEach(schema => {
35    for (let ii = 0; ii < schema.length; ++ii) {
36      const type = schema[ii]
37      if (!types[type]) throw unknownType(ii, type)
38    }
39    if (/E.*E/.test(schema)) throw moreThanOneError(schema)
40    addSchema(schema, arity)
41    if (/E/.test(schema)) {
42      addSchema(schema.replace(/E.*$/, 'E'), arity)
43      addSchema(schema.replace(/E/, 'Z'), arity)
44      if (schema.length === 1) addSchema('', arity)
45    }
46  })
47  let matching = arity[args.length]
48  if (!matching) {
49    throw wrongNumberOfArgs(Object.keys(arity), args.length)
50  }
51  for (let ii = 0; ii < args.length; ++ii) {
52    let newMatching = matching.filter(schema => {
53      const type = schema[ii]
54      const typeCheck = types[type].check
55      return typeCheck(args[ii])
56    })
57    if (!newMatching.length) {
58      const labels = matching.map(_ => types[_[ii]].label).filter(_ => _ != null)
59      throw invalidType(ii, labels, args[ii])
60    }
61    matching = newMatching
62  }
63}
64
65function missingRequiredArg (num) {
66  return newException('EMISSINGARG', 'Missing required argument #' + (num + 1))
67}
68
69function unknownType (num, type) {
70  return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1))
71}
72
73function invalidType (num, expectedTypes, value) {
74  let valueType
75  Object.keys(types).forEach(typeCode => {
76    if (types[typeCode].check(value)) valueType = types[typeCode].label
77  })
78  return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' +
79    englishList(expectedTypes) + ' but got ' + valueType)
80}
81
82function englishList (list) {
83  return list.join(', ').replace(/, ([^,]+)$/, ' or $1')
84}
85
86function wrongNumberOfArgs (expected, got) {
87  const english = englishList(expected)
88  const args = expected.every(ex => ex.length === 1)
89    ? 'argument'
90    : 'arguments'
91  return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got)
92}
93
94function moreThanOneError (schema) {
95  return newException('ETOOMANYERRORTYPES',
96    'Only one error type per argument signature is allowed, more than one found in "' + schema + '"')
97}
98
99function newException (code, msg) {
100  const err = new Error(msg)
101  err.code = code
102  /* istanbul ignore else */
103  if (Error.captureStackTrace) Error.captureStackTrace(err, validate)
104  return err
105}
106