@palmares/schemas 0.1.25 → 0.1.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/src/adapter/fields/array.cjs +96 -0
  3. package/dist/src/adapter/fields/array.d.ts.map +1 -0
  4. package/dist/src/adapter/fields/array.js +70 -0
  5. package/dist/src/adapter/fields/boolean.cjs +102 -0
  6. package/dist/src/adapter/fields/boolean.d.ts.map +1 -0
  7. package/dist/src/adapter/fields/boolean.js +76 -0
  8. package/dist/src/adapter/fields/datetime.cjs +102 -0
  9. package/dist/src/adapter/fields/datetime.d.ts.map +1 -0
  10. package/dist/src/adapter/fields/datetime.js +76 -0
  11. package/dist/src/adapter/fields/index.cjs +87 -0
  12. package/dist/src/adapter/fields/index.d.ts.map +1 -0
  13. package/dist/src/adapter/fields/index.js +61 -0
  14. package/dist/src/adapter/fields/number.cjs +102 -0
  15. package/dist/src/adapter/fields/number.d.ts.map +1 -0
  16. package/dist/src/adapter/fields/number.js +76 -0
  17. package/dist/src/adapter/fields/object.cjs +108 -0
  18. package/dist/src/adapter/fields/object.d.ts.map +1 -0
  19. package/dist/src/adapter/fields/object.js +82 -0
  20. package/dist/src/adapter/fields/string.cjs +102 -0
  21. package/dist/src/adapter/fields/string.d.ts.map +1 -0
  22. package/dist/src/adapter/fields/string.js +76 -0
  23. package/dist/src/adapter/fields/union.cjs +102 -0
  24. package/dist/src/adapter/fields/union.d.ts.map +1 -0
  25. package/dist/src/adapter/fields/union.js +76 -0
  26. package/dist/src/adapter/index.cjs +65 -0
  27. package/dist/src/adapter/index.d.ts.map +1 -0
  28. package/dist/src/adapter/index.js +40 -0
  29. package/dist/src/adapter/types.cjs +18 -0
  30. package/dist/src/adapter/types.d.ts.map +1 -0
  31. package/dist/src/adapter/types.js +0 -0
  32. package/dist/src/compile.cjs +59 -0
  33. package/dist/src/compile.d.ts.map +1 -0
  34. package/dist/src/compile.js +36 -0
  35. package/dist/src/conf.cjs +53 -0
  36. package/dist/src/conf.d.ts.map +1 -0
  37. package/dist/src/conf.js +27 -0
  38. package/dist/src/constants.cjs +40 -0
  39. package/dist/src/constants.d.ts.map +1 -0
  40. package/dist/src/constants.js +14 -0
  41. package/dist/src/domain.cjs +63 -0
  42. package/dist/src/domain.d.ts.map +1 -0
  43. package/dist/src/domain.js +40 -0
  44. package/dist/src/exceptions.cjs +58 -0
  45. package/dist/src/exceptions.d.ts.map +1 -0
  46. package/dist/src/exceptions.js +33 -0
  47. package/dist/src/index.cjs +6520 -0
  48. package/dist/src/index.d.ts.map +1 -0
  49. package/dist/src/index.js +6456 -0
  50. package/dist/src/middleware.cjs +58 -0
  51. package/dist/src/middleware.d.ts.map +1 -0
  52. package/dist/src/middleware.js +35 -0
  53. package/dist/src/model.cjs +6003 -0
  54. package/dist/src/model.d.ts.map +1 -0
  55. package/dist/src/model.js +5978 -0
  56. package/dist/src/parsers/convert-from-number.cjs +34 -0
  57. package/dist/src/parsers/convert-from-number.d.ts.map +1 -0
  58. package/dist/src/parsers/convert-from-number.js +11 -0
  59. package/dist/src/parsers/convert-from-string.cjs +40 -0
  60. package/dist/src/parsers/convert-from-string.d.ts.map +1 -0
  61. package/dist/src/parsers/convert-from-string.js +17 -0
  62. package/dist/src/parsers/index.cjs +50 -0
  63. package/dist/src/parsers/index.d.ts.map +1 -0
  64. package/dist/src/parsers/index.js +24 -0
  65. package/dist/src/schema/array.cjs +1863 -0
  66. package/dist/src/schema/array.d.ts.map +1 -0
  67. package/dist/src/schema/array.js +1837 -0
  68. package/dist/src/schema/boolean.cjs +1800 -0
  69. package/dist/src/schema/boolean.d.ts.map +1 -0
  70. package/dist/src/schema/boolean.js +1774 -0
  71. package/dist/src/schema/datetime.cjs +1789 -0
  72. package/dist/src/schema/datetime.d.ts.map +1 -0
  73. package/dist/src/schema/datetime.js +1763 -0
  74. package/dist/src/schema/index.cjs +2026 -0
  75. package/dist/src/schema/index.d.ts.map +1 -0
  76. package/dist/src/schema/index.js +2001 -0
  77. package/dist/src/schema/number.cjs +2026 -0
  78. package/dist/src/schema/number.d.ts.map +1 -0
  79. package/dist/src/schema/number.js +2000 -0
  80. package/dist/src/schema/object.cjs +1795 -0
  81. package/dist/src/schema/object.d.ts.map +1 -0
  82. package/dist/src/schema/object.js +1769 -0
  83. package/dist/src/schema/schema.cjs +844 -0
  84. package/dist/src/schema/schema.d.ts.map +1 -0
  85. package/dist/src/schema/schema.js +818 -0
  86. package/dist/src/schema/string.cjs +2126 -0
  87. package/dist/src/schema/string.d.ts.map +1 -0
  88. package/dist/src/schema/string.js +2100 -0
  89. package/dist/src/schema/types.cjs +18 -0
  90. package/dist/src/schema/types.d.ts.map +1 -0
  91. package/dist/src/schema/types.js +0 -0
  92. package/dist/src/schema/union.cjs +1737 -0
  93. package/dist/src/schema/union.d.ts.map +1 -0
  94. package/dist/src/schema/union.js +1711 -0
  95. package/dist/src/types.cjs +18 -0
  96. package/dist/src/types.d.ts.map +1 -0
  97. package/dist/src/types.js +0 -0
  98. package/dist/src/utils.cjs +477 -0
  99. package/dist/src/utils.d.ts.map +1 -0
  100. package/dist/src/utils.js +445 -0
  101. package/dist/src/validators/array.cjs +176 -0
  102. package/dist/src/validators/array.d.ts.map +1 -0
  103. package/dist/src/validators/array.js +150 -0
  104. package/dist/src/validators/boolean.cjs +71 -0
  105. package/dist/src/validators/boolean.d.ts.map +1 -0
  106. package/dist/src/validators/boolean.js +47 -0
  107. package/dist/src/validators/datetime.cjs +129 -0
  108. package/dist/src/validators/datetime.d.ts.map +1 -0
  109. package/dist/src/validators/datetime.js +103 -0
  110. package/dist/src/validators/number.cjs +194 -0
  111. package/dist/src/validators/number.d.ts.map +1 -0
  112. package/dist/src/validators/number.js +166 -0
  113. package/dist/src/validators/object.cjs +69 -0
  114. package/dist/src/validators/object.d.ts.map +1 -0
  115. package/dist/src/validators/object.js +46 -0
  116. package/dist/src/validators/schema.cjs +158 -0
  117. package/dist/src/validators/schema.d.ts.map +1 -0
  118. package/dist/src/validators/schema.js +132 -0
  119. package/dist/src/validators/string.cjs +255 -0
  120. package/dist/src/validators/string.d.ts.map +1 -0
  121. package/dist/src/validators/string.js +224 -0
  122. package/dist/src/validators/types.cjs +18 -0
  123. package/dist/src/validators/types.d.ts.map +1 -0
  124. package/dist/src/validators/types.js +0 -0
  125. package/dist/src/validators/union.cjs +69 -0
  126. package/dist/src/validators/union.d.ts.map +1 -0
  127. package/dist/src/validators/union.js +46 -0
  128. package/dist/src/validators/utils.cjs +165 -0
  129. package/dist/src/validators/utils.d.ts.map +1 -0
  130. package/dist/src/validators/utils.js +142 -0
  131. package/dist/tsconfig.types.tsbuildinfo +1 -0
  132. package/package.json +15 -23
  133. package/dist/cjs/src/adapter/fields/array.js +0 -152
  134. package/dist/cjs/src/adapter/fields/boolean.js +0 -162
  135. package/dist/cjs/src/adapter/fields/datetime.js +0 -162
  136. package/dist/cjs/src/adapter/fields/index.js +0 -311
  137. package/dist/cjs/src/adapter/fields/number.js +0 -162
  138. package/dist/cjs/src/adapter/fields/object.js +0 -171
  139. package/dist/cjs/src/adapter/fields/string.js +0 -162
  140. package/dist/cjs/src/adapter/fields/union.js +0 -162
  141. package/dist/cjs/src/adapter/index.js +0 -201
  142. package/dist/cjs/src/adapter/types.js +0 -4
  143. package/dist/cjs/src/compile.js +0 -262
  144. package/dist/cjs/src/conf.js +0 -26
  145. package/dist/cjs/src/constants.js +0 -36
  146. package/dist/cjs/src/domain.js +0 -156
  147. package/dist/cjs/src/exceptions.js +0 -168
  148. package/dist/cjs/src/index.js +0 -317
  149. package/dist/cjs/src/middleware.js +0 -213
  150. package/dist/cjs/src/model.js +0 -628
  151. package/dist/cjs/src/parsers/convert-from-number.js +0 -15
  152. package/dist/cjs/src/parsers/convert-from-string.js +0 -19
  153. package/dist/cjs/src/parsers/index.js +0 -20
  154. package/dist/cjs/src/schema/array.js +0 -1014
  155. package/dist/cjs/src/schema/boolean.js +0 -883
  156. package/dist/cjs/src/schema/datetime.js +0 -840
  157. package/dist/cjs/src/schema/index.js +0 -12
  158. package/dist/cjs/src/schema/number.js +0 -976
  159. package/dist/cjs/src/schema/object.js +0 -1052
  160. package/dist/cjs/src/schema/schema.js +0 -1840
  161. package/dist/cjs/src/schema/string.js +0 -1038
  162. package/dist/cjs/src/schema/types.js +0 -4
  163. package/dist/cjs/src/schema/union.js +0 -1070
  164. package/dist/cjs/src/types.js +0 -4
  165. package/dist/cjs/src/utils.js +0 -647
  166. package/dist/cjs/src/validators/array.js +0 -462
  167. package/dist/cjs/src/validators/boolean.js +0 -201
  168. package/dist/cjs/src/validators/datetime.js +0 -291
  169. package/dist/cjs/src/validators/number.js +0 -375
  170. package/dist/cjs/src/validators/object.js +0 -291
  171. package/dist/cjs/src/validators/schema.js +0 -322
  172. package/dist/cjs/src/validators/string.js +0 -467
  173. package/dist/cjs/src/validators/types.js +0 -4
  174. package/dist/cjs/src/validators/union.js +0 -233
  175. package/dist/cjs/src/validators/utils.js +0 -499
  176. package/dist/cjs/tsconfig.types.tsbuildinfo +0 -1
  177. package/dist/cjs/types/adapter/fields/array.d.ts.map +0 -1
  178. package/dist/cjs/types/adapter/fields/boolean.d.ts.map +0 -1
  179. package/dist/cjs/types/adapter/fields/datetime.d.ts.map +0 -1
  180. package/dist/cjs/types/adapter/fields/index.d.ts.map +0 -1
  181. package/dist/cjs/types/adapter/fields/number.d.ts.map +0 -1
  182. package/dist/cjs/types/adapter/fields/object.d.ts.map +0 -1
  183. package/dist/cjs/types/adapter/fields/string.d.ts.map +0 -1
  184. package/dist/cjs/types/adapter/fields/union.d.ts.map +0 -1
  185. package/dist/cjs/types/adapter/index.d.ts.map +0 -1
  186. package/dist/cjs/types/adapter/types.d.ts.map +0 -1
  187. package/dist/cjs/types/compile.d.ts.map +0 -1
  188. package/dist/cjs/types/conf.d.ts.map +0 -1
  189. package/dist/cjs/types/constants.d.ts.map +0 -1
  190. package/dist/cjs/types/domain.d.ts.map +0 -1
  191. package/dist/cjs/types/exceptions.d.ts.map +0 -1
  192. package/dist/cjs/types/index.d.ts.map +0 -1
  193. package/dist/cjs/types/middleware.d.ts.map +0 -1
  194. package/dist/cjs/types/model.d.ts.map +0 -1
  195. package/dist/cjs/types/parsers/convert-from-number.d.ts.map +0 -1
  196. package/dist/cjs/types/parsers/convert-from-string.d.ts.map +0 -1
  197. package/dist/cjs/types/parsers/index.d.ts.map +0 -1
  198. package/dist/cjs/types/schema/array.d.ts.map +0 -1
  199. package/dist/cjs/types/schema/boolean.d.ts.map +0 -1
  200. package/dist/cjs/types/schema/datetime.d.ts.map +0 -1
  201. package/dist/cjs/types/schema/index.d.ts.map +0 -1
  202. package/dist/cjs/types/schema/number.d.ts.map +0 -1
  203. package/dist/cjs/types/schema/object.d.ts.map +0 -1
  204. package/dist/cjs/types/schema/schema.d.ts.map +0 -1
  205. package/dist/cjs/types/schema/string.d.ts.map +0 -1
  206. package/dist/cjs/types/schema/types.d.ts.map +0 -1
  207. package/dist/cjs/types/schema/union.d.ts.map +0 -1
  208. package/dist/cjs/types/types.d.ts.map +0 -1
  209. package/dist/cjs/types/utils.d.ts.map +0 -1
  210. package/dist/cjs/types/validators/array.d.ts.map +0 -1
  211. package/dist/cjs/types/validators/boolean.d.ts.map +0 -1
  212. package/dist/cjs/types/validators/datetime.d.ts.map +0 -1
  213. package/dist/cjs/types/validators/number.d.ts.map +0 -1
  214. package/dist/cjs/types/validators/object.d.ts.map +0 -1
  215. package/dist/cjs/types/validators/schema.d.ts.map +0 -1
  216. package/dist/cjs/types/validators/string.d.ts.map +0 -1
  217. package/dist/cjs/types/validators/types.d.ts.map +0 -1
  218. package/dist/cjs/types/validators/union.d.ts.map +0 -1
  219. package/dist/cjs/types/validators/utils.d.ts.map +0 -1
  220. package/dist/esm/src/adapter/fields/array.js +0 -13
  221. package/dist/esm/src/adapter/fields/boolean.js +0 -20
  222. package/dist/esm/src/adapter/fields/datetime.js +0 -20
  223. package/dist/esm/src/adapter/fields/index.js +0 -37
  224. package/dist/esm/src/adapter/fields/number.js +0 -20
  225. package/dist/esm/src/adapter/fields/object.js +0 -26
  226. package/dist/esm/src/adapter/fields/string.js +0 -20
  227. package/dist/esm/src/adapter/fields/union.js +0 -20
  228. package/dist/esm/src/adapter/index.js +0 -21
  229. package/dist/esm/src/adapter/types.js +0 -1
  230. package/dist/esm/src/compile.js +0 -10
  231. package/dist/esm/src/conf.js +0 -18
  232. package/dist/esm/src/constants.js +0 -4
  233. package/dist/esm/src/domain.js +0 -11
  234. package/dist/esm/src/exceptions.js +0 -15
  235. package/dist/esm/src/index.js +0 -126
  236. package/dist/esm/src/middleware.js +0 -29
  237. package/dist/esm/src/model.js +0 -264
  238. package/dist/esm/src/parsers/convert-from-number.js +0 -8
  239. package/dist/esm/src/parsers/convert-from-string.js +0 -14
  240. package/dist/esm/src/parsers/index.js +0 -2
  241. package/dist/esm/src/schema/array.js +0 -487
  242. package/dist/esm/src/schema/boolean.js +0 -520
  243. package/dist/esm/src/schema/datetime.js +0 -477
  244. package/dist/esm/src/schema/index.js +0 -3
  245. package/dist/esm/src/schema/number.js +0 -610
  246. package/dist/esm/src/schema/object.js +0 -521
  247. package/dist/esm/src/schema/schema.js +0 -767
  248. package/dist/esm/src/schema/string.js +0 -668
  249. package/dist/esm/src/schema/types.js +0 -1
  250. package/dist/esm/src/schema/union.js +0 -468
  251. package/dist/esm/src/types.js +0 -14
  252. package/dist/esm/src/utils.js +0 -207
  253. package/dist/esm/src/validators/array.js +0 -140
  254. package/dist/esm/src/validators/boolean.js +0 -37
  255. package/dist/esm/src/validators/datetime.js +0 -89
  256. package/dist/esm/src/validators/number.js +0 -148
  257. package/dist/esm/src/validators/object.js +0 -39
  258. package/dist/esm/src/validators/schema.js +0 -118
  259. package/dist/esm/src/validators/string.js +0 -202
  260. package/dist/esm/src/validators/types.js +0 -1
  261. package/dist/esm/src/validators/union.js +0 -39
  262. package/dist/esm/src/validators/utils.js +0 -147
  263. /package/dist/{cjs/types → src}/adapter/fields/array.d.ts +0 -0
  264. /package/dist/{cjs/types → src}/adapter/fields/boolean.d.ts +0 -0
  265. /package/dist/{cjs/types → src}/adapter/fields/datetime.d.ts +0 -0
  266. /package/dist/{cjs/types → src}/adapter/fields/index.d.ts +0 -0
  267. /package/dist/{cjs/types → src}/adapter/fields/number.d.ts +0 -0
  268. /package/dist/{cjs/types → src}/adapter/fields/object.d.ts +0 -0
  269. /package/dist/{cjs/types → src}/adapter/fields/string.d.ts +0 -0
  270. /package/dist/{cjs/types → src}/adapter/fields/union.d.ts +0 -0
  271. /package/dist/{cjs/types → src}/adapter/index.d.ts +0 -0
  272. /package/dist/{cjs/types → src}/adapter/types.d.ts +0 -0
  273. /package/dist/{cjs/types → src}/compile.d.ts +0 -0
  274. /package/dist/{cjs/types → src}/conf.d.ts +0 -0
  275. /package/dist/{cjs/types → src}/constants.d.ts +0 -0
  276. /package/dist/{cjs/types → src}/domain.d.ts +0 -0
  277. /package/dist/{cjs/types → src}/exceptions.d.ts +0 -0
  278. /package/dist/{cjs/types → src}/index.d.ts +0 -0
  279. /package/dist/{cjs/types → src}/middleware.d.ts +0 -0
  280. /package/dist/{cjs/types → src}/model.d.ts +0 -0
  281. /package/dist/{cjs/types → src}/parsers/convert-from-number.d.ts +0 -0
  282. /package/dist/{cjs/types → src}/parsers/convert-from-string.d.ts +0 -0
  283. /package/dist/{cjs/types → src}/parsers/index.d.ts +0 -0
  284. /package/dist/{cjs/types → src}/schema/array.d.ts +0 -0
  285. /package/dist/{cjs/types → src}/schema/boolean.d.ts +0 -0
  286. /package/dist/{cjs/types → src}/schema/datetime.d.ts +0 -0
  287. /package/dist/{cjs/types → src}/schema/index.d.ts +0 -0
  288. /package/dist/{cjs/types → src}/schema/number.d.ts +0 -0
  289. /package/dist/{cjs/types → src}/schema/object.d.ts +0 -0
  290. /package/dist/{cjs/types → src}/schema/schema.d.ts +0 -0
  291. /package/dist/{cjs/types → src}/schema/string.d.ts +0 -0
  292. /package/dist/{cjs/types → src}/schema/types.d.ts +0 -0
  293. /package/dist/{cjs/types → src}/schema/union.d.ts +0 -0
  294. /package/dist/{cjs/types → src}/types.d.ts +0 -0
  295. /package/dist/{cjs/types → src}/utils.d.ts +0 -0
  296. /package/dist/{cjs/types → src}/validators/array.d.ts +0 -0
  297. /package/dist/{cjs/types → src}/validators/boolean.d.ts +0 -0
  298. /package/dist/{cjs/types → src}/validators/datetime.d.ts +0 -0
  299. /package/dist/{cjs/types → src}/validators/number.d.ts +0 -0
  300. /package/dist/{cjs/types → src}/validators/object.d.ts +0 -0
  301. /package/dist/{cjs/types → src}/validators/schema.d.ts +0 -0
  302. /package/dist/{cjs/types → src}/validators/string.d.ts +0 -0
  303. /package/dist/{cjs/types → src}/validators/types.d.ts +0 -0
  304. /package/dist/{cjs/types → src}/validators/union.d.ts +0 -0
  305. /package/dist/{cjs/types → src}/validators/utils.d.ts +0 -0
@@ -0,0 +1,2026 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/schema/index.ts
22
+ var schema_exports = {};
23
+ __export(schema_exports, {
24
+ number: () => number
25
+ });
26
+ module.exports = __toCommonJS(schema_exports);
27
+
28
+ // src/exceptions.ts
29
+ var NoAdapterFoundError = class extends Error {
30
+ static {
31
+ __name(this, "NoAdapterFoundError");
32
+ }
33
+ constructor() {
34
+ super("No adapter found, please define an adapter using setDefaultAdapter() before using any schema.");
35
+ }
36
+ };
37
+
38
+ // src/conf.ts
39
+ function getDefaultAdapter() {
40
+ if (!globalThis.$PSchemasAdapter) throw new NoAdapterFoundError();
41
+ return globalThis.$PSchemasAdapter;
42
+ }
43
+ __name(getDefaultAdapter, "getDefaultAdapter");
44
+
45
+ // src/validators/schema.ts
46
+ function optional(args) {
47
+ return {
48
+ name: "optional",
49
+ type: "high",
50
+ // eslint-disable-next-line ts/require-await
51
+ callback: /* @__PURE__ */ __name(async (value, path) => {
52
+ if (value === void 0) {
53
+ if (args.allow === true) return {
54
+ parsed: value,
55
+ errors: [],
56
+ preventChildValidation: true
57
+ };
58
+ return {
59
+ parsed: value,
60
+ errors: [
61
+ {
62
+ isValid: false,
63
+ message: args.message,
64
+ code: "required",
65
+ // eslint-disable-next-line ts/no-unnecessary-condition
66
+ path: path || []
67
+ }
68
+ ],
69
+ preventChildValidation: true
70
+ };
71
+ }
72
+ return {
73
+ parsed: value,
74
+ errors: [],
75
+ preventChildValidation: false
76
+ };
77
+ }, "callback")
78
+ };
79
+ }
80
+ __name(optional, "optional");
81
+ function nullable(args) {
82
+ return {
83
+ name: "nullable",
84
+ type: "high",
85
+ // eslint-disable-next-line ts/require-await
86
+ callback: /* @__PURE__ */ __name(async (value, path) => {
87
+ if (value === null) {
88
+ if (args.allow === true) return {
89
+ parsed: value,
90
+ errors: [],
91
+ preventChildValidation: true
92
+ };
93
+ return {
94
+ parsed: value,
95
+ errors: [
96
+ {
97
+ isValid: false,
98
+ message: args.message,
99
+ code: "null",
100
+ // eslint-disable-next-line ts/no-unnecessary-condition
101
+ path: path || []
102
+ }
103
+ ],
104
+ preventChildValidation: true
105
+ };
106
+ }
107
+ return {
108
+ parsed: value,
109
+ errors: [],
110
+ preventChildValidation: false
111
+ };
112
+ }, "callback")
113
+ };
114
+ }
115
+ __name(nullable, "nullable");
116
+ function checkType(args) {
117
+ return {
118
+ name: "checkType",
119
+ type: "medium",
120
+ // eslint-disable-next-line ts/require-await
121
+ callback: /* @__PURE__ */ __name(async (value, path) => {
122
+ if (args.check(value)) return {
123
+ parsed: value,
124
+ errors: [],
125
+ preventChildValidation: false
126
+ };
127
+ return {
128
+ parsed: value,
129
+ errors: [
130
+ {
131
+ isValid: false,
132
+ message: args.message,
133
+ code: "invalid_type",
134
+ // eslint-disable-next-line ts/no-unnecessary-condition
135
+ path: path || []
136
+ }
137
+ ],
138
+ preventChildValidation: true
139
+ };
140
+ }, "callback")
141
+ };
142
+ }
143
+ __name(checkType, "checkType");
144
+ function is(args) {
145
+ return {
146
+ name: "is",
147
+ type: "medium",
148
+ // eslint-disable-next-line ts/require-await
149
+ callback: /* @__PURE__ */ __name(async (value, path, _options) => {
150
+ const isValid = Array.isArray(args.value) ? args.value.includes(value) : value === args.value;
151
+ return {
152
+ parsed: value,
153
+ errors: isValid ? [] : [
154
+ {
155
+ isValid: false,
156
+ code: "is",
157
+ // eslint-disable-next-line ts/no-unnecessary-condition
158
+ path: path || [],
159
+ message: "Value is not a boolean"
160
+ }
161
+ ],
162
+ preventChildValidation: true
163
+ };
164
+ }, "callback")
165
+ };
166
+ }
167
+ __name(is, "is");
168
+
169
+ // src/validators/utils.ts
170
+ var priorityByType = {
171
+ low: 0,
172
+ medium: 1,
173
+ high: 2
174
+ };
175
+ var typeByPriority = Object.entries(priorityByType).reduce((acc, [key, value]) => {
176
+ acc[value] = key;
177
+ return acc;
178
+ }, {});
179
+ var Validator = class _Validator {
180
+ static {
181
+ __name(this, "Validator");
182
+ }
183
+ $$type = "$PValidator";
184
+ child;
185
+ parent;
186
+ fallbackNamesAdded = /* @__PURE__ */ new Set();
187
+ priority;
188
+ fallbacks = [];
189
+ constructor(type) {
190
+ this.fallbackNamesAdded = /* @__PURE__ */ new Set();
191
+ this.fallbacks = [];
192
+ this.priority = priorityByType[type];
193
+ }
194
+ /**
195
+ * We create all of the validators on the schema in order, i actually didn't want to go on that route but i
196
+ * found it easier to do so.
197
+ *
198
+ * The logic here is simple, if it's not the same priority we will walk on the linked list until we find
199
+ * a validator that matches the priority we are expecting. If we can't walk anymore, we create the next
200
+ * priority validator and append it to the linked list. Be aware that it's a double linked list, so we
201
+ * can walk both ways, from the end to the start and from the start to the end.
202
+ * So you don't really need to start from the root, the linked list can start from anywhere and it will
203
+ * find it's way through.
204
+ *
205
+ * I know there are better ways to do this instead of walking through the linked list, but like i explained
206
+ * before, this is enough for now.
207
+ *
208
+ * If the priority is higher than the current priority saved on the schema, we should substitute the
209
+ * rootValidator on the schema with the new one.
210
+ *
211
+ * @param schema - The schema that we are working on right now, all fallbacks are tied to that specific schema.
212
+ * @param type - The type of the fallback that we are adding.
213
+ * @param fallback - The fallback function that we are adding.
214
+ * @param childOrParent - If we are adding a fallback to the child or to the parent.
215
+ * @param options - The options that we are passing to the fallback.
216
+ */
217
+ checkAppendOrCreate(schema2, type, fallbackName, fallback, childOrParent, options) {
218
+ const schemaWithProtected = schema2;
219
+ if (this[childOrParent]) this[childOrParent].addFallback(schemaWithProtected, type, fallbackName, fallback, options);
220
+ else {
221
+ const nextPriority = childOrParent === "child" ? this.priority - 1 : this.priority + 1;
222
+ if (Object.keys(typeByPriority).includes(String(nextPriority))) {
223
+ const nextType = typeByPriority[nextPriority];
224
+ const validatorInstance = new _Validator(nextType);
225
+ this[childOrParent] = validatorInstance;
226
+ this[childOrParent][childOrParent === "parent" ? "child" : "parent"] = this;
227
+ this[childOrParent].addFallback(schemaWithProtected, type, fallbackName, fallback, options);
228
+ if (nextPriority > schemaWithProtected.__rootFallbacksValidator.priority) schemaWithProtected.__rootFallbacksValidator = validatorInstance;
229
+ }
230
+ }
231
+ }
232
+ addFallback(schema2, type, fallbackName, fallback, options) {
233
+ if (this.fallbackNamesAdded.has(fallbackName) && options?.removeCurrent !== true) return;
234
+ this.fallbackNamesAdded.add(fallbackName);
235
+ const priority = priorityByType[type];
236
+ if (this.priority === priority) {
237
+ if (typeof options?.at === "number") this.fallbacks.splice(options.at, options.removeCurrent === true ? 1 : 0, fallback);
238
+ else this.fallbacks.push(fallback);
239
+ } else if (priority > this.priority) this.checkAppendOrCreate(schema2, type, fallbackName, fallback, "parent", options);
240
+ else if (priority < this.priority) this.checkAppendOrCreate(schema2, type, fallbackName, fallback, "child", options);
241
+ }
242
+ /**
243
+ * Validates the value against all of the fallbacks, the fallbacks are executed in order, from the highest
244
+ * priority to the lowest priority. A validator can stop the execution of the other validators if it feels
245
+ * like so. Like on the example of a value being null or undefined.
246
+ *
247
+ * @param errorsAsHashedSet - This is a set that contains all of the errors that we already found, this is
248
+ * used to avoid duplicated errors.
249
+ * @param path - The path that we are validating right now.
250
+ * @param parseResult - The result of the parsing, it contains the parsed value and the errors that we found.
251
+ * @param options - The options that we are passing to the fallback.
252
+ */
253
+ async validate(errorsAsHashedSet, path, parseResult, options) {
254
+ let doesItShouldPreventChildValidation = false;
255
+ for (const fallback of this.fallbacks) {
256
+ const { parsed, errors, preventChildValidation } = await fallback(parseResult.parsed, path, options);
257
+ parseResult.parsed = parsed;
258
+ for (const error of errors) {
259
+ if (error.isValid === false) {
260
+ const sortedError = Object.fromEntries(Object.entries(error).sort(([a], [b]) => a.localeCompare(b)));
261
+ const hashedError = JSON.stringify(sortedError);
262
+ if (errorsAsHashedSet.has(hashedError)) continue;
263
+ errorsAsHashedSet.add(hashedError);
264
+ if (!Array.isArray(parseResult.errors)) parseResult.errors = [];
265
+ parseResult.errors.push({
266
+ ...error,
267
+ received: parseResult.parsed
268
+ });
269
+ }
270
+ }
271
+ doesItShouldPreventChildValidation = doesItShouldPreventChildValidation || preventChildValidation || false;
272
+ }
273
+ if (this.child && doesItShouldPreventChildValidation === false) return await this.child.validate(errorsAsHashedSet, path, parseResult, options);
274
+ return parseResult;
275
+ }
276
+ /**
277
+ * This static method takes care of everything for you. This means that you should only call this method
278
+ * for appending new fallbacks, it takes care of creating the root validator and making sure that the
279
+ * rootValidator on the schema is the highest priority one.
280
+ *
281
+ * @param schema - The schema that we are working on right now, all fallbacks are tied to that specific
282
+ * schema. We automatically define the rootValidator on the schema so you don't need to worry about that.
283
+ * @param fallback - The fallback that we are adding. This is an object that contains the type of the
284
+ * fallback and the callback that we are adding.
285
+ * @param options - The options that we are passing to the fallback. Options like `at` and `removeCurrent`
286
+ * are passed to the `addFallback` method.
287
+ */
288
+ static createAndAppendFallback(schema2, fallback, options) {
289
+ const schemaWithProtected = schema2;
290
+ let validatorInstance = schemaWithProtected.__rootFallbacksValidator;
291
+ if (schemaWithProtected.__rootFallbacksValidator === void 0) {
292
+ validatorInstance = new _Validator(fallback.type);
293
+ schemaWithProtected.__rootFallbacksValidator = validatorInstance;
294
+ }
295
+ validatorInstance.addFallback(schema2, fallback.type, fallback.name, fallback.callback, options);
296
+ return validatorInstance;
297
+ }
298
+ toString(ident = 0) {
299
+ return `Priority: ${this.priority}
300
+ Fallbacks: ${this.fallbacks.length}
301
+ ${this.child ? `Children:
302
+ ${this.child.toString(ident + 2)}` : ""}`;
303
+ }
304
+ };
305
+
306
+ // src/utils.ts
307
+ var WithFallback = class {
308
+ static {
309
+ __name(this, "WithFallback");
310
+ }
311
+ $$type = "$PWithFallback";
312
+ fallbackFor;
313
+ transformedSchema;
314
+ adapterType;
315
+ constructor(adapterType, fallbackFor, transformedSchema) {
316
+ this.adapterType = adapterType;
317
+ this.fallbackFor = new Set(fallbackFor);
318
+ this.transformedSchema = transformedSchema;
319
+ }
320
+ };
321
+ function withFallbackFactory(adapterType) {
322
+ return (fallbackFor, transformedSchema) => new WithFallback(adapterType, fallbackFor, transformedSchema);
323
+ }
324
+ __name(withFallbackFactory, "withFallbackFactory");
325
+ async function defaultTransform(type, schema2, adapter, fieldAdapter, getValidationData, fallbackFunctions, options) {
326
+ const validationData = await Promise.resolve(getValidationData(false));
327
+ const validationDataForStringVersion = options.shouldAddStringVersion ? await Promise.resolve(getValidationData(true)) : void 0;
328
+ const schemaWithPrivateFields = schema2;
329
+ const checkIfShouldUseParserAndAppend = /* @__PURE__ */ __name((parser) => {
330
+ const isValidationDataAParser = validationData.parsers?.[parser] !== void 0;
331
+ if (isValidationDataAParser) schema2.__parsers._fallbacks.add(parser);
332
+ }, "checkIfShouldUseParserAndAppend");
333
+ const getExtendedOrNotSchemaAndString = /* @__PURE__ */ __name((schema3, toStringVersion) => {
334
+ const extendedOrNotSchema2 = typeof schemaWithPrivateFields.__extends?.callback === "function" ? schemaWithPrivateFields.__extends.callback(schema3) : schema3;
335
+ const extendedOrNotSchemaString2 = typeof schemaWithPrivateFields.__extends?.toStringCallback === "function" ? schemaWithPrivateFields.__extends.toStringCallback(toStringVersion) : toStringVersion;
336
+ return [
337
+ extendedOrNotSchema2,
338
+ extendedOrNotSchemaString2
339
+ ];
340
+ }, "getExtendedOrNotSchemaAndString");
341
+ const checkIfShouldAppendFallbackAndAppend = /* @__PURE__ */ __name((fallback) => {
342
+ const wereArgumentsForThatFallbackDefinedAndFallbackFunctionDefined = validationData[fallback] !== void 0 && fallbackFunctions[fallback] !== void 0;
343
+ if (wereArgumentsForThatFallbackDefinedAndFallbackFunctionDefined) {
344
+ const fallbackReturnType = fallbackFunctions[fallback](validationData[fallback]);
345
+ Validator.createAndAppendFallback(schema2, fallbackReturnType);
346
+ }
347
+ }, "checkIfShouldAppendFallbackAndAppend");
348
+ const appendRootFallback = /* @__PURE__ */ __name(() => {
349
+ if (options.validatorsIfFallbackOrNotSupported) {
350
+ const validatorsIfFallbackOrNotSupported = Array.isArray(options.validatorsIfFallbackOrNotSupported) ? options.validatorsIfFallbackOrNotSupported : [
351
+ options.validatorsIfFallbackOrNotSupported
352
+ ];
353
+ for (const fallback of validatorsIfFallbackOrNotSupported) Validator.createAndAppendFallback(schema2, fallback);
354
+ }
355
+ }, "appendRootFallback");
356
+ const appendRequiredFallbacks = /* @__PURE__ */ __name(() => {
357
+ const hasFallbacks = schemaWithPrivateFields.__rootFallbacksValidator?.["$$type"] === "$PValidator";
358
+ if (hasFallbacks) {
359
+ Validator.createAndAppendFallback(schema2, optional(schemaWithPrivateFields.__optional));
360
+ Validator.createAndAppendFallback(schema2, nullable(schemaWithPrivateFields.__nullable));
361
+ Validator.createAndAppendFallback(schema2, checkType(schemaWithPrivateFields.__type));
362
+ }
363
+ }, "appendRequiredFallbacks");
364
+ const isFieldAdapterNotSupportedForThatFieldType = fieldAdapter === void 0;
365
+ if (options.fallbackIfNotSupported !== void 0 && isFieldAdapterNotSupportedForThatFieldType) {
366
+ const existingFallbacks = Object.keys(fallbackFunctions);
367
+ const allParsers = Object.keys(validationData["parsers"]);
368
+ appendRootFallback();
369
+ for (const fallback of existingFallbacks) checkIfShouldAppendFallbackAndAppend(fallback);
370
+ for (const parser of allParsers) checkIfShouldUseParserAndAppend(parser);
371
+ appendRequiredFallbacks();
372
+ return options.fallbackIfNotSupported();
373
+ }
374
+ if (!fieldAdapter) throw new Error("The field adapter is not supported and no fallback was provided.");
375
+ const translatedSchemaOrWithFallback = await Promise.resolve(fieldAdapter.translate(adapter.field, {
376
+ withFallback: withFallbackFactory(type),
377
+ ...validationData
378
+ }));
379
+ let stringVersion = "";
380
+ if (options.shouldAddStringVersion) stringVersion = await fieldAdapter.toString(adapter, adapter.field, validationDataForStringVersion);
381
+ if (translatedSchemaOrWithFallback?.["$$type"] === "$PWithFallback") {
382
+ appendRootFallback();
383
+ for (const fallback of translatedSchemaOrWithFallback.fallbackFor) {
384
+ checkIfShouldAppendFallbackAndAppend(fallback);
385
+ checkIfShouldUseParserAndAppend(fallback);
386
+ }
387
+ const [extendedOrNotSchema2, extendedOrNotSchemaString2] = getExtendedOrNotSchemaAndString(translatedSchemaOrWithFallback.transformedSchema, stringVersion);
388
+ appendRequiredFallbacks();
389
+ return [
390
+ {
391
+ transformed: extendedOrNotSchema2,
392
+ asString: extendedOrNotSchemaString2
393
+ }
394
+ ];
395
+ }
396
+ const [extendedOrNotSchema, extendedOrNotSchemaString] = getExtendedOrNotSchemaAndString(translatedSchemaOrWithFallback, stringVersion);
397
+ return [
398
+ {
399
+ transformed: extendedOrNotSchema,
400
+ asString: extendedOrNotSchemaString
401
+ }
402
+ ];
403
+ }
404
+ __name(defaultTransform, "defaultTransform");
405
+ async function defaultTransformToAdapter(callback, schema2, transformedSchemas, options, type) {
406
+ const isTransformedSchemasEmpty = Object.keys(transformedSchemas).length <= 0;
407
+ if (isTransformedSchemasEmpty) {
408
+ const adapterInstanceToUse = (
409
+ // eslint-disable-next-line ts/no-unnecessary-condition
410
+ options.schemaAdapter?.["$$type"] === "$PSchemaAdapter" ? options.schemaAdapter : getDefaultAdapter()
411
+ );
412
+ schema2["__transformedSchemas"][adapterInstanceToUse.name] = {
413
+ transformed: false,
414
+ adapter: adapterInstanceToUse,
415
+ schemas: []
416
+ };
417
+ }
418
+ const schemaAdapterNameToUse = options.schemaAdapter?.name || Object.keys(transformedSchemas)[0];
419
+ const isACustomSchemaAdapterAndNotYetDefined = (
420
+ // eslint-disable-next-line ts/no-unnecessary-condition
421
+ transformedSchemas[schemaAdapterNameToUse] === void 0 && options.schemaAdapter !== void 0
422
+ );
423
+ if (isACustomSchemaAdapterAndNotYetDefined) transformedSchemas[schemaAdapterNameToUse] = {
424
+ transformed: false,
425
+ adapter: options.schemaAdapter,
426
+ schemas: []
427
+ };
428
+ const shouldTranslate = transformedSchemas[schemaAdapterNameToUse].transformed === false || options.force === true;
429
+ if (shouldTranslate) {
430
+ const translatedSchemas = await callback(transformedSchemas[schemaAdapterNameToUse].adapter);
431
+ transformedSchemas[schemaAdapterNameToUse].schemas = translatedSchemas;
432
+ transformedSchemas[schemaAdapterNameToUse].transformed = true;
433
+ }
434
+ transformedSchemas[schemaAdapterNameToUse].transformed = true;
435
+ return transformedSchemas[schemaAdapterNameToUse].schemas;
436
+ }
437
+ __name(defaultTransformToAdapter, "defaultTransformToAdapter");
438
+ async function formatErrorFromParseMethod(adapter, fieldAdapter, error, received, schema2, path, errorsAsHashedSet) {
439
+ const formattedError = await fieldAdapter.formatError(adapter, adapter.field, schema2, error);
440
+ formattedError.path = Array.isArray(formattedError.path) ? [
441
+ ...path,
442
+ ...formattedError.path
443
+ ] : path;
444
+ const formattedErrorAsParseResultError = formattedError;
445
+ formattedErrorAsParseResultError.isValid = false;
446
+ const sortedError = Object.fromEntries(Object.entries(formattedErrorAsParseResultError).sort(([a], [b]) => a.localeCompare(b)));
447
+ const hashedError = JSON.stringify(sortedError);
448
+ errorsAsHashedSet.add(JSON.stringify(sortedError));
449
+ formattedErrorAsParseResultError.received = received;
450
+ return formattedErrorAsParseResultError;
451
+ }
452
+ __name(formatErrorFromParseMethod, "formatErrorFromParseMethod");
453
+
454
+ // src/schema/schema.ts
455
+ var Schema = class _Schema {
456
+ static {
457
+ __name(this, "Schema");
458
+ }
459
+ $$type = "$PSchema";
460
+ fieldType = "schema";
461
+ // Those functions will assume control of the validation process on adapters, instead of the schema.
462
+ // Why this is used? The idea is that the Schema has NO idea
463
+ // that one of it's children might be an UnionSchema for example. The adapter might not support unions,
464
+ // so then we give control to the union. The parent schema will already have an array of translated
465
+ // adapter schemas. This means for a union with Number and String it'll generate two schemas, one for number
466
+ // and one for the value as String. Of course this gets multiplied. So if we have a union with Number and String.
467
+ // We should take those two schemas from the array and validate them individually. This logic is
468
+ // handled by the union schema. If we have an intersection type for example, instead of validating
469
+ // One schema OR the other, we validate one schema AND the other. This will be handled
470
+ // by the schema that contains that intersection logic.
471
+ __beforeValidationCallbacks = /* @__PURE__ */ new Map();
472
+ __cachedGetParent;
473
+ set __getParent(value) {
474
+ this.__cachedGetParent = value;
475
+ }
476
+ get __getParent() {
477
+ return this.__cachedGetParent;
478
+ }
479
+ __alreadyAppliedModel;
480
+ __runBeforeParseAndData;
481
+ __rootFallbacksValidator;
482
+ __saveCallback;
483
+ __modelOmitCallback;
484
+ __parsers = {
485
+ high: /* @__PURE__ */ new Map(),
486
+ medium: /* @__PURE__ */ new Map(),
487
+ low: /* @__PURE__ */ new Map(),
488
+ _fallbacks: /* @__PURE__ */ new Set()
489
+ };
490
+ __refinements = [];
491
+ __nullable = {
492
+ message: "Cannot be null",
493
+ allow: false
494
+ };
495
+ __optional = {
496
+ message: "Required",
497
+ allow: false
498
+ };
499
+ __extends = void 0;
500
+ __transformedSchemas = {};
501
+ __defaultFunction = void 0;
502
+ __toRepresentation = void 0;
503
+ __toValidate = void 0;
504
+ __toInternal = void 0;
505
+ __type = {
506
+ message: "Invalid type",
507
+ check: /* @__PURE__ */ __name(() => true, "check")
508
+ };
509
+ __getDefaultTransformedSchemas() {
510
+ const adapterInstance = getDefaultAdapter();
511
+ if (this.__transformedSchemas[adapterInstance.constructor.name] === void 0) this.__transformedSchemas[adapterInstance.constructor.name] = {
512
+ transformed: false,
513
+ adapter: adapterInstance,
514
+ schemas: []
515
+ };
516
+ }
517
+ /**
518
+ * This will validate the data with the fallbacks, so internally, without relaying on the schema adapter.
519
+ * This is nice because we can support things that the schema adapter is not able to support by default.
520
+ *
521
+ * @param errorsAsHashedSet - The errors as a hashed set. This is used to prevent duplicate errors.
522
+ * @param path - The path of the error.
523
+ * @param parseResult - The result of the parse method.
524
+ */
525
+ async __validateByFallbacks(path, parseResult, options) {
526
+ if (this.__rootFallbacksValidator) return this.__rootFallbacksValidator.validate(options.errorsAsHashedSet, path, parseResult, options);
527
+ return parseResult;
528
+ }
529
+ /**
530
+ * This will validate by the adapter. In other words, we send the data to the schema adapter and then we validate
531
+ * that data.
532
+ * So understand that, first we send the data to the adapter, the adapter validates it, then, after we validate
533
+ * from the adapter we validate with the fallbacks so we can do all of the extra validations not handled by
534
+ * the adapter.
535
+ *
536
+ * @param value - The value to be validated.
537
+ * @param errorsAsHashedSet - The errors as a hashed set. This is used to prevent duplicate errors on the validator.
538
+ * @param path - The path of the error so we can construct an object with the nested paths of the error.
539
+ * @param parseResult - The result of the parse method.
540
+ *
541
+ * @returns The result and the errors of the parse method.
542
+ */
543
+ async __validateByAdapter(adapter, fieldAdapter, schema2, value, path, options) {
544
+ const parseResult = {
545
+ errors: [],
546
+ parsed: value
547
+ };
548
+ parseResult.errors = [];
549
+ parseResult.parsed = value;
550
+ if (fieldAdapter === void 0 || typeof fieldAdapter.parse !== "function") return parseResult;
551
+ const adapterParseResult = await fieldAdapter.parse(adapter, adapter.field, schema2.transformed, value, options.args);
552
+ parseResult.parsed = adapterParseResult.parsed;
553
+ if (adapterParseResult.errors) {
554
+ if (Array.isArray(adapterParseResult.errors)) parseResult.errors = await Promise.all(adapterParseResult.errors.map(async (error) => formatErrorFromParseMethod(adapter, fieldAdapter, error, value, schema2.transformed, path, options.errorsAsHashedSet || /* @__PURE__ */ new Set())));
555
+ else parseResult.errors = [
556
+ await formatErrorFromParseMethod(adapter, fieldAdapter, parseResult.errors, value, schema2.transformed, path, options.errorsAsHashedSet || /* @__PURE__ */ new Set())
557
+ ];
558
+ }
559
+ parseResult.errors = parseResult.errors.filter((error) => typeof error !== "undefined");
560
+ return parseResult;
561
+ }
562
+ // eslint-disable-next-line ts/require-await
563
+ async __transformToAdapter(_options) {
564
+ throw new Error("Not implemented");
565
+ }
566
+ /** */
567
+ async __parsersToTransformValue(value, parsersToUse) {
568
+ let shouldStop = false;
569
+ for (const [parserName, parser] of this.__parsers.high.entries()) {
570
+ if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
571
+ const result = await Promise.resolve(parser(value));
572
+ if (result.preventNextParsers) shouldStop = true;
573
+ value = result.value;
574
+ } else continue;
575
+ }
576
+ if (shouldStop === false) {
577
+ for (const [parserName, parser] of this.__parsers.medium.entries()) {
578
+ if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
579
+ const result = await Promise.resolve(parser(value));
580
+ if (result.preventNextParsers) shouldStop = true;
581
+ value = result.value;
582
+ } else continue;
583
+ }
584
+ }
585
+ if (shouldStop === false) {
586
+ for (const [parserName, parser] of this.__parsers.low.entries()) {
587
+ if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
588
+ const result = await Promise.resolve(parser(value));
589
+ if (result.preventNextParsers) shouldStop = true;
590
+ value = result.value;
591
+ } else continue;
592
+ }
593
+ }
594
+ return value;
595
+ }
596
+ async __parse(value, path = [], options) {
597
+ this.__getDefaultTransformedSchemas();
598
+ if (typeof this.__runBeforeParseAndData === "function") await this.__runBeforeParseAndData(this);
599
+ const shouldRunToInternalToBubbleUp = options.toInternalToBubbleUp === void 0;
600
+ if (shouldRunToInternalToBubbleUp) options.toInternalToBubbleUp = [];
601
+ if (options.errorsAsHashedSet instanceof Set === false) options.errorsAsHashedSet = /* @__PURE__ */ new Set();
602
+ const shouldCallDefaultFunction = value === void 0 && typeof this.__defaultFunction === "function";
603
+ const shouldCallToValidateCallback = typeof this.__toValidate === "function";
604
+ const schemaAdapterFieldType = this.fieldType;
605
+ if (shouldCallDefaultFunction) value = await this.__defaultFunction();
606
+ if (shouldCallToValidateCallback) value = await Promise.resolve(this.__toValidate(value));
607
+ const parseResult = {
608
+ errors: [],
609
+ parsed: value
610
+ };
611
+ value = await this.__parsersToTransformValue(value, this.__parsers._fallbacks);
612
+ if (options.appendFallbacksBeforeAdapterValidation === void 0) options.appendFallbacksBeforeAdapterValidation = (schema2, name, callback) => {
613
+ if (this !== schema2) this.__beforeValidationCallbacks.set(name, callback);
614
+ };
615
+ if (this.__transformedSchemas[options.schemaAdapter?.constructor.name || getDefaultAdapter().constructor.name].transformed === false) await this.__transformToAdapter(options);
616
+ const adapterToUse = options.schemaAdapter ? options.schemaAdapter : Object.values(this.__transformedSchemas)[0].adapter;
617
+ const parsedResultsAfterFallbacks = await this.__validateByFallbacks(path, {
618
+ errors: parseResult.errors,
619
+ parsed: value
620
+ }, options);
621
+ parseResult.parsed = parsedResultsAfterFallbacks.parsed;
622
+ parseResult.errors = (parseResult.errors || []).concat(parsedResultsAfterFallbacks.errors || []);
623
+ if (this.__beforeValidationCallbacks.size > 0) {
624
+ for (const callback of this.__beforeValidationCallbacks.values()) {
625
+ const parsedValuesAfterValidationCallbacks = await callback(adapterToUse, adapterToUse[schemaAdapterFieldType], this, this.__transformedSchemas[adapterToUse.constructor.name].schemas, value, path, options);
626
+ parseResult.parsed = parsedValuesAfterValidationCallbacks.parsed;
627
+ parseResult.errors = Array.isArray(parseResult.errors) && Array.isArray(parsedValuesAfterValidationCallbacks.errors) ? [
628
+ ...parseResult.errors,
629
+ ...parsedValuesAfterValidationCallbacks.errors
630
+ ] : Array.isArray(parseResult.errors) ? parseResult.errors : parsedValuesAfterValidationCallbacks.errors;
631
+ }
632
+ } else {
633
+ const parsedValuesAfterValidatingByAdapter = await this.__validateByAdapter(adapterToUse, adapterToUse[schemaAdapterFieldType], this.__transformedSchemas[adapterToUse.constructor.name].schemas[0], value, path, options);
634
+ parseResult.parsed = parsedValuesAfterValidatingByAdapter.parsed;
635
+ parseResult.errors = (parseResult.errors || []).concat(parsedValuesAfterValidatingByAdapter.errors);
636
+ }
637
+ const hasToInternalCallback = typeof this.__toInternal === "function";
638
+ const shouldCallToInternalDuringParse = hasToInternalCallback && (options.toInternalToBubbleUp?.length === 0 || Array.isArray(options.toInternalToBubbleUp) === false);
639
+ const hasNoErrors = parseResult.errors === void 0 || (parseResult.errors || []).length === 0;
640
+ await Promise.all(this.__refinements.map(async (refinement) => {
641
+ const errorOrNothing = await Promise.resolve(refinement(parseResult.parsed));
642
+ if (typeof errorOrNothing === "undefined") return;
643
+ parseResult.errors.push({
644
+ isValid: false,
645
+ code: errorOrNothing.code,
646
+ message: errorOrNothing.message,
647
+ received: parseResult.parsed,
648
+ path
649
+ });
650
+ }));
651
+ if (shouldCallToInternalDuringParse && hasNoErrors) parseResult.parsed = await this.__toInternal(value);
652
+ if (shouldRunToInternalToBubbleUp && hasNoErrors) for (const functionToModifyResult of options.toInternalToBubbleUp || []) await functionToModifyResult();
653
+ return parseResult;
654
+ }
655
+ /**
656
+ * This let's you refine the schema with custom validations. This is useful when you want to validate something
657
+ * that is not supported by default by the schema adapter.
658
+ *
659
+ * @example
660
+ * ```typescript
661
+ * import * as p from '@palmares/schemas';
662
+ *
663
+ * const numberSchema = p.number().refine((value) => {
664
+ * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
665
+ * });
666
+ *
667
+ * const { errors, parsed } = await numberSchema.parse(-1);
668
+ *
669
+ * console.log(errors);
670
+ * // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
671
+ * ```
672
+ *
673
+ * @param refinementCallback - The callback that will be called to validate the value.
674
+ * @param options - Options for the refinement.
675
+ * @param options.isAsync - Whether the callback is async or not. Defaults to true.
676
+ */
677
+ refine(refinementCallback) {
678
+ this.__refinements.push(refinementCallback);
679
+ return this;
680
+ }
681
+ /**
682
+ * Allows the value to be either undefined or null.
683
+ *
684
+ * @example
685
+ * ```typescript
686
+ * import * as p from '@palmares/schemas';
687
+ *
688
+ * const numberSchema = p.number().optional();
689
+ *
690
+ * const { errors, parsed } = await numberSchema.parse(undefined);
691
+ *
692
+ * console.log(parsed); // undefined
693
+ *
694
+ * const { errors, parsed } = await numberSchema.parse(null);
695
+ *
696
+ * console.log(parsed); // null
697
+ *
698
+ * const { errors, parsed } = await numberSchema.parse(1);
699
+ *
700
+ * console.log(parsed); // 1
701
+ * ```
702
+ *
703
+ * @returns - The schema we are working with.
704
+ */
705
+ optional(options) {
706
+ this.__optional = {
707
+ message: typeof options?.message === "string" ? options.message : "Required",
708
+ allow: typeof options?.allow === "boolean" ? options.allow : true
709
+ };
710
+ return this;
711
+ }
712
+ /**
713
+ * Allows the value to be null and ONLY null. You can also use this function to set a custom message when
714
+ * the value is NULL by setting the { message: 'Your custom message', allow: false } on the options.
715
+ *
716
+ * @example
717
+ * ```typescript
718
+ * import * as p from '@palmares/schemas';
719
+ *
720
+ * const numberSchema = p.number().nullable();
721
+ *
722
+ * const { errors, parsed } = await numberSchema.parse(null);
723
+ *
724
+ * console.log(parsed); // null
725
+ *
726
+ * const { errors, parsed } = await numberSchema.parse(undefined);
727
+ *
728
+ * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
729
+ * ```
730
+ *
731
+ * @param options - The options for the nullable function.
732
+ * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
733
+ * @param options.allow - Whether the value can be null or not. Defaults to true.
734
+ *
735
+ * @returns The schema.
736
+ */
737
+ nullable(options) {
738
+ this.__nullable = {
739
+ message: typeof options?.message === "string" ? options.message : "Cannot be null",
740
+ allow: typeof options?.allow === "boolean" ? options.allow : true
741
+ };
742
+ return this;
743
+ }
744
+ /**
745
+ * Appends a custom schema to the schema, this way it will bypass the creation of the schema in runtime.
746
+ *
747
+ * By default when validating, on the first validation we create the schema. Just during the first validation.
748
+ * With this function, you bypass that, so you can speed up the validation process.
749
+ *
750
+ * @example
751
+ * ```typescript
752
+ * import * as p from '@palmares/schemas';
753
+ * import * as z from 'zod';
754
+ *
755
+ * const numberSchema = p.number().appendSchema(z.number());
756
+ *
757
+ * const { errors, parsed } = await numberSchema.parse(1);
758
+ * ```
759
+ *
760
+ * @param schema - The schema to be appended.
761
+ * @param args - The arguments for the schema.
762
+ * @param args.adapter - The adapter to be used. If not provided, the default adapter will be used.
763
+ *
764
+ * @returns The same schema again.
765
+ */
766
+ appendSchema(schema2, args) {
767
+ const adapter = args?.adapter || getDefaultAdapter();
768
+ this.__transformedSchemas[adapter.constructor.name] = {
769
+ transformed: true,
770
+ adapter,
771
+ schemas: [
772
+ schema2
773
+ ]
774
+ };
775
+ return this;
776
+ }
777
+ /**
778
+ * This method will remove the value from the representation of the schema. If the value is undefined it will keep
779
+ * that way otherwise it will set the value to undefined after it's validated.
780
+ * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
781
+ * function. This will remove the value from the representation of the schema.
782
+ *
783
+ * By default, the value will be removed just from the representation, in other words, when you call the {@link data}
784
+ * function. But if you want to remove the value from the internal representation, you can pass the argument
785
+ * `toInternal` as true. Then if you still want to remove the value from the representation, you will need to pass
786
+ * the argument `toRepresentation` as true as well.
787
+ *
788
+ * @example
789
+ * ```typescript
790
+ * import * as p from '@palmares/schemas';
791
+ *
792
+ * const userSchema = p.object({
793
+ * id: p.number().optional(),
794
+ * name: p.string(),
795
+ * password: p.string().omit()
796
+ * });
797
+ *
798
+ * const user = await userSchema.data({
799
+ * id: 1,
800
+ * name: 'John Doe',
801
+ * password: '123456'
802
+ * });
803
+ *
804
+ * console.log(user); // { id: 1, name: 'John Doe' }
805
+ * ```
806
+ *
807
+ *
808
+ * @param args - By default, the value will be removed just from the representation, in other words, when you call
809
+ * the {@link data} function.
810
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
811
+ * as true. Then if you still want to remove the value from the representation, you will need to pass the
812
+ * argument `toRepresentation` as true as well.
813
+ *
814
+ * @returns The schema.
815
+ */
816
+ omit(args) {
817
+ const toRepresentation = typeof args?.toRepresentation === "boolean" ? args.toRepresentation : typeof args?.toInternal !== "boolean";
818
+ const toInternal = typeof args?.toInternal === "boolean" ? args.toInternal : false;
819
+ if (toInternal) {
820
+ if (this.__toInternal) {
821
+ const toInternal2 = this.__toInternal;
822
+ this.__toInternal = async (value) => {
823
+ await toInternal2(value);
824
+ return void 0;
825
+ };
826
+ } else this.__toInternal = async () => void 0;
827
+ } else if (toRepresentation) {
828
+ if (this.__toRepresentation) {
829
+ const toRepresentation2 = this.__toRepresentation;
830
+ this.__toRepresentation = async (value) => {
831
+ await toRepresentation2(value);
832
+ return void 0;
833
+ };
834
+ } else this.__toRepresentation = async () => void 0;
835
+ }
836
+ return this;
837
+ }
838
+ /**
839
+ * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external
840
+ * source like a database. You should always return the schema after you save the value, that way we will always have
841
+ * the correct type of the schema after the save operation.
842
+ *
843
+ * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
844
+ *
845
+ * @example
846
+ * ```typescript
847
+ * import * as p from '@palmares/schemas';
848
+ *
849
+ * import { User } from './models';
850
+ *
851
+ * const userSchema = p.object({
852
+ * id: p.number().optional(),
853
+ * name: p.string(),
854
+ * email: p.string().email(),
855
+ * }).onSave(async (value) => {
856
+ * // Create or update the user on the database using palmares models or any other library of your choice.
857
+ * if (value.id)
858
+ * await User.default.set(value, { search: { id: value.id } });
859
+ * else
860
+ * await User.default.set(value);
861
+ *
862
+ * return value;
863
+ * });
864
+ *
865
+ *
866
+ * // Then, on your controller, do something like this:
867
+ * const { isValid, save, errors } = await userSchema.validate(req.body);
868
+ * if (isValid) {
869
+ * const savedValue = await save();
870
+ * return Response.json(savedValue, { status: 201 });
871
+ * }
872
+ *
873
+ * return Response.json({ errors }, { status: 400 });
874
+ * ```
875
+ *
876
+ * @param callback - The callback that will be called to save the value on an external source.
877
+ *
878
+ * @returns The schema.
879
+ */
880
+ onSave(callback) {
881
+ this.__saveCallback = callback;
882
+ return this;
883
+ }
884
+ /**
885
+ * This function is used to validate the schema and save the value to the database. It is used in
886
+ * conjunction with the {@link onSave} function.
887
+ *
888
+ * Different from other validation libraries, palmares schemas is aware that you want to save. On your
889
+ * routes/functions we recommend to ALWAYS use this function instead of {@link parse} directly. This is because
890
+ * this function by default will return an object with the property `save` or the `errors`. If the errors are present,
891
+ * you can return the errors to the user. If the save property is present, you can use to save the value to an
892
+ * external source. e.g. a database.
893
+ *
894
+ * @example
895
+ * ```typescript
896
+ * import * as p from '@palmares/schemas';
897
+ *
898
+ * import { User } from './models';
899
+ *
900
+ * const userSchema = p.object({
901
+ * id: p.number().optional(),
902
+ * name: p.string(),
903
+ * email: p.string().email(),
904
+ * }).onSave(async (value) => {
905
+ * // Create or update the user on the database using palmares models or any other library of your choice.
906
+ * if (value.id)
907
+ * await User.default.set(value, { search: { id: value.id } });
908
+ * else
909
+ * await User.default.set(value);
910
+ *
911
+ * return value;
912
+ * });
913
+ *
914
+ *
915
+ * // Then, on your controller, do something like this:
916
+ * const { isValid, save, errors } = await userSchema.validate(req.body);
917
+ * if (isValid) {
918
+ * const savedValue = await save();
919
+ * return Response.json(savedValue, { status: 201 });
920
+ * }
921
+ *
922
+ * return Response.json({ errors }, { status: 400 });
923
+ * ```
924
+ *
925
+ * @param value - The value to be validated.
926
+ *
927
+ * @returns An object with the property isValid, if the value is valid, the function `save` will be present.
928
+ * If the value is invalid, the property errors will be present.
929
+ */
930
+ async validate(value, context) {
931
+ const { errors, parsed } = await this.__parse(value, [], {
932
+ context
933
+ });
934
+ if ((errors || []).length > 0) return {
935
+ isValid: false,
936
+ errors
937
+ };
938
+ return {
939
+ isValid: true,
940
+ save: /* @__PURE__ */ __name(async () => this._save.bind(this)(parsed, context), "save")
941
+ };
942
+ }
943
+ /**
944
+ * Internal function, when we call the {@link validate} function it's this function that gets called
945
+ * when the user uses the `save` function returned by the {@link validate} function if the value is valid.
946
+ *
947
+ * @param value - The value to be saved.
948
+ *
949
+ * @returns The value to representation.
950
+ */
951
+ async _save(value, context) {
952
+ if (this.__saveCallback) {
953
+ const result = await this.__saveCallback(value, context);
954
+ return this.data(result);
955
+ }
956
+ return this.data(value);
957
+ }
958
+ /**
959
+ * This function is used to validate and parse the value to the internal representation of the schema.
960
+ *
961
+ * @example
962
+ * ```typescript
963
+ * import * as p from '@palmares/schemas';
964
+ *
965
+ * const numberSchema = p.number().allowString();
966
+ *
967
+ * const { errors, parsed } = await numberSchema.parse('123');
968
+ *
969
+ * console.log(parsed); // 123
970
+ * ```
971
+ *
972
+ * @param value - The value to be parsed.
973
+ *
974
+ * @returns The parsed value.
975
+ */
976
+ async parse(value) {
977
+ return this.__parse(value, [], {});
978
+ }
979
+ /**
980
+ * This function is used to transform the value to the representation without validating it.
981
+ * This is useful when you want to return a data from a query directly to the user. But for example
982
+ * you are returning the data of a user, you can clean the password or any other sensitive data.
983
+ *
984
+ * @example
985
+ * ```typescript
986
+ * import * as p from '@palmares/schemas';
987
+ *
988
+ * const userSchema = p.object({
989
+ * id: p.number().optional(),
990
+ * name: p.string(),
991
+ * email: p.string().email(),
992
+ * password: p.string().optional()
993
+ * }).toRepresentation(async (value) => {
994
+ * return {
995
+ * id: value.id,
996
+ * name: value.name,
997
+ * email: value.email
998
+ * }
999
+ * });
1000
+ *
1001
+ * const user = await userSchema.data({
1002
+ * id: 1,
1003
+ * name: 'John Doe',
1004
+ * email: 'john@gmail.com',
1005
+ * password: '123456'
1006
+ * });
1007
+ * ```
1008
+ */
1009
+ async data(value) {
1010
+ this.__getDefaultTransformedSchemas();
1011
+ if (typeof this.__runBeforeParseAndData === "function") await this.__runBeforeParseAndData(this);
1012
+ value = await this.__parsersToTransformValue(value);
1013
+ if (this.__toRepresentation) value = await Promise.resolve(this.__toRepresentation(value));
1014
+ if (this.__defaultFunction && value === void 0) value = await Promise.resolve(this.__defaultFunction());
1015
+ return value;
1016
+ }
1017
+ instanceOf(args) {
1018
+ this.__type.check = typeof args.check === "function" ? args.check : this.__type.check;
1019
+ this.__type.message = typeof args.message === "string" ? args.message : this.__type.message;
1020
+ return this;
1021
+ }
1022
+ /**
1023
+ * This function is used to add a default value to the schema. If the value is either undefined or null,
1024
+ * the default value will be used.
1025
+ *
1026
+ * @example
1027
+ * ```typescript
1028
+ * import * as p from '@palmares/schemas';
1029
+ *
1030
+ * const numberSchema = p.number().default(0);
1031
+ *
1032
+ * const { errors, parsed } = await numberSchema.parse(undefined);
1033
+ *
1034
+ * console.log(parsed); // 0
1035
+ * ```
1036
+ */
1037
+ default(defaultValueOrFunction) {
1038
+ const isFunction = typeof defaultValueOrFunction === "function";
1039
+ if (isFunction) this.__defaultFunction = defaultValueOrFunction;
1040
+ else this.__defaultFunction = async () => defaultValueOrFunction;
1041
+ return this;
1042
+ }
1043
+ /**
1044
+ * This function let's you customize the schema your own way. After we translate the schema on the adapter we call
1045
+ * this function to let you customize the custom schema your own way. Our API does not support passthrough?
1046
+ * No problem, you can use this function to customize the zod schema.
1047
+ *
1048
+ * @example
1049
+ * ```typescript
1050
+ * import * as p from '@palmares/schemas';
1051
+ *
1052
+ * const numberSchema = p.number().extends((schema) => {
1053
+ * return schema.nonnegative();
1054
+ * });
1055
+ *
1056
+ * const { errors, parsed } = await numberSchema.parse(-1);
1057
+ *
1058
+ * console.log(errors);
1059
+ * // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
1060
+ * ```
1061
+ *
1062
+ * @param callback - The callback that will be called to customize the schema.
1063
+ * @param toStringCallback - The callback that will be called to transform the schema to a string when you want
1064
+ * to compile the underlying schema to a string so you can save it for future runs.
1065
+ *
1066
+ * @returns The schema.
1067
+ */
1068
+ extends(callback, toStringCallback) {
1069
+ this.__extends = {
1070
+ callback,
1071
+ toStringCallback
1072
+ };
1073
+ return this;
1074
+ }
1075
+ /**
1076
+ * This function is used to transform the value to the representation of the schema. When using the {@link data}
1077
+ * function. With this function you have full control to add data cleaning for example, transforming the data
1078
+ * and whatever. Another use case is when you want to return deeply nested recursive data.
1079
+ * The schema maps to itself.
1080
+ *
1081
+ * @example
1082
+ * ```typescript
1083
+ * import * as p from '@palmares/schemas';
1084
+ *
1085
+ * const recursiveSchema = p.object({
1086
+ * id: p.number().optional(),
1087
+ * name: p.string(),
1088
+ * }).toRepresentation(async (value) => {
1089
+ * return {
1090
+ * id: value.id,
1091
+ * name: value.name,
1092
+ * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
1093
+ * }
1094
+ * });
1095
+ *
1096
+ * const data = await recursiveSchema.data({
1097
+ * id: 1,
1098
+ * name: 'John Doe',
1099
+ * });
1100
+ * ```
1101
+ *
1102
+ * @example
1103
+ * ```
1104
+ * import * as p from '@palmares/schemas';
1105
+ *
1106
+ * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
1107
+ * switch (value) {
1108
+ * case 'red': return { r: 255, g: 0, b: 0 };
1109
+ * case 'green': return { r: 0, g: 255, b: 0 };
1110
+ * case 'blue': return { r: 0, g: 0, b: 255 };
1111
+ * default: return { r: 0, g: 0, b: 0 };
1112
+ * }
1113
+ * });
1114
+ * ```
1115
+ * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
1116
+ * @param options - Options for the toRepresentation function.
1117
+ * @param options.after - Whether the toRepresentationCallback should be called after the existing
1118
+ * toRepresentationCallback. Defaults to true.
1119
+ * @param options.before - Whether the toRepresentationCallback should be called before the existing
1120
+ * toRepresentationCallback. Defaults to true.
1121
+ *
1122
+ * @returns The schema with a new return type
1123
+ */
1124
+ toRepresentation(toRepresentationCallback, options) {
1125
+ if (this.__toRepresentation) {
1126
+ const before = typeof options?.before === "boolean" ? options.before : typeof options?.after === "boolean" ? !options.after : true;
1127
+ const existingToRepresentation = this.__toRepresentation;
1128
+ this.__toRepresentation = async (value) => {
1129
+ if (before) return toRepresentationCallback(await existingToRepresentation(value));
1130
+ else return existingToRepresentation(await toRepresentationCallback(value));
1131
+ };
1132
+ } else this.__toRepresentation = toRepresentationCallback;
1133
+ return this;
1134
+ }
1135
+ /**
1136
+ * This function is used to transform the value to the internal representation of the schema. This is useful
1137
+ * when you want to transform the value to a type that the schema adapter can understand. For example, you
1138
+ * might want to transform a string to a date. This is the function you use.
1139
+ *
1140
+ * @example
1141
+ * ```typescript
1142
+ * import * as p from '@palmares/schemas';
1143
+ *
1144
+ * const dateSchema = p.string().toInternal((value) => {
1145
+ * return new Date(value);
1146
+ * });
1147
+ *
1148
+ * const date = await dateSchema.parse('2021-01-01');
1149
+ *
1150
+ * console.log(date); // Date object
1151
+ *
1152
+ * const rgbToColorSchema = p.object({
1153
+ * r: p.number().min(0).max(255),
1154
+ * g: p.number().min(0).max(255),
1155
+ * b: p.number().min(0).max(255),
1156
+ * }).toInternal(async (value) => {
1157
+ * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
1158
+ * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
1159
+ * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
1160
+ * return `rgb(${value.r}, ${value.g}, ${value.b})`;
1161
+ * });
1162
+ * ```
1163
+ *
1164
+ * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
1165
+ *
1166
+ * @returns The schema with a new return type.
1167
+ */
1168
+ toInternal(toInternalCallback) {
1169
+ if (this.__toInternal) {
1170
+ const toInternal = this.__toInternal;
1171
+ this.__toInternal = async (value) => {
1172
+ const newValue = await toInternal(value);
1173
+ return toInternalCallback(newValue);
1174
+ };
1175
+ } else this.__toInternal = toInternalCallback;
1176
+ return this;
1177
+ }
1178
+ /**
1179
+ * Called before the validation of the schema. Let's say that you want to validate a date that might receive a
1180
+ * string, you can convert that string to a date here BEFORE the validation. This pretty much transforms the value
1181
+ * to a type that the schema adapter can understand.
1182
+ *
1183
+ * @example
1184
+ * ```
1185
+ * import * as p from '@palmares/schemas';
1186
+ * import * as z from 'zod';
1187
+ *
1188
+ * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
1189
+ * return new Map(value); // Before validating we transform the value to a map.
1190
+ * });
1191
+ *
1192
+ * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
1193
+ * ```
1194
+ *
1195
+ * @param toValidateCallback - The callback that will be called to validate the value.
1196
+ *
1197
+ * @returns The schema with a new return type.
1198
+ */
1199
+ toValidate(toValidateCallback) {
1200
+ this.__toValidate = toValidateCallback;
1201
+ return this;
1202
+ }
1203
+ /**
1204
+ * Used to transform the given schema on a stringfied version of the adapter.
1205
+ */
1206
+ async compile(adapter) {
1207
+ const data = await this.__transformToAdapter({
1208
+ shouldAddStringVersion: true,
1209
+ force: true
1210
+ });
1211
+ const stringVersions = data.map((value) => value.asString);
1212
+ return stringVersions;
1213
+ }
1214
+ static new(..._args) {
1215
+ const result = new _Schema();
1216
+ return result;
1217
+ }
1218
+ };
1219
+ var schema = Schema.new;
1220
+
1221
+ // src/constants.ts
1222
+ var DEFAULT_NUMBER_MAX_EXCEPTION = /* @__PURE__ */ __name((max2, inclusive) => `The number is greater than the allowed ${max2}.${inclusive ? ` The value ${max2} is accepted as well.` : ""}`, "DEFAULT_NUMBER_MAX_EXCEPTION");
1223
+ var DEFAULT_NUMBER_MIN_EXCEPTION = /* @__PURE__ */ __name((min2, inclusive) => `The number is less than the allowed ${min2}.${inclusive ? ` The value ${min2} is accepted as well.` : ""}`, "DEFAULT_NUMBER_MIN_EXCEPTION");
1224
+ var DEFAULT_NUMBER_INTEGER_EXCEPTION = /* @__PURE__ */ __name(() => `The number should be an integer.`, "DEFAULT_NUMBER_INTEGER_EXCEPTION");
1225
+
1226
+ // src/parsers/convert-from-string.ts
1227
+ function convertFromStringBuilder(callback) {
1228
+ return (value) => {
1229
+ if (typeof value === "string") return callback(value);
1230
+ return {
1231
+ value,
1232
+ preventNextParsers: false
1233
+ };
1234
+ };
1235
+ }
1236
+ __name(convertFromStringBuilder, "convertFromStringBuilder");
1237
+
1238
+ // src/validators/number.ts
1239
+ function numberValidation() {
1240
+ return {
1241
+ name: "number",
1242
+ type: "medium",
1243
+ // eslint-disable-next-line ts/require-await
1244
+ callback: /* @__PURE__ */ __name(async (value, path, _options) => {
1245
+ return {
1246
+ parsed: value,
1247
+ errors: [
1248
+ {
1249
+ isValid: typeof value === "number",
1250
+ code: "number",
1251
+ // eslint-disable-next-line ts/no-unnecessary-condition
1252
+ path: path || [],
1253
+ message: "The value must be a number. Received: " + typeof value
1254
+ }
1255
+ ]
1256
+ };
1257
+ }, "callback")
1258
+ };
1259
+ }
1260
+ __name(numberValidation, "numberValidation");
1261
+ function max(args) {
1262
+ return {
1263
+ name: "max",
1264
+ type: "low",
1265
+ // eslint-disable-next-line ts/require-await
1266
+ callback: /* @__PURE__ */ __name(async (value, path, _options) => {
1267
+ if (args.inclusive) return {
1268
+ parsed: value,
1269
+ errors: [
1270
+ {
1271
+ isValid: value <= args.value,
1272
+ code: "max",
1273
+ // eslint-disable-next-line ts/no-unnecessary-condition
1274
+ path: path || [],
1275
+ message: args.message
1276
+ }
1277
+ ]
1278
+ };
1279
+ return {
1280
+ parsed: value,
1281
+ errors: [
1282
+ {
1283
+ isValid: value < args.value,
1284
+ code: "max",
1285
+ // eslint-disable-next-line ts/no-unnecessary-condition
1286
+ path: path || [],
1287
+ message: args.message
1288
+ }
1289
+ ]
1290
+ };
1291
+ }, "callback")
1292
+ };
1293
+ }
1294
+ __name(max, "max");
1295
+ function min(args) {
1296
+ return {
1297
+ name: "min",
1298
+ type: "low",
1299
+ // eslint-disable-next-line ts/require-await
1300
+ callback: /* @__PURE__ */ __name(async (value, path) => {
1301
+ if (args.inclusive) return {
1302
+ parsed: value,
1303
+ errors: [
1304
+ {
1305
+ isValid: value >= args.value,
1306
+ message: args.message,
1307
+ code: "min",
1308
+ path: path || []
1309
+ }
1310
+ ]
1311
+ };
1312
+ return {
1313
+ parsed: value,
1314
+ errors: [
1315
+ {
1316
+ isValid: value > args.value,
1317
+ message: args.message,
1318
+ code: "min",
1319
+ path: path || []
1320
+ }
1321
+ ]
1322
+ };
1323
+ }, "callback")
1324
+ };
1325
+ }
1326
+ __name(min, "min");
1327
+ function integer(args) {
1328
+ return {
1329
+ name: "integer",
1330
+ type: "low",
1331
+ // eslint-disable-next-line ts/require-await
1332
+ callback: /* @__PURE__ */ __name(async (value, path) => {
1333
+ const isValid = Number.isInteger(value);
1334
+ return {
1335
+ parsed: value,
1336
+ errors: isValid ? [] : [
1337
+ {
1338
+ isValid,
1339
+ message: args.message,
1340
+ code: "integer",
1341
+ path: path || []
1342
+ }
1343
+ ]
1344
+ };
1345
+ }, "callback")
1346
+ };
1347
+ }
1348
+ __name(integer, "integer");
1349
+ function maxDigits(args) {
1350
+ return {
1351
+ name: "maxDigits",
1352
+ type: "low",
1353
+ // eslint-disable-next-line ts/require-await
1354
+ callback: /* @__PURE__ */ __name(async (value, path) => {
1355
+ const isValid = value.toString().replace(".", "").length <= args.value;
1356
+ return {
1357
+ parsed: value,
1358
+ errors: isValid ? [] : [
1359
+ {
1360
+ isValid,
1361
+ message: args.message,
1362
+ code: "maxDigits",
1363
+ path: path || []
1364
+ }
1365
+ ]
1366
+ };
1367
+ }, "callback")
1368
+ };
1369
+ }
1370
+ __name(maxDigits, "maxDigits");
1371
+ function decimalPlaces(args) {
1372
+ return {
1373
+ name: "decimalPlaces",
1374
+ type: "low",
1375
+ // eslint-disable-next-line ts/require-await
1376
+ callback: /* @__PURE__ */ __name(async (value, path) => {
1377
+ const isValid = value.toString().split(".")[1]?.length <= args.value;
1378
+ return {
1379
+ parsed: value,
1380
+ errors: isValid ? [] : [
1381
+ {
1382
+ isValid,
1383
+ message: args.message,
1384
+ code: "decimalPlaces",
1385
+ path: path || []
1386
+ }
1387
+ ]
1388
+ };
1389
+ }, "callback")
1390
+ };
1391
+ }
1392
+ __name(decimalPlaces, "decimalPlaces");
1393
+
1394
+ // src/schema/number.ts
1395
+ var NumberSchema = class _NumberSchema extends Schema {
1396
+ static {
1397
+ __name(this, "NumberSchema");
1398
+ }
1399
+ fieldType = "number";
1400
+ __allowString;
1401
+ __is;
1402
+ __integer;
1403
+ __maxDigits;
1404
+ __decimalPlaces;
1405
+ __max;
1406
+ __min;
1407
+ __type = {
1408
+ message: "Invalid type",
1409
+ check: /* @__PURE__ */ __name((value) => {
1410
+ const isNumber = new RegExp("^-?\\d*(\\.\\d+)?$").test(value);
1411
+ if (typeof value === "string" && this.__allowString && isNumber) return true;
1412
+ return typeof value === "number";
1413
+ }, "check")
1414
+ };
1415
+ async __transformToAdapter(options) {
1416
+ return defaultTransformToAdapter(async (adapter) => {
1417
+ return defaultTransform("number", this, adapter, adapter.number, () => ({
1418
+ is: this.__is,
1419
+ min: this.__min,
1420
+ max: this.__max,
1421
+ integer: this.__integer,
1422
+ optional: this.__optional,
1423
+ nullable: this.__nullable,
1424
+ maxDigits: this.__maxDigits,
1425
+ decimalPlaces: this.__decimalPlaces,
1426
+ type: this.__type,
1427
+ parsers: {
1428
+ allowString: this.__allowString,
1429
+ nullable: this.__nullable.allow,
1430
+ optional: this.__optional.allow
1431
+ }
1432
+ }), {
1433
+ max,
1434
+ min,
1435
+ maxDigits,
1436
+ is,
1437
+ optional,
1438
+ nullable,
1439
+ decimalPlaces,
1440
+ integer
1441
+ }, {
1442
+ validatorsIfFallbackOrNotSupported: numberValidation(),
1443
+ shouldAddStringVersion: options.shouldAddStringVersion,
1444
+ // eslint-disable-next-line ts/require-await
1445
+ fallbackIfNotSupported: /* @__PURE__ */ __name(async () => {
1446
+ return [];
1447
+ }, "fallbackIfNotSupported")
1448
+ });
1449
+ }, this, this.__transformedSchemas, options, "number");
1450
+ }
1451
+ /**
1452
+ * This let's you refine the schema with custom validations. This is useful when you want to validate something
1453
+ * that is not supported by default by the schema adapter.
1454
+ *
1455
+ * @example
1456
+ * ```typescript
1457
+ * import * as p from '@palmares/schemas';
1458
+ *
1459
+ * const numberSchema = p.number().refine((value) => {
1460
+ * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
1461
+ * });
1462
+ *
1463
+ * const { errors, parsed } = await numberSchema.parse(-1);
1464
+ *
1465
+ * console.log(errors);
1466
+ * // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
1467
+ * ```
1468
+ *
1469
+ * @param refinementCallback - The callback that will be called to validate the value.
1470
+ * @param options - Options for the refinement.
1471
+ * @param options.isAsync - Whether the callback is async or not. Defaults to true.
1472
+ *
1473
+ * @returns The schema.
1474
+ */
1475
+ refine(refinementCallback) {
1476
+ return super.refine(refinementCallback);
1477
+ }
1478
+ /**
1479
+ * Allows the value to be either undefined or null.
1480
+ *
1481
+ * @example
1482
+ * ```typescript
1483
+ * import * as p from '@palmares/schemas';
1484
+ *
1485
+ * const numberSchema = p.number().optional();
1486
+ *
1487
+ * const { errors, parsed } = await numberSchema.parse(undefined);
1488
+ *
1489
+ * console.log(parsed); // undefined
1490
+ *
1491
+ * const { errors, parsed } = await numberSchema.parse(null);
1492
+ *
1493
+ * console.log(parsed); // null
1494
+ *
1495
+ * const { errors, parsed } = await numberSchema.parse(1);
1496
+ *
1497
+ * console.log(parsed); // 1
1498
+ * ```
1499
+ *
1500
+ * @returns - The schema we are working with.
1501
+ */
1502
+ optional(options) {
1503
+ return super.optional(options);
1504
+ }
1505
+ /**
1506
+ * Just adds a message when the value is undefined. It's just a syntax sugar for
1507
+ *
1508
+ * ```typescript
1509
+ * p.string().optional({ message: 'This value cannot be null', allow: false })
1510
+ * ```
1511
+ *
1512
+ * @param options - The options of nonOptional function
1513
+ * @param options.message - A custom message if the value is undefined.
1514
+ *
1515
+ * @returns - The schema.
1516
+ */
1517
+ nonOptional(options) {
1518
+ return super.optional({
1519
+ message: options?.message,
1520
+ allow: false
1521
+ });
1522
+ }
1523
+ /**
1524
+ * Allows the value to be null and ONLY null. You can also use this function to set a custom message when the value
1525
+ * is NULL by setting the { message: 'Your custom message', allow: false } on the options.
1526
+ *
1527
+ * @example
1528
+ * ```typescript
1529
+ * import * as p from '@palmares/schemas';
1530
+ *
1531
+ * const numberSchema = p.number().nullable();
1532
+ *
1533
+ * const { errors, parsed } = await numberSchema.parse(null);
1534
+ *
1535
+ * console.log(parsed); // null
1536
+ *
1537
+ * const { errors, parsed } = await numberSchema.parse(undefined);
1538
+ *
1539
+ * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
1540
+ * ```
1541
+ *
1542
+ * @param options - The options for the nullable function.
1543
+ * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
1544
+ * @param options.allow - Whether the value can be null or not. Defaults to true.
1545
+ *
1546
+ * @returns The schema.
1547
+ */
1548
+ nullable(options) {
1549
+ return super.nullable(options);
1550
+ }
1551
+ /**
1552
+ * Just adds a message when the value is null. It's just a syntax sugar for
1553
+ *
1554
+ * ```typescript
1555
+ * p.string().nullable({ message: 'This value cannot be null', allow: false })
1556
+ * ```
1557
+ *
1558
+ * @param options - The options of nonNullable function
1559
+ * @param options.message - A custom message if the value is null.
1560
+ *
1561
+ * @returns - The schema.
1562
+ */
1563
+ nonNullable(options) {
1564
+ return super.nullable({
1565
+ message: options?.message || "",
1566
+ allow: false
1567
+ });
1568
+ }
1569
+ /**
1570
+ * This method will remove the value from the representation of the schema. If the value is undefined it will keep
1571
+ * that way otherwise it will set the value to undefined after it's validated.
1572
+ * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
1573
+ * function. This will remove the value from the representation of the schema.
1574
+ *
1575
+ * By default, the value will be removed just from the representation, in other words, when you call the {@link data}
1576
+ * function.
1577
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
1578
+ * as true. Then if you still want to remove the value from the representation, you will need to pass the argument
1579
+ * `toRepresentation` as true as well.
1580
+ *
1581
+ * @example
1582
+ * ```typescript
1583
+ * import * as p from '@palmares/schemas';
1584
+ *
1585
+ * const userSchema = p.object({
1586
+ * id: p.number().optional(),
1587
+ * name: p.string(),
1588
+ * password: p.string().omit()
1589
+ * });
1590
+ *
1591
+ * const user = await userSchema.data({
1592
+ * id: 1,
1593
+ * name: 'John Doe',
1594
+ * password: '123456'
1595
+ * });
1596
+ *
1597
+ * console.log(user); // { id: 1, name: 'John Doe' }
1598
+ * ```
1599
+ *
1600
+ *
1601
+ * @param args - By default, the value will be removed just from the representation, in other words, when you call
1602
+ * the {@link data} function.
1603
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
1604
+ * as true. Then if you still want to remove the value from the representation, you will need to pass the argument
1605
+ * `toRepresentation` as true as well.
1606
+ *
1607
+ * @returns The schema.
1608
+ */
1609
+ omit(args) {
1610
+ return super.omit(args);
1611
+ }
1612
+ /**
1613
+ * This will allow the value to be a string, it does not validate, it just parses inputs as strings and allows the
1614
+ * result to be a string as well.
1615
+ *
1616
+ * @example
1617
+ * ```ts
1618
+ * number().allowString().parse('true') // true
1619
+ * ```
1620
+ *
1621
+ * @returns - The schema instance
1622
+ */
1623
+ allowString() {
1624
+ this.__allowString = true;
1625
+ this.__parsers.low.set("allowString", convertFromStringBuilder((value) => {
1626
+ return {
1627
+ value: Number(value),
1628
+ preventNextParsers: false
1629
+ };
1630
+ }));
1631
+ return this;
1632
+ }
1633
+ /**
1634
+ * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external
1635
+ * source like a database. You should always return the schema after you save the value, that way we will always
1636
+ * have the correct type of the schema after the save operation.
1637
+ *
1638
+ * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
1639
+ *
1640
+ * @example
1641
+ * ```typescript
1642
+ * import * as p from '@palmares/schemas';
1643
+ *
1644
+ * import { User } from './models';
1645
+ *
1646
+ * const userSchema = p.object({
1647
+ * id: p.number().optional(),
1648
+ * name: p.string(),
1649
+ * email: p.string().email(),
1650
+ * }).onSave(async (value) => {
1651
+ * // Create or update the user on the database using palmares models or any other library of your choice.
1652
+ * if (value.id)
1653
+ * await User.default.set(value, { search: { id: value.id } });
1654
+ * else
1655
+ * await User.default.set(value);
1656
+ *
1657
+ * return value;
1658
+ * });
1659
+ *
1660
+ *
1661
+ * // Then, on your controller, do something like this:
1662
+ * const { isValid, save, errors } = await userSchema.validate(req.body);
1663
+ * if (isValid) {
1664
+ * const savedValue = await save();
1665
+ * return Response.json(savedValue, { status: 201 });
1666
+ * }
1667
+ *
1668
+ * return Response.json({ errors }, { status: 400 });
1669
+ * ```
1670
+ *
1671
+ * @param callback - The callback that will be called to save the value on an external source.
1672
+ *
1673
+ * @returns The schema.
1674
+ */
1675
+ onSave(callback) {
1676
+ return super.onSave(callback);
1677
+ }
1678
+ /**
1679
+ * This function is used to add a default value to the schema. If the value is either undefined or null, the default
1680
+ * value will be used.
1681
+ *
1682
+ * @example
1683
+ * ```typescript
1684
+ * import * as p from '@palmares/schemas';
1685
+ *
1686
+ * const numberSchema = p.number().default(0);
1687
+ *
1688
+ * const { errors, parsed } = await numberSchema.parse(undefined);
1689
+ *
1690
+ * console.log(parsed); // 0
1691
+ * ```
1692
+ */
1693
+ default(defaultValueOrFunction) {
1694
+ return super.default(defaultValueOrFunction);
1695
+ }
1696
+ /**
1697
+ * This function let's you customize the schema your own way. After we translate the schema on the adapter we call
1698
+ * this function to let you customize the custom schema your own way. Our API does not support passthrough?
1699
+ * No problem, you can use this function to customize the zod schema.
1700
+ *
1701
+ * @example
1702
+ * ```typescript
1703
+ * import * as p from '@palmares/schemas';
1704
+ *
1705
+ * const numberSchema = p.number().extends((schema) => {
1706
+ * return schema.nonnegative();
1707
+ * });
1708
+ *
1709
+ * const { errors, parsed } = await numberSchema.parse(-1);
1710
+ *
1711
+ * console.log(errors);
1712
+ * // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
1713
+ * ```
1714
+ *
1715
+ * @param callback - The callback that will be called to customize the schema.
1716
+ * @param toStringCallback - The callback that will be called to transform the schema to a string when you
1717
+ * want to compile the underlying schema to a string so you can save it for future runs.
1718
+ *
1719
+ * @returns The schema.
1720
+ */
1721
+ extends(callback, toStringCallback) {
1722
+ return super.extends(callback, toStringCallback);
1723
+ }
1724
+ /**
1725
+ * This function is used to transform the value to the representation of the schema. When using the {@link data}
1726
+ * function. With this function you have full control to add data cleaning for example, transforming the data and
1727
+ * whatever. Another use case is when you want to return deeply nested recursive data.
1728
+ * The schema maps to itself.
1729
+ *
1730
+ * @example
1731
+ * ```typescript
1732
+ * import * as p from '@palmares/schemas';
1733
+ *
1734
+ * const recursiveSchema = p.object({
1735
+ * id: p.number().optional(),
1736
+ * name: p.string(),
1737
+ * }).toRepresentation(async (value) => {
1738
+ * return {
1739
+ * id: value.id,
1740
+ * name: value.name,
1741
+ * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
1742
+ * }
1743
+ * });
1744
+ *
1745
+ * const data = await recursiveSchema.data({
1746
+ * id: 1,
1747
+ * name: 'John Doe',
1748
+ * });
1749
+ * ```
1750
+ *
1751
+ * @example
1752
+ * ```
1753
+ * import * as p from '@palmares/schemas';
1754
+ *
1755
+ * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
1756
+ * switch (value) {
1757
+ * case 'red': return { r: 255, g: 0, b: 0 };
1758
+ * case 'green': return { r: 0, g: 255, b: 0 };
1759
+ * case 'blue': return { r: 0, g: 0, b: 255 };
1760
+ * default: return { r: 0, g: 0, b: 0 };
1761
+ * }
1762
+ * });
1763
+ * ```
1764
+ * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
1765
+ *
1766
+ * @returns The schema with a new return type
1767
+ */
1768
+ toRepresentation(toRepresentationCallback) {
1769
+ return super.toRepresentation(toRepresentationCallback);
1770
+ }
1771
+ /**
1772
+ * This function is used to transform the value to the internal representation of the schema. This is useful when
1773
+ * you want to transform the value to a type that the schema adapter can understand. For example, you might want
1774
+ * to transform a string to a date. This is the function you use.
1775
+ *
1776
+ * @example
1777
+ * ```typescript
1778
+ * import * as p from '@palmares/schemas';
1779
+ *
1780
+ * const dateSchema = p.string().toInternal((value) => {
1781
+ * return new Date(value);
1782
+ * });
1783
+ *
1784
+ * const date = await dateSchema.parse('2021-01-01');
1785
+ *
1786
+ * console.log(date); // Date object
1787
+ *
1788
+ * const rgbToColorSchema = p.object({
1789
+ * r: p.number().min(0).max(255),
1790
+ * g: p.number().min(0).max(255),
1791
+ * b: p.number().min(0).max(255),
1792
+ * }).toInternal(async (value) => {
1793
+ * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
1794
+ * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
1795
+ * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
1796
+ * return `rgb(${value.r}, ${value.g}, ${value.b})`;
1797
+ * });
1798
+ * ```
1799
+ *
1800
+ * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
1801
+ *
1802
+ * @returns The schema with a new return type.
1803
+ */
1804
+ toInternal(toInternalCallback) {
1805
+ return super.toInternal(toInternalCallback);
1806
+ }
1807
+ /**
1808
+ * Called before the validation of the schema. Let's say that you want to validate a date that might receive a string,
1809
+ * you can convert that string to a date
1810
+ * here BEFORE the validation. This pretty much transforms the value to a type that the schema adapter can understand.
1811
+ *
1812
+ * @example
1813
+ * ```
1814
+ * import * as p from '@palmares/schemas';
1815
+ * import * as z from 'zod';
1816
+ *
1817
+ * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
1818
+ * return new Map(value); // Before validating we transform the value to a map.
1819
+ * });
1820
+ *
1821
+ * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
1822
+ * ```
1823
+ *
1824
+ * @param toValidateCallback - The callback that will be called to validate the value.
1825
+ *
1826
+ * @returns The schema with a new return type.
1827
+ */
1828
+ toValidate(toValidateCallback) {
1829
+ return super.toValidate(toValidateCallback);
1830
+ }
1831
+ /**
1832
+ * Defines a list of numbers that are allowed, it's not a range but the actual numbers that are allowed, it's useful
1833
+ * when you want to allow only specific set of numbers.
1834
+ *
1835
+ * @example
1836
+ * ```typescript
1837
+ * import * as p from '@palmares/schema';
1838
+ *
1839
+ * const schema = p.number().is([1, 2, 3]);
1840
+ *
1841
+ * schema.parse(1); // { errors: [], parsed: 1 }
1842
+ * schema.parse(2); // { errors: [], parsed: 2 }
1843
+ * schema.parse(3); // { errors: [], parsed: 3 }
1844
+ * schema.parse(4); // { errors: [{ code: 'is', message: 'The value should be equal to 1,2,3' }], parsed: 4 }
1845
+ * ```
1846
+ *
1847
+ * @param value - The list of numbers that are allowed
1848
+ *
1849
+ * @returns - The schema instance
1850
+ */
1851
+ is(value, options) {
1852
+ this.__is = {
1853
+ value,
1854
+ message: typeof options?.message === "string" ? options.message : `The value should be equal to ${value.join(",")}`
1855
+ };
1856
+ return this;
1857
+ }
1858
+ /**
1859
+ * Allows only numbers that are less than the value passed. If you want to allow the number to be equal to the value,
1860
+ * you can pass the option `inclusive` as `true`.
1861
+ * Otherwise, it will only allow numbers less than the value.
1862
+ *
1863
+ * @example
1864
+ * ```typescript
1865
+ * import * as p from '@palmares/schema';
1866
+ *
1867
+ * const schema = p.number().max(10);
1868
+ *
1869
+ * schema.parse(10); // { errors: [{ code: 'max', message: 'The number should be less than 10' }], parsed: 10 }
1870
+ * schema.parse(9); // { errors: [], parsed: 9 }
1871
+ *
1872
+ * const schema = p.number().max(10, { inclusive: true });
1873
+ *
1874
+ * schema.parse(10); // { errors: [], parsed: 10 }
1875
+ * ```
1876
+ *
1877
+ * @param value - The value to compare with the number
1878
+ * @param options - The options to be passed to the validation
1879
+ * @param options.inclusive - If you want to allow the number to be equal to the value, you can pass this option
1880
+ * @param options.message - The message to be returned if the validation fails
1881
+ *
1882
+ * @returns - The schema instance
1883
+ */
1884
+ max(value, options) {
1885
+ const inclusive = typeof options?.inclusive === "boolean" ? options.inclusive : false;
1886
+ const message = typeof options?.message === "string" ? options.message : DEFAULT_NUMBER_MAX_EXCEPTION(value, inclusive);
1887
+ this.__max = {
1888
+ value,
1889
+ inclusive,
1890
+ message
1891
+ };
1892
+ return this;
1893
+ }
1894
+ /**
1895
+ * This method will validate if the number is greater than the value passed. If you want to allow the number to be
1896
+ * equal to the value, you can pass the option `inclusive` as `true`.
1897
+ * Otherwise, it will only allow numbers greater than the value.
1898
+ *
1899
+ * @example
1900
+ * ```typescript
1901
+ * import * as p from '@palmares/schema';
1902
+ *
1903
+ * const schema = p.number().min(10);
1904
+ *
1905
+ * schema.parse(10); // { errors: [], parsed: 10 }
1906
+ * schema.parse(9); // { errors: [{ code: 'min', message: 'The number should be greater than 10' }], parsed: 9 }
1907
+ *
1908
+ * const schema = p.number().min(10, { inclusive: true });
1909
+ *
1910
+ * schema.parse(10); // { errors: [], parsed: 10 }
1911
+ * ```
1912
+ *
1913
+ * @param value - The value to compare with the number
1914
+ * @param options - The options to be passed to the validation
1915
+ * @param options.inclusive - If you want to allow the number to be equal to the value, you can pass this option
1916
+ * @param options.message - The message to be returned if the validation fails
1917
+ *
1918
+ * @returns - The schema instance
1919
+ */
1920
+ min(value, options) {
1921
+ const inclusive = typeof options?.inclusive === "boolean" ? options.inclusive : false;
1922
+ const message = typeof options?.message === "string" ? options.message : DEFAULT_NUMBER_MIN_EXCEPTION(value, inclusive);
1923
+ this.__min = {
1924
+ value,
1925
+ inclusive,
1926
+ message
1927
+ };
1928
+ return this;
1929
+ }
1930
+ /**
1931
+ * This method will validate the number to have the exact number of decimal places. It's usually useful for decimal
1932
+ * numbers like currencies.
1933
+ *
1934
+ * @example
1935
+ * ```
1936
+ * const schema = number().decimalPlaces(2);
1937
+ *
1938
+ * schema.parse(10.00); // { errors: [], parsed: 10.00}
1939
+ *
1940
+ * schema.parse(10.000);
1941
+ * // { errors: [{ code: 'decimal_places', message: 'The number should have 2 decimal places' }], parsed: 10.000}
1942
+ * ```
1943
+ *
1944
+ * @param value - The number of decimal places.
1945
+ * @param options - The options.
1946
+ * @param options.message - The message to show if the validation fails.
1947
+ *
1948
+ * @returns The schema so you can chain other methods.
1949
+ */
1950
+ decimalPlaces(value, options) {
1951
+ const message = typeof options?.message === "string" ? options.message : `The number should have ${value} decimal places`;
1952
+ this.__decimalPlaces = {
1953
+ value,
1954
+ message
1955
+ };
1956
+ return this;
1957
+ }
1958
+ /**
1959
+ * This method will validate the number to have at most the number of digits specified. If used in conjunction with
1960
+ * {@link decimalPlaces}, this number should be bigger than the value of the decimal places.
1961
+ *
1962
+ * Think about that
1963
+ *
1964
+ * - If you have a number with 2 decimal places, the number 10.00 has 4 digits and 2 decimal places.
1965
+ * - The number 10.000 has 5 digits and 3 decimal places.
1966
+ *
1967
+ * @example
1968
+ * ```
1969
+ * const schema = number().maxDigits(4);
1970
+ *
1971
+ * schema.parse(10); // { errors: [], parsed: 10}
1972
+ * schema.parse(100); // { errors: [], parsed: 100}
1973
+ * schema.parse(1000); // { errors: [], parsed: 1000}
1974
+ * ```
1975
+ *
1976
+ * @param value - The maximum number of digits, counting the digits before and after the decimal point.
1977
+ * @param options - Custom options for the validation.
1978
+ * @param options.message - The message to show if the validation fails.
1979
+ *
1980
+ * @returns - The schema so you can chain other methods.
1981
+ */
1982
+ maxDigits(value, options) {
1983
+ const message = typeof options?.message === "string" ? options.message : `The number should have at most ${value} digits`;
1984
+ this.__maxDigits = {
1985
+ value,
1986
+ message
1987
+ };
1988
+ return this;
1989
+ }
1990
+ /**
1991
+ * With this method we will validate if the number is an integer. If it's not, we will return an error.
1992
+ *
1993
+ * @example
1994
+ * ```typescript
1995
+ * import * as p from '@palmares/schema';
1996
+ *
1997
+ * const schema = p.number().integer();
1998
+ *
1999
+ * schema.parse(10); // { errors: [], parsed: 10 }
2000
+ * schema.parse(10.1); // { errors: [{ code: 'integer', message: 'The number should be an integer' }], parsed: 10.1 }
2001
+ * ```
2002
+ *
2003
+ * @param options - The options to be passed to the validation
2004
+ * @param options.message - The message to be returned if the validation fails
2005
+ *
2006
+ * @returns - The schema instance
2007
+ */
2008
+ integer(options) {
2009
+ const message = typeof options?.message === "string" ? options.message : DEFAULT_NUMBER_INTEGER_EXCEPTION();
2010
+ this.__integer = {
2011
+ message
2012
+ };
2013
+ return this;
2014
+ }
2015
+ static new() {
2016
+ const returnValue = new _NumberSchema();
2017
+ return returnValue;
2018
+ }
2019
+ };
2020
+
2021
+ // src/schema/index.ts
2022
+ var number = NumberSchema.new;
2023
+ // Annotate the CommonJS export names for ESM import in node:
2024
+ 0 && (module.exports = {
2025
+ number
2026
+ });