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