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