reliant-type 1.0.0 → 2.1.4

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 (66) hide show
  1. package/README.md +113 -688
  2. package/dist/cjs/core/schema/extensions/mods/typescript-generator.js +45 -16
  3. package/dist/cjs/core/schema/extensions/mods/typescript-generator.js.map +1 -1
  4. package/dist/cjs/core/schema/mode/interfaces/Interface.js +0 -12
  5. package/dist/cjs/core/schema/mode/interfaces/Interface.js.map +1 -1
  6. package/dist/cjs/core/schema/mode/interfaces/InterfaceSchema.js +34 -3
  7. package/dist/cjs/core/schema/mode/interfaces/InterfaceSchema.js.map +1 -1
  8. package/dist/cjs/core/schema/mode/interfaces/errors/SchemaValidationError.js +16 -0
  9. package/dist/cjs/core/schema/mode/interfaces/errors/SchemaValidationError.js.map +1 -0
  10. package/dist/cjs/core/schema/mode/interfaces/precompilation/FieldPrecompilers.js +119 -0
  11. package/dist/cjs/core/schema/mode/interfaces/precompilation/FieldPrecompilers.js.map +1 -1
  12. package/dist/cjs/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.js +49 -0
  13. package/dist/cjs/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.js.map +1 -1
  14. package/dist/cjs/core/schema/mode/interfaces/typescript/TypeInference.js.map +1 -1
  15. package/dist/cjs/core/schema/mode/interfaces/validators/ConstraintParser.js +6 -0
  16. package/dist/cjs/core/schema/mode/interfaces/validators/ConstraintParser.js.map +1 -1
  17. package/dist/cjs/core/schema/mode/interfaces/validators/TypeGuards.js +7 -0
  18. package/dist/cjs/core/schema/mode/interfaces/validators/TypeGuards.js.map +1 -1
  19. package/dist/cjs/core/schema/mode/interfaces/validators/mods/securityValidator.js +1 -1
  20. package/dist/cjs/core/schema/mode/interfaces/validators/mods/securityValidator.js.map +1 -1
  21. package/dist/cjs/core/utils/Mod.js +33 -4
  22. package/dist/cjs/core/utils/Mod.js.map +1 -1
  23. package/dist/cjs/index.js +74 -1
  24. package/dist/cjs/index.js.map +1 -1
  25. package/dist/esm/core/schema/extensions/mods/typescript-generator.js +45 -16
  26. package/dist/esm/core/schema/extensions/mods/typescript-generator.js.map +1 -1
  27. package/dist/esm/core/schema/mode/interfaces/Interface.js +1 -12
  28. package/dist/esm/core/schema/mode/interfaces/Interface.js.map +1 -1
  29. package/dist/esm/core/schema/mode/interfaces/InterfaceSchema.js +32 -1
  30. package/dist/esm/core/schema/mode/interfaces/InterfaceSchema.js.map +1 -1
  31. package/dist/esm/core/schema/mode/interfaces/errors/SchemaValidationError.js +14 -0
  32. package/dist/esm/core/schema/mode/interfaces/errors/SchemaValidationError.js.map +1 -0
  33. package/dist/esm/core/schema/mode/interfaces/precompilation/FieldPrecompilers.js +119 -0
  34. package/dist/esm/core/schema/mode/interfaces/precompilation/FieldPrecompilers.js.map +1 -1
  35. package/dist/esm/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.js +49 -0
  36. package/dist/esm/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.js.map +1 -1
  37. package/dist/esm/core/schema/mode/interfaces/typescript/TypeInference.js.map +1 -1
  38. package/dist/esm/core/schema/mode/interfaces/validators/ConstraintParser.js +6 -0
  39. package/dist/esm/core/schema/mode/interfaces/validators/ConstraintParser.js.map +1 -1
  40. package/dist/esm/core/schema/mode/interfaces/validators/TypeGuards.js +7 -0
  41. package/dist/esm/core/schema/mode/interfaces/validators/TypeGuards.js.map +1 -1
  42. package/dist/esm/core/schema/mode/interfaces/validators/mods/securityValidator.js +1 -1
  43. package/dist/esm/core/schema/mode/interfaces/validators/mods/securityValidator.js.map +1 -1
  44. package/dist/esm/core/utils/Mod.js +33 -4
  45. package/dist/esm/core/utils/Mod.js.map +1 -1
  46. package/dist/esm/index.js +78 -1
  47. package/dist/esm/index.js.map +1 -1
  48. package/dist/schema.d.ts +44 -3
  49. package/docs/FUNCTION-TYPES.md +120 -0
  50. package/docs/GETTING-STARTED.md +56 -53
  51. package/docs/VSCODE-EXTENSION.md +58 -47
  52. package/package.json +4 -4
  53. package/src/core/schema/extensions/components/AutoDocumentation/Docs.ts +1 -1
  54. package/src/core/schema/extensions/mods/typescript-generator.ts +342 -295
  55. package/src/core/schema/mode/interfaces/Interface.ts +1 -13
  56. package/src/core/schema/mode/interfaces/InterfaceSchema.ts +41 -1
  57. package/src/core/schema/mode/interfaces/errors/SchemaValidationError.ts +13 -0
  58. package/src/core/schema/mode/interfaces/precompilation/FieldPrecompilers.ts +146 -0
  59. package/src/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.ts +79 -0
  60. package/src/core/schema/mode/interfaces/typescript/TypeInference.ts +67 -16
  61. package/src/core/schema/mode/interfaces/validators/ConstraintParser.ts +8 -0
  62. package/src/core/schema/mode/interfaces/validators/TypeGuards.ts +19 -5
  63. package/src/core/schema/mode/interfaces/validators/mods/securityValidator.ts +1 -1
  64. package/src/core/types/SchemaValidator.type.ts +4 -0
  65. package/src/core/utils/Mod.ts +35 -4
  66. package/src/index.ts +9 -0
package/README.md CHANGED
@@ -1,17 +1,17 @@
1
1
  # ReliantType
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/reliant-type.svg)](https://badge.fury.io/js/reliant-type)
4
- [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
4
+ [![TypeScript](https://img.shields.io/badge/-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
5
5
  [![Build Status](https://github.com/nehonisteam/ReliantType/workflows/CI/badge.svg)](https://github.com/nehonisteam/ReliantType/actions)
6
6
  [![Bundle Size](https://img.shields.io/bundlephobia/minzip/reliant-type)](https://bundlephobia.com/package/reliant-type)
7
- [![VS Code Extension](https://img.shields.io/badge/VS%20Code-Extension%20Available-blue)](https://sdk.nehonix.space/pkgs/mods/vscode/latest/reliant-type.vsix)
7
+ [![VS Code Extension](https://img.shields.io/badge/VS%20Code-Extension%20Available-blue)](https://sdk.nehonix.com/pkgs/mods/vscode/latest/reliant-type.vsix)
8
8
 
9
9
  <div align="center">
10
- <img src="https://sdk.nehonix.space/sdks/assets/reliant-type.jpg" alt="ReliantType Logo" width="250" />
10
+ <img src="https://sdk.nehonix.com/sdks/assets/reliant-type.jpg" alt="ReliantType Logo" width="250" />
11
11
  </div>
12
12
 
13
13
  <div align="center">
14
- <img src="https://sdk.nehonix.space/sdks/assets/vscode-extension-preview.gif" alt="VSCode extension preview" width="500" />
14
+ <img src="https://sdk.nehonix.com/sdks/assets/vscode-extension-preview.gif" alt="VSCode extension preview" width="500" />
15
15
  </div>
16
16
 
17
17
  **TypeScript Schema Validation with Interface-Like Syntax**
@@ -20,15 +20,16 @@ A modern TypeScript validation library designed around familiar interface syntax
20
20
 
21
21
  > **Formerly Fortify Schema** - Originally developed at [github.com/Nehonix-Team/fortify-schema](https://github.com/Nehonix-Team/fortify-schema)
22
22
 
23
- ⚠️ **Migration Notice**: The `fortify-schema` package will be deprecated in favor of `reliant-type`. While `fortify-schema` will continue to receive critical security updates, new features and improvements will only be available in `reliant-type`. We recommend migrating to `reliant-type` for the best experience and ongoing support.
23
+ **Migration Notice**: The `fortify-schema` package will be deprecated in favor of `reliant-type`. While `fortify-schema` will continue to receive critical security updates, new features and improvements will only be available in `reliant-type`. We recommend migrating to `reliant-type` for the best experience and ongoing support.
24
24
 
25
- ## 🆕 What's New
25
+ ## New Features
26
26
 
27
- - **Required Fields (`!`)**: Enforce non-empty strings and non-zero numbers with `"string!"` and `"number!"`
28
- - **Object Types**: Validate generic object structures with `"object"` and `"object?"`
29
- - **Enhanced Security**: All string operations now use secure regex patterns instead of potentially vulnerable methods
30
- - **Improved Performance**: Optimized validation paths with better caching and precompilation
31
- - **Better Error Messages**: More descriptive validation errors with clear property paths
27
+ - **Function Types**: Define strict contracts for functions with `fn(...)` syntax, enforcing argument types and return values at runtime.
28
+ - **Required Fields**: Enforce non-empty strings and non-zero numbers with `"string!"` and `"number!"`.
29
+ - **Object Types**: Validate generic object structures with `"object"` and `"object?"`.
30
+ - **Enhanced Security**: All string operations now use secure regex patterns.
31
+ - **Improved Performance**: Optimized validation paths with better caching and precompilation.
32
+ - **Better Error Messages**: More descriptive validation errors with clear property paths.
32
33
 
33
34
  ## Quick Start
34
35
 
@@ -42,12 +43,15 @@ import { Interface } from "reliant-type";
42
43
  // Define schemas with familiar TypeScript-like syntax
43
44
  const UserSchema = Interface({
44
45
  id: "uuid",
45
- email: "email!", // 🆕 Required (non-empty) email
46
- name: "string(2,50)!", // 🆕 Required string with length constraints
46
+ email: "email!", // Required (non-empty) email
47
+ name: "string(2,50)!", // Required string with length constraints
47
48
  age: "number(18,120)?",
48
49
  role: "admin|user|guest",
49
50
 
50
- // 🆕 Object and array types
51
+ // Function validation
52
+ onUpdate: "fn((status: string) => boolean)",
53
+
54
+ // Object and array types
51
55
  profile: "object", // Any object structure
52
56
  tags: "string[]", // Array of strings
53
57
  metadata: "record<string, any>", // Dynamic key-value pairs
@@ -70,16 +74,14 @@ _Note: For nested objects, we recommend limiting depth to 50-100 or no more than
70
74
 
71
75
  Test by running:
72
76
 
73
- - bun src\_\_tests\_\_\test_nested_obj.ts note: you may have bun installed if using this command. "npm i -g bun" (recommanded because it's faster than node)
74
-
75
- - npm run benchmark:nestedObject
76
-
77
- _Note: you may have tsx installed if using this command. "npm i -g tsx"._
77
+ - `bun src/__tests__/test_nested_obj.ts` (requires bun: `npm i -g bun`)
78
+ - `npm run benchmark:nestedObject` (requires tsx: `npm i -g tsx`)
78
79
 
79
80
  ## Table of Contents
80
81
 
81
82
  - [Installation & Setup](#installation--setup)
82
83
  - [Core Features](#core-features)
84
+ - [Function Types](#function-types)
83
85
  - [Utility Functions](#utility-functions)
84
86
  - [Conditional Validation](#conditional-validation)
85
87
  - [Live Utility - Real-time Validation](#live-utility---real-time-validation)
@@ -117,29 +119,29 @@ bun add reliant-type
117
119
 
118
120
  Enhance your development workflow with our dedicated VS Code extension featuring comprehensive developer tools:
119
121
 
120
- #### **🎨 Enhanced Features**
122
+ #### Enhanced Features
121
123
 
122
- - **Syntax Highlighting**: Full syntax highlighting for all Reliant Type types and utilities
123
- - **Hover Documentation**: Detailed type information, examples, and use cases on hover
124
- - **Go-to-Definition**: Ctrl+Click on types to open comprehensive documentation
125
- - **IntelliSense Support**: Smart autocomplete for schema definitions
126
- - **Error Detection**: Real-time validation of schema syntax
127
- - **Code Snippets**: Pre-built templates for common schema patterns
124
+ - **Syntax Highlighting**: Full syntax highlighting for all Reliant Type types and utilities.
125
+ - **Hover Documentation**: Detailed type information, examples, and use cases on hover.
126
+ - **Go-to-Definition**: Ctrl+Click on types to open comprehensive documentation.
127
+ - **IntelliSense Support**: Smart autocomplete for schema definitions.
128
+ - **Error Detection**: Real-time validation of schema syntax.
129
+ - **Code Snippets**: Pre-built templates for common schema patterns.
128
130
 
129
- #### **📖 Interactive Documentation**
131
+ #### Interactive Documentation
130
132
 
131
133
  When you hover over any type in `Interface({...})` blocks, you'll see:
132
134
 
133
- - **Type Description**: What the type validates
134
- - **Usage Examples**: `"string"`, `"string?"`, `"string[]"`
135
- - **Use Cases**: When and where to use each type
136
- - **Code Examples**: Complete working examples
135
+ - **Type Description**: What the type validates.
136
+ - **Usage Examples**: `"string"`, `"string?"`, `"string[]"`.
137
+ - **Use Cases**: When and where to use each type.
138
+ - **Code Examples**: Complete working examples.
137
139
 
138
- #### **🔧 Installation**
140
+ #### Installation
139
141
 
140
142
  ```bash
141
143
  # Download and install
142
- curl https://sdk.nehonix.space/pkgs/mods/vscode/latest/reliant-type.vsix -o reliant-type.vsix
144
+ curl https://sdk.nehonix.com/pkgs/mods/vscode/latest/reliant-type.vsix -o reliant-type.vsix
143
145
  code --install-extension reliant-type.vsix
144
146
 
145
147
  # Or just search for "reliant-type" in the vscode marketplace
@@ -193,7 +195,7 @@ const ComprehensiveSchema = Interface({
193
195
  nickname: "string?",
194
196
  bio: "string?",
195
197
 
196
- // 🆕 Required fields (cannot be empty/zero)
198
+ // Required fields (cannot be empty/zero)
197
199
  requiredName: "string!", // Non-empty string required
198
200
  requiredCount: "number!", // Non-zero number required
199
201
 
@@ -219,7 +221,7 @@ const ComprehensiveSchema = Interface({
219
221
  status: "active|inactive|pending",
220
222
  role: "user|admin|moderator",
221
223
 
222
- // 🆕 Object types
224
+ // Object types
223
225
  profile: "object", // Any object
224
226
  config: "object?", // Optional object
225
227
 
@@ -234,37 +236,52 @@ const ComprehensiveSchema = Interface({
234
236
  });
235
237
  ```
236
238
 
237
- ### Deep Object Validation
239
+ ## Function Types
240
+
241
+ ReliantType introduces powerful runtime and compile-time validation for function signatures using the `fn` type. This feature allows you to define strict contracts for functions within your schema.
242
+
243
+ ### Syntax
238
244
 
239
245
  ```typescript
240
- const UserProfileSchema = Interface({
241
- user: {
242
- id: "uuid",
243
- email: "email",
244
- profile: {
245
- firstName: "string(1,50)",
246
- lastName: "string(1,50)",
247
- avatar: "url?",
248
- preferences: {
249
- theme: "light|dark|auto",
250
- language: "string(/^[a-z]{2}$/)",
251
- notifications: "boolean",
252
- },
253
- },
254
- },
255
- metadata: {
256
- createdAt: "date",
257
- lastLogin: "date?",
258
- loginCount: "number(0,)",
259
- },
246
+ "fn((argument_list) => return_type)";
247
+ ```
248
+
249
+ ### Examples
250
+
251
+ ```typescript
252
+ const ServiceSchema = Interface({
253
+ // Basic function: takes string, returns boolean
254
+ isValid: "fn((input: string) => boolean)",
255
+
256
+ // Multiple arguments
257
+ add: "fn((a: number, b: number) => number)",
258
+
259
+ // Optional arguments
260
+ log: "fn((message: string, context?: object) => void)",
261
+
262
+ // Rest parameters (Spread operator)
263
+ sum: "fn((...numbers: number[]) => number)",
264
+
265
+ // Generic placeholder (TYPE = any)
266
+ transform: "fn((input: TYPE) => TYPE)",
260
267
  });
261
268
  ```
262
269
 
263
- ### Utility Functions
270
+ ### Runtime Behavior
271
+
272
+ When a function defined in a schema is accessed, it is wrapped in a validation proxy that enforces:
273
+
274
+ 1. **Argument Count**: Throws an error if required arguments are missing.
275
+ 2. **Argument Types**: Throws an error if arguments do not match defined types.
276
+ 3. **Return Type**: Throws an error if the return value does not match the defined type.
277
+
278
+ This ensures strict contract adherence during execution.
279
+
280
+ ## Utility Functions
264
281
 
265
282
  Reliant Type provides powerful utility functions for advanced schema definition:
266
283
 
267
- #### **Make.const() - Constant Values**
284
+ ### Make.const() - Constant Values
268
285
 
269
286
  Create schemas that validate against exact constant values:
270
287
 
@@ -292,17 +309,9 @@ const ConfigSchema = Interface({
292
309
  // Array constants
293
310
  supportedFormats: Make.const(["json", "xml", "csv"]),
294
311
  });
295
-
296
- // Usage
297
- const config = {
298
- apiVersion: "v2.1", // ✅ Valid
299
- environment: "staging", // ❌ Invalid - must be exactly "production"
300
- maxRetries: 3, // ✅ Valid
301
- timeout: 3000, // ❌ Invalid - must be exactly 5000
302
- };
303
312
  ```
304
313
 
305
- #### **Record Types - Dynamic Objects**
314
+ ### Record Types - Dynamic Objects
306
315
 
307
316
  Validate objects with dynamic keys but consistent value types:
308
317
 
@@ -320,25 +329,6 @@ const DynamicSchema = Interface({
320
329
  // Optional record types
321
330
  optionalSettings: "record<string, boolean>?",
322
331
  });
323
-
324
- // Usage
325
- const data = {
326
- metadata: {
327
- userId: "123",
328
- timestamp: new Date(),
329
- flags: ["active", "verified"],
330
- },
331
- scores: {
332
- math: 95,
333
- science: 87,
334
- english: 92,
335
- },
336
- translations: {
337
- hello: "Hola",
338
- goodbye: "Adiós",
339
- welcome: "Bienvenido",
340
- },
341
- };
342
332
  ```
343
333
 
344
334
  ## Conditional Validation
@@ -358,7 +348,7 @@ const SmartUserSchema = Interface({
358
348
  role: "admin|user|guest",
359
349
 
360
350
  // Dynamic validation based on runtime state
361
- hasPermissions: "when config.permissions.$exists() *? boolean : =false",
351
+ hasPermissions: "when config.permissions.$exists() *? string[] : =[]",
362
352
  hasProfile: "when user.profile.$exists() *? boolean : =false",
363
353
  isListEmpty: "when config.items.$empty() *? boolean : =true",
364
354
  hasAdminRole: "when user.roles.$contains(admin) *? boolean : =false",
@@ -408,19 +398,19 @@ const RuntimeMethodsSchema = Interface({
408
398
  });
409
399
  ```
410
400
 
411
- ## Live Utility - Real-time Validation (still in progress so not recommended for production use yet)
401
+ ## Live Utility - Real-time Validation
412
402
 
413
403
  The Live utility transforms Reliant Type into a powerful real-time validation system with EventEmitter-like interface, data transformation pipelines, and stream control methods. Perfect for modern applications requiring reactive validation.
414
404
 
415
405
  ### Key Features
416
406
 
417
- - **Real-time Field Validation** - Validate form fields as users type
418
- - **EventEmitter Interface** - Full `.on()`, `.emit()`, `.off()`, `.once()` support
419
- - **Data Transformation Pipeline** - Chain `.transform()`, `.filter()`, `.map()` operations
420
- - **Stream Control** - `.pause()`, `.resume()`, `.destroy()` for flow control
421
- - **Stream Piping** - Connect validators with `.pipe()` for complex workflows
422
- - **Performance Monitoring** - Built-in statistics and performance tracking
423
- - **InterfaceSchema Sync** - Perfect synchronization with Interface validation
407
+ - **Real-time Field Validation**: Validate form fields as users type.
408
+ - **EventEmitter Interface**: Full `.on()`, `.emit()`, `.off()`, `.once()` support.
409
+ - **Data Transformation Pipeline**: Chain `.transform()`, `.filter()`, `.map()` operations.
410
+ - **Stream Control**: `.pause()`, `.resume()`, `.destroy()` for flow control.
411
+ - **Stream Piping**: Connect validators with `.pipe()` for complex workflows.
412
+ - **Performance Monitoring**: Built-in statistics and performance tracking.
413
+ - **InterfaceSchema Sync**: Perfect synchronization with Interface validation.
424
414
 
425
415
  ### Quick Example
426
416
 
@@ -440,62 +430,14 @@ const validator = Live.stream(UserSchema)
440
430
  .map((data) => ({ ...data, name: data.name.toUpperCase() }));
441
431
 
442
432
  // Listen for results
443
- validator.on("valid", (data) => console.log("Valid:", data));
444
- validator.on("invalid", (data, errors) => console.log("Invalid:", errors));
445
- validator.on("filtered", (data) => console.log("🚫 Filtered:", data));
433
+ validator.on("valid", (data) => console.log("Valid:", data));
434
+ validator.on("invalid", (data, errors) => console.log("Invalid:", errors));
435
+ validator.on("filtered", (data) => console.log("Filtered:", data));
446
436
 
447
437
  // Process data
448
438
  validator.validate({ name: "john", email: "john@example.com", age: 25 });
449
- // Output: ✅ Valid: { name: "JOHN", email: "john@example.com", age: 25, timestamp: 1703123456789 }
450
- ```
451
-
452
- ### Stream Control Example
453
-
454
- ```typescript
455
- const streamValidator = Live.stream(UserSchema);
456
-
457
- // Pause stream (queues data)
458
- streamValidator.pause();
459
- streamValidator.validate(userData1); // Queued
460
- streamValidator.validate(userData2); // Queued
461
-
462
- console.log("Queue length:", streamValidator.queueLength); // 2
463
-
464
- // Resume and process queue
465
- streamValidator.resume(); // Processes both queued items
466
-
467
- // Stream piping
468
- const sourceValidator = Live.stream(InputSchema);
469
- const destinationValidator = Live.stream(OutputSchema);
470
-
471
- sourceValidator.pipe(destinationValidator);
472
- // Valid data flows: source → destination
473
439
  ```
474
440
 
475
- ### Form Integration Example
476
-
477
- ```typescript
478
- const formValidator = Live.form(UserSchema);
479
-
480
- // Bind form fields
481
- formValidator.bindField("email", emailInput);
482
- formValidator.bindField("name", nameInput);
483
-
484
- // Enable real-time validation
485
- formValidator.enableAutoValidation();
486
-
487
- // Handle form submission
488
- formValidator.onSubmit((isValid, data, errors) => {
489
- if (isValid) {
490
- submitToAPI(data);
491
- } else {
492
- displayErrors(errors);
493
- }
494
- });
495
- ```
496
-
497
- The Live utility provides **100% coverage** of standard stream methods while maintaining **perfect synchronization** with InterfaceSchema validation logic.
498
-
499
441
  ## Real-World Applications
500
442
 
501
443
  ### E-Commerce Product Management
@@ -584,22 +526,10 @@ const performanceFeatures = {
584
526
 
585
527
  Our continuous performance monitoring shows excellent results across all validation scenarios:
586
528
 
587
- - **High Throughput**: Millions of operations per second for common validation patterns
588
- - **Consistent Performance**: Low variation in execution times
589
- - **Memory Efficient**: Minimal memory overhead per schema instance
590
- - **Scalable**: Performance scales predictably with data complexity
591
-
592
- ### Performance Testing
593
-
594
- Validate performance on your specific use cases:
595
-
596
- ```bash
597
- # Run comprehensive benchmarks
598
- bun run scripts/benchmark.js
599
-
600
- ```
601
-
602
- View detailed [benchmark results](./src/bench/BENCHMARK-RESULTS.md) for comprehensive performance analysis.
529
+ - **High Throughput**: Millions of operations per second for common validation patterns.
530
+ - **Consistent Performance**: Low variation in execution times.
531
+ - **Memory Efficient**: Minimal memory overhead per schema instance.
532
+ - **Scalable**: Performance scales predictably with data complexity.
603
533
 
604
534
  ## Advanced Capabilities
605
535
 
@@ -663,11 +593,11 @@ try {
663
593
 
664
594
  Our dedicated VS Code extension transforms your development experience:
665
595
 
666
- - **Intelligent Syntax Highlighting** for schema definitions
667
- - **Advanced IntelliSense** with type and method completion
668
- - **Real-time Validation** with inline error detection
669
- - **Rich Hover Documentation** for all types and methods
670
- - **Multiple Theme Support** for different coding preferences
596
+ - **Intelligent Syntax Highlighting** for schema definitions.
597
+ - **Advanced IntelliSense** with type and method completion.
598
+ - **Real-time Validation** with inline error detection.
599
+ - **Rich Hover Documentation** for all types and methods.
600
+ - **Multiple Theme Support** for different coding preferences.
671
601
 
672
602
  ```typescript
673
603
  const UserSchema = Interface({
@@ -687,30 +617,30 @@ const UserSchema = Interface({
687
617
 
688
618
  ### Design Philosophy
689
619
 
690
- - **Developer-Centric**: Built around familiar TypeScript patterns and conventions
691
- - **Interface Syntax**: Schema definitions that feel like native TypeScript interfaces
692
- - **Conditional Intelligence**: Advanced runtime validation based on dynamic properties
693
- - **Performance Focused**: Optimized for high-throughput production applications
694
- - **Tooling Excellence**: Professional-grade development tools and IDE integration
695
- - **Type Safety**: Complete TypeScript inference and compile-time validation
620
+ - **Developer-Centric**: Built around familiar TypeScript patterns and conventions.
621
+ - **Interface Syntax**: Schema definitions that feel like native TypeScript interfaces.
622
+ - **Conditional Intelligence**: Advanced runtime validation based on dynamic properties.
623
+ - **Performance Focused**: Optimized for high-throughput production applications.
624
+ - **Tooling Excellence**: Professional-grade development tools and IDE integration.
625
+ - **Type Safety**: Complete TypeScript inference and compile-time validation.
696
626
 
697
627
  ### Key Strengths
698
628
 
699
- - **Familiar Syntax**: Write schemas using TypeScript-like interface definitions
700
- - **Advanced Conditionals**: Unique runtime property validation and business logic
701
- - **Rich Tooling**: Dedicated VS Code extension with comprehensive development support
702
- - **Type Integration**: Seamless TypeScript integration with full type inference
703
- - **Production Ready**: Battle-tested with comprehensive error handling and debugging
629
+ - **Familiar Syntax**: Write schemas using TypeScript-like interface definitions.
630
+ - **Advanced Conditionals**: Unique runtime property validation and business logic.
631
+ - **Rich Tooling**: Dedicated VS Code extension with comprehensive development support.
632
+ - **Type Integration**: Seamless TypeScript integration with full type inference.
633
+ - **Production Ready**: Battle-tested with comprehensive error handling and debugging.
704
634
 
705
635
  ### Community and Growth
706
636
 
707
637
  We're building Reliant Type with transparency and community feedback at its core. We welcome:
708
638
 
709
- - **Real-world usage feedback** and performance insights
710
- - **Issue reports** with detailed reproduction cases
711
- - **Feature requests** based on practical development needs
712
- - **Performance benchmarking** on diverse use cases
713
- - **Constructive feedback** on API design and developer experience
639
+ - **Real-world usage feedback** and performance insights.
640
+ - **Issue reports** with detailed reproduction cases.
641
+ - **Feature requests** based on practical development needs.
642
+ - **Performance benchmarking** on diverse use cases.
643
+ - **Constructive feedback** on API design and developer experience.
714
644
 
715
645
  ## API Reference
716
646
 
@@ -798,508 +728,3 @@ if (result.success) {
798
728
  #### `schema.safeParseUnknownAsync(data)`
799
729
 
800
730
  Asynchronous safe validation for unknown data types.
801
-
802
- ```typescript
803
- const result = await UserSchema.safeParseUnknownAsync(unknownData);
804
- if (result.success) {
805
- console.log("Valid data:", result.data);
806
- } else {
807
- console.error("Validation errors:", result.errors);
808
- }
809
- ```
810
-
811
- ### Schema Transformation Operations
812
-
813
- #### `Mod.partial(schema)` - Optional Fields
814
-
815
- ```typescript
816
- const PartialUserSchema = Mod.partial(UserSchema);
817
- // Converts all fields to optional
818
- ```
819
-
820
- #### `Mod.required(schema)` - Required Fields
821
-
822
- ```typescript
823
- const RequiredUserSchema = Mod.required(PartialUserSchema);
824
- // Makes all fields required
825
- ```
826
-
827
- #### `Mod.pick(schema, keys)` - Field Selection
828
-
829
- ```typescript
830
- const PublicUserSchema = Mod.pick(UserSchema, ["id", "name", "email"]);
831
- // Creates schema with only specified fields
832
- ```
833
-
834
- #### `Mod.omit(schema, keys)` - Field Exclusion
835
-
836
- ```typescript
837
- const SafeUserSchema = Mod.omit(UserSchema, ["password", "internalId"]);
838
- // Creates schema excluding specified fields
839
- ```
840
-
841
- #### `Mod.extend(schema, extension)` - Schema Extension
842
-
843
- ```typescript
844
- const ExtendedUserSchema = Mod.extend(UserSchema, {
845
- lastLogin: "date?",
846
- preferences: {
847
- theme: "light|dark",
848
- },
849
- });
850
- ```
851
-
852
- #### `Mod.merge(schema1, schema2)` - Schema Merging
853
-
854
- ```typescript
855
- const CombinedSchema = Mod.merge(UserSchema, ProfileSchema);
856
- // Combines two schemas into one
857
- ```
858
-
859
- ### Available Extensions
860
-
861
- ReliantType provides powerful extensions for enhanced functionality:
862
-
863
- ```typescript
864
- // Import extensions for advanced features
865
- export {
866
- Smart, // Smart schema inference from samples and TypeScript types
867
- When, // Advanced conditional validation builder
868
- Live, // Real-time validation for forms and streaming data
869
- Docs, // Auto-documentation generation (OpenAPI, TypeScript, etc.)
870
- Extensions, // Extension utilities and helpers
871
- Quick, // Quick access utilities for common operations
872
- TypeScriptGenerator, // TypeScript code generation from schemas
873
- } from "reliant-type";
874
- ```
875
-
876
- #### Smart Inference
877
-
878
- ```typescript
879
- import { Smart } from "reliant-type";
880
-
881
- // Infer schema from sample data
882
- const sampleUser = {
883
- id: 1,
884
- email: "user@example.com",
885
- name: "John Doe",
886
- tags: ["developer", "typescript"],
887
- };
888
-
889
- const UserSchema = Smart.fromSample(sampleUser);
890
- // Generates: { id: "positive", email: "email", name: "string", tags: "string[]" }
891
- ```
892
-
893
- #### Conditional Builder
894
-
895
- ```typescript
896
- import { When } from "reliant-type";
897
-
898
- const OrderSchema = Interface({
899
- orderType: "pickup|delivery",
900
- address: "string?",
901
-
902
- // Advanced conditional validation
903
- deliveryFee: When.field("orderType")
904
- .is("delivery")
905
- .then("number(0,)")
906
- .default("number?"),
907
- });
908
- ```
909
-
910
- #### Real-time Validation with Live Utility
911
-
912
- The Live utility provides comprehensive real-time validation with full EventEmitter-like interface, data transformation pipelines, and stream control methods. Perfect for forms, streaming data, and reactive applications.
913
-
914
- ```typescript
915
- import { Live } from "reliant-type";
916
-
917
- const UserSchema = Interface({
918
- id: "number",
919
- name: "string(2,50)",
920
- email: "email",
921
- age: "number(18,120)",
922
- });
923
- ```
924
-
925
- ##### Live Validator - Real-time Field Validation
926
-
927
- ```typescript
928
- // Create live validator for real-time field validation
929
- const liveValidator = Live.validator(UserSchema);
930
-
931
- // Listen for validation changes
932
- liveValidator.onValidation((result) => {
933
- console.log("Validation result:", result.isValid);
934
- console.log("Current errors:", result.errors);
935
- updateUI(result);
936
- });
937
-
938
- // Validate fields in real-time
939
- liveValidator.validateField("email", "user@example.com");
940
- liveValidator.validateField("name", "John Doe");
941
-
942
- // Get current validation state
943
- console.log("Is valid:", liveValidator.isValid);
944
- console.log("All errors:", liveValidator.errors);
945
-
946
- // Validate entire object
947
- const fullResult = liveValidator.validateAll(userData);
948
- ```
949
-
950
- ##### Stream Validator - Advanced Stream Processing
951
-
952
- The StreamValidator provides a complete EventEmitter-like interface with all standard stream methods:
953
-
954
- ```typescript
955
- // Create stream validator
956
- const streamValidator = Live.stream(UserSchema);
957
-
958
- // ===== EVENT EMITTER METHODS =====
959
-
960
- // Generic event listeners (.on, .once, .off, .emit)
961
- streamValidator.on("valid", (data) => {
962
- console.log("Valid data received:", data);
963
- });
964
-
965
- streamValidator.once("invalid", (data, errors) => {
966
- console.log("First invalid data:", errors);
967
- });
968
-
969
- streamValidator.on("error", (error) => {
970
- console.error("Stream error:", error);
971
- });
972
-
973
- // Custom events
974
- streamValidator.on("custom-event", (message) => {
975
- console.log("Custom event:", message);
976
- });
977
-
978
- streamValidator.emit("custom-event", "Hello from stream!");
979
-
980
- // Remove listeners
981
- streamValidator.off("valid", specificListener);
982
- streamValidator.off("invalid"); // Remove all listeners for event
983
- ```
984
-
985
- ##### Data Transformation Pipeline
986
-
987
- ```typescript
988
- // Build comprehensive data transformation pipeline
989
- const transformValidator = Live.stream(UserSchema)
990
- .transform((data) => {
991
- // Add metadata
992
- return { ...data, timestamp: Date.now(), source: "api" };
993
- })
994
- .filter((data) => {
995
- // Filter by business rules
996
- return data.age >= 21; // Only adults
997
- })
998
- .map((data) => {
999
- // Transform data format
1000
- return {
1001
- ...data,
1002
- name: data.name.toUpperCase(),
1003
- email: data.email.toLowerCase(),
1004
- };
1005
- });
1006
-
1007
- // Listen for pipeline results
1008
- transformValidator.on("valid", (data) => {
1009
- console.log("Processed data:", data); // Transformed and validated
1010
- });
1011
-
1012
- transformValidator.on("filtered", (data) => {
1013
- console.log("Data filtered out:", data); // Failed filter conditions
1014
- });
1015
-
1016
- transformValidator.on("invalid", (data, errors) => {
1017
- console.log("Validation failed after transformation:", errors);
1018
- });
1019
-
1020
- // Process data through pipeline
1021
- transformValidator.validate(rawUserData);
1022
- ```
1023
-
1024
- ##### Stream Control Methods
1025
-
1026
- ```typescript
1027
- // Stream control with pause/resume/destroy
1028
- const controlValidator = Live.stream(UserSchema);
1029
-
1030
- // Pause stream (queues incoming data)
1031
- controlValidator.pause();
1032
- console.log("Stream paused:", controlValidator.paused);
1033
-
1034
- // Data sent while paused gets queued
1035
- controlValidator.validate(userData1); // Queued
1036
- controlValidator.validate(userData2); // Queued
1037
-
1038
- console.log("Queue length:", controlValidator.queueLength);
1039
-
1040
- // Resume stream (processes queued data)
1041
- controlValidator.resume();
1042
- console.log("Stream resumed, queue processed");
1043
-
1044
- // Destroy stream (cleanup and prevent further use)
1045
- controlValidator.on("destroy", () => {
1046
- console.log("Stream destroyed and cleaned up");
1047
- });
1048
-
1049
- controlValidator.destroy();
1050
- console.log("Stream destroyed:", controlValidator.destroyed);
1051
- ```
1052
-
1053
- ##### Stream Piping
1054
-
1055
- ```typescript
1056
- // Pipe data between stream validators
1057
- const sourceValidator = Live.stream(InputSchema);
1058
- const destinationValidator = Live.stream(OutputSchema);
1059
-
1060
- // Pipe valid data from source to destination
1061
- sourceValidator.pipe(destinationValidator);
1062
-
1063
- // Data flows: source → destination
1064
- sourceValidator.validate(inputData);
1065
- // If valid, automatically sent to destinationValidator
1066
-
1067
- // Chain multiple streams
1068
- const pipeline = sourceValidator
1069
- .pipe(transformValidator)
1070
- .pipe(destinationValidator);
1071
- ```
1072
-
1073
- ##### Form Validator - Advanced Form Integration
1074
-
1075
- ```typescript
1076
- // Create form validator with field binding
1077
- const formValidator = Live.form(UserSchema);
1078
-
1079
- // Bind form fields to validator
1080
- formValidator.bindField("email", emailInput);
1081
- formValidator.bindField("name", nameInput);
1082
- formValidator.bindField("age", ageInput);
1083
-
1084
- // Enable automatic validation on input changes
1085
- formValidator.enableAutoValidation();
1086
-
1087
- // Handle form submission
1088
- formValidator.onSubmit((isValid, data, errors) => {
1089
- if (isValid) {
1090
- console.log("Form is valid, submitting:", data);
1091
- submitToAPI(data);
1092
- } else {
1093
- console.log("Form has errors:", errors);
1094
- displayErrors(errors);
1095
- }
1096
- });
1097
-
1098
- // Manual form validation
1099
- const formResult = formValidator.validateForm();
1100
- console.log("Form valid:", formResult.isValid);
1101
- ```
1102
-
1103
- ##### Advanced Event Handling
1104
-
1105
- ```typescript
1106
- const streamValidator = Live.stream(UserSchema);
1107
-
1108
- // Listen for all validation events
1109
- streamValidator.on("data", (data) => {
1110
- console.log("Data received for validation:", data);
1111
- });
1112
-
1113
- streamValidator.on("validated", (data, result) => {
1114
- console.log("Validation completed:", result.isValid);
1115
- });
1116
-
1117
- streamValidator.on("queued", (data) => {
1118
- console.log("Data queued (stream paused):", data);
1119
- });
1120
-
1121
- streamValidator.on("pause", () => {
1122
- console.log("Stream paused");
1123
- });
1124
-
1125
- streamValidator.on("resume", () => {
1126
- console.log("Stream resumed");
1127
- });
1128
-
1129
- // Error handling
1130
- streamValidator.on("error", (error) => {
1131
- console.error("Stream error:", error.message);
1132
- // Handle gracefully without crashing
1133
- });
1134
- ```
1135
-
1136
- ##### Performance and Statistics
1137
-
1138
- ```typescript
1139
- // Monitor stream performance
1140
- streamValidator.onStats((stats) => {
1141
- console.log("Validation Statistics:");
1142
- console.log(`- Total validated: ${stats.totalValidated}`);
1143
- console.log(`- Valid count: ${stats.validCount}`);
1144
- console.log(`- Invalid count: ${stats.invalidCount}`);
1145
- console.log(`- Error rate: ${(stats.errorRate * 100).toFixed(2)}%`);
1146
- console.log(`- Running since: ${stats.startTime}`);
1147
- });
1148
-
1149
- // Get current statistics
1150
- const currentStats = streamValidator.getStats();
1151
- console.log("Current performance:", currentStats);
1152
- ```
1153
-
1154
- ##### Integration with InterfaceSchema
1155
-
1156
- The Live utility is fully synchronized with InterfaceSchema modules, ensuring consistent validation behavior:
1157
-
1158
- ```typescript
1159
- const schema = Interface({
1160
- email: "email",
1161
- age: "number(18,120)",
1162
- role: "admin|user|guest",
1163
- });
1164
-
1165
- // Both produce identical validation results
1166
- const interfaceResult = schema.safeParse(userData);
1167
- const liveResult = Live.stream(schema).validate(userData);
1168
-
1169
- // Perfect synchronization guaranteed
1170
- console.log("Results match:", interfaceResult.success === liveResult.isValid);
1171
- ```
1172
-
1173
- #### Documentation Generation
1174
-
1175
- ```typescript
1176
- import { Docs } from "reliant-type"; //in beta
1177
-
1178
- // Generate OpenAPI specification
1179
- const openApiSpec = Docs.openapi(UserSchema, {
1180
- title: "User API",
1181
- version: "1.0.0",
1182
- servers: ["https://api.example.com"],
1183
- });
1184
-
1185
- // Generate TypeScript definitions
1186
- const typeDefinitions = Docs.typescript(UserSchema, {
1187
- exportName: "User",
1188
- namespace: "API",
1189
- });
1190
- ```
1191
-
1192
- #### Quick Utilities
1193
-
1194
- ```typescript
1195
- import { Quick } from "reliant-type";
1196
-
1197
- // Quick schema inference
1198
- const schema = Quick.fromSample(sampleData);
1199
-
1200
- // Quick conditional validation
1201
- const conditionalField = Quick.when("status").is("active").then("string");
1202
-
1203
- // Quick documentation
1204
- const docs = Quick.docs(schema);
1205
- const typescript = Quick.typescript(schema);
1206
- ```
1207
-
1208
- ### Validation Configuration
1209
-
1210
- #### Method Chaining
1211
-
1212
- ```typescript
1213
- const FlexibleSchema = UserSchema.loose() // Enable automatic type coercion
1214
- .allowUnknown() // Accept extra properties
1215
- .min(1) // Set minimum constraints
1216
- .max(100) // Set maximum constraints
1217
- .unique() // Require unique array values
1218
- .pattern(/^[A-Z]/) // Apply regex pattern validation
1219
- .default("N/A"); // Set default value
1220
- ```
1221
-
1222
- ## Contributing
1223
-
1224
- By contributing to ReliantType, you help reliant-type to:
1225
-
1226
- - Improve the quality of TypeScript validation
1227
- - Expand the reach of TypeScript in the JavaScript ecosystem
1228
- - Provide a robust and reliable validation solution for developers
1229
- - Foster a community of developers who care about code quality and security
1230
-
1231
- ### Development Environment
1232
-
1233
- ```bash
1234
- # Repository setup
1235
- git clone https://github.com/Nehonix-Team/reliant-type.git
1236
- cd reliant-type
1237
-
1238
- # Dependency installation
1239
- npm install
1240
-
1241
- # Test suite execution
1242
- npm run test
1243
-
1244
- # Performance benchmarking
1245
- npm run benchmark
1246
-
1247
- # Project build
1248
- npm run build
1249
- ```
1250
-
1251
- ### Quality Standards
1252
-
1253
- - **TypeScript**: Strict mode with comprehensive type checking
1254
- - **Test Coverage**: 95%+ coverage requirement
1255
- - **Performance**: All benchmarks must pass performance thresholds
1256
- - **Documentation**: Complete JSDoc comments for all public APIs
1257
- - **Code Quality**: ESLint and Prettier configuration compliance
1258
-
1259
- ### Contribution Process
1260
-
1261
- 1. **Fork** the repository on GitHub
1262
- 2. **Create** a feature branch: `git checkout -b feature/enhancement-name`
1263
- 3. **Implement** changes with comprehensive test coverage
1264
- 4. **Verify** all tests pass: `npm test`
1265
- 5. **Validate** performance: `npm run benchmark`
1266
- 6. **Commit** changes: `git commit -m 'Add enhancement: description'`
1267
- 7. **Push** to branch: `git push origin feature/enhancement-name`
1268
- 8. **Submit** a Pull Request with detailed description
1269
-
1270
- ### Issue Reporting
1271
-
1272
- For effective issue resolution, please provide:
1273
-
1274
- - **Environment Details**: Reliant Type, TypeScript, and Node.js versions
1275
- - **Reproduction Case**: Minimal code example demonstrating the issue
1276
- - **Expected Behavior**: Clear description of intended functionality
1277
- - **Actual Behavior**: Detailed explanation of observed behavior
1278
- - **Error Information**: Complete error messages and stack traces
1279
-
1280
- ## Release History
1281
-
1282
- See [CHANGELOG.md](./CHANGELOG.md) for comprehensive release notes and migration guides.
1283
-
1284
- ## License
1285
-
1286
- MIT License - see [LICENSE](./LICENSE) file for complete terms.
1287
-
1288
- ## Support Resources
1289
-
1290
- - **Complete Documentation**: [Full documentation](./docs/)
1291
- - **Issue Tracking**: [GitHub Issues](https://github.com/Nehonix-Team/reliant-type/issues)
1292
- - **Community Discussions**: [GitHub Discussions](https://github.com/Nehonix-Team/reliant-type/discussions)
1293
-
1294
- ---
1295
-
1296
- **Development Status**: Reliant Type is in active development with a focus on production readiness. We maintain transparency about capabilities and limitations while continuously improving based on community feedback and real-world usage patterns.
1297
-
1298
- <div align="center">
1299
- <p><strong>Built by Nehonix</strong></p>
1300
- <p>
1301
- <a href="https://nehonix.space">Website</a> •
1302
- <a href="https://sdk.nehonix.space">SDK</a> •
1303
- <a href="https://github.com/Nehonix-Team">GitHub</a>
1304
- </p>
1305
- </div>