index.d.ts 80 KB

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