@palmares/schemas 0.1.25 → 0.2.0

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