@palmares/schemas 0.1.21 → 0.1.22

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 (78) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/package.json +10 -4
  3. package/.turbo/turbo-build$colon$watch.log +0 -24
  4. package/.turbo/turbo-build.log +0 -13
  5. package/.turbo/turbo-build:watch.log +0 -26
  6. package/__tests__/.drizzle/migrations/0000_skinny_harrier.sql +0 -22
  7. package/__tests__/.drizzle/migrations/meta/0000_snapshot.json +0 -156
  8. package/__tests__/.drizzle/migrations/meta/_journal.json +0 -13
  9. package/__tests__/.drizzle/schema.ts +0 -35
  10. package/__tests__/drizzle.config.ts +0 -11
  11. package/__tests__/eslint.config.js +0 -10
  12. package/__tests__/manage.ts +0 -5
  13. package/__tests__/node_modules/.bin/drizzle-kit +0 -17
  14. package/__tests__/node_modules/.bin/node-gyp +0 -17
  15. package/__tests__/node_modules/.bin/tsc +0 -17
  16. package/__tests__/node_modules/.bin/tsserver +0 -17
  17. package/__tests__/node_modules/.bin/tsx +0 -17
  18. package/__tests__/package.json +0 -34
  19. package/__tests__/sqlite.db +0 -0
  20. package/__tests__/src/core/array.test.ts +0 -131
  21. package/__tests__/src/core/boolean.test.ts +0 -66
  22. package/__tests__/src/core/datetime.test.ts +0 -102
  23. package/__tests__/src/core/index.ts +0 -35
  24. package/__tests__/src/core/model.test.ts +0 -260
  25. package/__tests__/src/core/models.ts +0 -50
  26. package/__tests__/src/core/numbers.test.ts +0 -177
  27. package/__tests__/src/core/object.test.ts +0 -218
  28. package/__tests__/src/core/string.test.ts +0 -222
  29. package/__tests__/src/core/test.test.ts +0 -59
  30. package/__tests__/src/core/types.test.ts +0 -97
  31. package/__tests__/src/core/union.test.ts +0 -99
  32. package/__tests__/src/settings.ts +0 -69
  33. package/__tests__/tsconfig.json +0 -11
  34. package/src/adapter/fields/array.ts +0 -31
  35. package/src/adapter/fields/boolean.ts +0 -43
  36. package/src/adapter/fields/datetime.ts +0 -43
  37. package/src/adapter/fields/index.ts +0 -72
  38. package/src/adapter/fields/number.ts +0 -43
  39. package/src/adapter/fields/object.ts +0 -52
  40. package/src/adapter/fields/string.ts +0 -43
  41. package/src/adapter/fields/union.ts +0 -43
  42. package/src/adapter/index.ts +0 -37
  43. package/src/adapter/types.ts +0 -276
  44. package/src/compile.ts +0 -14
  45. package/src/conf.ts +0 -30
  46. package/src/constants.ts +0 -7
  47. package/src/domain.ts +0 -15
  48. package/src/exceptions.ts +0 -17
  49. package/src/index.ts +0 -318
  50. package/src/middleware.ts +0 -52
  51. package/src/model.ts +0 -518
  52. package/src/parsers/convert-from-number.ts +0 -13
  53. package/src/parsers/convert-from-string.ts +0 -19
  54. package/src/parsers/index.ts +0 -2
  55. package/src/schema/array.ts +0 -825
  56. package/src/schema/boolean.ts +0 -792
  57. package/src/schema/datetime.ts +0 -704
  58. package/src/schema/index.ts +0 -5
  59. package/src/schema/number.ts +0 -929
  60. package/src/schema/object.ts +0 -799
  61. package/src/schema/schema.ts +0 -1179
  62. package/src/schema/string.ts +0 -941
  63. package/src/schema/types.ts +0 -154
  64. package/src/schema/union.ts +0 -724
  65. package/src/types.ts +0 -66
  66. package/src/utils.ts +0 -389
  67. package/src/validators/array.ts +0 -183
  68. package/src/validators/boolean.ts +0 -52
  69. package/src/validators/datetime.ts +0 -121
  70. package/src/validators/number.ts +0 -178
  71. package/src/validators/object.ts +0 -56
  72. package/src/validators/schema.ts +0 -142
  73. package/src/validators/string.ts +0 -278
  74. package/src/validators/types.ts +0 -1
  75. package/src/validators/union.ts +0 -52
  76. package/src/validators/utils.ts +0 -226
  77. package/tsconfig.json +0 -9
  78. package/tsconfig.types.json +0 -10
@@ -1,825 +0,0 @@
1
- import { Schema } from './schema';
2
- import {
3
- defaultTransform,
4
- defaultTransformToAdapter,
5
- shouldRunDataOnComplexSchemas,
6
- transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas
7
- } from '../utils';
8
- import { arrayValidation, maxLength, minLength, nonEmpty } from '../validators/array';
9
- import { nullable, optional } from '../validators/schema';
10
- import { Validator } from '../validators/utils';
11
-
12
- import type { DefinitionsOfSchemaType, ExtractTypeFromArrayOfSchemas } from './types';
13
-
14
- export class ArraySchema<
15
- TType extends {
16
- input: any;
17
- validate: any;
18
- internal: any;
19
- output: any;
20
- representation: any;
21
- } = {
22
- input: any[];
23
- output: any[];
24
- internal: any[];
25
- representation: any[];
26
- validate: any[];
27
- },
28
- TDefinitions extends DefinitionsOfSchemaType = DefinitionsOfSchemaType,
29
- TSchemas extends readonly [Schema, ...Schema[]] | [[Schema]] = [[Schema]]
30
- > extends Schema<TType, TDefinitions> {
31
- protected $$type = '$PArraySchema';
32
- protected fieldType = 'array';
33
-
34
- protected __schemas: readonly [Schema, ...Schema[]] | [[Schema]];
35
-
36
- protected __type: {
37
- message: string;
38
- check: (value: TType['input']) => boolean;
39
- } = {
40
- message: 'Invalid type',
41
- check: (value) => Array.isArray(value)
42
- };
43
-
44
- protected __minLength!: {
45
- value: number;
46
- inclusive: boolean;
47
- message: string;
48
- };
49
-
50
- protected __maxLength!: {
51
- value: number;
52
- inclusive: boolean;
53
- message: string;
54
- };
55
-
56
- protected __nonEmpty!: {
57
- message: string;
58
- };
59
-
60
- constructor(...schemas: TSchemas) {
61
- super();
62
- this.__schemas = schemas;
63
- }
64
-
65
- protected async __transformToAdapter(options: Parameters<Schema['__transformToAdapter']>[0]): Promise<any> {
66
- return defaultTransformToAdapter(
67
- async (adapter) => {
68
- const schemas = Array.isArray(this.__schemas[0]) ? this.__schemas[0] : this.__schemas;
69
- const transformedSchemasAsString: string[] = [];
70
- const transformedSchemas = [] as unknown as [any, ...any[]] | [any];
71
- let shouldBeHandledByFallback = false;
72
-
73
- await Promise.all(
74
- (schemas as unknown as Schema[]).map(async (schema) => {
75
- const [transformedData, shouldAddFallbackValidationForThisSchema] =
76
- await transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas(schema, options);
77
-
78
- if (shouldAddFallbackValidationForThisSchema) shouldBeHandledByFallback = true;
79
-
80
- for (const transformedSchema of transformedData) {
81
- transformedSchemasAsString.push(transformedSchema.asString);
82
- transformedSchemas.push(transformedSchema.transformed);
83
- }
84
- })
85
- );
86
-
87
- // eslint-disable-next-line ts/no-unnecessary-condition
88
- if (shouldBeHandledByFallback)
89
- Validator.createAndAppendFallback(
90
- this,
91
- arrayValidation(
92
- Array.isArray(this.__schemas[0]) === false,
93
- (Array.isArray(this.__schemas[0]) ? this.__schemas[0] : this.__schemas) as unknown as Schema<any, any>[]
94
- )
95
- );
96
-
97
- return defaultTransform(
98
- 'array',
99
- this,
100
- adapter,
101
- adapter.array,
102
- () => ({
103
- isTuple: Array.isArray(this.__schemas[0]) === false,
104
- nullable: this.__nullable,
105
- optional: this.__optional,
106
- maxLength: this.__maxLength,
107
- minLength: this.__minLength,
108
- nonEmpty: this.__nonEmpty,
109
- schemas: transformedSchemas,
110
- type: this.__type,
111
- parsers: {
112
- nullable: this.__nullable.allow,
113
- optional: this.__optional.allow
114
- }
115
- }),
116
- {
117
- optional,
118
- nullable,
119
- minLength,
120
- maxLength,
121
- nonEmpty
122
- },
123
- {
124
- shouldAddStringVersion: options.shouldAddStringVersion,
125
- // eslint-disable-next-line ts/require-await
126
- fallbackIfNotSupported: async () => []
127
- }
128
- );
129
- },
130
- this,
131
- this.__transformedSchemas,
132
- options,
133
- 'array'
134
- );
135
- }
136
-
137
- /**
138
- * This let's you refine the schema with custom validations. This is useful when you want to validate something that
139
- * is not supported by default by the schema adapter.
140
- *
141
- * @example
142
- * ```typescript
143
- * import * as p from '@palmares/schemas';
144
- *
145
- * const numberSchema = p.number().refine((value) => {
146
- * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
147
- * });
148
- *
149
- * const { errors, parsed } = await numberSchema.parse(-1);
150
- *
151
- * // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
152
- * console.log(errors);
153
- * ```
154
- *
155
- * @param refinementCallback - The callback that will be called to validate the value.
156
- * @param options - Options for the refinement.
157
- * @param options.isAsync - Whether the callback is async or not. Defaults to true.
158
- */
159
- refine(
160
- refinementCallback: (
161
- value: TType['input']
162
- ) =>
163
- | Promise<void | undefined | { code: string; message: string }>
164
- | void
165
- | undefined
166
- | { code: string; message: string }
167
- ) {
168
- return super.refine(refinementCallback) as unknown as ArraySchema<
169
- {
170
- input: TType['input'];
171
- validate: TType['validate'];
172
- internal: TType['internal'];
173
- output: TType['output'];
174
- representation: TType['representation'];
175
- },
176
- TDefinitions,
177
- TSchemas
178
- >;
179
- }
180
-
181
- /**
182
- * Allows the value to be either undefined or null. Different from the `optional` method on other schemas, You can
183
- * pass `outputOnly` as `true` to this method.
184
- * This will allow you to pass `null` or `undefined` as a value on the {@link Schema.data} method, but it will not
185
- * allow the value to be `null` or `undefined`. This is useful for typing purposes.
186
- *
187
- * @example
188
- * ```typescript
189
- * import * as p from '@palmares/schemas';
190
- *
191
- * const numberSchema = p.number().optional();
192
- *
193
- * const { errors, parsed } = await numberSchema.parse(undefined);
194
- *
195
- * console.log(parsed); // undefined
196
- *
197
- * const { errors, parsed } = await numberSchema.parse(null);
198
- *
199
- * console.log(parsed); // null
200
- *
201
- * const { errors, parsed } = await numberSchema.parse(1);
202
- *
203
- * console.log(parsed); // 1
204
- *
205
- * const companySchema = p.object({ id: p.number(), name: p.string() });
206
- * const userSchema = p.object({
207
- * id: p.number(),
208
- * name: p.string(),
209
- * company: companySchema.optional({ outputOnly: true })
210
- * });
211
- *
212
- * // Will not allow the company to be null or undefined on a typing level.
213
- * const { errors, parsed } = await userSchema.data({ id: 1, name: 'John Doe' });
214
- * // Will allow the company to be null or undefined on a typing level
215
- * const value = await userSchema.data({ id: 1, name: 'John Doe' });
216
- * ```
217
- *
218
- * @returns - The schema we are working with.
219
- */
220
- optional<TOutputOnly extends boolean = false>(options?: {
221
- message?: string;
222
- allow?: false;
223
- outputOnly?: TOutputOnly;
224
- }) {
225
- return (options?.outputOnly ? this : super.optional(options)) as unknown as ArraySchema<
226
- TOutputOnly extends true
227
- ? {
228
- input: TType['input'];
229
- validate: TType['validate'];
230
- internal: TType['internal'];
231
- output: TType['output'] | undefined | null;
232
- representation: TType['representation'];
233
- }
234
- : {
235
- input: TType['input'] | undefined | null;
236
- validate: TType['validate'] | undefined | null;
237
- internal: TType['internal'] | undefined | null;
238
- output: TType['output'] | undefined | null;
239
- representation: TType['representation'] | undefined | null;
240
- },
241
- TDefinitions,
242
- TSchemas
243
- >;
244
- }
245
-
246
- /**
247
- * Just adds a message when the value is undefined. It's just a syntax sugar for
248
- *
249
- * ```typescript
250
- * p.datetime().optional({ message: 'This value should be defined', allow: false })
251
- * ```
252
- *
253
- * @param options - The options of nonOptional function
254
- * @param options.message - A custom message if the value is undefined.
255
- *
256
- * @returns - The schema.
257
- */
258
- nonOptional(options?: { message: string }) {
259
- return super.optional({
260
- message: options?.message,
261
- allow: false
262
- }) as unknown as ArraySchema<
263
- {
264
- input: TType['input'];
265
- validate: TType['validate'];
266
- internal: TType['internal'];
267
- output: TType['output'];
268
- representation: TType['representation'];
269
- },
270
- TDefinitions
271
- >;
272
- }
273
-
274
- /**
275
- * Allows the value to be null and ONLY null. You can also use this function to set a custom message when the value
276
- * is NULL by setting the { message: 'Your custom message', allow: false } on the options.
277
- *
278
- * @example
279
- * ```typescript
280
- * import * as p from '@palmares/schemas';
281
- *
282
- * const numberSchema = p.number().nullable();
283
- *
284
- * const { errors, parsed } = await numberSchema.parse(null);
285
- *
286
- * console.log(parsed); // null
287
- *
288
- * const { errors, parsed } = await numberSchema.parse(undefined);
289
- *
290
- * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
291
- * ```
292
- *
293
- * @param options - The options for the nullable function.
294
- * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
295
- * @param options.allow - Whether the value can be null or not. Defaults to true.
296
- *
297
- * @returns The schema.
298
- */
299
- nullable(options?: { message: string; allow: false }) {
300
- return super.nullable(options) as unknown as ArraySchema<
301
- {
302
- input: TType['input'] | null;
303
- validate: TType['validate'] | null;
304
- internal: TType['internal'] | null;
305
- output: TType['output'] | null;
306
- representation: TType['representation'] | null;
307
- },
308
- TDefinitions,
309
- TSchemas
310
- >;
311
- }
312
-
313
- /**
314
- * Just adds a message when the value is null. It's just a syntax sugar for
315
- *
316
- * ```typescript
317
- * p.datetime().nullable({ message: 'This value cannot be null', allow: false })
318
- * ```
319
- *
320
- * @param options - The options of nonNullable function
321
- * @param options.message - A custom message if the value is null.
322
- *
323
- * @returns - The schema.
324
- */
325
- nonNullable(options?: { message: string }) {
326
- return super.nullable({
327
- message: options?.message || '',
328
- allow: false
329
- }) as unknown as ArraySchema<
330
- {
331
- input: TType['input'];
332
- validate: TType['validate'];
333
- internal: TType['internal'];
334
- output: TType['output'];
335
- representation: TType['representation'];
336
- },
337
- TDefinitions
338
- >;
339
- }
340
-
341
- /**
342
- * This method will remove the value from the representation of the schema. If the value is undefined it will keep
343
- * that way otherwise it will set the value to undefined after it's validated.
344
- * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
345
- * function. This will remove the value from the representation of the schema.
346
- *
347
- * By default, the value will be removed just from the representation, in other words, when you call the {@link data}
348
- * function. But if you want to remove the value from the internal representation, you can pass the argument
349
- * `toInternal` as true. Then if you still want to remove the value from the representation, you will need to pass
350
- * the argument `toRepresentation` as true as well.
351
- *
352
- * @example
353
- * ```typescript
354
- * import * as p from '@palmares/schemas';
355
- *
356
- * const userSchema = p.object({
357
- * id: p.number().optional(),
358
- * name: p.string(),
359
- * password: p.string().omit()
360
- * });
361
- *
362
- * const user = await userSchema.data({
363
- * id: 1,
364
- * name: 'John Doe',
365
- * password: '123456'
366
- * });
367
- *
368
- * console.log(user); // { id: 1, name: 'John Doe' }
369
- * ```
370
- *
371
- *
372
- * @param args - By default, the value will be removed just from the representation, in other words, when you call
373
- * the {@link data} function.
374
- * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
375
- * as true.
376
- * Then if you still want to remove the value from the representation, you will need to pass the argument
377
- * `toRepresentation` as true as well.
378
- *
379
- * @returns The schema.
380
- */
381
- omit<
382
- TToInternal extends boolean,
383
- TToRepresentation extends boolean = boolean extends TToInternal ? true : false
384
- >(args?: { toInternal?: TToInternal; toRepresentation?: TToRepresentation }) {
385
- return super.omit(args) as unknown as ArraySchema<
386
- {
387
- input: TToInternal extends true ? TType['input'] | undefined : TType['input'];
388
- validate: TToInternal extends true ? TType['validate'] | undefined : TType['validate'];
389
- internal: TToInternal extends true ? undefined : TType['internal'];
390
- output: TToRepresentation extends true ? TType['output'] | undefined : TType['output'];
391
- representation: TToRepresentation extends true ? undefined : TType['representation'];
392
- },
393
- TDefinitions,
394
- TSchemas
395
- >;
396
- }
397
-
398
- /**
399
- * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external
400
- * source like a database. You should always return the schema after you save the value, that way we will always have
401
- * the correct type of the schema after the save operation.
402
- *
403
- * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
404
- *
405
- * @example
406
- * ```typescript
407
- * import * as p from '@palmares/schemas';
408
- *
409
- * import { User } from './models';
410
- *
411
- * const userSchema = p.object({
412
- * id: p.number().optional(),
413
- * name: p.string(),
414
- * email: p.string().email(),
415
- * }).onSave(async (value) => {
416
- * // Create or update the user on the database using palmares models or any other library of your choice.
417
- * if (value.id)
418
- * await User.default.set(value, { search: { id: value.id } });
419
- * else
420
- * await User.default.set(value);
421
- *
422
- * return value;
423
- * });
424
- *
425
- *
426
- * // Then, on your controller, do something like this:
427
- * const { isValid, save, errors } = await userSchema.validate(req.body);
428
- * if (isValid) {
429
- * const savedValue = await save();
430
- * return Response.json(savedValue, { status: 201 });
431
- * }
432
- *
433
- * return Response.json({ errors }, { status: 400 });
434
- * ```
435
- *
436
- * @param callback - The callback that will be called to save the value on an external source.
437
- *
438
- * @returns The schema.
439
- */
440
- onSave(
441
- callback: <TContext = any>(
442
- value: TType['internal'],
443
- context: TContext
444
- ) => Promise<TType['output']> | TType['output']
445
- ) {
446
- return super.onSave(callback) as unknown as ArraySchema<
447
- {
448
- input: TType['input'];
449
- validate: TType['validate'];
450
- internal: TType['internal'];
451
- output: TType['output'];
452
- representation: TType['representation'];
453
- },
454
- TDefinitions & {
455
- hasSave: true;
456
- },
457
- TSchemas
458
- >;
459
- }
460
-
461
- /**
462
- * This function is used to add a default value to the schema. If the value is either undefined or null, the default
463
- * value will be used.
464
- *
465
- * @example
466
- * ```typescript
467
- * import * as p from '@palmares/schemas';
468
- *
469
- * const numberSchema = p.number().default(0);
470
- *
471
- * const { errors, parsed } = await numberSchema.parse(undefined);
472
- *
473
- * console.log(parsed); // 0
474
- * ```
475
- */
476
- default<TDefaultValue extends TType['input'] | (() => Promise<TType['input']>)>(
477
- defaultValueOrFunction: TDefaultValue
478
- ) {
479
- return super.default(defaultValueOrFunction) as unknown as ArraySchema<
480
- {
481
- input: TType['input'] | undefined | null;
482
- validate: TType['validate'];
483
- internal: TType['internal'];
484
- output: TType['output'] | undefined | null;
485
- representation: TType['representation'];
486
- },
487
- TDefinitions,
488
- TSchemas
489
- >;
490
- }
491
-
492
- /**
493
- * This function is used to transform the value to the representation without validating it.
494
- * This is useful when you want to return a data from a query directly to the user. But for example
495
- * you are returning the data of a user, you can clean the password or any other sensitive data.
496
- *
497
- * @example
498
- * ```typescript
499
- * import * as p from '@palmares/schemas';
500
- *
501
- * const userSchema = p.object({
502
- * id: p.number().optional(),
503
- * name: p.string(),
504
- * email: p.string().email(),
505
- * password: p.string().optional()
506
- * }).toRepresentation(async (value) => {
507
- * return {
508
- * id: value.id,
509
- * name: value.name,
510
- * email: value.email
511
- * }
512
- * });
513
- *
514
- * const user = await userSchema.data({
515
- * id: 1,
516
- * name: 'John Doe',
517
- * email: 'john@gmail.com',
518
- * password: '123456'
519
- * });
520
- * ```
521
- */
522
- async data(value: TType['output']): Promise<TType['representation']> {
523
- let parsedValue = await super.data(value);
524
- if (Array.isArray(parsedValue)) {
525
- parsedValue = (await Promise.all(
526
- Array.isArray(this.__schemas[0])
527
- ? parsedValue.map((value: any) => {
528
- const schema = (this.__schemas as unknown as [[Schema]])[0][0];
529
-
530
- return shouldRunDataOnComplexSchemas(schema) ? schema.data(value) : value;
531
- })
532
- : (this.__schemas as [Schema, ...Schema[]]).map(async (schema) => {
533
- return shouldRunDataOnComplexSchemas(schema) ? schema.data(value) : value;
534
- })
535
- )) as unknown as TType['representation'];
536
- }
537
- return parsedValue;
538
- }
539
-
540
- /**
541
- * This function let's you customize the schema your own way. After we translate the schema on the adapter we call
542
- * this function to let you customize the custom schema your own way. Our API does not support passthrough?
543
- * No problem, you can use this function to customize the zod schema.
544
- *
545
- * @example
546
- * ```typescript
547
- * import * as p from '@palmares/schemas';
548
- *
549
- * const numberSchema = p.number().extends((schema) => {
550
- * return schema.nonnegative();
551
- * });
552
- *
553
- * const { errors, parsed } = await numberSchema.parse(-1);
554
- *
555
- * // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
556
- * console.log(errors);
557
- * ```
558
- *
559
- * @param callback - The callback that will be called to customize the schema.
560
- * @param toStringCallback - The callback that will be called to transform the schema to a string when you want to
561
- * compile the underlying schema to a string so you can save it for future runs.
562
- *
563
- * @returns The schema.
564
- */
565
- extends(
566
- callback: (
567
- schema: Awaited<ReturnType<NonNullable<TDefinitions['schemaAdapter']['object']>['translate']>>
568
- ) => Awaited<ReturnType<NonNullable<TDefinitions['schemaAdapter']['field']>['translate']>> | any,
569
- toStringCallback?: (schemaAsString: string) => string
570
- ) {
571
- return super.extends(callback, toStringCallback);
572
- }
573
-
574
- /**
575
- * This function is used to transform the value to the representation of the schema. When using the {@link data}
576
- * function. With this function you have full control to add data cleaning for example, transforming the data and
577
- * whatever. Another use case is when you want to return deeply nested recursive data.
578
- * The schema maps to itself.
579
- *
580
- * @example
581
- * ```typescript
582
- * import * as p from '@palmares/schemas';
583
- *
584
- * const recursiveSchema = p.object({
585
- * id: p.number().optional(),
586
- * name: p.string(),
587
- * }).toRepresentation(async (value) => {
588
- * return {
589
- * id: value.id,
590
- * name: value.name,
591
- * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
592
- * }
593
- * });
594
- *
595
- * const data = await recursiveSchema.data({
596
- * id: 1,
597
- * name: 'John Doe',
598
- * });
599
- * ```
600
- *
601
- * @example
602
- * ```
603
- * import * as p from '@palmares/schemas';
604
- *
605
- * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
606
- * switch (value) {
607
- * case 'red': return { r: 255, g: 0, b: 0 };
608
- * case 'green': return { r: 0, g: 255, b: 0 };
609
- * case 'blue': return { r: 0, g: 0, b: 255 };
610
- * default: return { r: 0, g: 0, b: 0 };
611
- * }
612
- * });
613
- * ```
614
- * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
615
- *
616
- * @returns The schema with a new return type
617
- */
618
- toRepresentation<TRepresentation>(
619
- toRepresentationCallback: (value: TType['representation']) => Promise<TRepresentation>
620
- ) {
621
- return super.toRepresentation(toRepresentationCallback) as unknown as ArraySchema<
622
- {
623
- input: TType['input'];
624
- validate: TType['validate'];
625
- internal: TType['internal'];
626
- output: TType['output'];
627
- representation: TRepresentation;
628
- },
629
- TDefinitions,
630
- TSchemas
631
- >;
632
- }
633
-
634
- /**
635
- * This function is used to transform the value to the internal representation of the schema. This is useful when you
636
- * want to transform the value to a type that the schema adapter can understand. For example, you might want to
637
- * transform a string to a date. This is the function you use.
638
- *
639
- * @example
640
- * ```typescript
641
- * import * as p from '@palmares/schemas';
642
- *
643
- * const dateSchema = p.string().toInternal((value) => {
644
- * return new Date(value);
645
- * });
646
- *
647
- * const date = await dateSchema.parse('2021-01-01');
648
- *
649
- * console.log(date); // Date object
650
- *
651
- * const rgbToColorSchema = p.object({
652
- * r: p.number().min(0).max(255),
653
- * g: p.number().min(0).max(255),
654
- * b: p.number().min(0).max(255),
655
- * }).toInternal(async (value) => {
656
- * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
657
- * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
658
- * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
659
- * return `rgb(${value.r}, ${value.g}, ${value.b})`;
660
- * });
661
- * ```
662
- *
663
- * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
664
- *
665
- * @returns The schema with a new return type.
666
- */
667
- toInternal<TInternal>(toInternalCallback: (value: TType['validate']) => Promise<TInternal>) {
668
- return super.toInternal(toInternalCallback) as unknown as ArraySchema<
669
- {
670
- input: TType['input'];
671
- validate: TType['validate'];
672
- internal: TInternal;
673
- output: TType['output'];
674
- representation: TType['representation'];
675
- },
676
- TDefinitions,
677
- TSchemas
678
- >;
679
- }
680
-
681
- /**
682
- * Called before the validation of the schema. Let's say that you want to validate a date that might receive a string,
683
- * you can convert that string to a date here BEFORE the validation. This pretty much transforms the value to a type
684
- * that the schema adapter can understand.
685
- *
686
- * @example
687
- * ```
688
- * import * as p from '@palmares/schemas';
689
- * import * as z from 'zod';
690
- *
691
- * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
692
- * return new Map(value); // Before validating we transform the value to a map.
693
- * });
694
- *
695
- * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
696
- * ```
697
- *
698
- * @param toValidateCallback - The callback that will be called to validate the value.
699
- *
700
- * @returns The schema with a new return type.
701
- */
702
- toValidate<TValidate>(toValidateCallback: (value: TType['input']) => Promise<TValidate> | TValidate) {
703
- return super.toValidate(toValidateCallback) as unknown as ArraySchema<
704
- {
705
- input: TType['input'];
706
- validate: TValidate;
707
- internal: TType['internal'];
708
- output: TType['output'];
709
- representation: TType['representation'];
710
- },
711
- TDefinitions,
712
- TSchemas
713
- >;
714
- }
715
-
716
- minLength(value: number, options?: Omit<ArraySchema['__minLength'], 'value'>) {
717
- const message = options?.message || `The array must have a minimum length of ${value}`;
718
- this.__minLength = {
719
- value: value,
720
- inclusive: typeof options?.inclusive === 'boolean' ? options.inclusive : true,
721
- message: message
722
- };
723
-
724
- return this as unknown as ArraySchema<
725
- {
726
- input: [TType['input'][number], ...TType['input'][number][]];
727
- validate: [TType['validate'][number], ...TType['validate'][number][]];
728
- internal: [TType['internal'][number], ...TType['internal'][number][]];
729
- output: [TType['output'][number], ...TType['output'][number][]];
730
- representation: [TType['representation'][number], ...TType['representation'][number][]];
731
- },
732
- TDefinitions,
733
- TSchemas
734
- >;
735
- }
736
-
737
- maxLength(value: number, options?: Omit<ArraySchema['__maxLength'], 'value'>) {
738
- const message = options?.message || `The array must have a maximum length of ${value}`;
739
- this.__maxLength = {
740
- value: value,
741
- inclusive: typeof options?.inclusive === 'boolean' ? options.inclusive : true,
742
- message: message
743
- };
744
-
745
- return this;
746
- }
747
-
748
- static new<
749
- TSchemas extends readonly [Schema, ...Schema[]] | [[Schema]],
750
- TDefinitions extends DefinitionsOfSchemaType = DefinitionsOfSchemaType
751
- >(
752
- ...schemas: TSchemas
753
- ): TSchemas extends [[Schema]]
754
- ? ArraySchema<
755
- {
756
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
757
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
758
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
759
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
760
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
761
- },
762
- TDefinitions,
763
- TSchemas
764
- >
765
- : ArraySchema<
766
- {
767
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
768
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
769
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
770
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
771
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
772
- },
773
- TDefinitions,
774
- TSchemas
775
- > & {
776
- maxLength: never;
777
- minLength: never;
778
- } {
779
- const returnValue = new ArraySchema<
780
- {
781
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
782
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
783
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
784
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
785
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
786
- },
787
- TDefinitions,
788
- TSchemas
789
- >(...schemas);
790
-
791
- return returnValue as TSchemas extends [[Schema]]
792
- ? ArraySchema<
793
- {
794
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
795
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
796
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
797
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
798
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
799
- },
800
- TDefinitions,
801
- TSchemas
802
- >
803
- : ArraySchema<
804
- {
805
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
806
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
807
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
808
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
809
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
810
- },
811
- TDefinitions,
812
- TSchemas
813
- > & {
814
- maxLength: never;
815
- minLength: never;
816
- };
817
- }
818
- }
819
-
820
- export const array = <
821
- TSchemas extends readonly [Schema, ...Schema[]] | [[Schema]],
822
- TDefinitions extends DefinitionsOfSchemaType
823
- >(
824
- ...schemas: TSchemas
825
- ) => ArraySchema.new<TSchemas, TDefinitions>(...schemas);