index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. 'use strict';
  2. const Hoek = require('@hapi/hoek');
  3. const Any = require('./types/any');
  4. const Cast = require('./cast');
  5. const Errors = require('./errors');
  6. const Lazy = require('./types/lazy');
  7. const Ref = require('./ref');
  8. const internals = {
  9. alternatives: require('./types/alternatives'),
  10. array: require('./types/array'),
  11. boolean: require('./types/boolean'),
  12. binary: require('./types/binary'),
  13. date: require('./types/date'),
  14. func: require('./types/func'),
  15. number: require('./types/number'),
  16. object: require('./types/object'),
  17. string: require('./types/string'),
  18. symbol: require('./types/symbol')
  19. };
  20. internals.callWithDefaults = function (schema, args) {
  21. Hoek.assert(this, 'Must be invoked on a Joi instance.');
  22. if (this._defaults) {
  23. schema = this._defaults(schema);
  24. }
  25. schema._currentJoi = this;
  26. return schema._init(...args);
  27. };
  28. internals.root = function () {
  29. const any = new Any();
  30. const root = any.clone();
  31. Any.prototype._currentJoi = root;
  32. root._currentJoi = root;
  33. root._binds = new Set(['any', 'alternatives', 'alt', 'array', 'bool', 'boolean', 'binary', 'date', 'func', 'number', 'object', 'string', 'symbol', 'validate', 'describe', 'compile', 'assert', 'attempt', 'lazy', 'defaults', 'extend', 'allow', 'valid', 'only', 'equal', 'invalid', 'disallow', 'not', 'required', 'exist', 'optional', 'forbidden', 'strip', 'when', 'empty', 'default']);
  34. root.any = function (...args) {
  35. Hoek.assert(args.length === 0, 'Joi.any() does not allow arguments.');
  36. return internals.callWithDefaults.call(this, any, args);
  37. };
  38. root.alternatives = root.alt = function (...args) {
  39. return internals.callWithDefaults.call(this, internals.alternatives, args);
  40. };
  41. root.array = function (...args) {
  42. Hoek.assert(args.length === 0, 'Joi.array() does not allow arguments.');
  43. return internals.callWithDefaults.call(this, internals.array, args);
  44. };
  45. root.boolean = root.bool = function (...args) {
  46. Hoek.assert(args.length === 0, 'Joi.boolean() does not allow arguments.');
  47. return internals.callWithDefaults.call(this, internals.boolean, args);
  48. };
  49. root.binary = function (...args) {
  50. Hoek.assert(args.length === 0, 'Joi.binary() does not allow arguments.');
  51. return internals.callWithDefaults.call(this, internals.binary, args);
  52. };
  53. root.date = function (...args) {
  54. Hoek.assert(args.length === 0, 'Joi.date() does not allow arguments.');
  55. return internals.callWithDefaults.call(this, internals.date, args);
  56. };
  57. root.func = function (...args) {
  58. Hoek.assert(args.length === 0, 'Joi.func() does not allow arguments.');
  59. return internals.callWithDefaults.call(this, internals.func, args);
  60. };
  61. root.number = function (...args) {
  62. Hoek.assert(args.length === 0, 'Joi.number() does not allow arguments.');
  63. return internals.callWithDefaults.call(this, internals.number, args);
  64. };
  65. root.object = function (...args) {
  66. return internals.callWithDefaults.call(this, internals.object, args);
  67. };
  68. root.string = function (...args) {
  69. Hoek.assert(args.length === 0, 'Joi.string() does not allow arguments.');
  70. return internals.callWithDefaults.call(this, internals.string, args);
  71. };
  72. root.symbol = function (...args) {
  73. Hoek.assert(args.length === 0, 'Joi.symbol() does not allow arguments.');
  74. return internals.callWithDefaults.call(this, internals.symbol, args);
  75. };
  76. root.ref = function (...args) {
  77. return Ref.create(...args);
  78. };
  79. root.isRef = function (ref) {
  80. return Ref.isRef(ref);
  81. };
  82. root.validate = function (value, ...args /*, [schema], [options], callback */) {
  83. const last = args[args.length - 1];
  84. const callback = typeof last === 'function' ? last : null;
  85. const count = args.length - (callback ? 1 : 0);
  86. if (count === 0) {
  87. return any.validate(value, callback);
  88. }
  89. const options = count === 2 ? args[1] : undefined;
  90. const schema = this.compile(args[0]);
  91. return schema._validateWithOptions(value, options, callback);
  92. };
  93. root.describe = function (...args) {
  94. const schema = args.length ? this.compile(args[0]) : any;
  95. return schema.describe();
  96. };
  97. root.compile = function (schema) {
  98. try {
  99. return Cast.schema(this, schema);
  100. }
  101. catch (err) {
  102. if (err.hasOwnProperty('path')) {
  103. err.message = err.message + '(' + err.path + ')';
  104. }
  105. throw err;
  106. }
  107. };
  108. root.assert = function (value, schema, message) {
  109. this.attempt(value, schema, message);
  110. };
  111. root.attempt = function (value, schema, message) {
  112. const result = this.validate(value, schema);
  113. const error = result.error;
  114. if (error) {
  115. if (!message) {
  116. if (typeof error.annotate === 'function') {
  117. error.message = error.annotate();
  118. }
  119. throw error;
  120. }
  121. if (!(message instanceof Error)) {
  122. if (typeof error.annotate === 'function') {
  123. error.message = `${message} ${error.annotate()}`;
  124. }
  125. throw error;
  126. }
  127. throw message;
  128. }
  129. return result.value;
  130. };
  131. root.reach = function (schema, path) {
  132. Hoek.assert(schema && schema instanceof Any, 'you must provide a joi schema');
  133. Hoek.assert(Array.isArray(path) || typeof path === 'string', 'path must be a string or an array of strings');
  134. const reach = (sourceSchema, schemaPath) => {
  135. if (!schemaPath.length) {
  136. return sourceSchema;
  137. }
  138. const children = sourceSchema._inner.children;
  139. if (!children) {
  140. return;
  141. }
  142. const key = schemaPath.shift();
  143. for (let i = 0; i < children.length; ++i) {
  144. const child = children[i];
  145. if (child.key === key) {
  146. return reach(child.schema, schemaPath);
  147. }
  148. }
  149. };
  150. const schemaPath = typeof path === 'string' ? (path ? path.split('.') : []) : path.slice();
  151. return reach(schema, schemaPath);
  152. };
  153. root.lazy = function (...args) {
  154. return internals.callWithDefaults.call(this, Lazy, args);
  155. };
  156. root.defaults = function (fn) {
  157. Hoek.assert(typeof fn === 'function', 'Defaults must be a function');
  158. let joi = Object.create(this.any());
  159. joi = fn(joi);
  160. Hoek.assert(joi && joi instanceof this.constructor, 'defaults() must return a schema');
  161. Object.assign(joi, this, joi.clone()); // Re-add the types from `this` but also keep the settings from joi's potential new defaults
  162. joi._defaults = (schema) => {
  163. if (this._defaults) {
  164. schema = this._defaults(schema);
  165. Hoek.assert(schema instanceof this.constructor, 'defaults() must return a schema');
  166. }
  167. schema = fn(schema);
  168. Hoek.assert(schema instanceof this.constructor, 'defaults() must return a schema');
  169. return schema;
  170. };
  171. return joi;
  172. };
  173. root.bind = function () {
  174. const joi = Object.create(this);
  175. joi._binds.forEach((bind) => {
  176. joi[bind] = joi[bind].bind(joi);
  177. });
  178. return joi;
  179. };
  180. root.extend = function (...args) {
  181. const extensions = Hoek.flatten(args);
  182. Hoek.assert(extensions.length > 0, 'You need to provide at least one extension');
  183. this.assert(extensions, root.extensionsSchema);
  184. const joi = Object.create(this.any());
  185. Object.assign(joi, this);
  186. joi._currentJoi = joi;
  187. joi._binds = new Set(joi._binds);
  188. for (let i = 0; i < extensions.length; ++i) {
  189. let extension = extensions[i];
  190. if (typeof extension === 'function') {
  191. extension = extension(joi);
  192. }
  193. this.assert(extension, root.extensionSchema);
  194. const base = (extension.base || this.any()).clone(); // Cloning because we're going to override language afterwards
  195. const ctor = base.constructor;
  196. const type = class extends ctor { // eslint-disable-line no-loop-func
  197. constructor() {
  198. super();
  199. if (extension.base) {
  200. Object.assign(this, base);
  201. }
  202. this._type = extension.name;
  203. }
  204. };
  205. if (extension.language) {
  206. const lang = {
  207. [extension.name]: extension.language
  208. };
  209. type.prototype._language = Hoek.applyToDefaults(type.prototype._language || (base._settings && base._settings.language) || {}, lang);
  210. }
  211. if (extension.coerce) {
  212. type.prototype._coerce = function (value, state, options) {
  213. if (ctor.prototype._coerce) {
  214. const baseRet = ctor.prototype._coerce.call(this, value, state, options);
  215. if (baseRet.errors) {
  216. return baseRet;
  217. }
  218. value = baseRet.value;
  219. }
  220. const ret = extension.coerce.call(this, value, state, options);
  221. if (ret instanceof Errors.Err) {
  222. return { value, errors: ret };
  223. }
  224. return { value: ret };
  225. };
  226. }
  227. if (extension.pre) {
  228. type.prototype._base = function (value, state, options) {
  229. if (ctor.prototype._base) {
  230. const baseRet = ctor.prototype._base.call(this, value, state, options);
  231. if (baseRet.errors) {
  232. return baseRet;
  233. }
  234. value = baseRet.value;
  235. }
  236. const ret = extension.pre.call(this, value, state, options);
  237. if (ret instanceof Errors.Err) {
  238. return { value, errors: ret };
  239. }
  240. return { value: ret };
  241. };
  242. }
  243. if (extension.rules) {
  244. for (let j = 0; j < extension.rules.length; ++j) {
  245. const rule = extension.rules[j];
  246. const ruleArgs = rule.params ?
  247. (rule.params instanceof Any ? rule.params._inner.children.map((k) => k.key) : Object.keys(rule.params)) :
  248. [];
  249. const validateArgs = rule.params ? Cast.schema(this, rule.params) : null;
  250. type.prototype[rule.name] = function (...rArgs) { // eslint-disable-line no-loop-func
  251. if (rArgs.length > ruleArgs.length) {
  252. throw new Error('Unexpected number of arguments');
  253. }
  254. let hasRef = false;
  255. let arg = {};
  256. for (let k = 0; k < ruleArgs.length; ++k) {
  257. arg[ruleArgs[k]] = rArgs[k];
  258. if (!hasRef && Ref.isRef(rArgs[k])) {
  259. hasRef = true;
  260. }
  261. }
  262. if (validateArgs) {
  263. arg = joi.attempt(arg, validateArgs);
  264. }
  265. let schema;
  266. if (rule.validate && !rule.setup) {
  267. const validate = function (value, state, options) {
  268. return rule.validate.call(this, arg, value, state, options);
  269. };
  270. schema = this._test(rule.name, arg, validate, {
  271. description: rule.description,
  272. hasRef
  273. });
  274. }
  275. else {
  276. schema = this.clone();
  277. }
  278. if (rule.setup) {
  279. const newSchema = rule.setup.call(schema, arg);
  280. if (newSchema !== undefined) {
  281. Hoek.assert(newSchema instanceof Any, `Setup of extension Joi.${this._type}().${rule.name}() must return undefined or a Joi object`);
  282. schema = newSchema;
  283. }
  284. if (rule.validate) {
  285. const validate = function (value, state, options) {
  286. return rule.validate.call(this, arg, value, state, options);
  287. };
  288. schema = schema._test(rule.name, arg, validate, {
  289. description: rule.description,
  290. hasRef
  291. });
  292. }
  293. }
  294. return schema;
  295. };
  296. }
  297. }
  298. if (extension.describe) {
  299. type.prototype.describe = function () {
  300. const description = ctor.prototype.describe.call(this);
  301. return extension.describe.call(this, description);
  302. };
  303. }
  304. const instance = new type();
  305. joi[extension.name] = function (...extArgs) {
  306. return internals.callWithDefaults.call(this, instance, extArgs);
  307. };
  308. joi._binds.add(extension.name);
  309. }
  310. return joi;
  311. };
  312. root.extensionSchema = internals.object.keys({
  313. base: internals.object.type(Any, 'Joi object'),
  314. name: internals.string.required(),
  315. coerce: internals.func.arity(3),
  316. pre: internals.func.arity(3),
  317. language: internals.object,
  318. describe: internals.func.arity(1),
  319. rules: internals.array.items(internals.object.keys({
  320. name: internals.string.required(),
  321. setup: internals.func.arity(1),
  322. validate: internals.func.arity(4),
  323. params: [
  324. internals.object.pattern(/.*/, internals.object.type(Any, 'Joi object')),
  325. internals.object.type(internals.object.constructor, 'Joi object')
  326. ],
  327. description: [internals.string, internals.func.arity(1)]
  328. }).or('setup', 'validate'))
  329. }).strict();
  330. root.extensionsSchema = internals.array.items([internals.object, internals.func.arity(1)]).strict();
  331. root.version = require('../package.json').version;
  332. return root;
  333. };
  334. module.exports = internals.root();