@palmares/schemas 0.0.1

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 (219) hide show
  1. package/.turbo/turbo-build$colon$watch.log +424 -0
  2. package/.turbo/turbo-build.log +13 -0
  3. package/.turbo/turbo-build:watch.log +26 -0
  4. package/CHANGELOG.md +11 -0
  5. package/LICENSE +21 -0
  6. package/dist/cjs/src/adapter/fields/array.js +157 -0
  7. package/dist/cjs/src/adapter/fields/boolean.js +167 -0
  8. package/dist/cjs/src/adapter/fields/datetime.js +167 -0
  9. package/dist/cjs/src/adapter/fields/index.js +311 -0
  10. package/dist/cjs/src/adapter/fields/number.js +167 -0
  11. package/dist/cjs/src/adapter/fields/object.js +167 -0
  12. package/dist/cjs/src/adapter/fields/string.js +167 -0
  13. package/dist/cjs/src/adapter/fields/union.js +167 -0
  14. package/dist/cjs/src/adapter/index.js +198 -0
  15. package/dist/cjs/src/adapter/types.js +4 -0
  16. package/dist/cjs/src/compile.js +262 -0
  17. package/dist/cjs/src/conf.js +27 -0
  18. package/dist/cjs/src/constants.js +42 -0
  19. package/dist/cjs/src/domain.js +12 -0
  20. package/dist/cjs/src/exceptions.js +168 -0
  21. package/dist/cjs/src/index.js +365 -0
  22. package/dist/cjs/src/model.js +628 -0
  23. package/dist/cjs/src/parsers/convert-from-number.js +20 -0
  24. package/dist/cjs/src/parsers/convert-from-string.js +24 -0
  25. package/dist/cjs/src/parsers/index.js +25 -0
  26. package/dist/cjs/src/schema/array.js +890 -0
  27. package/dist/cjs/src/schema/boolean.js +826 -0
  28. package/dist/cjs/src/schema/datetime.js +778 -0
  29. package/dist/cjs/src/schema/index.js +17 -0
  30. package/dist/cjs/src/schema/number.js +960 -0
  31. package/dist/cjs/src/schema/object.js +999 -0
  32. package/dist/cjs/src/schema/schema.js +1788 -0
  33. package/dist/cjs/src/schema/string.js +948 -0
  34. package/dist/cjs/src/schema/types.js +4 -0
  35. package/dist/cjs/src/schema/union.js +952 -0
  36. package/dist/cjs/src/types.js +4 -0
  37. package/dist/cjs/src/utils.js +627 -0
  38. package/dist/cjs/src/validators/array.js +457 -0
  39. package/dist/cjs/src/validators/boolean.js +199 -0
  40. package/dist/cjs/src/validators/datetime.js +287 -0
  41. package/dist/cjs/src/validators/number.js +403 -0
  42. package/dist/cjs/src/validators/object.js +290 -0
  43. package/dist/cjs/src/validators/schema.js +318 -0
  44. package/dist/cjs/src/validators/string.js +439 -0
  45. package/dist/cjs/src/validators/types.js +4 -0
  46. package/dist/cjs/src/validators/union.js +232 -0
  47. package/dist/cjs/src/validators/utils.js +426 -0
  48. package/dist/cjs/tsconfig.types.tsbuildinfo +1 -0
  49. package/dist/cjs/types/adapter/fields/array.d.ts +20 -0
  50. package/dist/cjs/types/adapter/fields/array.d.ts.map +1 -0
  51. package/dist/cjs/types/adapter/fields/boolean.d.ts +25 -0
  52. package/dist/cjs/types/adapter/fields/boolean.d.ts.map +1 -0
  53. package/dist/cjs/types/adapter/fields/datetime.d.ts +25 -0
  54. package/dist/cjs/types/adapter/fields/datetime.d.ts.map +1 -0
  55. package/dist/cjs/types/adapter/fields/index.d.ts +31 -0
  56. package/dist/cjs/types/adapter/fields/index.d.ts.map +1 -0
  57. package/dist/cjs/types/adapter/fields/number.d.ts +25 -0
  58. package/dist/cjs/types/adapter/fields/number.d.ts.map +1 -0
  59. package/dist/cjs/types/adapter/fields/object.d.ts +25 -0
  60. package/dist/cjs/types/adapter/fields/object.d.ts.map +1 -0
  61. package/dist/cjs/types/adapter/fields/string.d.ts +25 -0
  62. package/dist/cjs/types/adapter/fields/string.d.ts.map +1 -0
  63. package/dist/cjs/types/adapter/fields/union.d.ts +25 -0
  64. package/dist/cjs/types/adapter/fields/union.d.ts.map +1 -0
  65. package/dist/cjs/types/adapter/index.d.ts +25 -0
  66. package/dist/cjs/types/adapter/index.d.ts.map +1 -0
  67. package/dist/cjs/types/adapter/types.d.ts +144 -0
  68. package/dist/cjs/types/adapter/types.d.ts.map +1 -0
  69. package/dist/cjs/types/compile.d.ts +3 -0
  70. package/dist/cjs/types/compile.d.ts.map +1 -0
  71. package/dist/cjs/types/conf.d.ts +16 -0
  72. package/dist/cjs/types/conf.d.ts.map +1 -0
  73. package/dist/cjs/types/constants.d.ts +6 -0
  74. package/dist/cjs/types/constants.d.ts.map +1 -0
  75. package/dist/cjs/types/domain.d.ts +21 -0
  76. package/dist/cjs/types/domain.d.ts.map +1 -0
  77. package/dist/cjs/types/exceptions.d.ts +13 -0
  78. package/dist/cjs/types/exceptions.d.ts.map +1 -0
  79. package/dist/cjs/types/index.d.ts +240 -0
  80. package/dist/cjs/types/index.d.ts.map +1 -0
  81. package/dist/cjs/types/model.d.ts +136 -0
  82. package/dist/cjs/types/model.d.ts.map +1 -0
  83. package/dist/cjs/types/parsers/convert-from-number.d.ts +15 -0
  84. package/dist/cjs/types/parsers/convert-from-number.d.ts.map +1 -0
  85. package/dist/cjs/types/parsers/convert-from-string.d.ts +9 -0
  86. package/dist/cjs/types/parsers/convert-from-string.d.ts.map +1 -0
  87. package/dist/cjs/types/parsers/index.d.ts +3 -0
  88. package/dist/cjs/types/parsers/index.d.ts.map +1 -0
  89. package/dist/cjs/types/schema/array.d.ts +429 -0
  90. package/dist/cjs/types/schema/array.d.ts.map +1 -0
  91. package/dist/cjs/types/schema/boolean.d.ts +501 -0
  92. package/dist/cjs/types/schema/boolean.d.ts.map +1 -0
  93. package/dist/cjs/types/schema/datetime.d.ts +474 -0
  94. package/dist/cjs/types/schema/datetime.d.ts.map +1 -0
  95. package/dist/cjs/types/schema/index.d.ts +4 -0
  96. package/dist/cjs/types/schema/index.d.ts.map +1 -0
  97. package/dist/cjs/types/schema/number.d.ts +667 -0
  98. package/dist/cjs/types/schema/number.d.ts.map +1 -0
  99. package/dist/cjs/types/schema/object.d.ts +450 -0
  100. package/dist/cjs/types/schema/object.d.ts.map +1 -0
  101. package/dist/cjs/types/schema/schema.d.ts +646 -0
  102. package/dist/cjs/types/schema/schema.d.ts.map +1 -0
  103. package/dist/cjs/types/schema/string.d.ts +606 -0
  104. package/dist/cjs/types/schema/string.d.ts.map +1 -0
  105. package/dist/cjs/types/schema/types.d.ts +70 -0
  106. package/dist/cjs/types/schema/types.d.ts.map +1 -0
  107. package/dist/cjs/types/schema/union.d.ts +388 -0
  108. package/dist/cjs/types/schema/union.d.ts.map +1 -0
  109. package/dist/cjs/types/types.d.ts +11 -0
  110. package/dist/cjs/types/types.d.ts.map +1 -0
  111. package/dist/cjs/types/utils.d.ts +79 -0
  112. package/dist/cjs/types/utils.d.ts.map +1 -0
  113. package/dist/cjs/types/validators/array.d.ts +8 -0
  114. package/dist/cjs/types/validators/array.d.ts.map +1 -0
  115. package/dist/cjs/types/validators/boolean.d.ts +4 -0
  116. package/dist/cjs/types/validators/boolean.d.ts.map +1 -0
  117. package/dist/cjs/types/validators/datetime.d.ts +7 -0
  118. package/dist/cjs/types/validators/datetime.d.ts.map +1 -0
  119. package/dist/cjs/types/validators/number.d.ts +10 -0
  120. package/dist/cjs/types/validators/number.d.ts.map +1 -0
  121. package/dist/cjs/types/validators/object.d.ts +6 -0
  122. package/dist/cjs/types/validators/object.d.ts.map +1 -0
  123. package/dist/cjs/types/validators/schema.d.ts +10 -0
  124. package/dist/cjs/types/validators/schema.d.ts.map +1 -0
  125. package/dist/cjs/types/validators/string.d.ts +12 -0
  126. package/dist/cjs/types/validators/string.d.ts.map +1 -0
  127. package/dist/cjs/types/validators/types.d.ts +2 -0
  128. package/dist/cjs/types/validators/types.d.ts.map +1 -0
  129. package/dist/cjs/types/validators/union.d.ts +4 -0
  130. package/dist/cjs/types/validators/union.d.ts.map +1 -0
  131. package/dist/cjs/types/validators/utils.d.ts +83 -0
  132. package/dist/cjs/types/validators/utils.d.ts.map +1 -0
  133. package/dist/esm/src/adapter/fields/array.js +13 -0
  134. package/dist/esm/src/adapter/fields/boolean.js +20 -0
  135. package/dist/esm/src/adapter/fields/datetime.js +20 -0
  136. package/dist/esm/src/adapter/fields/index.js +37 -0
  137. package/dist/esm/src/adapter/fields/number.js +20 -0
  138. package/dist/esm/src/adapter/fields/object.js +20 -0
  139. package/dist/esm/src/adapter/fields/string.js +20 -0
  140. package/dist/esm/src/adapter/fields/union.js +20 -0
  141. package/dist/esm/src/adapter/index.js +18 -0
  142. package/dist/esm/src/adapter/types.js +1 -0
  143. package/dist/esm/src/compile.js +10 -0
  144. package/dist/esm/src/conf.js +19 -0
  145. package/dist/esm/src/constants.js +5 -0
  146. package/dist/esm/src/domain.js +2 -0
  147. package/dist/esm/src/exceptions.js +15 -0
  148. package/dist/esm/src/index.js +160 -0
  149. package/dist/esm/src/model.js +255 -0
  150. package/dist/esm/src/parsers/convert-from-number.js +8 -0
  151. package/dist/esm/src/parsers/convert-from-string.js +14 -0
  152. package/dist/esm/src/parsers/index.js +2 -0
  153. package/dist/esm/src/schema/array.js +403 -0
  154. package/dist/esm/src/schema/boolean.js +465 -0
  155. package/dist/esm/src/schema/datetime.js +423 -0
  156. package/dist/esm/src/schema/index.js +3 -0
  157. package/dist/esm/src/schema/number.js +592 -0
  158. package/dist/esm/src/schema/object.js +464 -0
  159. package/dist/esm/src/schema/schema.js +728 -0
  160. package/dist/esm/src/schema/string.js +579 -0
  161. package/dist/esm/src/schema/types.js +1 -0
  162. package/dist/esm/src/schema/union.js +388 -0
  163. package/dist/esm/src/types.js +1 -0
  164. package/dist/esm/src/utils.js +175 -0
  165. package/dist/esm/src/validators/array.js +135 -0
  166. package/dist/esm/src/validators/boolean.js +35 -0
  167. package/dist/esm/src/validators/datetime.js +85 -0
  168. package/dist/esm/src/validators/number.js +162 -0
  169. package/dist/esm/src/validators/object.js +38 -0
  170. package/dist/esm/src/validators/schema.js +114 -0
  171. package/dist/esm/src/validators/string.js +174 -0
  172. package/dist/esm/src/validators/types.js +1 -0
  173. package/dist/esm/src/validators/union.js +38 -0
  174. package/dist/esm/src/validators/utils.js +120 -0
  175. package/package.json +48 -0
  176. package/src/adapter/fields/array.ts +31 -0
  177. package/src/adapter/fields/boolean.ts +48 -0
  178. package/src/adapter/fields/datetime.ts +49 -0
  179. package/src/adapter/fields/index.ts +72 -0
  180. package/src/adapter/fields/number.ts +49 -0
  181. package/src/adapter/fields/object.ts +49 -0
  182. package/src/adapter/fields/string.ts +49 -0
  183. package/src/adapter/fields/union.ts +49 -0
  184. package/src/adapter/index.ts +34 -0
  185. package/src/adapter/types.ts +261 -0
  186. package/src/compile.ts +14 -0
  187. package/src/conf.ts +27 -0
  188. package/src/constants.ts +9 -0
  189. package/src/domain.ts +3 -0
  190. package/src/exceptions.ts +17 -0
  191. package/src/index.ts +338 -0
  192. package/src/model.ts +501 -0
  193. package/src/parsers/convert-from-number.ts +13 -0
  194. package/src/parsers/convert-from-string.ts +19 -0
  195. package/src/parsers/index.ts +2 -0
  196. package/src/schema/array.ts +633 -0
  197. package/src/schema/boolean.ts +700 -0
  198. package/src/schema/datetime.ts +613 -0
  199. package/src/schema/index.ts +5 -0
  200. package/src/schema/number.ts +885 -0
  201. package/src/schema/object.ts +699 -0
  202. package/src/schema/schema.ts +1093 -0
  203. package/src/schema/string.ts +807 -0
  204. package/src/schema/types.ts +126 -0
  205. package/src/schema/union.ts +596 -0
  206. package/src/types.ts +13 -0
  207. package/src/utils.ts +322 -0
  208. package/src/validators/array.ts +164 -0
  209. package/src/validators/boolean.ts +46 -0
  210. package/src/validators/datetime.ts +113 -0
  211. package/src/validators/number.ts +188 -0
  212. package/src/validators/object.ts +55 -0
  213. package/src/validators/schema.ts +134 -0
  214. package/src/validators/string.ts +215 -0
  215. package/src/validators/types.ts +1 -0
  216. package/src/validators/union.ts +52 -0
  217. package/src/validators/utils.ts +200 -0
  218. package/tsconfig.json +9 -0
  219. package/tsconfig.types.json +10 -0
@@ -0,0 +1,596 @@
1
+
2
+ import Schema from './schema';
3
+ import { getDefaultAdapter } from '../conf';
4
+ import {
5
+ defaultTransform,
6
+ defaultTransformToAdapter,
7
+ transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas,
8
+ } from '../utils';
9
+ import { unionValidation } from '../validators/union';
10
+ import Validator from '../validators/utils';
11
+
12
+ import type { DefinitionsOfSchemaType } from './types';
13
+ import type FieldAdapter from '../adapter/fields';
14
+ import type { Narrow } from '@palmares/core';
15
+
16
+ export default class UnionSchema<
17
+ TType extends {
18
+ input: any;
19
+ validate: any;
20
+ internal: any;
21
+ representation: any;
22
+ output: any;
23
+ } = {
24
+ input: Record<any, any>;
25
+ output: Record<any, any>;
26
+ validate: Record<any, any>;
27
+ internal: Record<any, any>;
28
+ representation: Record<any, any>;
29
+ },
30
+ TDefinitions extends DefinitionsOfSchemaType = DefinitionsOfSchemaType,
31
+ TSchemas extends readonly [Schema<any, any>, Schema<any, any>, ...Schema<any, any>[]] = [
32
+ Schema<any, any>,
33
+ Schema<any, any>,
34
+ ...Schema<any, any>[],
35
+ ],
36
+ > extends Schema<TType, TDefinitions> {
37
+ protected __schemas = new Set<Schema<any>>();
38
+
39
+ constructor(schemas: TSchemas) {
40
+ super();
41
+ this.__schemas = new Set(schemas);
42
+ }
43
+
44
+ protected async _transformToAdapter(
45
+ options: Parameters<Schema['__transformToAdapter']>[0]
46
+ ): Promise<ReturnType<FieldAdapter['translate']>> {
47
+ return await defaultTransformToAdapter(
48
+ async (adapter) => {
49
+ const promises: Promise<any>[] = [];
50
+ const shouldBeHighPriorityFallback = adapter.union === undefined;
51
+ const transformedSchemasAsString: string[] = [];
52
+ const transformedSchemas: any[] = [];
53
+ let shouldBeHandledByFallback = shouldBeHighPriorityFallback;
54
+
55
+ for (const schemaToTransform of this.__schemas.values()) {
56
+ const awaitableTransformer = async () => {
57
+ const [transformedData, shouldAddFallbackValidationForThisKey] =
58
+ await transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas(schemaToTransform, options);
59
+ if (shouldAddFallbackValidationForThisKey) shouldBeHandledByFallback = true;
60
+
61
+ for (const transformedSchema of transformedData) {
62
+ transformedSchemasAsString.push(transformedSchema.asString);
63
+ transformedSchemas.push(transformedSchema.transformed);
64
+ }
65
+ };
66
+ promises.push(awaitableTransformer());
67
+ }
68
+
69
+ if (shouldBeHandledByFallback) {
70
+ Validator.createAndAppendFallback(
71
+ this,
72
+ unionValidation(
73
+ Array.from(this.__schemas) as unknown as readonly [
74
+ Schema<any, any>,
75
+ Schema<any, any>,
76
+ ...Schema<any, any>[],
77
+ ]
78
+ ),
79
+ {
80
+ at: 0,
81
+ removeCurrent: true,
82
+ }
83
+ );
84
+ }
85
+
86
+ await Promise.all(promises);
87
+ return defaultTransform(
88
+ 'union',
89
+ this,
90
+ adapter,
91
+ adapter.union,
92
+ (isStringVersion) => ({
93
+ nullable: this.__nullable,
94
+ optional: this.__optional,
95
+ schemas: isStringVersion ? transformedSchemasAsString : transformedSchemas,
96
+ parsers: {
97
+ nullable: this.__nullable.allow,
98
+ optional: this.__optional.allow,
99
+ },
100
+ }),
101
+ {},
102
+ {
103
+ shouldAddStringVersion: options.shouldAddStringVersion,
104
+ fallbackIfNotSupported: async () => {
105
+ if (options.appendFallbacksBeforeAdapterValidation)
106
+ options.appendFallbacksBeforeAdapterValidation(
107
+ 'union',
108
+ async (adapter, fieldAdapter, schema, translatedSchemas, value, path, options) => {
109
+ const parsedValues = {
110
+ parsed: value,
111
+ errors: [],
112
+ } as { parsed: any; errors: any[] };
113
+ // const initialErrorsAsHashedSet = new Set(Array.from(options.errorsAsHashedSet || []));
114
+ for (const translatedSchema of translatedSchemas) {
115
+ //options.errorsAsHashedSet = initialErrorsAsHashedSet;
116
+ const { parsed, errors } = await schema.__validateByAdapter(
117
+ adapter,
118
+ fieldAdapter,
119
+ translatedSchema,
120
+ value,
121
+ path,
122
+ options
123
+ );
124
+
125
+ // eslint-disable-next-line ts/no-unnecessary-condition
126
+ if ((errors || []).length <= 0) return { parsed, errors };
127
+ else {
128
+ parsedValues.parsed = parsed;
129
+ // eslint-disable-next-line ts/no-unnecessary-condition
130
+ parsedValues.errors = (parsedValues.errors || []).concat(errors || []);
131
+ }
132
+ }
133
+ return parsedValues;
134
+ }
135
+ );
136
+
137
+ const transformedSchemasAsPromises = [];
138
+ for (const schema of this.__schemas)
139
+ transformedSchemasAsPromises.push((schema as any).__transformToAdapter(options));
140
+
141
+ console.log((await Promise.all(transformedSchemasAsPromises)).flat());
142
+ return (await Promise.all(transformedSchemasAsPromises)).flat();
143
+ },
144
+ }
145
+ );
146
+ },
147
+ this.__transformedSchemas,
148
+ options,
149
+ 'union'
150
+ );
151
+ }
152
+
153
+ /**
154
+ * This let's you refine the schema with custom validations. This is useful when you want to validate something that is not supported by default by the schema adapter.
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * import * as p from '@palmares/schemas';
159
+ *
160
+ * const numberSchema = p.number().refine((value) => {
161
+ * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
162
+ * });
163
+ *
164
+ * const { errors, parsed } = await numberSchema.parse(-1);
165
+ *
166
+ * console.log(errors); // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
167
+ * ```
168
+ *
169
+ * @param refinementCallback - The callback that will be called to validate the value.
170
+ * @param options - Options for the refinement.
171
+ * @param options.isAsync - Whether the callback is async or not. Defaults to true.
172
+ */
173
+ refine(
174
+ refinementCallback: (value: TType['input']) => Promise<void | undefined | { code: string; message: string }> | void | undefined | { code: string; message: string }
175
+ ) {
176
+ return super.refine(refinementCallback) as unknown as UnionSchema<
177
+ {
178
+ input: TType['input'];
179
+ validate: TType['validate'];
180
+ internal: TType['internal'];
181
+ output: TType['output'];
182
+ representation: TType['representation'];
183
+ },
184
+ TDefinitions,
185
+ TSchemas
186
+ >;
187
+ }
188
+
189
+ /**
190
+ * Allows the value to be either undefined or null.
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * import * as p from '@palmares/schemas';
195
+ *
196
+ * const numberSchema = p.number().optional();
197
+ *
198
+ * const { errors, parsed } = await numberSchema.parse(undefined);
199
+ *
200
+ * console.log(parsed); // undefined
201
+ *
202
+ * const { errors, parsed } = await numberSchema.parse(null);
203
+ *
204
+ * console.log(parsed); // null
205
+ *
206
+ * const { errors, parsed } = await numberSchema.parse(1);
207
+ *
208
+ * console.log(parsed); // 1
209
+ * ```
210
+ *
211
+ * @returns - The schema we are working with.
212
+ */
213
+ optional(options?: { message: string; allow: false }) {
214
+ return super.optional(options) as unknown as UnionSchema<
215
+ {
216
+ input: TType['input'] | undefined | null;
217
+ validate: TType['validate'] | undefined | null;
218
+ internal: TType['internal'] | undefined | null;
219
+ output: TType['output'] | undefined | null;
220
+ representation: TType['representation'] | undefined | null;
221
+ },
222
+ TDefinitions,
223
+ TSchemas
224
+ >;
225
+ }
226
+
227
+ /**
228
+ * Allows the value to be null and ONLY null. You can also use this function to set a custom message when the value is NULL by setting
229
+ * the { message: 'Your custom message', allow: false } on the options.
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * import * as p from '@palmares/schemas';
234
+ *
235
+ * const numberSchema = p.number().nullable();
236
+ *
237
+ * const { errors, parsed } = await numberSchema.parse(null);
238
+ *
239
+ * console.log(parsed); // null
240
+ *
241
+ * const { errors, parsed } = await numberSchema.parse(undefined);
242
+ *
243
+ * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
244
+ * ```
245
+ *
246
+ * @param options - The options for the nullable function.
247
+ * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
248
+ * @param options.allow - Whether the value can be null or not. Defaults to true.
249
+ *
250
+ * @returns The schema.
251
+ */
252
+ nullable(options?: { message: string; allow: false }) {
253
+ return super.nullable(options) as unknown as UnionSchema<
254
+ {
255
+ input: TType['input'] | null;
256
+ validate: TType['validate'] | null;
257
+ internal: TType['internal'] | null;
258
+ output: TType['output'] | null;
259
+ representation: TType['representation'] | null;
260
+ },
261
+ TDefinitions,
262
+ TSchemas
263
+ >;
264
+ }
265
+
266
+ /**
267
+ * This method will remove the value from the representation of the schema. If the value is undefined it will keep that way
268
+ * otherwise it will set the value to undefined after it's validated.
269
+ * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
270
+ * function. This will remove the value from the representation of the schema.
271
+ *
272
+ * By default, the value will be removed just from the representation, in other words, when you call the {@link data} function.
273
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal` as true.
274
+ * Then if you still want to remove the value from the representation, you will need to pass the argument `toRepresentation` as true as well.
275
+ *
276
+ * @example
277
+ * ```typescript
278
+ * import * as p from '@palmares/schemas';
279
+ *
280
+ * const userSchema = p.object({
281
+ * id: p.number().optional(),
282
+ * name: p.string(),
283
+ * password: p.string().omit()
284
+ * });
285
+ *
286
+ * const user = await userSchema.data({
287
+ * id: 1,
288
+ * name: 'John Doe',
289
+ * password: '123456'
290
+ * });
291
+ *
292
+ * console.log(user); // { id: 1, name: 'John Doe' }
293
+ * ```
294
+ *
295
+ *
296
+ * @param args - By default, the value will be removed just from the representation, in other words, when you call the {@link data} function.
297
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal` as true.
298
+ * Then if you still want to remove the value from the representation, you will need to pass the argument `toRepresentation` as true as well.
299
+ *
300
+ * @returns The schema.
301
+ */
302
+ omit<
303
+ TToInternal extends boolean,
304
+ TToRepresentation extends boolean = boolean extends TToInternal ? true : false
305
+ >(args?: { toInternal?: TToInternal, toRepresentation?: TToRepresentation }) {
306
+ return super.omit(args) as unknown as UnionSchema<
307
+ {
308
+ input: TToInternal extends true ? TType['input'] | undefined : TType['input'];
309
+ validate: TToInternal extends true ? TType['validate'] | undefined : TType['validate'];
310
+ internal: TToInternal extends true ? undefined : TType['internal'];
311
+ output: TToRepresentation extends true ? TType['output'] | undefined : TType['output'];
312
+ representation: TToRepresentation extends true ? undefined : TType['representation'];
313
+ },
314
+ TDefinitions,
315
+ TSchemas
316
+ >;
317
+ }
318
+
319
+ /**
320
+ * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external source
321
+ * like a database. You should always return the schema after you save the value, that way we will always have the correct type
322
+ * of the schema after the save operation.
323
+ *
324
+ * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
325
+ *
326
+ * @example
327
+ * ```typescript
328
+ * import * as p from '@palmares/schemas';
329
+ *
330
+ * import { User } from './models';
331
+ *
332
+ * const userSchema = p.object({
333
+ * id: p.number().optional(),
334
+ * name: p.string(),
335
+ * email: p.string().email(),
336
+ * }).onSave(async (value) => {
337
+ * // Create or update the user on the database using palmares models or any other library of your choice.
338
+ * if (value.id)
339
+ * await User.default.set(value, { search: { id: value.id } });
340
+ * else
341
+ * await User.default.set(value);
342
+ *
343
+ * return value;
344
+ * });
345
+ *
346
+ *
347
+ * // Then, on your controller, do something like this:
348
+ * const { isValid, save, errors } = await userSchema.validate(req.body);
349
+ * if (isValid) {
350
+ * const savedValue = await save();
351
+ * return Response.json(savedValue, { status: 201 });
352
+ * }
353
+ *
354
+ * return Response.json({ errors }, { status: 400 });
355
+ * ```
356
+ *
357
+ * @param callback - The callback that will be called to save the value on an external source.
358
+ *
359
+ * @returns The schema.
360
+ */
361
+ onSave(callback: (value: TType['internal']) => Promise<TType['output']> | TType['output']) {
362
+ return super.onSave(callback) as unknown as UnionSchema<
363
+ {
364
+ input: TType['input'];
365
+ validate: TType['validate'];
366
+ internal: TType['internal'];
367
+ output: TType['output'];
368
+ representation: TType['representation'];
369
+ },
370
+ TDefinitions & {
371
+ hasSave: true;
372
+ },
373
+ TSchemas
374
+ >;
375
+ }
376
+
377
+
378
+ /**
379
+ * This function is used to add a default value to the schema. If the value is either undefined or null, the default value will be used.
380
+ *
381
+ * @example
382
+ * ```typescript
383
+ * import * as p from '@palmares/schemas';
384
+ *
385
+ * const numberSchema = p.number().default(0);
386
+ *
387
+ * const { errors, parsed } = await numberSchema.parse(undefined);
388
+ *
389
+ * console.log(parsed); // 0
390
+ * ```
391
+ */
392
+ default<TDefaultValue extends TType['input'] | (() => Promise<TType['input']>)>(
393
+ defaultValueOrFunction: TDefaultValue
394
+ ) {
395
+ return super.default(defaultValueOrFunction) as unknown as UnionSchema<
396
+ {
397
+ input: TType['input'] | undefined | null;
398
+ validate: TType['validate'];
399
+ internal: TType['internal'];
400
+ output: TType['output'] | undefined | null;
401
+ representation: TType['representation'];
402
+ },
403
+ TDefinitions,
404
+ TSchemas
405
+ >;
406
+ }
407
+
408
+ /**
409
+ * This function let's you customize the schema your own way. After we translate the schema on the adapter we call this function to let you customize
410
+ * the custom schema your own way. Our API does not support passthrough? No problem, you can use this function to customize the zod schema.
411
+ *
412
+ * @example
413
+ * ```typescript
414
+ * import * as p from '@palmares/schemas';
415
+ *
416
+ * const numberSchema = p.number().extends((schema) => {
417
+ * return schema.nonnegative();
418
+ * });
419
+ *
420
+ * const { errors, parsed } = await numberSchema.parse(-1);
421
+ *
422
+ * console.log(errors); // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
423
+ * ```
424
+ *
425
+ * @param callback - The callback that will be called to customize the schema.
426
+ * @param toStringCallback - The callback that will be called to transform the schema to a string when you want to compile the underlying schema
427
+ * to a string so you can save it for future runs.
428
+ *
429
+ * @returns The schema.
430
+ */
431
+ extends(
432
+ callback: (
433
+ schema: Awaited<ReturnType<NonNullable<TDefinitions['schemaAdapter']['union']>['translate']>>
434
+ ) => Awaited<ReturnType<NonNullable<TDefinitions['schemaAdapter']['field']>['translate']>> | any,
435
+ toStringCallback?: (schemaAsString: string) => string
436
+ ) {
437
+ return super.extends(callback, toStringCallback);
438
+ }
439
+
440
+ /**
441
+ * This function is used to transform the value to the representation of the schema. When using the {@link data} function. With this function you have full
442
+ * control to add data cleaning for example, transforming the data and whatever. Another use case is when you want to return deeply nested recursive data.
443
+ * The schema maps to itself.
444
+ *
445
+ * @example
446
+ * ```typescript
447
+ * import * as p from '@palmares/schemas';
448
+ *
449
+ * const recursiveSchema = p.object({
450
+ * id: p.number().optional(),
451
+ * name: p.string(),
452
+ * }).toRepresentation(async (value) => {
453
+ * return {
454
+ * id: value.id,
455
+ * name: value.name,
456
+ * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
457
+ * }
458
+ * });
459
+ *
460
+ * const data = await recursiveSchema.data({
461
+ * id: 1,
462
+ * name: 'John Doe',
463
+ * });
464
+ * ```
465
+ *
466
+ * @example
467
+ * ```
468
+ * import * as p from '@palmares/schemas';
469
+ *
470
+ * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
471
+ * switch (value) {
472
+ * case 'red': return { r: 255, g: 0, b: 0 };
473
+ * case 'green': return { r: 0, g: 255, b: 0 };
474
+ * case 'blue': return { r: 0, g: 0, b: 255 };
475
+ * default: return { r: 0, g: 0, b: 0 };
476
+ * }
477
+ * });
478
+ * ```
479
+ * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
480
+ *
481
+ * @returns The schema with a new return type
482
+ */
483
+ toRepresentation<TRepresentation>(
484
+ toRepresentationCallback: (value: TType['representation']) => Promise<TRepresentation>
485
+ ) {
486
+ return super.toRepresentation(toRepresentationCallback) as unknown as UnionSchema<
487
+ {
488
+ input: TType['input'];
489
+ validate: TType['validate'];
490
+ internal: TType['internal'];
491
+ output: TType['output'];
492
+ representation: TRepresentation;
493
+ },
494
+ TDefinitions,
495
+ TSchemas
496
+ >;
497
+ }
498
+
499
+ /**
500
+ * This function is used to transform the value to the internal representation of the schema. This is useful when you want to transform the value
501
+ * to a type that the schema adapter can understand. For example, you might want to transform a string to a date. This is the function you use.
502
+ *
503
+ * @example
504
+ * ```typescript
505
+ * import * as p from '@palmares/schemas';
506
+ *
507
+ * const dateSchema = p.string().toInternal((value) => {
508
+ * return new Date(value);
509
+ * });
510
+ *
511
+ * const date = await dateSchema.parse('2021-01-01');
512
+ *
513
+ * console.log(date); // Date object
514
+ *
515
+ * const rgbToColorSchema = p.object({
516
+ * r: p.number().min(0).max(255),
517
+ * g: p.number().min(0).max(255),
518
+ * b: p.number().min(0).max(255),
519
+ * }).toInternal(async (value) => {
520
+ * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
521
+ * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
522
+ * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
523
+ * return `rgb(${value.r}, ${value.g}, ${value.b})`;
524
+ * });
525
+ * ```
526
+ *
527
+ * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
528
+ *
529
+ * @returns The schema with a new return type.
530
+ */
531
+ toInternal<TInternal>(toInternalCallback: (value: TType['validate']) => Promise<TInternal>) {
532
+ return super.toInternal(toInternalCallback) as unknown as UnionSchema<
533
+ {
534
+ input: TType['input'];
535
+ validate: TType['validate'];
536
+ internal: TInternal;
537
+ output: TType['output'];
538
+ representation: TType['representation'];
539
+ },
540
+ TDefinitions,
541
+ TSchemas
542
+ >;
543
+ }
544
+
545
+ /**
546
+ * Called before the validation of the schema. Let's say that you want to validate a date that might receive a string, you can convert that string to a date
547
+ * here BEFORE the validation. This pretty much transforms the value to a type that the schema adapter can understand.
548
+ *
549
+ * @example
550
+ * ```
551
+ * import * as p from '@palmares/schemas';
552
+ * import * as z from 'zod';
553
+ *
554
+ * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
555
+ * return new Map(value); // Before validating we transform the value to a map.
556
+ * });
557
+ *
558
+ * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
559
+ * ```
560
+ *
561
+ * @param toValidateCallback - The callback that will be called to validate the value.
562
+ *
563
+ * @returns The schema with a new return type.
564
+ */
565
+ toValidate<TValidate>(toValidateCallback: (value: TType['input']) => Promise<TValidate> | TValidate) {
566
+ return super.toValidate(toValidateCallback) as unknown as UnionSchema<
567
+ {
568
+ input: TType['input'];
569
+ validate: TValidate;
570
+ internal: TType['internal'];
571
+ output: TType['output'];
572
+ representation: TType['representation'];
573
+ },
574
+ TDefinitions,
575
+ TSchemas
576
+ >;
577
+ }
578
+
579
+ static new<
580
+ TSchemas extends readonly [Schema<any, any>, Schema<any, any>, ...Schema<any, any>[]],
581
+ TDefinitions extends DefinitionsOfSchemaType = DefinitionsOfSchemaType,
582
+ >(schemas: Narrow<TSchemas>): UnionSchema<TSchemas[number] extends Schema<infer TType, any> ? TType : never> {
583
+ const returnValue = new UnionSchema<TSchemas[number] extends Schema<infer TType, any> ? TType : never, TDefinitions, TSchemas>(schemas as TSchemas);
584
+
585
+ const adapterInstance = getDefaultAdapter();
586
+
587
+ returnValue.__transformedSchemas[adapterInstance.constructor.name] = {
588
+ transformed: false,
589
+ adapter: adapterInstance,
590
+ schemas: [],
591
+ };
592
+ return returnValue as any;
593
+ }
594
+ }
595
+
596
+ export const union = UnionSchema.new;
package/src/types.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type Schema from './schema/schema';
2
+ import type { ValidatorTypes } from './validators/types';
3
+
4
+ export type MaybePromise<T> = T | Promise<T>;
5
+
6
+ export type FallbackFunctionsType<TArguments> = {
7
+ [TKey in keyof TArguments]?: (args: NonNullable<TArguments[TKey]>) => {
8
+ type: ValidatorTypes;
9
+ callback: NonNullable<Schema['__rootFallbacksValidator']['fallbacks'][number]>;
10
+ };
11
+ };
12
+
13
+ export type SupportedSchemas = 'number' | 'object' | 'union' | 'string' | 'array' | 'boolean' | 'datetime';