index.d.ts 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365
  1. // The following definitions have been copied (almost) as-is from:
  2. // https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/hapi__joi
  3. //
  4. // Note: This file is expected to change dramatically in the next major release and have been
  5. // imported here to make migrating back to the "joi" module name simpler. It include known bugs
  6. // and other issues. It does not include some new features included in version 17.2.0 or newer.
  7. //
  8. // TypeScript Version: 2.8
  9. // TODO express type of Schema in a type-parameter (.default, .valid, .example etc)
  10. declare namespace Joi {
  11. type Types =
  12. | 'any'
  13. | 'alternatives'
  14. | 'array'
  15. | 'boolean'
  16. | 'binary'
  17. | 'date'
  18. | 'function'
  19. | 'link'
  20. | 'number'
  21. | 'object'
  22. | 'string'
  23. | 'symbol';
  24. type BasicType = boolean | number | string | any[] | object | null;
  25. type LanguageMessages = Record<string, string | Record<string, string>>;
  26. type PresenceMode = 'optional' | 'required' | 'forbidden';
  27. interface ErrorFormattingOptions {
  28. /**
  29. * when true, error message templates will escape special characters to HTML entities, for security purposes.
  30. *
  31. * @default false
  32. */
  33. escapeHtml?: boolean;
  34. /**
  35. * defines the value used to set the label context variable.
  36. */
  37. label?: 'path' | 'key' | false;
  38. /**
  39. * The preferred language code for error messages.
  40. * The value is matched against keys at the root of the messages object, and then the error code as a child key of that.
  41. * Can be a reference to the value, global context, or local context which is the root value passed to the validation function.
  42. *
  43. * Note that references to the value are usually not what you want as they move around the value structure relative to where the error happens.
  44. * Instead, either use the global context, or the absolute value (e.g. `Joi.ref('/variable')`)
  45. */
  46. language?: keyof LanguageMessages;
  47. /**
  48. * when false, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time.
  49. *
  50. * @default true
  51. */
  52. render?: boolean;
  53. /**
  54. * when true, the main error will possess a stack trace, otherwise it will be disabled.
  55. * Defaults to false for performances reasons. Has no effect on platforms other than V8/node.js as it uses the Stack trace API.
  56. *
  57. * @default false
  58. */
  59. stack?: boolean;
  60. /**
  61. * overrides the way values are wrapped (e.g. `[]` around arrays, `""` around labels).
  62. * Each key can be set to a string with one (same character before and after the value) or two characters (first character
  63. * before and second character after), or `false` to disable wrapping.
  64. */
  65. wrap?: {
  66. /**
  67. * the characters used around `{#label}` references. Defaults to `'"'`.
  68. *
  69. * @default '"'
  70. */
  71. label?: string | false,
  72. /**
  73. * the characters used around array values. Defaults to `'[]'`
  74. *
  75. * @default '[]'
  76. */
  77. array?: string | false
  78. /**
  79. * the characters used around array string values. Defaults to no wrapping.
  80. *
  81. * @default false
  82. */
  83. string?: string | false
  84. };
  85. }
  86. interface BaseValidationOptions {
  87. /**
  88. * when true, stops validation on the first error, otherwise returns all the errors found.
  89. *
  90. * @default true
  91. */
  92. abortEarly?: boolean;
  93. /**
  94. * when true, allows object to contain unknown keys which are ignored.
  95. *
  96. * @default false
  97. */
  98. allowUnknown?: boolean;
  99. /**
  100. * when true, return artifacts alongside the value.
  101. *
  102. * @default false
  103. */
  104. artifacts?: boolean;
  105. /**
  106. * when true, schema caching is enabled (for schemas with explicit caching rules).
  107. *
  108. * @default false
  109. */
  110. cache?: boolean;
  111. /**
  112. * provides an external data set to be used in references
  113. */
  114. context?: Context;
  115. /**
  116. * when true, attempts to cast values to the required types (e.g. a string to a number).
  117. *
  118. * @default true
  119. */
  120. convert?: boolean;
  121. /**
  122. * sets the string format used when converting dates to strings in error messages and casting.
  123. *
  124. * @default 'iso'
  125. */
  126. dateFormat?: 'date' | 'iso' | 'string' | 'time' | 'utc';
  127. /**
  128. * when true, valid results and throw errors are decorated with a debug property which includes an array of the validation steps used to generate the returned result.
  129. *
  130. * @default false
  131. */
  132. debug?: boolean;
  133. /**
  134. * error formatting settings.
  135. */
  136. errors?: ErrorFormattingOptions;
  137. /**
  138. * if false, the external rules set with `any.external()` are ignored, which is required to ignore any external validations in synchronous mode (or an exception is thrown).
  139. *
  140. * @default true
  141. */
  142. externals?: boolean;
  143. /**
  144. * when true, do not apply default values.
  145. *
  146. * @default false
  147. */
  148. noDefaults?: boolean;
  149. /**
  150. * when true, inputs are shallow cloned to include non-enumerable properties.
  151. *
  152. * @default false
  153. */
  154. nonEnumerables?: boolean;
  155. /**
  156. * sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'.
  157. *
  158. * @default 'optional'
  159. */
  160. presence?: PresenceMode;
  161. /**
  162. * when true, ignores unknown keys with a function value.
  163. *
  164. * @default false
  165. */
  166. skipFunctions?: boolean;
  167. /**
  168. * remove unknown elements from objects and arrays.
  169. * - when true, all unknown elements will be removed
  170. * - when an object:
  171. * - objects - set to true to remove unknown keys from objects
  172. *
  173. * @default false
  174. */
  175. stripUnknown?: boolean | { arrays?: boolean; objects?: boolean };
  176. }
  177. interface ValidationOptions extends BaseValidationOptions {
  178. /**
  179. * overrides individual error messages. Defaults to no override (`{}`).
  180. * Messages use the same rules as templates.
  181. * Variables in double braces `{{var}}` are HTML escaped if the option `errors.escapeHtml` is set to true.
  182. *
  183. * @default {}
  184. */
  185. messages?: LanguageMessages;
  186. }
  187. interface AsyncValidationOptions extends ValidationOptions {
  188. /**
  189. * when true, artifacts are returned alongside the value (i.e. `{ value, artifacts }`)
  190. *
  191. * @default false
  192. */
  193. artifacts?: boolean;
  194. /**
  195. * when true, warnings are returned alongside the value (i.e. `{ value, warning }`).
  196. *
  197. * @default false
  198. */
  199. warnings?: boolean;
  200. }
  201. interface LanguageMessageTemplate {
  202. source: string;
  203. rendered: string;
  204. }
  205. interface ErrorValidationOptions extends BaseValidationOptions {
  206. messages?: Record<string, LanguageMessageTemplate>;
  207. }
  208. interface RenameOptions {
  209. /**
  210. * if true, does not delete the old key name, keeping both the new and old keys in place.
  211. *
  212. * @default false
  213. */
  214. alias?: boolean;
  215. /**
  216. * if true, allows renaming multiple keys to the same destination where the last rename wins.
  217. *
  218. * @default false
  219. */
  220. multiple?: boolean;
  221. /**
  222. * if true, allows renaming a key over an existing key.
  223. *
  224. * @default false
  225. */
  226. override?: boolean;
  227. /**
  228. * if true, skip renaming of a key if it's undefined.
  229. *
  230. * @default false
  231. */
  232. ignoreUndefined?: boolean;
  233. }
  234. interface TopLevelDomainOptions {
  235. /**
  236. * - `true` to use the IANA list of registered TLDs. This is the default value.
  237. * - `false` to allow any TLD not listed in the `deny` list, if present.
  238. * - A `Set` or array of the allowed TLDs. Cannot be used together with `deny`.
  239. */
  240. allow?: Set<string> | string[] | boolean;
  241. /**
  242. * - A `Set` or array of the forbidden TLDs. Cannot be used together with a custom `allow` list.
  243. */
  244. deny?: Set<string> | string[];
  245. }
  246. interface HierarchySeparatorOptions {
  247. /**
  248. * overrides the default `.` hierarchy separator. Set to false to treat the key as a literal value.
  249. *
  250. * @default '.'
  251. */
  252. separator?: string | false;
  253. }
  254. interface DependencyOptions extends HierarchySeparatorOptions {
  255. /**
  256. * overrides the default check for a present value.
  257. *
  258. * @default (resolved) => resolved !== undefined
  259. */
  260. isPresent?: (resolved: any) => boolean;
  261. }
  262. interface EmailOptions {
  263. /**
  264. * if `true`, domains ending with a `.` character are permitted
  265. *
  266. * @default false
  267. */
  268. allowFullyQualified?: boolean;
  269. /**
  270. * If `true`, Unicode characters are permitted
  271. *
  272. * @default true
  273. */
  274. allowUnicode?: boolean;
  275. /**
  276. * if `true`, ignore invalid email length errors.
  277. *
  278. * @default false
  279. */
  280. ignoreLength?: boolean;
  281. /**
  282. * if true, allows multiple email addresses in a single string, separated by , or the separator characters.
  283. *
  284. * @default false
  285. */
  286. multiple?: boolean;
  287. /**
  288. * when multiple is true, overrides the default , separator. String can be a single character or multiple separator characters.
  289. *
  290. * @default ','
  291. */
  292. separator?: string | string[];
  293. /**
  294. * Options for TLD (top level domain) validation. By default, the TLD must be a valid name listed on the [IANA registry](http://data.iana.org/TLD/tlds-alpha-by-domain.txt)
  295. *
  296. * @default { allow: true }
  297. */
  298. tlds?: TopLevelDomainOptions | false;
  299. /**
  300. * Number of segments required for the domain. Be careful since some domains, such as `io`, directly allow email.
  301. *
  302. * @default 2
  303. */
  304. minDomainSegments?: number;
  305. /**
  306. * The maximum number of domain segments (e.g. `x.y.z` has 3 segments) allowed. Defaults to no limit.
  307. *
  308. * @default Infinity
  309. */
  310. maxDomainSegments?: number;
  311. }
  312. interface DomainOptions {
  313. /**
  314. * if `true`, domains ending with a `.` character are permitted
  315. *
  316. * @default false
  317. */
  318. allowFullyQualified?: boolean;
  319. /**
  320. * If `true`, Unicode characters are permitted
  321. *
  322. * @default true
  323. */
  324. allowUnicode?: boolean;
  325. /**
  326. * Options for TLD (top level domain) validation. By default, the TLD must be a valid name listed on the [IANA registry](http://data.iana.org/TLD/tlds-alpha-by-domain.txt)
  327. *
  328. * @default { allow: true }
  329. */
  330. tlds?: TopLevelDomainOptions | false;
  331. /**
  332. * Number of segments required for the domain.
  333. *
  334. * @default 2
  335. */
  336. minDomainSegments?: number;
  337. /**
  338. * The maximum number of domain segments (e.g. `x.y.z` has 3 segments) allowed. Defaults to no limit.
  339. *
  340. * @default Infinity
  341. */
  342. maxDomainSegments?: number;
  343. }
  344. interface HexOptions {
  345. /**
  346. * hex decoded representation must be byte aligned.
  347. * @default false
  348. */
  349. byteAligned?: boolean;
  350. /**
  351. * controls whether the prefix `0x` or `0X` is allowed (or required) on hex strings.
  352. * When `true`, the prefix must be provided.
  353. * When `false`, the prefix is forbidden.
  354. * When `optional`, the prefix is allowed but not required.
  355. *
  356. * @default false
  357. */
  358. prefix?: boolean | 'optional';
  359. }
  360. interface IpOptions {
  361. /**
  362. * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture
  363. */
  364. version?: string | string[];
  365. /**
  366. * Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden
  367. */
  368. cidr?: PresenceMode;
  369. }
  370. type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5' | 'uuidv6' | 'uuidv7' | 'uuidv8';
  371. interface GuidOptions {
  372. version?: GuidVersions[] | GuidVersions;
  373. separator?: boolean | '-' | ':';
  374. }
  375. interface UriOptions {
  376. /**
  377. * Specifies one or more acceptable Schemes, should only include the scheme name.
  378. * Can be an Array or String (strings are automatically escaped for use in a Regular Expression).
  379. */
  380. scheme?: string | RegExp | Array<string | RegExp>;
  381. /**
  382. * Allow relative URIs.
  383. *
  384. * @default false
  385. */
  386. allowRelative?: boolean;
  387. /**
  388. * Restrict only relative URIs.
  389. *
  390. * @default false
  391. */
  392. relativeOnly?: boolean;
  393. /**
  394. * Allows unencoded square brackets inside the query string.
  395. * This is NOT RFC 3986 compliant but query strings like abc[]=123&abc[]=456 are very common these days.
  396. *
  397. * @default false
  398. */
  399. allowQuerySquareBrackets?: boolean;
  400. /**
  401. * Validate the domain component using the options specified in `string.domain()`.
  402. */
  403. domain?: DomainOptions;
  404. /**
  405. * Encode URI before validation.
  406. *
  407. * @default false
  408. */
  409. encodeUri?: boolean;
  410. }
  411. interface DataUriOptions {
  412. /**
  413. * optional parameter defaulting to true which will require `=` padding if true or make padding optional if false
  414. *
  415. * @default true
  416. */
  417. paddingRequired?: boolean;
  418. }
  419. interface Base64Options extends Pick<DataUriOptions, 'paddingRequired'> {
  420. /**
  421. * if true, uses the URI-safe base64 format which replaces `+` with `-` and `\` with `_`.
  422. *
  423. * @default false
  424. */
  425. urlSafe?: boolean;
  426. }
  427. interface SwitchCases {
  428. /**
  429. * the required condition joi type.
  430. */
  431. is: SchemaLike;
  432. /**
  433. * the alternative schema type if the condition is true.
  434. */
  435. then: SchemaLike;
  436. }
  437. interface SwitchDefault {
  438. /**
  439. * the alternative schema type if no cases matched.
  440. * Only one otherwise statement is allowed in switch as the last array item.
  441. */
  442. otherwise: SchemaLike;
  443. }
  444. interface WhenOptions {
  445. /**
  446. * the required condition joi type.
  447. */
  448. is?: SchemaLike;
  449. /**
  450. * the negative version of `is` (`then` and `otherwise` have reverse
  451. * roles).
  452. */
  453. not?: SchemaLike;
  454. /**
  455. * the alternative schema type if the condition is true. Required if otherwise or switch are missing.
  456. */
  457. then?: SchemaLike;
  458. /**
  459. * the alternative schema type if the condition is false. Required if then or switch are missing.
  460. */
  461. otherwise?: SchemaLike;
  462. /**
  463. * the list of cases. Required if then is missing. Required if then or otherwise are missing.
  464. */
  465. switch?: Array<SwitchCases | SwitchDefault>;
  466. /**
  467. * whether to stop applying further conditions if the condition is true.
  468. */
  469. break?: boolean;
  470. }
  471. interface WhenSchemaOptions {
  472. /**
  473. * the alternative schema type if the condition is true. Required if otherwise is missing.
  474. */
  475. then?: SchemaLike;
  476. /**
  477. * the alternative schema type if the condition is false. Required if then is missing.
  478. */
  479. otherwise?: SchemaLike;
  480. }
  481. interface Cache {
  482. /**
  483. * Add an item to the cache.
  484. *
  485. * Note that key and value can be anything including objects, array, etc.
  486. */
  487. set(key: any, value: any): void;
  488. /**
  489. * Retrieve an item from the cache.
  490. *
  491. * Note that key and value can be anything including objects, array, etc.
  492. */
  493. get(key: any): any;
  494. }
  495. interface CacheProvisionOptions {
  496. /**
  497. * number of items to store in the cache before the least used items are dropped.
  498. *
  499. * @default 1000
  500. */
  501. max: number;
  502. }
  503. interface CacheConfiguration {
  504. /**
  505. * Provisions a simple LRU cache for caching simple inputs (`undefined`, `null`, strings, numbers, and booleans).
  506. */
  507. provision(options?: CacheProvisionOptions): void;
  508. }
  509. interface CompileOptions {
  510. /**
  511. * If true and the provided schema is (or contains parts) using an older version of joi, will return a compiled schema that is compatible with the older version.
  512. * If false, the schema is always compiled using the current version and if older schema components are found, an error is thrown.
  513. */
  514. legacy: boolean;
  515. }
  516. interface IsSchemaOptions {
  517. /**
  518. * If true, will identify schemas from older versions of joi, otherwise will throw an error.
  519. *
  520. * @default false
  521. */
  522. legacy: boolean;
  523. }
  524. interface ReferenceOptions extends HierarchySeparatorOptions {
  525. /**
  526. * a function with the signature `function(value)` where `value` is the resolved reference value and the return value is the adjusted value to use.
  527. * Note that the adjust feature will not perform any type validation on the adjusted value and it must match the value expected by the rule it is used in.
  528. * Cannot be used with `map`.
  529. *
  530. * @example `(value) => value + 5`
  531. */
  532. adjust?: (value: any) => any;
  533. /**
  534. * an array of array pairs using the format `[[key, value], [key, value]]` used to maps the resolved reference value to another value.
  535. * If the resolved value is not in the map, it is returned as-is.
  536. * Cannot be used with `adjust`.
  537. */
  538. map?: Array<[any, any]>;
  539. /**
  540. * overrides default prefix characters.
  541. */
  542. prefix?: {
  543. /**
  544. * references to the globally provided context preference.
  545. *
  546. * @default '$'
  547. */
  548. global?: string;
  549. /**
  550. * references to error-specific or rule specific context.
  551. *
  552. * @default '#'
  553. */
  554. local?: string;
  555. /**
  556. * references to the root value being validated.
  557. *
  558. * @default '/'
  559. */
  560. root?: string;
  561. };
  562. /**
  563. * If set to a number, sets the reference relative starting point.
  564. * Cannot be combined with separator prefix characters.
  565. * Defaults to the reference key prefix (or 1 if none present)
  566. */
  567. ancestor?: number;
  568. /**
  569. * creates an in-reference.
  570. */
  571. in?: boolean;
  572. /**
  573. * when true, the reference resolves by reaching into maps and sets.
  574. */
  575. iterables?: boolean;
  576. /**
  577. * when true, the value of the reference is used instead of its name in error messages
  578. * and template rendering. Defaults to false.
  579. */
  580. render?: boolean;
  581. }
  582. interface StringRegexOptions {
  583. /**
  584. * optional pattern name.
  585. */
  586. name?: string;
  587. /**
  588. * when true, the provided pattern will be disallowed instead of required.
  589. *
  590. * @default false
  591. */
  592. invert?: boolean;
  593. }
  594. interface RuleOptions {
  595. /**
  596. * if true, the rules will not be replaced by the same unique rule later.
  597. *
  598. * For example, `Joi.number().min(1).rule({ keep: true }).min(2)` will keep both `min()` rules instead of the later rule overriding the first.
  599. *
  600. * @default false
  601. */
  602. keep?: boolean;
  603. /**
  604. * a single message string or a messages object where each key is an error code and corresponding message string as value.
  605. *
  606. * The object is the same as the messages used as an option in `any.validate()`.
  607. * The strings can be plain messages or a message template.
  608. */
  609. message?: string | LanguageMessages;
  610. /**
  611. * if true, turns any error generated by the ruleset to warnings.
  612. */
  613. warn?: boolean;
  614. }
  615. interface ErrorReport extends Error {
  616. code: string;
  617. flags: Record<string, ExtensionFlag>;
  618. path: string[];
  619. prefs: ErrorValidationOptions;
  620. messages: LanguageMessages;
  621. state: State;
  622. value: any;
  623. local: any;
  624. }
  625. interface ValidationError extends Error {
  626. name: 'ValidationError';
  627. isJoi: boolean;
  628. /**
  629. * array of errors.
  630. */
  631. details: ValidationErrorItem[];
  632. /**
  633. * function that returns a string with an annotated version of the object pointing at the places where errors occurred.
  634. *
  635. * NOTE: This method does not exist in browser builds of Joi
  636. *
  637. * @param stripColors - if truthy, will strip the colors out of the output.
  638. */
  639. annotate(stripColors?: boolean): string;
  640. _original: any;
  641. }
  642. interface ValidationErrorItem {
  643. message: string;
  644. path: Array<string | number>;
  645. type: string;
  646. context?: Context;
  647. }
  648. type ValidationErrorFunction = (errors: ErrorReport[]) => string | ValidationErrorItem | Error | ErrorReport[];
  649. interface ValidationWarning {
  650. message: string;
  651. details: ValidationErrorItem[];
  652. }
  653. type ValidationResult<TSchema = any> = {
  654. error: undefined;
  655. warning?: ValidationError;
  656. value: TSchema;
  657. } | {
  658. error: ValidationError;
  659. warning?: ValidationError;
  660. value: any;
  661. }
  662. interface CreateErrorOptions {
  663. flags?: boolean;
  664. messages?: LanguageMessages;
  665. }
  666. interface ModifyOptions {
  667. each?: boolean;
  668. once?: boolean;
  669. ref?: boolean;
  670. schema?: boolean;
  671. }
  672. interface MutateRegisterOptions {
  673. family?: any;
  674. key?: any;
  675. }
  676. interface SetFlagOptions {
  677. clone: boolean;
  678. }
  679. interface CustomHelpers<V = any> {
  680. schema: ExtensionBoundSchema;
  681. state: State;
  682. prefs: ValidationOptions;
  683. original: V;
  684. warn: (code: string, local?: Context) => void;
  685. error: (code: string, local?: Context, localState?: State) => ErrorReport;
  686. message: (messages: LanguageMessages, local?: Context) => ErrorReport;
  687. }
  688. type CustomValidator<V = any, R = V> = (value: V, helpers: CustomHelpers<R>) => R | ErrorReport;
  689. interface ExternalHelpers<V = any> {
  690. schema: ExtensionBoundSchema;
  691. linked: ExtensionBoundSchema | null;
  692. state: State;
  693. prefs: ValidationOptions;
  694. original: V;
  695. warn: (code: string, local?: Context) => void;
  696. error: (code: string, local?: Context) => ErrorReport;
  697. message: (messages: LanguageMessages, local?: Context) => ErrorReport;
  698. }
  699. type ExternalValidationFunction<V = any, R = V> = (value: V, helpers: ExternalHelpers<R>) => R | undefined;
  700. type SchemaLikeWithoutArray = string | number | boolean | null | Schema | SchemaMap;
  701. type SchemaLike = SchemaLikeWithoutArray | object;
  702. type NullableType<T> = undefined | null | T
  703. type IsPrimitiveSubset<T> =
  704. [T] extends [string]
  705. ? true
  706. : [T] extends [number]
  707. ? true
  708. : [T] extends [bigint]
  709. ? true
  710. : [T] extends [boolean]
  711. ? true
  712. : [T] extends [symbol]
  713. ? true
  714. : [T] extends [null]
  715. ? true
  716. : [T] extends [undefined]
  717. ? true
  718. : false;
  719. type IsUnion<T, U extends T = T> =
  720. T extends unknown ? [U] extends [T] ? false : true : false;
  721. type IsNonPrimitiveSubsetUnion<T> = true extends IsUnion<T> ? true extends IsPrimitiveSubset<T> ? false : true : false;
  722. type ObjectPropertiesSchema<T = any> =
  723. true extends IsNonPrimitiveSubsetUnion<Exclude<T, undefined | null>>
  724. ? Joi.AlternativesSchema
  725. : T extends NullableType<string>
  726. ? Joi.StringSchema
  727. : T extends NullableType<number>
  728. ? Joi.NumberSchema
  729. : T extends NullableType<bigint>
  730. ? Joi.NumberSchema
  731. : T extends NullableType<boolean>
  732. ? Joi.BooleanSchema
  733. : T extends NullableType<Date>
  734. ? Joi.DateSchema
  735. : T extends NullableType<Buffer>
  736. ? Joi.BinarySchema
  737. : T extends NullableType<Array<any>>
  738. ? Joi.ArraySchema
  739. : T extends NullableType<object>
  740. ? (StrictSchemaMap<T> | ObjectSchema<T>)
  741. : never
  742. type PartialSchemaMap<TSchema = any> = {
  743. [key in keyof TSchema]?: SchemaLike | SchemaLike[];
  744. }
  745. type StrictSchemaMap<TSchema = any> = {
  746. [key in keyof TSchema]-?: ObjectPropertiesSchema<TSchema[key]>
  747. };
  748. type SchemaMap<TSchema = any, isStrict = false> = isStrict extends true ? StrictSchemaMap<TSchema> : PartialSchemaMap<TSchema>
  749. type Schema<P = any> =
  750. | AnySchema<P>
  751. | ArraySchema<P>
  752. | AlternativesSchema<P>
  753. | BinarySchema<P>
  754. | BooleanSchema<P>
  755. | DateSchema<P>
  756. | FunctionSchema<P>
  757. | NumberSchema<P>
  758. | ObjectSchema<P>
  759. | StringSchema<P>
  760. | LinkSchema<P>
  761. | SymbolSchema<P>;
  762. type SchemaFunction = (schema: Schema) => Schema;
  763. interface AddRuleOptions {
  764. name: string;
  765. args?: {
  766. [key: string]: any;
  767. };
  768. }
  769. interface GetRuleOptions {
  770. args?: Record<string, any>;
  771. method?: string;
  772. name: string;
  773. operator?: string;
  774. }
  775. interface SchemaInternals {
  776. /**
  777. * Parent schema object.
  778. */
  779. $_super: Schema;
  780. /**
  781. * Terms of current schema.
  782. */
  783. $_terms: Record<string, any>;
  784. /**
  785. * Adds a rule to current validation schema.
  786. */
  787. $_addRule(rule: string | AddRuleOptions): Schema;
  788. /**
  789. * Internally compiles schema.
  790. */
  791. $_compile(schema: SchemaLike, options?: CompileOptions): Schema;
  792. /**
  793. * Creates a joi error object.
  794. */
  795. $_createError(
  796. code: string,
  797. value: any,
  798. context: Context,
  799. state: State,
  800. prefs: ValidationOptions,
  801. options?: CreateErrorOptions,
  802. ): Err;
  803. /**
  804. * Get value from given flag.
  805. */
  806. $_getFlag(name: string): any;
  807. /**
  808. * Retrieve some rule configuration.
  809. */
  810. $_getRule(name: string): GetRuleOptions | undefined;
  811. $_mapLabels(path: string | string[]): string;
  812. /**
  813. * Returns true if validations runs fine on given value.
  814. */
  815. $_match(value: any, state: State, prefs: ValidationOptions): boolean;
  816. $_modify(options?: ModifyOptions): Schema;
  817. /**
  818. * Resets current schema.
  819. */
  820. $_mutateRebuild(): this;
  821. $_mutateRegister(schema: Schema, options?: MutateRegisterOptions): void;
  822. /**
  823. * Get value from given property.
  824. */
  825. $_property(name: string): any;
  826. /**
  827. * Get schema at given path.
  828. */
  829. $_reach(path: string[]): Schema;
  830. /**
  831. * Get current schema root references.
  832. */
  833. $_rootReferences(): any;
  834. /**
  835. * Set flag to given value.
  836. */
  837. $_setFlag(flag: string, value: any, options?: SetFlagOptions): void;
  838. /**
  839. * Runs internal validations against given value.
  840. */
  841. $_validate(value: any, state: State, prefs: ValidationOptions): ValidationResult;
  842. }
  843. interface AnySchema<TSchema = any> extends SchemaInternals {
  844. /**
  845. * Flags of current schema.
  846. */
  847. _flags: Record<string, any>;
  848. /**
  849. * Starts a ruleset in order to apply multiple rule options. The set ends when `rule()`, `keep()`, `message()`, or `warn()` is called.
  850. */
  851. $: this;
  852. /**
  853. * Starts a ruleset in order to apply multiple rule options. The set ends when `rule()`, `keep()`, `message()`, or `warn()` is called.
  854. */
  855. ruleset: this;
  856. type?: Types | string;
  857. /**
  858. * Whitelists a value
  859. */
  860. allow(...values: any[]): this;
  861. /**
  862. * Assign target alteration options to a schema that are applied when `any.tailor()` is called.
  863. * @param targets - an object where each key is a target name, and each value is a function that takes an schema and returns an schema.
  864. */
  865. alter(targets: Record<string, (schema: this) => Schema>): this;
  866. /**
  867. * Assigns the schema an artifact id which is included in the validation result if the rule passed validation.
  868. * @param id - any value other than undefined which will be returned as-is in the result artifacts map.
  869. */
  870. artifact(id: any): this;
  871. /**
  872. * By default, some Joi methods to function properly need to rely on the Joi instance they are attached to because
  873. * they use `this` internally.
  874. * So `Joi.string()` works but if you extract the function from it and call `string()` it won't.
  875. * `bind()` creates a new Joi instance where all the functions relying on `this` are bound to the Joi instance.
  876. */
  877. bind(): this;
  878. /**
  879. * Adds caching to the schema which will attempt to cache the validation results (success and failures) of incoming inputs.
  880. * If no cache is passed, a default cache is provisioned by using `cache.provision()` internally.
  881. */
  882. cache(cache?: Cache): this;
  883. /**
  884. * Casts the validated value to the specified type.
  885. */
  886. cast(to: 'map' | 'number' | 'set' | 'string'): this;
  887. /**
  888. * Returns a new type that is the result of adding the rules of one type to another.
  889. */
  890. concat(schema: this): this;
  891. /**
  892. * Adds a custom validation function.
  893. */
  894. custom(fn: CustomValidator, description?: string): this;
  895. /**
  896. * Sets a default value if the original value is `undefined` where:
  897. * @param value - the default value. One of:
  898. * - a literal value (string, number, object, etc.)
  899. * - a [references](#refkey-options)
  900. * - a function which returns the default value using the signature `function(parent, helpers)` where:
  901. * - `parent` - a clone of the object containing the value being validated. Note that since specifying a
  902. * `parent` argument performs cloning, do not declare format arguments if you are not using them.
  903. * - `helpers` - same as those described in [`any.custom()`](anycustomermethod_description)
  904. *
  905. * When called without any `value` on an object schema type, a default value will be automatically generated
  906. * based on the default values of the object keys.
  907. *
  908. * Note that if value is an object, any changes to the object after `default()` is called will change the
  909. * reference and any future assignment.
  910. */
  911. default(value?: BasicType | Reference | ((parent: any, helpers: CustomHelpers) => BasicType | Reference)): this;
  912. /**
  913. * Returns a plain object representing the schema's rules and properties
  914. */
  915. describe(): Description;
  916. /**
  917. * Annotates the key
  918. */
  919. description(desc: string): this;
  920. /**
  921. * Disallows values.
  922. */
  923. disallow(...values: any[]): this;
  924. /**
  925. * Considers anything that matches the schema to be empty (undefined).
  926. * @param schema - any object or joi schema to match. An undefined schema unsets that rule.
  927. */
  928. empty(schema?: SchemaLike): this;
  929. /**
  930. * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
  931. */
  932. equal(...values: any[]): this;
  933. /**
  934. * Overrides the default joi error with a custom error if the rule fails where:
  935. * @param err - can be:
  936. * an instance of `Error` - the override error.
  937. * a `function(errors)`, taking an array of errors as argument, where it must either:
  938. * return a `string` - substitutes the error message with this text
  939. * return a single ` object` or an `Array` of it, where:
  940. * `type` - optional parameter providing the type of the error (eg. `number.min`).
  941. * `message` - optional parameter if `template` is provided, containing the text of the error.
  942. * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors.
  943. * `context` - optional parameter, to provide context to your error if you are using the `template`.
  944. * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors.
  945. *
  946. * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the
  947. * normal joi error properties. If validation fails and another error is found before the error
  948. * override, that error will be returned and the override will be ignored (unless the `abortEarly`
  949. * option has been set to `false`).
  950. */
  951. error(err: Error | ValidationErrorFunction): this;
  952. /**
  953. * Annotates the key with an example value, must be valid.
  954. */
  955. example(value: any, options?: { override: boolean }): this;
  956. /**
  957. * Marks a key as required which will not allow undefined as value. All keys are optional by default.
  958. */
  959. exist(): this;
  960. /**
  961. * Adds an external validation rule.
  962. *
  963. * Note that external validation rules are only called after the all other validation rules for the entire schema (from the value root) are checked.
  964. * This means that any changes made to the value by the external rules are not available to any other validation rules during the non-external validation phase.
  965. * If schema validation failed, no external validation rules are called.
  966. */
  967. external(method: ExternalValidationFunction, description?: string): this;
  968. /**
  969. * Returns a sub-schema based on a path of object keys or schema ids.
  970. *
  971. * @param path - a dot `.` separated path string or a pre-split array of path keys. The keys must match the sub-schema id or object key (if no id was explicitly set).
  972. */
  973. extract(path: string | string[]): Schema;
  974. /**
  975. * Sets a failover value if the original value fails passing validation.
  976. *
  977. * @param value - the failover value. value supports references. value may be assigned a function which returns the default value.
  978. *
  979. * If value is specified as a function that accepts a single parameter, that parameter will be a context object that can be used to derive the resulting value.
  980. * Note that if value is an object, any changes to the object after `failover()` is called will change the reference and any future assignment.
  981. * Use a function when setting a dynamic value (e.g. the current time).
  982. * Using a function with a single argument performs some internal cloning which has a performance impact.
  983. * If you do not need access to the context, define the function without any arguments.
  984. */
  985. failover(value: any): this;
  986. /**
  987. * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
  988. */
  989. forbidden(): this;
  990. /**
  991. * Returns a new schema where each of the path keys listed have been modified.
  992. *
  993. * @param key - an array of key strings, a single key string, or an array of arrays of pre-split key strings.
  994. * @param adjuster - a function which must return a modified schema.
  995. */
  996. fork(key: string | string[] | string[][], adjuster: SchemaFunction): this;
  997. /**
  998. * Sets a schema id for reaching into the schema via `any.extract()`.
  999. * If no id is set, the schema id defaults to the object key it is associated with.
  1000. * If the schema is used in an array or alternatives type and no id is set, the schema in unreachable.
  1001. */
  1002. id(name?: string): this;
  1003. /**
  1004. * Disallows values.
  1005. */
  1006. invalid(...values: any[]): this;
  1007. /**
  1008. * Same as `rule({ keep: true })`.
  1009. *
  1010. * Note that `keep()` will terminate the current ruleset and cannot be followed by another rule option.
  1011. * Use `rule()` to apply multiple rule options.
  1012. */
  1013. keep(): this;
  1014. /**
  1015. * Overrides the key name in error messages.
  1016. */
  1017. label(name: string): this;
  1018. /**
  1019. * Same as `rule({ message })`.
  1020. *
  1021. * Note that `message()` will terminate the current ruleset and cannot be followed by another rule option.
  1022. * Use `rule()` to apply multiple rule options.
  1023. */
  1024. message(message: string): this;
  1025. /**
  1026. * Same as `any.prefs({ messages })`.
  1027. * Note that while `any.message()` applies only to the last rule or ruleset, `any.messages()` applies to the entire schema.
  1028. */
  1029. messages(messages: LanguageMessages): this;
  1030. /**
  1031. * Attaches metadata to the key.
  1032. */
  1033. meta(meta: object): this;
  1034. /**
  1035. * Disallows values.
  1036. */
  1037. not(...values: any[]): this;
  1038. /**
  1039. * Annotates the key
  1040. */
  1041. note(...notes: string[]): this;
  1042. /**
  1043. * Requires the validated value to match of the provided `any.allow()` values.
  1044. * It has not effect when called together with `any.valid()` since it already sets the requirements.
  1045. * When used with `any.allow()` it converts it to an `any.valid()`.
  1046. */
  1047. only(): this;
  1048. /**
  1049. * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.
  1050. */
  1051. optional(): this;
  1052. /**
  1053. * Overrides the global validate() options for the current key and any sub-key.
  1054. */
  1055. options(options: ValidationOptions): this;
  1056. /**
  1057. * Overrides the global validate() options for the current key and any sub-key.
  1058. */
  1059. prefs(options: ValidationOptions): this;
  1060. /**
  1061. * Overrides the global validate() options for the current key and any sub-key.
  1062. */
  1063. preferences(options: ValidationOptions): this;
  1064. /**
  1065. * Sets the presence mode for the schema.
  1066. */
  1067. presence(mode: PresenceMode): this;
  1068. /**
  1069. * Outputs the original untouched value instead of the casted value.
  1070. */
  1071. raw(enabled?: boolean): this;
  1072. /**
  1073. * Marks a key as required which will not allow undefined as value. All keys are optional by default.
  1074. */
  1075. required(): this;
  1076. /**
  1077. * Applies a set of rule options to the current ruleset or last rule added.
  1078. *
  1079. * When applying rule options, the last rule (e.g. `min()`) is used unless there is an active ruleset defined (e.g. `$.min().max()`)
  1080. * in which case the options are applied to all the provided rules.
  1081. * Once `rule()` is called, the previous rules can no longer be modified and any active ruleset is terminated.
  1082. *
  1083. * Rule modifications can only be applied to supported rules.
  1084. * Most of the `any` methods do not support rule modifications because they are implemented using schema flags (e.g. `required()`) or special
  1085. * internal implementation (e.g. `valid()`).
  1086. * In those cases, use the `any.messages()` method to override the error codes for the errors you want to customize.
  1087. */
  1088. rule(options: RuleOptions): this;
  1089. /**
  1090. * Registers a schema to be used by descendants of the current schema in named link references.
  1091. */
  1092. shared(ref: Schema): this;
  1093. /**
  1094. * Sets the options.convert options to false which prevent type casting for the current key and any child keys.
  1095. */
  1096. strict(isStrict?: boolean): this;
  1097. /**
  1098. * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output.
  1099. * @param [enabled=true] - if true, the value is stripped, otherwise the validated value is retained. Defaults to true.
  1100. */
  1101. strip(enabled?: boolean): this;
  1102. /**
  1103. * Annotates the key
  1104. */
  1105. tag(...tags: string[]): this;
  1106. /**
  1107. * Applies any assigned target alterations to a copy of the schema that were applied via `any.alter()`.
  1108. */
  1109. tailor(targets: string | string[]): Schema;
  1110. /**
  1111. * Annotates the key with an unit name.
  1112. */
  1113. unit(name: string): this;
  1114. /**
  1115. * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
  1116. */
  1117. valid(...values: any[]): this;
  1118. /**
  1119. * Validates a value using the schema and options.
  1120. */
  1121. validate(value: any, options?: ValidationOptions): ValidationResult<TSchema>;
  1122. /**
  1123. * Validates a value using the schema and options.
  1124. */
  1125. validateAsync<TOpts extends AsyncValidationOptions>(
  1126. value: any,
  1127. options?: TOpts
  1128. ): Promise<
  1129. TOpts extends { artifacts: true } | { warnings: true }
  1130. ? { value: TSchema } & (TOpts extends { artifacts: true }
  1131. ? { artifacts: Map<any, string[][]> }
  1132. : {}) &
  1133. (TOpts extends { warnings: true }
  1134. ? { warning: ValidationWarning }
  1135. : {})
  1136. : TSchema
  1137. >;
  1138. /**
  1139. * Same as `rule({ warn: true })`.
  1140. * Note that `warn()` will terminate the current ruleset and cannot be followed by another rule option.
  1141. * Use `rule()` to apply multiple rule options.
  1142. */
  1143. warn(): this;
  1144. /**
  1145. * Generates a warning.
  1146. * When calling `any.validateAsync()`, set the `warning` option to true to enable warnings.
  1147. * Warnings are reported separately from errors alongside the result value via the warning key (i.e. `{ value, warning }`).
  1148. * Warning are always included when calling `any.validate()`.
  1149. */
  1150. warning(code: string, context: Context): this;
  1151. /**
  1152. * Converts the type into an alternatives type where the conditions are merged into the type definition where:
  1153. */
  1154. when(ref: string | Reference, options: WhenOptions | WhenOptions[]): this;
  1155. /**
  1156. * Converts the type into an alternatives type where the conditions are merged into the type definition where:
  1157. */
  1158. when(ref: Schema, options: WhenSchemaOptions): this;
  1159. }
  1160. interface Description {
  1161. type?: Types | string;
  1162. label?: string;
  1163. description?: string;
  1164. flags?: object;
  1165. notes?: string[];
  1166. tags?: string[];
  1167. metas?: any[];
  1168. example?: any[];
  1169. valids?: any[];
  1170. invalids?: any[];
  1171. unit?: string;
  1172. options?: ValidationOptions;
  1173. [key: string]: any;
  1174. }
  1175. interface Context {
  1176. [key: string]: any;
  1177. key?: string;
  1178. label?: string;
  1179. value?: any;
  1180. }
  1181. interface State {
  1182. key?: string;
  1183. path?: (string | number)[];
  1184. parent?: any;
  1185. reference?: any;
  1186. ancestors?: any;
  1187. localize?(...args: any[]): State;
  1188. }
  1189. interface BooleanSchema<TSchema = boolean> extends AnySchema<TSchema> {
  1190. /**
  1191. * Allows for additional values to be considered valid booleans by converting them to false during validation.
  1192. * String comparisons are by default case insensitive,
  1193. * see `boolean.sensitive()` to change this behavior.
  1194. * @param values - strings, numbers or arrays of them
  1195. */
  1196. falsy(...values: Array<string | number | null>): this;
  1197. /**
  1198. * Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion
  1199. * (when not in `strict()` mode) to be matched in a case insensitive manner.
  1200. */
  1201. sensitive(enabled?: boolean): this;
  1202. /**
  1203. * Allows for additional values to be considered valid booleans by converting them to true during validation.
  1204. * String comparisons are by default case insensitive, see `boolean.sensitive()` to change this behavior.
  1205. * @param values - strings, numbers or arrays of them
  1206. */
  1207. truthy(...values: Array<string | number | null>): this;
  1208. }
  1209. interface NumberSchema<TSchema = number> extends AnySchema<TSchema> {
  1210. /**
  1211. * Specifies that the value must be greater than limit.
  1212. * It can also be a reference to another field.
  1213. */
  1214. greater(limit: number | Reference): this;
  1215. /**
  1216. * Requires the number to be an integer (no floating point).
  1217. */
  1218. integer(): this;
  1219. /**
  1220. * Specifies that the value must be less than limit.
  1221. * It can also be a reference to another field.
  1222. */
  1223. less(limit: number | Reference): this;
  1224. /**
  1225. * Specifies the maximum value.
  1226. * It can also be a reference to another field.
  1227. */
  1228. max(limit: number | Reference): this;
  1229. /**
  1230. * Specifies the minimum value.
  1231. * It can also be a reference to another field.
  1232. */
  1233. min(limit: number | Reference): this;
  1234. /**
  1235. * Specifies that the value must be a multiple of base.
  1236. */
  1237. multiple(base: number | Reference): this;
  1238. /**
  1239. * Requires the number to be negative.
  1240. */
  1241. negative(): this;
  1242. /**
  1243. * Requires the number to be a TCP port, so between 0 and 65535.
  1244. */
  1245. port(): this;
  1246. /**
  1247. * Requires the number to be positive.
  1248. */
  1249. positive(): this;
  1250. /**
  1251. * Specifies the maximum number of decimal places where:
  1252. * @param limit - the maximum number of decimal places allowed.
  1253. */
  1254. precision(limit: number): this;
  1255. /**
  1256. * Requires the number to be negative or positive.
  1257. */
  1258. sign(sign: 'positive' | 'negative'): this;
  1259. /**
  1260. * Allows the number to be outside of JavaScript's safety range (Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER).
  1261. */
  1262. unsafe(enabled?: any): this;
  1263. }
  1264. interface StringSchema<TSchema = string> extends AnySchema<TSchema> {
  1265. /**
  1266. * Requires the string value to only contain a-z, A-Z, and 0-9.
  1267. */
  1268. alphanum(): this;
  1269. /**
  1270. * Requires the string value to be a valid base64 string; does not check the decoded value.
  1271. */
  1272. base64(options?: Base64Options): this;
  1273. /**
  1274. * Sets the required string case.
  1275. */
  1276. case(direction: 'upper' | 'lower'): this;
  1277. /**
  1278. * Requires the number to be a credit card number (Using Luhn Algorithm).
  1279. */
  1280. creditCard(): this;
  1281. /**
  1282. * Requires the string value to be a valid data URI string.
  1283. */
  1284. dataUri(options?: DataUriOptions): this;
  1285. /**
  1286. * Requires the string value to be a valid domain.
  1287. */
  1288. domain(options?: DomainOptions): this;
  1289. /**
  1290. * Requires the string value to be a valid email address.
  1291. */
  1292. email(options?: EmailOptions): this;
  1293. /**
  1294. * Requires the string value to be a valid GUID.
  1295. */
  1296. guid(options?: GuidOptions): this;
  1297. /**
  1298. * Requires the string value to be a valid hexadecimal string.
  1299. */
  1300. hex(options?: HexOptions): this;
  1301. /**
  1302. * Requires the string value to be a valid hostname as per RFC1123.
  1303. */
  1304. hostname(): this;
  1305. /**
  1306. * Allows the value to match any whitelist of blacklist item in a case insensitive comparison.
  1307. */
  1308. insensitive(): this;
  1309. /**
  1310. * Requires the string value to be a valid ip address.
  1311. */
  1312. ip(options?: IpOptions): this;
  1313. /**
  1314. * Requires the string value to be in valid ISO 8601 date format.
  1315. */
  1316. isoDate(): this;
  1317. /**
  1318. * Requires the string value to be in valid ISO 8601 duration format.
  1319. */
  1320. isoDuration(): this;
  1321. /**
  1322. * Specifies the exact string length required
  1323. * @param limit - the required string length. It can also be a reference to another field.
  1324. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
  1325. */
  1326. length(limit: number | Reference, encoding?: string): this;
  1327. /**
  1328. * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase.
  1329. */
  1330. lowercase(): this;
  1331. /**
  1332. * Specifies the maximum number of string characters.
  1333. * @param limit - the maximum number of string characters allowed. It can also be a reference to another field.
  1334. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
  1335. */
  1336. max(limit: number | Reference, encoding?: string): this;
  1337. /**
  1338. * Specifies the minimum number string characters.
  1339. * @param limit - the minimum number of string characters required. It can also be a reference to another field.
  1340. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
  1341. */
  1342. min(limit: number | Reference, encoding?: string): this;
  1343. /**
  1344. * Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized.
  1345. * @param [form='NFC'] - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD
  1346. */
  1347. normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this;
  1348. /**
  1349. * Defines a regular expression rule.
  1350. * @param pattern - a regular expression object the string value must match against.
  1351. * @param options - optional, can be:
  1352. * Name for patterns (useful with multiple patterns). Defaults to 'required'.
  1353. * An optional configuration object with the following supported properties:
  1354. * name - optional pattern name.
  1355. * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
  1356. */
  1357. pattern(pattern: RegExp, options?: string | StringRegexOptions): this;
  1358. /**
  1359. * Defines a regular expression rule.
  1360. * @param pattern - a regular expression object the string value must match against.
  1361. * @param options - optional, can be:
  1362. * Name for patterns (useful with multiple patterns). Defaults to 'required'.
  1363. * An optional configuration object with the following supported properties:
  1364. * name - optional pattern name.
  1365. * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
  1366. */
  1367. regex(pattern: RegExp, options?: string | StringRegexOptions): this;
  1368. /**
  1369. * Replace characters matching the given pattern with the specified replacement string where:
  1370. * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced.
  1371. * @param replacement - the string that will replace the pattern.
  1372. */
  1373. replace(pattern: RegExp | string, replacement: string): this;
  1374. /**
  1375. * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.
  1376. */
  1377. token(): this;
  1378. /**
  1379. * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed.
  1380. * @param [enabled=true] - optional parameter defaulting to true which allows you to reset the behavior of trim by providing a falsy value.
  1381. */
  1382. trim(enabled?: any): this;
  1383. /**
  1384. * Specifies whether the string.max() limit should be used as a truncation.
  1385. * @param [enabled=true] - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value.
  1386. */
  1387. truncate(enabled?: boolean): this;
  1388. /**
  1389. * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase.
  1390. */
  1391. uppercase(): this;
  1392. /**
  1393. * Requires the string value to be a valid RFC 3986 URI.
  1394. */
  1395. uri(options?: UriOptions): this;
  1396. /**
  1397. * Requires the string value to be a valid GUID.
  1398. */
  1399. uuid(options?: GuidOptions): this;
  1400. }
  1401. interface SymbolSchema<TSchema = Symbol> extends AnySchema<TSchema> {
  1402. // TODO: support number and symbol index
  1403. map(iterable: Iterable<[string | number | boolean | symbol, symbol]> | { [key: string]: symbol }): this;
  1404. }
  1405. interface ArraySortOptions {
  1406. /**
  1407. * @default 'ascending'
  1408. */
  1409. order?: 'ascending' | 'descending';
  1410. by?: string | Reference;
  1411. }
  1412. interface ArrayUniqueOptions extends HierarchySeparatorOptions {
  1413. /**
  1414. * if true, undefined values for the dot notation string comparator will not cause the array to fail on uniqueness.
  1415. *
  1416. * @default false
  1417. */
  1418. ignoreUndefined?: boolean;
  1419. }
  1420. type ComparatorFunction = (a: any, b: any) => boolean;
  1421. interface ArraySchema<TSchema = any[]> extends AnySchema<TSchema> {
  1422. /**
  1423. * Verifies that an assertion passes for at least one item in the array, where:
  1424. * `schema` - the validation rules required to satisfy the assertion. If the `schema` includes references, they are resolved against
  1425. * the array item being tested, not the value of the `ref` target.
  1426. */
  1427. has(schema: SchemaLike): this;
  1428. /**
  1429. * List the types allowed for the array values.
  1430. * If a given type is .required() then there must be a matching item in the array.
  1431. * If a type is .forbidden() then it cannot appear in the array.
  1432. * Required items can be added multiple times to signify that multiple items must be found.
  1433. * Errors will contain the number of items that didn't match.
  1434. * Any unmatched item having a label will be mentioned explicitly.
  1435. *
  1436. * @param type - a joi schema object to validate each array item against.
  1437. */
  1438. items(...types: SchemaLikeWithoutArray[]): this;
  1439. /**
  1440. * Specifies the exact number of items in the array.
  1441. */
  1442. length(limit: number | Reference): this;
  1443. /**
  1444. * Specifies the maximum number of items in the array.
  1445. */
  1446. max(limit: number | Reference): this;
  1447. /**
  1448. * Specifies the minimum number of items in the array.
  1449. */
  1450. min(limit: number | Reference): this;
  1451. /**
  1452. * Lists the types in sequence order for the array values where:
  1453. * @param type - a joi schema object to validate against each array item in sequence order. type can be multiple values passed as individual arguments.
  1454. * If a given type is .required() then there must be a matching item with the same index position in the array.
  1455. * Errors will contain the number of items that didn't match.
  1456. * Any unmatched item having a label will be mentioned explicitly.
  1457. */
  1458. ordered(...types: SchemaLikeWithoutArray[]): this;
  1459. /**
  1460. * Allow single values to be checked against rules as if it were provided as an array.
  1461. * enabled can be used with a falsy value to go back to the default behavior.
  1462. */
  1463. single(enabled?: any): this;
  1464. /**
  1465. * Sorts the array by given order.
  1466. */
  1467. sort(options?: ArraySortOptions): this;
  1468. /**
  1469. * Allow this array to be sparse.
  1470. * enabled can be used with a falsy value to go back to the default behavior.
  1471. */
  1472. sparse(enabled?: any): this;
  1473. /**
  1474. * Requires the array values to be unique.
  1475. * Remember that if you provide a custom comparator function,
  1476. * different types can be passed as parameter depending on the rules you set on items.
  1477. * Be aware that a deep equality is performed on elements of the array having a type of object,
  1478. * a performance penalty is to be expected for this kind of operation.
  1479. */
  1480. unique(comparator?: string | ComparatorFunction, options?: ArrayUniqueOptions): this;
  1481. }
  1482. interface ObjectPatternOptions {
  1483. fallthrough?: boolean;
  1484. matches: SchemaLike | Reference;
  1485. }
  1486. interface ObjectSchema<TSchema = any> extends AnySchema<TSchema> {
  1487. /**
  1488. * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well.
  1489. *
  1490. * Optional settings must be the last argument.
  1491. */
  1492. and(...peers: Array<string | DependencyOptions>): this;
  1493. /**
  1494. * Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied.
  1495. */
  1496. append(schema?: SchemaMap<TSchema>): this;
  1497. append<TSchemaExtended = any, T = TSchemaExtended>(schema?: SchemaMap<T>): ObjectSchema<T>
  1498. /**
  1499. * Verifies an assertion where.
  1500. */
  1501. assert(ref: string | Reference, schema: SchemaLike, message?: string): this;
  1502. /**
  1503. * Requires the object to be an instance of a given constructor.
  1504. *
  1505. * @param constructor - the constructor function that the object must be an instance of.
  1506. * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name.
  1507. */
  1508. // tslint:disable-next-line:ban-types
  1509. instance(constructor: Function, name?: string): this;
  1510. /**
  1511. * Sets or extends the allowed object keys.
  1512. */
  1513. keys(schema?: SchemaMap<TSchema>): this;
  1514. /**
  1515. * Specifies the exact number of keys in the object.
  1516. */
  1517. length(limit: number): this;
  1518. /**
  1519. * Specifies the maximum number of keys in the object.
  1520. */
  1521. max(limit: number | Reference): this;
  1522. /**
  1523. * Specifies the minimum number of keys in the object.
  1524. */
  1525. min(limit: number | Reference): this;
  1526. /**
  1527. * Defines a relationship between keys where not all peers can be present at the same time.
  1528. *
  1529. * Optional settings must be the last argument.
  1530. */
  1531. nand(...peers: Array<string | DependencyOptions>): this;
  1532. /**
  1533. * Defines a relationship between keys where one of the peers is required (and more than one is allowed).
  1534. *
  1535. * Optional settings must be the last argument.
  1536. */
  1537. or(...peers: Array<string | DependencyOptions>): this;
  1538. /**
  1539. * Defines an exclusive relationship between a set of keys where only one is allowed but none are required.
  1540. *
  1541. * Optional settings must be the last argument.
  1542. */
  1543. oxor(...peers: Array<string | DependencyOptions>): this;
  1544. /**
  1545. * Specify validation rules for unknown keys matching a pattern.
  1546. *
  1547. * @param pattern - a pattern that can be either a regular expression or a joi schema that will be tested against the unknown key names
  1548. * @param schema - the schema object matching keys must validate against
  1549. */
  1550. pattern(pattern: RegExp | SchemaLike, schema: SchemaLike, options?: ObjectPatternOptions): this;
  1551. /**
  1552. * Requires the object to be a Joi reference.
  1553. */
  1554. ref(): this;
  1555. /**
  1556. * Requires the object to be a `RegExp` object.
  1557. */
  1558. regex(): this;
  1559. /**
  1560. * Renames a key to another name (deletes the renamed key).
  1561. */
  1562. rename(from: string | RegExp, to: string, options?: RenameOptions): this;
  1563. /**
  1564. * Requires the object to be a Joi schema instance.
  1565. */
  1566. schema(type?: SchemaLike): this;
  1567. /**
  1568. * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children).
  1569. */
  1570. unknown(allow?: boolean): this;
  1571. /**
  1572. * Requires the presence of other keys whenever the specified key is present.
  1573. */
  1574. with(key: string, peers: string | string[], options?: DependencyOptions): this;
  1575. /**
  1576. * Forbids the presence of other keys whenever the specified is present.
  1577. */
  1578. without(key: string, peers: string | string[], options?: DependencyOptions): this;
  1579. /**
  1580. * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time.
  1581. *
  1582. * Optional settings must be the last argument.
  1583. */
  1584. xor(...peers: Array<string | DependencyOptions>): this;
  1585. }
  1586. interface BinarySchema<TSchema = Buffer> extends AnySchema<TSchema> {
  1587. /**
  1588. * Sets the string encoding format if a string input is converted to a buffer.
  1589. */
  1590. encoding(encoding: string): this;
  1591. /**
  1592. * Specifies the minimum length of the buffer.
  1593. */
  1594. min(limit: number | Reference): this;
  1595. /**
  1596. * Specifies the maximum length of the buffer.
  1597. */
  1598. max(limit: number | Reference): this;
  1599. /**
  1600. * Specifies the exact length of the buffer:
  1601. */
  1602. length(limit: number | Reference): this;
  1603. }
  1604. interface DateSchema<TSchema = Date> extends AnySchema<TSchema> {
  1605. /**
  1606. * Specifies that the value must be greater than date.
  1607. * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
  1608. * allowing to explicitly ensure a date is either in the past or in the future.
  1609. * It can also be a reference to another field.
  1610. */
  1611. greater(date: 'now' | Date | number | string | Reference): this;
  1612. /**
  1613. * Requires the string value to be in valid ISO 8601 date format.
  1614. */
  1615. iso(): this;
  1616. /**
  1617. * Specifies that the value must be less than date.
  1618. * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
  1619. * allowing to explicitly ensure a date is either in the past or in the future.
  1620. * It can also be a reference to another field.
  1621. */
  1622. less(date: 'now' | Date | number | string | Reference): this;
  1623. /**
  1624. * Specifies the oldest date allowed.
  1625. * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
  1626. * allowing to explicitly ensure a date is either in the past or in the future.
  1627. * It can also be a reference to another field.
  1628. */
  1629. min(date: 'now' | Date | number | string | Reference): this;
  1630. /**
  1631. * Specifies the latest date allowed.
  1632. * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
  1633. * allowing to explicitly ensure a date is either in the past or in the future.
  1634. * It can also be a reference to another field.
  1635. */
  1636. max(date: 'now' | Date | number | string | Reference): this;
  1637. /**
  1638. * Requires the value to be a timestamp interval from Unix Time.
  1639. * @param type - the type of timestamp (allowed values are unix or javascript [default])
  1640. */
  1641. timestamp(type?: 'javascript' | 'unix'): this;
  1642. }
  1643. interface FunctionSchema<TSchema = Function> extends ObjectSchema<TSchema> {
  1644. /**
  1645. * Specifies the arity of the function where:
  1646. * @param n - the arity expected.
  1647. */
  1648. arity(n: number): this;
  1649. /**
  1650. * Requires the function to be a class.
  1651. */
  1652. class(): this;
  1653. /**
  1654. * Specifies the minimal arity of the function where:
  1655. * @param n - the minimal arity expected.
  1656. */
  1657. minArity(n: number): this;
  1658. /**
  1659. * Specifies the minimal arity of the function where:
  1660. * @param n - the minimal arity expected.
  1661. */
  1662. maxArity(n: number): this;
  1663. }
  1664. interface AlternativesSchema<TSchema = any> extends AnySchema<TSchema> {
  1665. /**
  1666. * Adds a conditional alternative schema type, either based on another key value, or a schema peeking into the current value.
  1667. */
  1668. conditional(ref: string | Reference, options: WhenOptions | WhenOptions[]): this;
  1669. conditional(ref: Schema, options: WhenSchemaOptions): this;
  1670. /**
  1671. * Requires the validated value to match a specific set of the provided alternative.try() schemas.
  1672. * Cannot be combined with `alternatives.conditional()`.
  1673. */
  1674. match(mode: 'any' | 'all' | 'one'): this;
  1675. /**
  1676. * Adds an alternative schema type for attempting to match against the validated value.
  1677. */
  1678. try(...types: SchemaLikeWithoutArray[]): this;
  1679. }
  1680. interface LinkSchema<TSchema = any> extends AnySchema<TSchema> {
  1681. /**
  1682. * Same as `any.concat()` but the schema is merged after the link is resolved which allows merging with schemas of the same type as the resolved link.
  1683. * Will throw an exception during validation if the merged types are not compatible.
  1684. */
  1685. concat(schema: Schema): this;
  1686. /**
  1687. * Initializes the schema after constructions for cases where the schema has to be constructed first and then initialized.
  1688. * If `ref` was not passed to the constructor, `link.ref()` must be called prior to usage.
  1689. */
  1690. ref(ref: string): this;
  1691. }
  1692. interface Reference extends Exclude<ReferenceOptions, 'prefix'> {
  1693. depth: number;
  1694. type: string;
  1695. key: string;
  1696. root: string;
  1697. path: string[];
  1698. display: string;
  1699. toString(): string;
  1700. }
  1701. type ExtensionBoundSchema = Schema & SchemaInternals;
  1702. interface RuleArgs {
  1703. name: string;
  1704. ref?: boolean;
  1705. assert?: ((value: any) => boolean) | AnySchema;
  1706. message?: string;
  1707. /**
  1708. * Undocumented properties
  1709. */
  1710. normalize?(value: any): any;
  1711. }
  1712. type RuleMethod = (...args: any[]) => any;
  1713. interface ExtensionRule {
  1714. /**
  1715. * alternative name for this rule.
  1716. */
  1717. alias?: string;
  1718. /**
  1719. * whether rule supports multiple invocations.
  1720. */
  1721. multi?: boolean;
  1722. /**
  1723. * Dual rule: converts or validates.
  1724. */
  1725. convert?: boolean;
  1726. /**
  1727. * list of arguments accepted by `method`.
  1728. */
  1729. args?: Array<RuleArgs | string>;
  1730. /**
  1731. * rule body.
  1732. */
  1733. method?: RuleMethod | false;
  1734. /**
  1735. * validation function.
  1736. */
  1737. validate?(value: any, helpers: any, args: Record<string, any>, options: any): any;
  1738. /**
  1739. * undocumented flags.
  1740. */
  1741. priority?: boolean;
  1742. manifest?: boolean;
  1743. }
  1744. interface CoerceResult {
  1745. errors?: ErrorReport[];
  1746. value?: any;
  1747. }
  1748. type CoerceFunction = (value: any, helpers: CustomHelpers) => CoerceResult;
  1749. interface CoerceObject {
  1750. method: CoerceFunction;
  1751. from?: string | string[];
  1752. }
  1753. interface ExtensionFlag {
  1754. setter?: string;
  1755. default?: any;
  1756. }
  1757. interface ExtensionTermManifest {
  1758. mapped: {
  1759. from: string;
  1760. to: string;
  1761. };
  1762. }
  1763. interface ExtensionTerm {
  1764. init: any[] | null;
  1765. register?: any;
  1766. manifest?: Record<string, 'schema' | 'single' | ExtensionTermManifest>;
  1767. }
  1768. interface Extension {
  1769. type: string | RegExp;
  1770. args?(...args: SchemaLike[]): Schema;
  1771. base?: Schema;
  1772. coerce?: CoerceFunction | CoerceObject;
  1773. flags?: Record<string, ExtensionFlag>;
  1774. manifest?: {
  1775. build?(obj: ExtensionBoundSchema, desc: Record<string, any>): any;
  1776. };
  1777. messages?: LanguageMessages | string;
  1778. modifiers?: Record<string, (rule: any, enabled?: boolean) => any>;
  1779. overrides?: Record<string, (value: any) => Schema>;
  1780. prepare?(value: any, helpers: CustomHelpers): any;
  1781. rebuild?(schema: ExtensionBoundSchema): void;
  1782. rules?: Record<string, ExtensionRule & ThisType<SchemaInternals>>;
  1783. terms?: Record<string, ExtensionTerm>;
  1784. validate?(value: any, helpers: CustomHelpers): any;
  1785. /**
  1786. * undocumented options
  1787. */
  1788. cast?: Record<string, { from(value: any): any; to(value: any, helpers: CustomHelpers): any }>;
  1789. properties?: Record<string, any>;
  1790. }
  1791. type ExtensionFactory = (joi: Root) => Extension;
  1792. interface Err {
  1793. toString(): string;
  1794. }
  1795. // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
  1796. interface Root {
  1797. /**
  1798. * Current version of the joi package.
  1799. */
  1800. version: string;
  1801. ValidationError: new (message: string, details: ValidationErrorItem[], original: any) => ValidationError;
  1802. /**
  1803. * Generates a schema object that matches any data type.
  1804. */
  1805. any<TSchema = any>(): AnySchema<TSchema>;
  1806. /**
  1807. * Generates a schema object that matches an array data type.
  1808. */
  1809. array<TSchema = any[]>(): ArraySchema<TSchema>;
  1810. /**
  1811. * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via boolean().
  1812. */
  1813. bool<TSchema = boolean>(): BooleanSchema<TSchema>;
  1814. /**
  1815. * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool().
  1816. */
  1817. boolean<TSchema = boolean>(): BooleanSchema<TSchema>;
  1818. /**
  1819. * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers).
  1820. */
  1821. binary<TSchema = Buffer>(): BinarySchema<TSchema>;
  1822. /**
  1823. * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds).
  1824. */
  1825. date<TSchema = Date>(): DateSchema<TSchema>;
  1826. /**
  1827. * Generates a schema object that matches a function type.
  1828. */
  1829. func<TSchema = Function>(): FunctionSchema<TSchema>;
  1830. /**
  1831. * Generates a schema object that matches a function type.
  1832. */
  1833. function<TSchema = Function>(): FunctionSchema<TSchema>;
  1834. /**
  1835. * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers).
  1836. */
  1837. number<TSchema = number>(): NumberSchema<TSchema>;
  1838. /**
  1839. * Generates a schema object that matches an object data type (as well as JSON strings that have been parsed into objects).
  1840. */
  1841. // tslint:disable-next-line:no-unnecessary-generics
  1842. object<TSchema = any, isStrict = false, T = TSchema>(schema?: SchemaMap<T, isStrict>): ObjectSchema<TSchema>;
  1843. /**
  1844. * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow('').
  1845. */
  1846. string<TSchema = string>(): StringSchema<TSchema>;
  1847. /**
  1848. * Generates a schema object that matches any symbol.
  1849. */
  1850. symbol<TSchema = Symbol>(): SymbolSchema<TSchema>;
  1851. /**
  1852. * Generates a type that will match one of the provided alternative schemas
  1853. */
  1854. alternatives<TSchema = any>(types: SchemaLike[]): AlternativesSchema<TSchema>;
  1855. alternatives<TSchema = any>(...types: SchemaLike[]): AlternativesSchema<TSchema>;
  1856. /**
  1857. * Alias for `alternatives`
  1858. */
  1859. alt<TSchema = any>(types: SchemaLike[]): AlternativesSchema<TSchema>;
  1860. alt<TSchema = any>(...types: SchemaLike[]): AlternativesSchema<TSchema>;
  1861. /**
  1862. * Links to another schema node and reuses it for validation, typically for creative recursive schemas.
  1863. *
  1864. * @param ref - the reference to the linked schema node.
  1865. * Cannot reference itself or its children as well as other links.
  1866. * Links can be expressed in relative terms like value references (`Joi.link('...')`),
  1867. * in absolute terms from the schema run-time root (`Joi.link('/a')`),
  1868. * or using schema ids implicitly using object keys or explicitly using `any.id()` (`Joi.link('#a.b.c')`).
  1869. */
  1870. link<TSchema = any>(ref?: string): LinkSchema<TSchema>;
  1871. /**
  1872. * Validates a value against a schema and throws if validation fails.
  1873. *
  1874. * @param value - the value to validate.
  1875. * @param schema - the schema object.
  1876. * @param message - optional message string prefix added in front of the error message. may also be an Error object.
  1877. */
  1878. assert(value: any, schema: Schema, options?: ValidationOptions): void;
  1879. assert(value: any, schema: Schema, message: string | Error, options?: ValidationOptions): void;
  1880. /**
  1881. * Validates a value against a schema, returns valid object, and throws if validation fails.
  1882. *
  1883. * @param value - the value to validate.
  1884. * @param schema - the schema object.
  1885. * @param message - optional message string prefix added in front of the error message. may also be an Error object.
  1886. */
  1887. attempt<TSchema extends Schema>(value: any, schema: TSchema, options?: ValidationOptions): TSchema extends Schema<infer Value> ? Value : never;
  1888. attempt<TSchema extends Schema>(value: any, schema: TSchema, message: string | Error, options?: ValidationOptions): TSchema extends Schema<infer Value> ? Value : never;
  1889. cache: CacheConfiguration;
  1890. /**
  1891. * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object).
  1892. */
  1893. compile(schema: SchemaLike, options?: CompileOptions): Schema;
  1894. /**
  1895. * Checks if the provided preferences are valid.
  1896. *
  1897. * Throws an exception if the prefs object is invalid.
  1898. *
  1899. * The method is provided to perform inputs validation for the `any.validate()` and `any.validateAsync()` methods.
  1900. * Validation is not performed automatically for performance reasons. Instead, manually validate the preferences passed once and reuse.
  1901. */
  1902. checkPreferences(prefs: ValidationOptions): void;
  1903. /**
  1904. * Creates a custom validation schema.
  1905. */
  1906. custom(fn: CustomValidator, description?: string): Schema;
  1907. /**
  1908. * Creates a new Joi instance that will apply defaults onto newly created schemas
  1909. * through the use of the fn function that takes exactly one argument, the schema being created.
  1910. *
  1911. * @param fn - The function must always return a schema, even if untransformed.
  1912. */
  1913. defaults(fn: SchemaFunction): Root;
  1914. /**
  1915. * Generates a dynamic expression using a template string.
  1916. */
  1917. expression(template: string, options?: ReferenceOptions): any;
  1918. /**
  1919. * Creates a new Joi instance customized with the extension(s) you provide included.
  1920. */
  1921. extend(...extensions: Array<Extension | ExtensionFactory>): any;
  1922. /**
  1923. * Creates a reference that when resolved, is used as an array of values to match against the rule.
  1924. */
  1925. in(ref: string, options?: ReferenceOptions): Reference;
  1926. /**
  1927. * Checks whether or not the provided argument is an instance of ValidationError
  1928. */
  1929. isError(error: any): error is ValidationError;
  1930. /**
  1931. * Checks whether or not the provided argument is an expression.
  1932. */
  1933. isExpression(expression: any): boolean;
  1934. /**
  1935. * Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages.
  1936. */
  1937. isRef(ref: any): ref is Reference;
  1938. /**
  1939. * Checks whether or not the provided argument is a joi schema.
  1940. */
  1941. isSchema(schema: any, options?: CompileOptions): schema is AnySchema;
  1942. /**
  1943. * A special value used with `any.allow()`, `any.invalid()`, and `any.valid()` as the first value to reset any previously set values.
  1944. */
  1945. override: symbol;
  1946. /**
  1947. * Generates a reference to the value of the named key.
  1948. */
  1949. ref(key: string, options?: ReferenceOptions): Reference;
  1950. /**
  1951. * Returns an object where each key is a plain joi schema type.
  1952. * Useful for creating type shortcuts using deconstruction.
  1953. * Note that the types are already formed and do not need to be called as functions (e.g. `string`, not `string()`).
  1954. */
  1955. types(): {
  1956. alternatives: AlternativesSchema;
  1957. any: AnySchema;
  1958. array: ArraySchema;
  1959. binary: BinarySchema;
  1960. boolean: BooleanSchema;
  1961. date: DateSchema;
  1962. function: FunctionSchema;
  1963. link: LinkSchema;
  1964. number: NumberSchema;
  1965. object: ObjectSchema;
  1966. string: StringSchema;
  1967. symbol: SymbolSchema;
  1968. };
  1969. /**
  1970. * Generates a dynamic expression using a template string.
  1971. */
  1972. x(template: string, options?: ReferenceOptions): any;
  1973. // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
  1974. // Below are undocumented APIs. use at your own risk
  1975. // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
  1976. /**
  1977. * Whitelists a value
  1978. */
  1979. allow(...values: any[]): Schema;
  1980. /**
  1981. * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
  1982. */
  1983. valid(...values: any[]): Schema;
  1984. equal(...values: any[]): Schema;
  1985. /**
  1986. * Blacklists a value
  1987. */
  1988. invalid(...values: any[]): Schema;
  1989. disallow(...values: any[]): Schema;
  1990. not(...values: any[]): Schema;
  1991. /**
  1992. * Marks a key as required which will not allow undefined as value. All keys are optional by default.
  1993. */
  1994. required(): Schema;
  1995. /**
  1996. * Alias of `required`.
  1997. */
  1998. exist(): Schema;
  1999. /**
  2000. * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.
  2001. */
  2002. optional(): Schema;
  2003. /**
  2004. * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
  2005. */
  2006. forbidden(): Schema;
  2007. /**
  2008. * Overrides the global validate() options for the current key and any sub-key.
  2009. */
  2010. preferences(options: ValidationOptions): Schema;
  2011. /**
  2012. * Overrides the global validate() options for the current key and any sub-key.
  2013. */
  2014. prefs(options: ValidationOptions): Schema;
  2015. /**
  2016. * Converts the type into an alternatives type where the conditions are merged into the type definition where:
  2017. */
  2018. when(ref: string | Reference, options: WhenOptions | WhenOptions[]): AlternativesSchema;
  2019. when(ref: Schema, options: WhenSchemaOptions): AlternativesSchema;
  2020. /**
  2021. * Unsure, maybe alias for `compile`?
  2022. */
  2023. build(...args: any[]): any;
  2024. /**
  2025. * Unsure, maybe alias for `preferences`?
  2026. */
  2027. options(...args: any[]): any;
  2028. /**
  2029. * Unsure, maybe leaked from `@hapi/lab/coverage/initialize`
  2030. */
  2031. trace(...args: any[]): any;
  2032. untrace(...args: any[]): any;
  2033. }
  2034. }
  2035. declare const Joi: Joi.Root;
  2036. export = Joi;