reliant-type 1.0.0

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 (345) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1305 -0
  3. package/dist/cjs/constants/SECURITY_CONSTANTS.js +49 -0
  4. package/dist/cjs/constants/SECURITY_CONSTANTS.js.map +1 -0
  5. package/dist/cjs/constants/VALIDATION_CONSTANTS.js +103 -0
  6. package/dist/cjs/constants/VALIDATION_CONSTANTS.js.map +1 -0
  7. package/dist/cjs/core/schema/extensions/SmartInference.js +200 -0
  8. package/dist/cjs/core/schema/extensions/SmartInference.js.map +1 -0
  9. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/Docs.js +100 -0
  10. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/Docs.js.map +1 -0
  11. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/DocumentationGenerator.js +192 -0
  12. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/DocumentationGenerator.js.map +1 -0
  13. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/InteractiveDocumentationGenerator.js +174 -0
  14. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/InteractiveDocumentationGenerator.js.map +1 -0
  15. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/SchemaAnalyzer.js +54 -0
  16. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/SchemaAnalyzer.js.map +1 -0
  17. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/TypeScriptGenerator.js +50 -0
  18. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/TypeScriptGenerator.js.map +1 -0
  19. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/index.js +15 -0
  20. package/dist/cjs/core/schema/extensions/components/AutoDocumentation/index.js.map +1 -0
  21. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/ConditionalBuilder.js +70 -0
  22. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/ConditionalBuilder.js.map +1 -0
  23. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/ConditionalElse.js +40 -0
  24. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/ConditionalElse.js.map +1 -0
  25. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/ConditionalThen.js +19 -0
  26. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/ConditionalThen.js.map +1 -0
  27. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/MultiConditionalBuilder.js +20 -0
  28. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/MultiConditionalBuilder.js.map +1 -0
  29. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/MultiConditionalThen.js +49 -0
  30. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/MultiConditionalThen.js.map +1 -0
  31. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/index.js +98 -0
  32. package/dist/cjs/core/schema/extensions/components/ConditionalValidation/index.js.map +1 -0
  33. package/dist/cjs/core/schema/extensions/components/RealtimeValidation/FormValidator.js +85 -0
  34. package/dist/cjs/core/schema/extensions/components/RealtimeValidation/FormValidator.js.map +1 -0
  35. package/dist/cjs/core/schema/extensions/components/RealtimeValidation/LiveValidator.js +133 -0
  36. package/dist/cjs/core/schema/extensions/components/RealtimeValidation/LiveValidator.js.map +1 -0
  37. package/dist/cjs/core/schema/extensions/components/RealtimeValidation/StreamValidator.js +351 -0
  38. package/dist/cjs/core/schema/extensions/components/RealtimeValidation/StreamValidator.js.map +1 -0
  39. package/dist/cjs/core/schema/extensions/components/RealtimeValidation/index.js +109 -0
  40. package/dist/cjs/core/schema/extensions/components/RealtimeValidation/index.js.map +1 -0
  41. package/dist/cjs/core/schema/extensions/index.js +61 -0
  42. package/dist/cjs/core/schema/extensions/index.js.map +1 -0
  43. package/dist/cjs/core/schema/extensions/mods/index.js +51 -0
  44. package/dist/cjs/core/schema/extensions/mods/index.js.map +1 -0
  45. package/dist/cjs/core/schema/extensions/mods/openapi-converter.js +227 -0
  46. package/dist/cjs/core/schema/extensions/mods/openapi-converter.js.map +1 -0
  47. package/dist/cjs/core/schema/extensions/mods/typescript-generator.js +287 -0
  48. package/dist/cjs/core/schema/extensions/mods/typescript-generator.js.map +1 -0
  49. package/dist/cjs/core/schema/extensions/mods/validation-engine.js +224 -0
  50. package/dist/cjs/core/schema/extensions/mods/validation-engine.js.map +1 -0
  51. package/dist/cjs/core/schema/mode/interfaces/Interface.js +277 -0
  52. package/dist/cjs/core/schema/mode/interfaces/Interface.js.map +1 -0
  53. package/dist/cjs/core/schema/mode/interfaces/InterfaceSchema.js +1431 -0
  54. package/dist/cjs/core/schema/mode/interfaces/InterfaceSchema.js.map +1 -0
  55. package/dist/cjs/core/schema/mode/interfaces/conditional/evaluator/ConditionalEvaluator.js +520 -0
  56. package/dist/cjs/core/schema/mode/interfaces/conditional/evaluator/ConditionalEvaluator.js.map +1 -0
  57. package/dist/cjs/core/schema/mode/interfaces/conditional/parser/ConditionalAST.js +624 -0
  58. package/dist/cjs/core/schema/mode/interfaces/conditional/parser/ConditionalAST.js.map +1 -0
  59. package/dist/cjs/core/schema/mode/interfaces/conditional/parser/ConditionalLexer.js +811 -0
  60. package/dist/cjs/core/schema/mode/interfaces/conditional/parser/ConditionalLexer.js.map +1 -0
  61. package/dist/cjs/core/schema/mode/interfaces/conditional/parser/ConditionalParser.js +599 -0
  62. package/dist/cjs/core/schema/mode/interfaces/conditional/parser/ConditionalParser.js.map +1 -0
  63. package/dist/cjs/core/schema/mode/interfaces/conditional/types/ConditionalTypes.js +89 -0
  64. package/dist/cjs/core/schema/mode/interfaces/conditional/types/ConditionalTypes.js.map +1 -0
  65. package/dist/cjs/core/schema/mode/interfaces/errors/ErrorHandler.js +356 -0
  66. package/dist/cjs/core/schema/mode/interfaces/errors/ErrorHandler.js.map +1 -0
  67. package/dist/cjs/core/schema/mode/interfaces/errors/types/errors.type.js +80 -0
  68. package/dist/cjs/core/schema/mode/interfaces/errors/types/errors.type.js.map +1 -0
  69. package/dist/cjs/core/schema/mode/interfaces/precompilation/FieldPrecompilers.js +778 -0
  70. package/dist/cjs/core/schema/mode/interfaces/precompilation/FieldPrecompilers.js.map +1 -0
  71. package/dist/cjs/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.js +523 -0
  72. package/dist/cjs/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.js.map +1 -0
  73. package/dist/cjs/core/schema/mode/interfaces/typescript/ConditionalTypes.js +681 -0
  74. package/dist/cjs/core/schema/mode/interfaces/typescript/ConditionalTypes.js.map +1 -0
  75. package/dist/cjs/core/schema/mode/interfaces/typescript/IDESupport.js +430 -0
  76. package/dist/cjs/core/schema/mode/interfaces/typescript/IDESupport.js.map +1 -0
  77. package/dist/cjs/core/schema/mode/interfaces/typescript/TypeInference.js +225 -0
  78. package/dist/cjs/core/schema/mode/interfaces/typescript/TypeInference.js.map +1 -0
  79. package/dist/cjs/core/schema/mode/interfaces/typescript/index.js +44 -0
  80. package/dist/cjs/core/schema/mode/interfaces/typescript/index.js.map +1 -0
  81. package/dist/cjs/core/schema/mode/interfaces/validators/ConstraintParser.js +1134 -0
  82. package/dist/cjs/core/schema/mode/interfaces/validators/ConstraintParser.js.map +1 -0
  83. package/dist/cjs/core/schema/mode/interfaces/validators/TypeGuards.js +256 -0
  84. package/dist/cjs/core/schema/mode/interfaces/validators/TypeGuards.js.map +1 -0
  85. package/dist/cjs/core/schema/mode/interfaces/validators/TypeValidators.js +429 -0
  86. package/dist/cjs/core/schema/mode/interfaces/validators/TypeValidators.js.map +1 -0
  87. package/dist/cjs/core/schema/mode/interfaces/validators/UnionCache.js +404 -0
  88. package/dist/cjs/core/schema/mode/interfaces/validators/UnionCache.js.map +1 -0
  89. package/dist/cjs/core/schema/mode/interfaces/validators/ValidationHelpers.js +851 -0
  90. package/dist/cjs/core/schema/mode/interfaces/validators/ValidationHelpers.js.map +1 -0
  91. package/dist/cjs/core/schema/mode/interfaces/validators/mods/passValidator.js +262 -0
  92. package/dist/cjs/core/schema/mode/interfaces/validators/mods/passValidator.js.map +1 -0
  93. package/dist/cjs/core/schema/mode/interfaces/validators/mods/securityValidator.js +887 -0
  94. package/dist/cjs/core/schema/mode/interfaces/validators/mods/securityValidator.js.map +1 -0
  95. package/dist/cjs/core/schema/mode/interfaces/validators/mods/urlValidation.js +191 -0
  96. package/dist/cjs/core/schema/mode/interfaces/validators/mods/urlValidation.js.map +1 -0
  97. package/dist/cjs/core/schema/optimization/ObjectValidationCache.js +462 -0
  98. package/dist/cjs/core/schema/optimization/ObjectValidationCache.js.map +1 -0
  99. package/dist/cjs/core/schema/optimization/PerformanceMonitor.js +773 -0
  100. package/dist/cjs/core/schema/optimization/PerformanceMonitor.js.map +1 -0
  101. package/dist/cjs/core/schema/optimization/SchemaCompiler.js +600 -0
  102. package/dist/cjs/core/schema/optimization/SchemaCompiler.js.map +1 -0
  103. package/dist/cjs/core/types/ValidatorTypes.js +70 -0
  104. package/dist/cjs/core/types/ValidatorTypes.js.map +1 -0
  105. package/dist/cjs/core/types/parser.type.js +12 -0
  106. package/dist/cjs/core/types/parser.type.js.map +1 -0
  107. package/dist/cjs/core/utils/Make.js +61 -0
  108. package/dist/cjs/core/utils/Make.js.map +1 -0
  109. package/dist/cjs/core/utils/Mod.js +1033 -0
  110. package/dist/cjs/core/utils/Mod.js.map +1 -0
  111. package/dist/cjs/core/utils/UrlArgs.js +102 -0
  112. package/dist/cjs/core/utils/UrlArgs.js.map +1 -0
  113. package/dist/cjs/core/utils/arrayToEnum.js +18 -0
  114. package/dist/cjs/core/utils/arrayToEnum.js.map +1 -0
  115. package/dist/cjs/core/utils/createUrlArgsEnumFArray.js +13 -0
  116. package/dist/cjs/core/utils/createUrlArgsEnumFArray.js.map +1 -0
  117. package/dist/cjs/core/utils/securityHelpers.js +215 -0
  118. package/dist/cjs/core/utils/securityHelpers.js.map +1 -0
  119. package/dist/cjs/core/utils/securityValidatorHelpers.js +65 -0
  120. package/dist/cjs/core/utils/securityValidatorHelpers.js.map +1 -0
  121. package/dist/cjs/index.js +31 -0
  122. package/dist/cjs/index.js.map +1 -0
  123. package/dist/cjs/package.json +3 -0
  124. package/dist/esm/constants/SECURITY_CONSTANTS.js +47 -0
  125. package/dist/esm/constants/SECURITY_CONSTANTS.js.map +1 -0
  126. package/dist/esm/constants/VALIDATION_CONSTANTS.js +98 -0
  127. package/dist/esm/constants/VALIDATION_CONSTANTS.js.map +1 -0
  128. package/dist/esm/core/schema/extensions/SmartInference.js +197 -0
  129. package/dist/esm/core/schema/extensions/SmartInference.js.map +1 -0
  130. package/dist/esm/core/schema/extensions/components/AutoDocumentation/Docs.js +98 -0
  131. package/dist/esm/core/schema/extensions/components/AutoDocumentation/Docs.js.map +1 -0
  132. package/dist/esm/core/schema/extensions/components/AutoDocumentation/DocumentationGenerator.js +190 -0
  133. package/dist/esm/core/schema/extensions/components/AutoDocumentation/DocumentationGenerator.js.map +1 -0
  134. package/dist/esm/core/schema/extensions/components/AutoDocumentation/InteractiveDocumentationGenerator.js +172 -0
  135. package/dist/esm/core/schema/extensions/components/AutoDocumentation/InteractiveDocumentationGenerator.js.map +1 -0
  136. package/dist/esm/core/schema/extensions/components/AutoDocumentation/SchemaAnalyzer.js +52 -0
  137. package/dist/esm/core/schema/extensions/components/AutoDocumentation/SchemaAnalyzer.js.map +1 -0
  138. package/dist/esm/core/schema/extensions/components/AutoDocumentation/TypeScriptGenerator.js +48 -0
  139. package/dist/esm/core/schema/extensions/components/AutoDocumentation/TypeScriptGenerator.js.map +1 -0
  140. package/dist/esm/core/schema/extensions/components/AutoDocumentation/index.js +12 -0
  141. package/dist/esm/core/schema/extensions/components/AutoDocumentation/index.js.map +1 -0
  142. package/dist/esm/core/schema/extensions/components/ConditionalValidation/ConditionalBuilder.js +68 -0
  143. package/dist/esm/core/schema/extensions/components/ConditionalValidation/ConditionalBuilder.js.map +1 -0
  144. package/dist/esm/core/schema/extensions/components/ConditionalValidation/ConditionalElse.js +38 -0
  145. package/dist/esm/core/schema/extensions/components/ConditionalValidation/ConditionalElse.js.map +1 -0
  146. package/dist/esm/core/schema/extensions/components/ConditionalValidation/ConditionalThen.js +17 -0
  147. package/dist/esm/core/schema/extensions/components/ConditionalValidation/ConditionalThen.js.map +1 -0
  148. package/dist/esm/core/schema/extensions/components/ConditionalValidation/MultiConditionalBuilder.js +18 -0
  149. package/dist/esm/core/schema/extensions/components/ConditionalValidation/MultiConditionalBuilder.js.map +1 -0
  150. package/dist/esm/core/schema/extensions/components/ConditionalValidation/MultiConditionalThen.js +45 -0
  151. package/dist/esm/core/schema/extensions/components/ConditionalValidation/MultiConditionalThen.js.map +1 -0
  152. package/dist/esm/core/schema/extensions/components/ConditionalValidation/index.js +92 -0
  153. package/dist/esm/core/schema/extensions/components/ConditionalValidation/index.js.map +1 -0
  154. package/dist/esm/core/schema/extensions/components/RealtimeValidation/FormValidator.js +83 -0
  155. package/dist/esm/core/schema/extensions/components/RealtimeValidation/FormValidator.js.map +1 -0
  156. package/dist/esm/core/schema/extensions/components/RealtimeValidation/LiveValidator.js +131 -0
  157. package/dist/esm/core/schema/extensions/components/RealtimeValidation/LiveValidator.js.map +1 -0
  158. package/dist/esm/core/schema/extensions/components/RealtimeValidation/StreamValidator.js +349 -0
  159. package/dist/esm/core/schema/extensions/components/RealtimeValidation/StreamValidator.js.map +1 -0
  160. package/dist/esm/core/schema/extensions/components/RealtimeValidation/index.js +103 -0
  161. package/dist/esm/core/schema/extensions/components/RealtimeValidation/index.js.map +1 -0
  162. package/dist/esm/core/schema/extensions/index.js +53 -0
  163. package/dist/esm/core/schema/extensions/index.js.map +1 -0
  164. package/dist/esm/core/schema/extensions/mods/index.js +47 -0
  165. package/dist/esm/core/schema/extensions/mods/index.js.map +1 -0
  166. package/dist/esm/core/schema/extensions/mods/openapi-converter.js +225 -0
  167. package/dist/esm/core/schema/extensions/mods/openapi-converter.js.map +1 -0
  168. package/dist/esm/core/schema/extensions/mods/typescript-generator.js +284 -0
  169. package/dist/esm/core/schema/extensions/mods/typescript-generator.js.map +1 -0
  170. package/dist/esm/core/schema/extensions/mods/validation-engine.js +222 -0
  171. package/dist/esm/core/schema/extensions/mods/validation-engine.js.map +1 -0
  172. package/dist/esm/core/schema/mode/interfaces/Interface.js +269 -0
  173. package/dist/esm/core/schema/mode/interfaces/Interface.js.map +1 -0
  174. package/dist/esm/core/schema/mode/interfaces/InterfaceSchema.js +1429 -0
  175. package/dist/esm/core/schema/mode/interfaces/InterfaceSchema.js.map +1 -0
  176. package/dist/esm/core/schema/mode/interfaces/conditional/evaluator/ConditionalEvaluator.js +518 -0
  177. package/dist/esm/core/schema/mode/interfaces/conditional/evaluator/ConditionalEvaluator.js.map +1 -0
  178. package/dist/esm/core/schema/mode/interfaces/conditional/parser/ConditionalAST.js +620 -0
  179. package/dist/esm/core/schema/mode/interfaces/conditional/parser/ConditionalAST.js.map +1 -0
  180. package/dist/esm/core/schema/mode/interfaces/conditional/parser/ConditionalLexer.js +809 -0
  181. package/dist/esm/core/schema/mode/interfaces/conditional/parser/ConditionalLexer.js.map +1 -0
  182. package/dist/esm/core/schema/mode/interfaces/conditional/parser/ConditionalParser.js +597 -0
  183. package/dist/esm/core/schema/mode/interfaces/conditional/parser/ConditionalParser.js.map +1 -0
  184. package/dist/esm/core/schema/mode/interfaces/conditional/types/ConditionalTypes.js +89 -0
  185. package/dist/esm/core/schema/mode/interfaces/conditional/types/ConditionalTypes.js.map +1 -0
  186. package/dist/esm/core/schema/mode/interfaces/errors/ErrorHandler.js +354 -0
  187. package/dist/esm/core/schema/mode/interfaces/errors/ErrorHandler.js.map +1 -0
  188. package/dist/esm/core/schema/mode/interfaces/errors/types/errors.type.js +80 -0
  189. package/dist/esm/core/schema/mode/interfaces/errors/types/errors.type.js.map +1 -0
  190. package/dist/esm/core/schema/mode/interfaces/precompilation/FieldPrecompilers.js +776 -0
  191. package/dist/esm/core/schema/mode/interfaces/precompilation/FieldPrecompilers.js.map +1 -0
  192. package/dist/esm/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.js +521 -0
  193. package/dist/esm/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.js.map +1 -0
  194. package/dist/esm/core/schema/mode/interfaces/typescript/ConditionalTypes.js +681 -0
  195. package/dist/esm/core/schema/mode/interfaces/typescript/ConditionalTypes.js.map +1 -0
  196. package/dist/esm/core/schema/mode/interfaces/typescript/IDESupport.js +428 -0
  197. package/dist/esm/core/schema/mode/interfaces/typescript/IDESupport.js.map +1 -0
  198. package/dist/esm/core/schema/mode/interfaces/typescript/TypeInference.js +223 -0
  199. package/dist/esm/core/schema/mode/interfaces/typescript/TypeInference.js.map +1 -0
  200. package/dist/esm/core/schema/mode/interfaces/typescript/index.js +35 -0
  201. package/dist/esm/core/schema/mode/interfaces/typescript/index.js.map +1 -0
  202. package/dist/esm/core/schema/mode/interfaces/validators/ConstraintParser.js +1132 -0
  203. package/dist/esm/core/schema/mode/interfaces/validators/ConstraintParser.js.map +1 -0
  204. package/dist/esm/core/schema/mode/interfaces/validators/TypeGuards.js +254 -0
  205. package/dist/esm/core/schema/mode/interfaces/validators/TypeGuards.js.map +1 -0
  206. package/dist/esm/core/schema/mode/interfaces/validators/TypeValidators.js +427 -0
  207. package/dist/esm/core/schema/mode/interfaces/validators/TypeValidators.js.map +1 -0
  208. package/dist/esm/core/schema/mode/interfaces/validators/UnionCache.js +400 -0
  209. package/dist/esm/core/schema/mode/interfaces/validators/UnionCache.js.map +1 -0
  210. package/dist/esm/core/schema/mode/interfaces/validators/ValidationHelpers.js +849 -0
  211. package/dist/esm/core/schema/mode/interfaces/validators/ValidationHelpers.js.map +1 -0
  212. package/dist/esm/core/schema/mode/interfaces/validators/mods/passValidator.js +260 -0
  213. package/dist/esm/core/schema/mode/interfaces/validators/mods/passValidator.js.map +1 -0
  214. package/dist/esm/core/schema/mode/interfaces/validators/mods/securityValidator.js +881 -0
  215. package/dist/esm/core/schema/mode/interfaces/validators/mods/securityValidator.js.map +1 -0
  216. package/dist/esm/core/schema/mode/interfaces/validators/mods/urlValidation.js +189 -0
  217. package/dist/esm/core/schema/mode/interfaces/validators/mods/urlValidation.js.map +1 -0
  218. package/dist/esm/core/schema/optimization/ObjectValidationCache.js +460 -0
  219. package/dist/esm/core/schema/optimization/ObjectValidationCache.js.map +1 -0
  220. package/dist/esm/core/schema/optimization/PerformanceMonitor.js +771 -0
  221. package/dist/esm/core/schema/optimization/PerformanceMonitor.js.map +1 -0
  222. package/dist/esm/core/schema/optimization/SchemaCompiler.js +598 -0
  223. package/dist/esm/core/schema/optimization/SchemaCompiler.js.map +1 -0
  224. package/dist/esm/core/types/ValidatorTypes.js +65 -0
  225. package/dist/esm/core/types/ValidatorTypes.js.map +1 -0
  226. package/dist/esm/core/types/parser.type.js +12 -0
  227. package/dist/esm/core/types/parser.type.js.map +1 -0
  228. package/dist/esm/core/utils/Make.js +59 -0
  229. package/dist/esm/core/utils/Make.js.map +1 -0
  230. package/dist/esm/core/utils/Mod.js +1031 -0
  231. package/dist/esm/core/utils/Mod.js.map +1 -0
  232. package/dist/esm/core/utils/UrlArgs.js +98 -0
  233. package/dist/esm/core/utils/UrlArgs.js.map +1 -0
  234. package/dist/esm/core/utils/arrayToEnum.js +16 -0
  235. package/dist/esm/core/utils/arrayToEnum.js.map +1 -0
  236. package/dist/esm/core/utils/createUrlArgsEnumFArray.js +11 -0
  237. package/dist/esm/core/utils/createUrlArgsEnumFArray.js.map +1 -0
  238. package/dist/esm/core/utils/securityHelpers.js +207 -0
  239. package/dist/esm/core/utils/securityHelpers.js.map +1 -0
  240. package/dist/esm/core/utils/securityValidatorHelpers.js +62 -0
  241. package/dist/esm/core/utils/securityValidatorHelpers.js.map +1 -0
  242. package/dist/esm/index.js +12 -0
  243. package/dist/esm/index.js.map +1 -0
  244. package/dist/esm/package.json +3 -0
  245. package/dist/schema.d.ts +2595 -0
  246. package/docs/ALL_TYPES.md +120 -0
  247. package/docs/API-STABILITY.md +336 -0
  248. package/docs/CONDITIONAL-VALIDATION.md +637 -0
  249. package/docs/EXAMPLES.md +876 -0
  250. package/docs/FIELD-TYPES.md +829 -0
  251. package/docs/GETTING-STARTED.md +394 -0
  252. package/docs/LIVE-UTILITY.md +1137 -0
  253. package/docs/QUICK-REFERENCE.md +346 -0
  254. package/docs/README.md +205 -0
  255. package/docs/VSCODE-EXTENSION.md +458 -0
  256. package/package.json +219 -0
  257. package/src/bench/BENCHMARK-RESULTS.md +211 -0
  258. package/src/bench/benchmark-results.json +148 -0
  259. package/src/bench/performance-comparison.ts +218 -0
  260. package/src/bench/precompilation-benchmark.ts +218 -0
  261. package/src/constants/SECURITY_CONSTANTS.ts +44 -0
  262. package/src/constants/VALIDATION_CONSTANTS.ts +176 -0
  263. package/src/core/README.md +395 -0
  264. package/src/core/compiler/SchemaTransformer.ts +279 -0
  265. package/src/core/compiler/TypeAnalyzer.ts +378 -0
  266. package/src/core/compiler/TypeScriptCompilerIntegration.ts +220 -0
  267. package/src/core/compiler/TypeToSchemaConverter.ts +288 -0
  268. package/src/core/index.ts +70 -0
  269. package/src/core/schema/extensions/AutoDocumentation.ts +572 -0
  270. package/src/core/schema/extensions/ConditionalValidation.ts +330 -0
  271. package/src/core/schema/extensions/README.md +171 -0
  272. package/src/core/schema/extensions/RealtimeValidation.ts +656 -0
  273. package/src/core/schema/extensions/SmartInference.ts +224 -0
  274. package/src/core/schema/extensions/components/AutoDocumentation/Docs.ts +98 -0
  275. package/src/core/schema/extensions/components/AutoDocumentation/DocumentationGenerator.ts +201 -0
  276. package/src/core/schema/extensions/components/AutoDocumentation/InteractiveDocumentationGenerator.ts +176 -0
  277. package/src/core/schema/extensions/components/AutoDocumentation/OpenAPIGenerator.ts +175 -0
  278. package/src/core/schema/extensions/components/AutoDocumentation/SchemaAnalyzer.ts +49 -0
  279. package/src/core/schema/extensions/components/AutoDocumentation/TypeScriptGenerator.ts +54 -0
  280. package/src/core/schema/extensions/components/AutoDocumentation/index.ts +17 -0
  281. package/src/core/schema/extensions/components/ConditionalValidation/ConditionalBuilder.ts +101 -0
  282. package/src/core/schema/extensions/components/ConditionalValidation/ConditionalElse.ts +65 -0
  283. package/src/core/schema/extensions/components/ConditionalValidation/ConditionalThen.ts +33 -0
  284. package/src/core/schema/extensions/components/ConditionalValidation/Extend.ts +75 -0
  285. package/src/core/schema/extensions/components/ConditionalValidation/MultiConditionalBuilder.ts +16 -0
  286. package/src/core/schema/extensions/components/ConditionalValidation/MultiConditionalThen.ts +50 -0
  287. package/src/core/schema/extensions/components/ConditionalValidation/index.ts +104 -0
  288. package/src/core/schema/extensions/components/RealtimeValidation/FormValidator.ts +88 -0
  289. package/src/core/schema/extensions/components/RealtimeValidation/LiveValidator.ts +171 -0
  290. package/src/core/schema/extensions/components/RealtimeValidation/StreamValidator.ts +397 -0
  291. package/src/core/schema/extensions/components/RealtimeValidation/index.ts +114 -0
  292. package/src/core/schema/extensions/index.ts +76 -0
  293. package/src/core/schema/extensions/mods/index.ts +131 -0
  294. package/src/core/schema/extensions/mods/openapi-converter.ts +338 -0
  295. package/src/core/schema/extensions/mods/typescript-generator.ts +379 -0
  296. package/src/core/schema/extensions/mods/validation-engine.ts +295 -0
  297. package/src/core/schema/mode/interfaces/Interface.ts +364 -0
  298. package/src/core/schema/mode/interfaces/InterfaceSchema.ts +1838 -0
  299. package/src/core/schema/mode/interfaces/README.md +278 -0
  300. package/src/core/schema/mode/interfaces/conditional/evaluator/ConditionalEvaluator.ts +657 -0
  301. package/src/core/schema/mode/interfaces/conditional/parser/ConditionalAST.ts +826 -0
  302. package/src/core/schema/mode/interfaces/conditional/parser/ConditionalLexer.ts +992 -0
  303. package/src/core/schema/mode/interfaces/conditional/parser/ConditionalParser.ts +803 -0
  304. package/src/core/schema/mode/interfaces/conditional/parser/readme.md +406 -0
  305. package/src/core/schema/mode/interfaces/conditional/types/ConditionalTypes.ts +273 -0
  306. package/src/core/schema/mode/interfaces/errors/ErrorHandler.ts +624 -0
  307. package/src/core/schema/mode/interfaces/errors/types/errors.type.ts +102 -0
  308. package/src/core/schema/mode/interfaces/precompilation/FieldPrecompilers.ts +962 -0
  309. package/src/core/schema/mode/interfaces/precompilation/SchemaPrecompiler.ts +667 -0
  310. package/src/core/schema/mode/interfaces/typescript/ConditionalTypes.ts +1534 -0
  311. package/src/core/schema/mode/interfaces/typescript/IDESupport.ts +534 -0
  312. package/src/core/schema/mode/interfaces/typescript/TypeInference.ts +737 -0
  313. package/src/core/schema/mode/interfaces/typescript/index.ts +92 -0
  314. package/src/core/schema/mode/interfaces/validators/ConstraintParser.ts +1438 -0
  315. package/src/core/schema/mode/interfaces/validators/EnhancedErrorReporting.ts +227 -0
  316. package/src/core/schema/mode/interfaces/validators/TypeGuards.ts +288 -0
  317. package/src/core/schema/mode/interfaces/validators/TypeValidators.ts +660 -0
  318. package/src/core/schema/mode/interfaces/validators/UnionCache.ts +508 -0
  319. package/src/core/schema/mode/interfaces/validators/ValidationHelpers.ts +1257 -0
  320. package/src/core/schema/mode/interfaces/validators/index.ts +21 -0
  321. package/src/core/schema/mode/interfaces/validators/mods/passValidator.ts +424 -0
  322. package/src/core/schema/mode/interfaces/validators/mods/securityValidator.ts +1634 -0
  323. package/src/core/schema/mode/interfaces/validators/mods/urlValidation.ts +333 -0
  324. package/src/core/schema/optimization/ObjectValidationCache.ts +560 -0
  325. package/src/core/schema/optimization/PerformanceInitializer.ts +188 -0
  326. package/src/core/schema/optimization/PerformanceMonitor.ts +898 -0
  327. package/src/core/schema/optimization/SchemaCompiler.ts +730 -0
  328. package/src/core/testing/TestDataGenerator.ts +590 -0
  329. package/src/core/types/SchemaValidator.type.ts +210 -0
  330. package/src/core/types/ValidatorTypes.ts +93 -0
  331. package/src/core/types/extension.type.ts +109 -0
  332. package/src/core/types/objValidationCache.ts +17 -0
  333. package/src/core/types/parser.type.ts +15 -0
  334. package/src/core/types/perfoMonitor.ts +37 -0
  335. package/src/core/types/scompiler.ts +22 -0
  336. package/src/core/types/securityValidator.type.ts +10 -0
  337. package/src/core/types/types.ts +154 -0
  338. package/src/core/utils/Make.ts +97 -0
  339. package/src/core/utils/Mod.ts +1168 -0
  340. package/src/core/utils/UrlArgs.ts +124 -0
  341. package/src/core/utils/arrayToEnum.ts +89 -0
  342. package/src/core/utils/createUrlArgsEnumFArray.ts +11 -0
  343. package/src/core/utils/securityHelpers.ts +341 -0
  344. package/src/core/utils/securityValidatorHelpers.ts +76 -0
  345. package/src/index.ts +124 -0
@@ -0,0 +1,1431 @@
1
+ 'use strict';
2
+
3
+ require('./validators/TypeValidators.js');
4
+ var ConstraintParser = require('./validators/ConstraintParser.js');
5
+ var TypeGuards = require('./validators/TypeGuards.js');
6
+ var ValidationHelpers = require('./validators/ValidationHelpers.js');
7
+ var ErrorHandler = require('./errors/ErrorHandler.js');
8
+ var ConditionalParser = require('./conditional/parser/ConditionalParser.js');
9
+ var ConditionalEvaluator = require('./conditional/evaluator/ConditionalEvaluator.js');
10
+ var SchemaCompiler = require('../../optimization/SchemaCompiler.js');
11
+ var ObjectValidationCache = require('../../optimization/ObjectValidationCache.js');
12
+ var PerformanceMonitor = require('../../optimization/PerformanceMonitor.js');
13
+ var SchemaPrecompiler = require('./precompilation/SchemaPrecompiler.js');
14
+ var VALIDATION_CONSTANTS = require('../../../../constants/VALIDATION_CONSTANTS.js');
15
+ var Interface = require('./Interface.js');
16
+ var errors_type = require('./errors/types/errors.type.js');
17
+
18
+ /**
19
+ * TypeScript Interface-like Schema Definition System
20
+ *
21
+ * Allows defining schemas using TypeScript-like syntax with string literals
22
+ * that feel natural and are much easier to read and write.
23
+ */
24
+ /**
25
+ * Interface Schema class for TypeScript-like schema definitions
26
+ */
27
+ class InterfaceSchema {
28
+ constructor(definition, options = {}) {
29
+ this.definition = definition;
30
+ this.options = options;
31
+ this.compiledFields = [];
32
+ this.schemaKeys = [];
33
+ this.schemaComplexity = 0;
34
+ this.isOptimized = false;
35
+ this.optimizationLevel = SchemaPrecompiler.OptimizationLevel.NONE;
36
+ // Initialize conditional parser
37
+ this.ConditionalParser = new ConditionalParser.ConditionalParser({
38
+ allowNestedConditionals: true,
39
+ maxNestingDepth: VALIDATION_CONSTANTS.MAX_OBJECT_DEPTH,
40
+ strictMode: false,
41
+ enableDebug: false,
42
+ });
43
+ // ULTRA-OPTIMIZED: Pre-compile schema with advanced optimization
44
+ this.precompileSchema();
45
+ // Apply performance optimizations (skip if requested to prevent circular dependency)
46
+ if (!this.options.skipOptimization) {
47
+ this.applyOptimizations();
48
+ // Create precompiled validator for maximum speed
49
+ this.createPrecompiledValidator();
50
+ }
51
+ }
52
+ /**
53
+ * Check if a field type uses conditional syntax using secure regex pattern
54
+ */
55
+ isConditionalSyntax(fieldType) {
56
+ // Secure regex pattern to match: when <condition> *? <thenValue> [: <elseValue>]
57
+ const conditionalPattern = /^\s*when\s+.+?\s*\*\?\s*.+/;
58
+ return conditionalPattern.test(fieldType);
59
+ }
60
+ /**
61
+ * Apply performance optimizations based on schema characteristics
62
+ */
63
+ applyOptimizations() {
64
+ // Calculate schema complexity
65
+ this.schemaComplexity = this.calculateComplexity();
66
+ // Check if schema has conditional fields
67
+ const hasConditionalFields = this.compiledFields.some((field) => field.isConditional);
68
+ // Check nesting depth to avoid optimization bugs with deep nested objects
69
+ const maxNestingDepth = this.calculateMaxNestingDepth();
70
+ // debugging optimization decisions:
71
+ //// console.log(`[DEBUG] Schema optimization analysis:
72
+ // - Complexity: ${this.schemaComplexity}
73
+ // - Has conditionals: ${hasConditionalFields}
74
+ // - Max nesting depth: ${maxNestingDepth}
75
+ // - Will use advanced optimization: ${this.schemaComplexity > 15 && !hasConditionalFields && maxNestingDepth <= 3}
76
+ // - Will use caching: ${this.schemaComplexity > 5 && !hasConditionalFields && maxNestingDepth <= 3}`);
77
+ // Apply optimizations based on complexity, but avoid advanced optimizations for conditional fields or deep nesting
78
+ if (this.schemaComplexity > 15 &&
79
+ !hasConditionalFields &&
80
+ maxNestingDepth <= 3) {
81
+ // High complexity, no conditionals, shallow nesting - use advanced optimizations
82
+ this.compiledValidator = SchemaCompiler.SchemaCompiler.compileSchema(this.definition, this.options);
83
+ this.isOptimized = true;
84
+ }
85
+ else if (this.schemaComplexity > 5 &&
86
+ !hasConditionalFields &&
87
+ maxNestingDepth <= 3) {
88
+ // Medium complexity, no conditionals, shallow nesting - use caching
89
+ this.isOptimized = true;
90
+ }
91
+ // Note: Conditional fields or deep nesting use the standard validation path for reliability
92
+ // Start performance monitoring if enabled
93
+ if (this.options.enablePerformanceMonitoring) {
94
+ PerformanceMonitor.PerformanceMonitor.startMonitoring();
95
+ }
96
+ }
97
+ /**
98
+ * Create precompiled validator for maximum speed
99
+ * SAFETY: Now includes recursion protection and cycle detection
100
+ */
101
+ createPrecompiledValidator() {
102
+ // Only create precompiled validator for non-conditional schemas and non-loose mode
103
+ const hasConditionalFields = this.compiledFields.some((field) => field.isConditional);
104
+ // Check nesting depth to avoid precompilation bugs with deep nested objects
105
+ const maxNestingDepth = this.calculateMaxNestingDepth();
106
+ // CRITICAL FIX: Also check for nested conditional fields
107
+ const hasNestedConditionalFields = this.hasNestedConditionalFields();
108
+ // Skip precompilation if loose mode is enabled (needs type coercion support), deep nesting, or nested conditionals
109
+ if (!hasConditionalFields &&
110
+ !hasNestedConditionalFields &&
111
+ !this.options.loose &&
112
+ maxNestingDepth <= 3) {
113
+ try {
114
+ this.precompiledValidator = SchemaPrecompiler.SchemaPrecompiler.precompileSchema(this.definition, this.options);
115
+ this.optimizationLevel = this.precompiledValidator._optimizationLevel;
116
+ }
117
+ catch (error) {
118
+ // Fallback to standard validation if precompilation fails
119
+ // console.warn(
120
+ // "Schema precompilation failed, falling back to standard validation:",
121
+ // error
122
+ // );
123
+ }
124
+ }
125
+ }
126
+ /**
127
+ * Check if schema has nested conditional fields
128
+ * CRITICAL FIX: This prevents precompilation for schemas with nested conditionals
129
+ */
130
+ hasNestedConditionalFields() {
131
+ const checkObject = (obj) => {
132
+ for (const [key, value] of Object.entries(obj)) {
133
+ if (typeof value === "string") {
134
+ // Check if this field has conditional syntax
135
+ if (this.isConditionalSyntax(value)) {
136
+ return true;
137
+ }
138
+ // Note: Precompilation issues have been fixed for double, positive, negative, and regex patterns
139
+ }
140
+ else if (typeof value === "object" &&
141
+ value !== null &&
142
+ !Array.isArray(value)) {
143
+ // Recursively check nested objects
144
+ if (checkObject(value)) {
145
+ return true;
146
+ }
147
+ }
148
+ }
149
+ return false;
150
+ };
151
+ return checkObject(this.definition);
152
+ }
153
+ /**
154
+ * Calculate schema complexity score
155
+ */
156
+ calculateComplexity() {
157
+ let complexity = this.compiledFields.length;
158
+ for (const field of this.compiledFields) {
159
+ if (field.isConditional)
160
+ complexity += 5;
161
+ if (field.isArray)
162
+ complexity += 2;
163
+ if (typeof field.originalType === "object")
164
+ complexity += 3;
165
+ }
166
+ return complexity;
167
+ }
168
+ /**
169
+ * Calculate maximum nesting depth to avoid optimization bugs
170
+ */
171
+ calculateMaxNestingDepth() {
172
+ const calculateDepth = (obj, currentDepth = 0) => {
173
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
174
+ return currentDepth;
175
+ }
176
+ let maxDepth = currentDepth;
177
+ for (const value of Object.values(obj)) {
178
+ if (typeof value === "object" &&
179
+ value !== null &&
180
+ !Array.isArray(value)) {
181
+ const depth = calculateDepth(value, currentDepth + 1);
182
+ maxDepth = Math.max(maxDepth, depth);
183
+ }
184
+ }
185
+ return maxDepth;
186
+ };
187
+ return calculateDepth(this.definition);
188
+ }
189
+ /**
190
+ * Pre-compile schema for faster validation
191
+ */
192
+ precompileSchema() {
193
+ const entries = Object.entries(this.definition);
194
+ this.schemaKeys = entries.map(([key]) => key);
195
+ this.compiledFields = [];
196
+ for (const [key, fieldType] of entries) {
197
+ const compiled = {
198
+ key,
199
+ originalType: fieldType,
200
+ isString: typeof fieldType === "string",
201
+ isConditional: false,
202
+ };
203
+ if (typeof fieldType === "string") {
204
+ // Check for conditional syntax (when ... *? ... : ...)
205
+ if (this.isConditionalSyntax(fieldType)) {
206
+ compiled.isConditional = true;
207
+ // Parse with parser
208
+ const { ast, errors } = this.ConditionalParser.parse(fieldType);
209
+ if (ast && errors.length === 0) {
210
+ compiled.ConditionalAST = ast;
211
+ }
212
+ else {
213
+ // If parsing fails, treat as regular field type
214
+ // console.warn(
215
+ // `Failed to parse conditional expression: ${fieldType}`,
216
+ // errors
217
+ // );
218
+ const parsed = ConstraintParser.ConstraintParser.parseConstraints(fieldType);
219
+ compiled.parsedConstraints = parsed;
220
+ compiled.isOptional = parsed.optional;
221
+ // Secure regex pattern to check for array type
222
+ const arrayPattern = /\[\]$/;
223
+ compiled.isArray = arrayPattern.test(parsed.type);
224
+ compiled.elementType = compiled.isArray
225
+ ? parsed.type.replace(/\[\]$/, "")
226
+ : parsed.type;
227
+ compiled.isConditional = false;
228
+ compiled.isConditional = false;
229
+ }
230
+ }
231
+ else {
232
+ // Pre-parse constraints for regular field types
233
+ const parsed = ConstraintParser.ConstraintParser.parseConstraints(fieldType);
234
+ compiled.parsedConstraints = parsed;
235
+ compiled.isOptional = parsed.optional;
236
+ // Secure regex pattern to check for array type
237
+ const arrayPattern = /\[\]$/;
238
+ compiled.isArray = arrayPattern.test(parsed.type);
239
+ compiled.elementType = compiled.isArray
240
+ ? parsed.type.replace(/\[\]$/, "")
241
+ : parsed.type;
242
+ }
243
+ }
244
+ else if (TypeGuards.TypeGuards.isConditionalValidation(fieldType)) {
245
+ // Object-based conditional validation (keep for backward compatibility)
246
+ compiled.isConditional = true;
247
+ compiled.conditionalConfig = fieldType;
248
+ }
249
+ this.compiledFields.push(compiled);
250
+ }
251
+ }
252
+ /**
253
+ * Validate data against the interface schema - ULTRA-OPTIMIZED version
254
+ */
255
+ validate(data) {
256
+ const startTime = performance.now();
257
+ const operationId = `schema-${this.schemaComplexity}`;
258
+ let result;
259
+ // Check if schema has conditional fields - if so, force standard validation
260
+ const hasConditionalFields = this.compiledFields.some((field) => field.isConditional);
261
+ // Check for required fields (need standard validation for proper required field handling)
262
+ const hasRequiredFields = this.compiledFields.some((field) => field.parsedConstraints?.required === true);
263
+ // Use precompiled validator first (fastest path)
264
+ // BUT: Skip precompiled validator if loose mode is enabled (needs type coercion)
265
+ // ALSO: Skip ALL optimizations if schema has conditional fields (they need special handling)
266
+ // ALSO: Skip precompiled validator if schema has required fields (they need proper validation)
267
+ if (this.precompiledValidator &&
268
+ !this.options.loose &&
269
+ !hasConditionalFields &&
270
+ !hasRequiredFields) {
271
+ // console.log("using precompiled validator");
272
+ result = this.precompiledValidator(data);
273
+ }
274
+ else if (this.isOptimized &&
275
+ this.compiledValidator &&
276
+ !hasConditionalFields) {
277
+ // console.log("using compiled validator");
278
+ // Use compiled validator (second fastest) - but not for conditional fields
279
+ result = this.compiledValidator.validate(data);
280
+ }
281
+ else if (this.isOptimized &&
282
+ this.schemaComplexity > 5 &&
283
+ !hasConditionalFields) {
284
+ // console.log("using cached validation for medium complexity");
285
+ // Use cached validation for medium complexity - but not for conditional fields
286
+ result = ObjectValidationCache.ObjectValidationCache.getCachedValidation(data, (value) => this.validateStandard(value), []);
287
+ }
288
+ else {
289
+ // console.log(
290
+ // "using standard validation for simple schemas or conditional schemas"
291
+ // );
292
+ // Standard validation for simple schemas or conditional schemas
293
+ result = this.validateStandard(data);
294
+ }
295
+ // Record performance metrics
296
+ const duration = performance.now() - startTime;
297
+ PerformanceMonitor.PerformanceMonitor.recordOperation(operationId, duration, this.schemaComplexity, this.isOptimized || !!this.precompiledValidator);
298
+ return result;
299
+ }
300
+ /**
301
+ * Standard validation method (original implementation)
302
+ */
303
+ validateStandard(data) {
304
+ // console.log("validating standard");
305
+ // Fast path for non-objects
306
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
307
+ return ValidationHelpers.ValidationHelpers.createErrorResult("Expected object", data);
308
+ }
309
+ const validatedData = {};
310
+ const errors = [];
311
+ const warnings = [];
312
+ let hasErrors = false;
313
+ // Apply default values if they exist
314
+ const defaults = this.options?.defaults;
315
+ if (defaults) {
316
+ for (const [key, defaultValue] of Object.entries(defaults)) {
317
+ if (!(key in data) || data[key] === undefined) {
318
+ data = { ...data, [key]: defaultValue };
319
+ }
320
+ }
321
+ }
322
+ // Use pre-compiled fields for faster validation
323
+ for (let i = 0; i < this.compiledFields.length; i++) {
324
+ const field = this.compiledFields[i];
325
+ const value = data[field.key];
326
+ let fieldResult;
327
+ // Use pre-compiled information to skip parsing
328
+ if (field.isConditional) {
329
+ // console.log("validating conditional field");
330
+ if (field.isConditional && field.ConditionalAST) {
331
+ // FIXED: Use conditional validation with proper nested context
332
+ // Pass the current data object as nested context for field resolution
333
+ fieldResult = this.validateEnhancedConditionalField(field.ConditionalAST, value, data, // Full data for fallback
334
+ data // Nested context (same as data at this level)
335
+ );
336
+ }
337
+ else {
338
+ // console.log("validating legacy conditional field");
339
+ // Use legacy conditional validation
340
+ fieldResult = this.validateConditionalFieldWithContext(field.conditionalConfig, value, data);
341
+ }
342
+ }
343
+ else if (field.isString && field.parsedConstraints) {
344
+ // console.log("validating precompiled string field");
345
+ // Use pre-parsed constraints for string fields
346
+ fieldResult = this.validatePrecompiledStringField(field, value);
347
+ }
348
+ else {
349
+ // console.log("fallback to original validation for complex types");
350
+ // Fallback to original validation for complex types
351
+ fieldResult = this.validateField(field.key, field.originalType, value, data);
352
+ }
353
+ // Process field result
354
+ if (!fieldResult.success) {
355
+ hasErrors = true;
356
+ // Batch error processing with proper path tracking
357
+ for (let j = 0; j < fieldResult.errors.length; j++) {
358
+ const error = fieldResult.errors[j];
359
+ // Convert string errors to ValidationError objects and add field path
360
+ if (typeof error === "string") {
361
+ errors.push(ErrorHandler.ErrorHandler.createSimpleError(error, [field.key]));
362
+ }
363
+ else if (error && typeof error === "object" && "message" in error) {
364
+ // This is already a ValidationError object, add field to path and enhance message
365
+ const validationError = error;
366
+ const fullPath = [field.key, ...validationError.path];
367
+ // Always use the full path for field context, replacing any existing field context
368
+ let message = validationError.message;
369
+ // Remove any existing field context to avoid duplication
370
+ const fieldContextRegex = / in field "[^"]*"$/;
371
+ message = message.replace(fieldContextRegex, "");
372
+ // Add the complete field path context
373
+ const fieldContext = fullPath.length > 0 ? ` in field "${fullPath.join(".")}"` : "";
374
+ errors.push({
375
+ ...validationError,
376
+ path: fullPath,
377
+ message: `${message}${fieldContext}`,
378
+ });
379
+ }
380
+ else {
381
+ // Fallback for unknown error format
382
+ errors.push(ErrorHandler.ErrorHandler.createSimpleError(JSON.stringify(error), [field.key]));
383
+ }
384
+ }
385
+ }
386
+ else if (fieldResult.data !== undefined) {
387
+ validatedData[field.key] = fieldResult.data;
388
+ }
389
+ // Batch warning processing
390
+ for (let j = 0; j < fieldResult.warnings.length; j++) {
391
+ warnings.push(`${field.key}: ${fieldResult.warnings[j]}`);
392
+ }
393
+ }
394
+ // Handle extra properties efficiently using pre-computed schema keys
395
+ const inputKeys = Object.keys(data);
396
+ const omittedFields = this.options._omittedFields || [];
397
+ // Check for strict mode or additionalProperties setting
398
+ const isStrict = this.options.strict === true ||
399
+ this.options.additionalProperties === false;
400
+ const allowAdditional = this.options.allowUnknown === true ||
401
+ this.options.additionalProperties === true;
402
+ if (allowAdditional && !isStrict) {
403
+ // Allow unknown properties
404
+ for (let i = 0; i < inputKeys.length; i++) {
405
+ const key = inputKeys[i];
406
+ // Secure check using indexOf instead of includes for security
407
+ if (this.schemaKeys.indexOf(key) === -1 &&
408
+ omittedFields.indexOf(key) === -1) {
409
+ validatedData[key] = data[key];
410
+ }
411
+ }
412
+ }
413
+ else {
414
+ // Check for extra keys in strict mode or when additional properties are not allowed
415
+ const extraKeys = [];
416
+ for (let i = 0; i < inputKeys.length; i++) {
417
+ const key = inputKeys[i];
418
+ // Secure check using indexOf instead of includes for security
419
+ if (this.schemaKeys.indexOf(key) === -1 &&
420
+ omittedFields.indexOf(key) === -1) {
421
+ extraKeys.push(key);
422
+ }
423
+ }
424
+ if (extraKeys.length > 0) {
425
+ if (isStrict) {
426
+ // In strict mode, reject extra properties
427
+ hasErrors = true;
428
+ errors.push(ErrorHandler.ErrorHandler.createSimpleError(`Unexpected properties: ${extraKeys.join(", ")}`, []));
429
+ }
430
+ }
431
+ }
432
+ // console.log("validation error: ", validatedData);
433
+ return {
434
+ success: !hasErrors,
435
+ errors: errors,
436
+ warnings,
437
+ data: hasErrors ? undefined : validatedData,
438
+ };
439
+ }
440
+ /**
441
+ * Validate pre-compiled string field for maximum performance
442
+ */
443
+ validatePrecompiledStringField(field, value) {
444
+ const { parsedConstraints } = field;
445
+ const { type, constraints, optional: isOptional, required: isRequired, } = parsedConstraints;
446
+ // Fast path for undefined/null values
447
+ if (value === undefined) {
448
+ return isOptional
449
+ ? {
450
+ success: true,
451
+ errors: [],
452
+ warnings: [],
453
+ data: this.options.default,
454
+ }
455
+ : {
456
+ success: false,
457
+ errors: [ErrorHandler.ErrorHandler.createMissingFieldError([], field.key)],
458
+ warnings: [],
459
+ data: value,
460
+ };
461
+ }
462
+ if (value === null) {
463
+ return isOptional
464
+ ? { success: true, errors: [], warnings: [], data: null }
465
+ : {
466
+ success: false,
467
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "null", value)],
468
+ warnings: [],
469
+ data: value,
470
+ };
471
+ }
472
+ // Handle array types
473
+ if (field.isArray) {
474
+ if (!Array.isArray(value)) {
475
+ return {
476
+ success: false,
477
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "array", value)],
478
+ warnings: [],
479
+ data: value,
480
+ };
481
+ }
482
+ // Check array constraints
483
+ if (constraints.minItems !== undefined &&
484
+ value.length < constraints.minItems) {
485
+ return {
486
+ success: false,
487
+ errors: [
488
+ ErrorHandler.ErrorHandler.createArrayError([], `must have at least ${constraints.minItems} items, got ${value.length}`, value, errors_type.ErrorCode.ARRAY_TOO_SHORT),
489
+ ],
490
+ warnings: [],
491
+ data: value,
492
+ };
493
+ }
494
+ if (constraints.maxItems !== undefined &&
495
+ value.length > constraints.maxItems) {
496
+ return {
497
+ success: false,
498
+ errors: [
499
+ ErrorHandler.ErrorHandler.createArrayError([], `must have at most ${constraints.maxItems} items, got ${value.length}`, value, errors_type.ErrorCode.ARRAY_TOO_LONG),
500
+ ],
501
+ warnings: [],
502
+ data: value,
503
+ };
504
+ }
505
+ // Validate array elements
506
+ const validatedArray = [];
507
+ const errors = [];
508
+ for (let i = 0; i < value.length; i++) {
509
+ // Use validateStringFieldType to handle union types properly
510
+ const elementResult = this.validateStringFieldType(field.elementType, value[i]);
511
+ if (!elementResult.success) {
512
+ errors.push(...elementResult.errors.map((error) => ({
513
+ ...error,
514
+ path: [i.toString(), ...error.path],
515
+ })));
516
+ }
517
+ else {
518
+ validatedArray.push(elementResult.data);
519
+ }
520
+ }
521
+ if (errors.length > 0) {
522
+ return { success: false, errors, warnings: [], data: value };
523
+ }
524
+ // Check uniqueness if required
525
+ if (constraints.unique) {
526
+ const uniqueValues = new Set(validatedArray);
527
+ if (uniqueValues.size !== validatedArray.length) {
528
+ return {
529
+ success: false,
530
+ errors: [
531
+ ErrorHandler.ErrorHandler.createArrayError([], "values must be unique", value, errors_type.ErrorCode.ARRAY_VALUES_NOT_UNIQUE),
532
+ ],
533
+ warnings: [],
534
+ data: value,
535
+ };
536
+ }
537
+ }
538
+ return { success: true, errors: [], warnings: [], data: validatedArray };
539
+ }
540
+ // Handle constant values using secure regex
541
+ const constantPattern = /^=/;
542
+ if (constantPattern.test(type)) {
543
+ // Validate constant value
544
+ return ValidationHelpers.ValidationHelpers.validateConstantType(type.replace(/^=/, ""), value);
545
+ }
546
+ // Handle union types using secure regex
547
+ const unionPattern = /\|/;
548
+ if (unionPattern.test(type)) {
549
+ return ValidationHelpers.ValidationHelpers.validateUnionType(type, value);
550
+ }
551
+ // Handle basic types using pre-parsed constraints
552
+ return ValidationHelpers.ValidationHelpers.routeTypeValidation(type, value, { ...constraints, ...this.options }, constraints, isRequired // FIXED: Pass the required parameter
553
+ );
554
+ }
555
+ /**
556
+ * Validate individual field
557
+ */
558
+ validateField(_key, fieldType, value, fullData // NEW: Add full data context for nested validation
559
+ ) {
560
+ const result = {
561
+ success: true,
562
+ errors: [],
563
+ warnings: [],
564
+ data: value,
565
+ };
566
+ // console.log("checking for union types");
567
+ // Handle union values
568
+ if (TypeGuards.TypeGuards.isUnionValue(fieldType)) {
569
+ const allowedValues = fieldType.union;
570
+ // Secure check using indexOf instead of includes
571
+ if (allowedValues.indexOf(value) === -1) {
572
+ result.success = false;
573
+ result.errors.push(ErrorHandler.ErrorHandler.createUnionError([], allowedValues, value));
574
+ }
575
+ return result;
576
+ }
577
+ // console.log("checking for constant types");
578
+ // Handle constant values
579
+ if (TypeGuards.TypeGuards.isConstantValue(fieldType)) {
580
+ const expectedValue = fieldType.const;
581
+ const isOptional = "optional" in fieldType && fieldType.optional;
582
+ if (value === undefined && isOptional) {
583
+ result.data = this.options.default;
584
+ return result;
585
+ }
586
+ if (value !== expectedValue) {
587
+ result.success = false;
588
+ result.errors.push(ErrorHandler.ErrorHandler.createConstantError([], expectedValue, value, expectedValue));
589
+ }
590
+ return result;
591
+ }
592
+ // console.log("checking for optional constant types");
593
+ // Handle optional nested schemas
594
+ if (TypeGuards.TypeGuards.isOptionalSchemaInterface(fieldType)) {
595
+ // console.log("validating optional schema interface");
596
+ if (value === undefined) {
597
+ result.data = this.options.default;
598
+ return result;
599
+ }
600
+ const nestedSchema = new InterfaceSchema(fieldType.schema, this.options);
601
+ return nestedSchema.validate(value);
602
+ }
603
+ // console.log("checking for conditional validation objects");
604
+ // Handle conditional validation objects
605
+ if (TypeGuards.TypeGuards.isConditionalValidation(fieldType)) {
606
+ return this.validateConditionalField(fieldType, value);
607
+ }
608
+ // console.log("checking for nested objects");
609
+ // Handle nested objects
610
+ if (TypeGuards.TypeGuards.isSchemaInterface(fieldType)) {
611
+ const nestedSchema = new InterfaceSchema(fieldType, this.options);
612
+ // CRITICAL FIX: For nested objects, we need to pass the full data context
613
+ // so that conditional validation can access parent fields
614
+ const nestedResult = this.validateNestedObjectWithContext(nestedSchema, value, fullData);
615
+ // Path is already handled in the main validation loop, no need to add it here
616
+ // The main validation loop will add the field key to the path
617
+ return nestedResult;
618
+ }
619
+ // console.log("checking for array of schemas");
620
+ // Handle array of schemas
621
+ if (Array.isArray(fieldType) && fieldType.length === 1) {
622
+ if (!Array.isArray(value)) {
623
+ result.success = false;
624
+ result.errors.push(ErrorHandler.ErrorHandler.createTypeError([], "array", value));
625
+ return result;
626
+ }
627
+ const validatedArray = [];
628
+ const itemSchema = fieldType[0];
629
+ for (let i = 0; i < value.length; i++) {
630
+ const elementResult = this.validateField(`[${i}]`, itemSchema, value[i]);
631
+ if (!elementResult.success) {
632
+ result.success = false;
633
+ result.errors.push(...elementResult.errors.map((error) => ({
634
+ ...error,
635
+ path: [i.toString(), ...error.path],
636
+ })));
637
+ }
638
+ else {
639
+ validatedArray.push(elementResult.data);
640
+ }
641
+ }
642
+ if (result.success) {
643
+ result.data = validatedArray;
644
+ }
645
+ return result;
646
+ }
647
+ // Handle string field types
648
+ if (typeof fieldType === "string") {
649
+ // console.log("validating string field type");
650
+ // conditional validation is handled in the main validation loop
651
+ // This method is only for direct field type validation
652
+ return this.validateStringFieldType(fieldType, value);
653
+ }
654
+ // console.log("val/donex");
655
+ result.success = false;
656
+ result.errors.push(ErrorHandler.ErrorHandler.createUnknownFieldError([], fieldType));
657
+ return result;
658
+ }
659
+ /**
660
+ * Validate string-based field types - optimized version
661
+ */
662
+ validateStringFieldType(fieldType, value) {
663
+ // Check for conditional expressions first - route to conditional validation
664
+ if (this.isConditionalSyntax(fieldType)) {
665
+ // Parse conditional expression
666
+ const { ast, errors } = this.ConditionalParser.parse(fieldType);
667
+ if (ast && errors.length === 0) {
668
+ // Use conditional validation (without full data context)
669
+ return this.validateEnhancedConditionalField(ast, value, {}, {});
670
+ }
671
+ else {
672
+ // If parsing fails, return error
673
+ return {
674
+ success: false,
675
+ errors: [
676
+ ErrorHandler.ErrorHandler.createValidationError([], `Invalid conditional expression: ${fieldType}`, value),
677
+ ],
678
+ warnings: [],
679
+ data: value,
680
+ };
681
+ }
682
+ }
683
+ // Parse constraints once
684
+ const { type: parsedType, constraints, optional: isOptional, required: isRequired, } = ConstraintParser.ConstraintParser.parseConstraints(fieldType);
685
+ // Fast path for undefined/null values
686
+ if (value === undefined) {
687
+ return isOptional
688
+ ? {
689
+ success: true,
690
+ errors: [],
691
+ warnings: [],
692
+ data: this.options.default,
693
+ }
694
+ : {
695
+ success: false,
696
+ errors: [
697
+ {
698
+ path: [],
699
+ message: "Missing required field",
700
+ code: errors_type.ErrorCode.MISSING_REQUIRED_FIELD,
701
+ expected: "required field",
702
+ received: undefined,
703
+ receivedType: "undefined",
704
+ },
705
+ ],
706
+ warnings: [],
707
+ data: value,
708
+ };
709
+ }
710
+ if (value === null) {
711
+ return isOptional
712
+ ? { success: true, errors: [], warnings: [], data: null }
713
+ : {
714
+ success: false,
715
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "null", value)],
716
+ warnings: [],
717
+ data: value,
718
+ };
719
+ }
720
+ // Secure regex pattern to check for array type
721
+ const arrayPattern = /\[\]$/;
722
+ const isArray = arrayPattern.test(parsedType);
723
+ const elementType = isArray ? parsedType.replace(/\[\]$/, "") : parsedType;
724
+ // Handle array types
725
+ if (isArray) {
726
+ if (!Array.isArray(value)) {
727
+ return {
728
+ success: false,
729
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "array", value)],
730
+ warnings: [],
731
+ data: value,
732
+ };
733
+ }
734
+ // Apply parsed constraints to options, but preserve important options like loose
735
+ const Options = { ...constraints, ...this.options };
736
+ // Check array constraints
737
+ if (Options.minItems !== undefined && value.length < Options.minItems) {
738
+ return {
739
+ success: false,
740
+ errors: [
741
+ ErrorHandler.ErrorHandler.createArrayError([], `must have at least ${Options.minItems} items, got ${value.length}`, value, errors_type.ErrorCode.ARRAY_TOO_SHORT),
742
+ ],
743
+ warnings: [],
744
+ data: value,
745
+ };
746
+ }
747
+ if (Options.maxItems !== undefined && value.length > Options.maxItems) {
748
+ return {
749
+ success: false,
750
+ errors: [
751
+ ErrorHandler.ErrorHandler.createArrayError([], `must have at most ${Options.maxItems} items, got ${value.length}`, value, errors_type.ErrorCode.ARRAY_TOO_LONG),
752
+ ],
753
+ warnings: [],
754
+ data: value,
755
+ };
756
+ }
757
+ // Validate array elements
758
+ const validatedArray = [];
759
+ const errors = [];
760
+ for (let i = 0; i < value.length; i++) {
761
+ const elementResult = this.validateStringFieldType(elementType, value[i]);
762
+ if (!elementResult.success) {
763
+ errors.push(...elementResult.errors.map((error) => ({
764
+ ...error,
765
+ path: [i.toString(), ...error.path],
766
+ })));
767
+ }
768
+ else {
769
+ validatedArray.push(elementResult.data);
770
+ }
771
+ }
772
+ if (errors.length > 0) {
773
+ return { success: false, errors, warnings: [], data: value };
774
+ }
775
+ // Check uniqueness if required
776
+ if (Options.unique) {
777
+ const uniqueValues = new Set(validatedArray);
778
+ if (uniqueValues.size !== validatedArray.length) {
779
+ return {
780
+ success: false,
781
+ errors: [
782
+ ErrorHandler.ErrorHandler.createArrayError([], "values must be unique", value, errors_type.ErrorCode.ARRAY_VALUES_NOT_UNIQUE),
783
+ ],
784
+ warnings: [],
785
+ data: value,
786
+ };
787
+ }
788
+ }
789
+ return { success: true, errors: [], warnings: [], data: validatedArray };
790
+ }
791
+ // Note: Conditional "when" syntax is handled at the field level, not here
792
+ // Handle constant values (e.g., "=admin", "=user") using secure regex
793
+ const constantPattern = /^=/;
794
+ if (constantPattern.test(elementType)) {
795
+ return ValidationHelpers.ValidationHelpers.validateConstantType(elementType.replace(/^=/, ""), value);
796
+ }
797
+ // Handle union types (e.g., "pending|accepted|rejected" or "(user|admin|guest)") using secure regex
798
+ const unionPattern = /\|/;
799
+ if (unionPattern.test(elementType)) {
800
+ return ValidationHelpers.ValidationHelpers.validateUnionType(elementType, value);
801
+ }
802
+ // Handle basic types - pass the original fieldType to preserve constraints
803
+ return this.validateBasicType(fieldType, value);
804
+ }
805
+ /**
806
+ * Validate basic types with constraints
807
+ */
808
+ validateBasicType(fieldType, value) {
809
+ // Handle union types before constraint parsing (e.g., "(user|admin|guest)") using secure regex
810
+ const unionPattern = /\|/;
811
+ if (unionPattern.test(fieldType)) {
812
+ return ValidationHelpers.ValidationHelpers.validateUnionType(fieldType, value);
813
+ }
814
+ // Parse constraints from field type (include required field)
815
+ const { type, constraints, required: fieldIsRequired, } = ConstraintParser.ConstraintParser.parseConstraints(fieldType);
816
+ // Apply parsed constraints to options, but preserve important options like loose
817
+ const Options = { ...constraints, ...this.options };
818
+ // Check for Record types first (both lowercase and TypeScript-style uppercase) using secure regex
819
+ const recordPattern = /^(record|Record)<.*>$/;
820
+ if (recordPattern.test(type)) {
821
+ // Normalize to lowercase for the validator using secure regex
822
+ const uppercaseRecordPattern = /^Record</;
823
+ const normalizedType = uppercaseRecordPattern.test(type)
824
+ ? type.replace(/^Record/, "record")
825
+ : type;
826
+ return ValidationHelpers.ValidationHelpers.validateRecordType(normalizedType, value, (fieldType, value) => this.validateStringFieldType(fieldType, value));
827
+ }
828
+ // Route to appropriate type validator
829
+ const result = ValidationHelpers.ValidationHelpers.routeTypeValidation(type, // Use the type from the constraint parsing above
830
+ value, Options, constraints, fieldIsRequired // Use the required field from constraint parsing
831
+ );
832
+ return result;
833
+ }
834
+ /**
835
+ * Validate nested object with full data context for conditional field resolution
836
+ * CRITICAL FIX: This method ensures nested conditional validation has access to parent context
837
+ */
838
+ validateNestedObjectWithContext(nestedSchema, nestedValue, fullDataContext) {
839
+ // If we don't have full data context, fall back to standard validation
840
+ if (!fullDataContext) {
841
+ // console.log("no full data context, falling back to standard validation");
842
+ return nestedSchema.validate(nestedValue);
843
+ }
844
+ // console.log("validating nested object with full data context");
845
+ // CRITICAL FIX: Temporarily store the full context in the nested schema
846
+ // so that conditional validation can access parent fields
847
+ const originalValidateEnhancedConditionalField = nestedSchema["validateEnhancedConditionalField"];
848
+ // Override the conditional validation method to pass parent context
849
+ nestedSchema["validateEnhancedConditionalField"] = function (ast, value, localData, nestedContext) {
850
+ // console.log("validating enhanced conditional field with context");
851
+ return originalValidateEnhancedConditionalField.call(this, ast, value, fullDataContext, localData);
852
+ };
853
+ try {
854
+ // Perform the validation with the modified context
855
+ const result = nestedSchema.validate(nestedValue);
856
+ // console.log("nested validation result:", result);
857
+ return result;
858
+ }
859
+ finally {
860
+ // console.log("restoring original conditional validation method");
861
+ // Restore the original method
862
+ nestedSchema["validateEnhancedConditionalField"] =
863
+ originalValidateEnhancedConditionalField;
864
+ }
865
+ }
866
+ /**
867
+ * Validate enhanced conditional field using our new AST-based system
868
+ * FIXED: Now properly handles nested context for field resolution
869
+ */
870
+ validateEnhancedConditionalField(ast, value, fullData, nestedContext // Add nested context parameter
871
+ ) {
872
+ try {
873
+ // CRITICAL FIX: For nested conditional validation, we need to provide both
874
+ // the local context (nested object) and the full context (root object)
875
+ // This allows field resolution to work correctly for both local and parent references
876
+ // Create enhanced context that supports both local and parent field resolution
877
+ const contextData = nestedContext || fullData;
878
+ // FIXED: Pass both contexts to the evaluator for proper field resolution
879
+ const evaluationResult = ConditionalEvaluator.ConditionalEvaluator.evaluate(ast, contextData, {
880
+ strict: this.options.strict || false,
881
+ debug: true, // Enable debug to get condition result
882
+ schema: this.definition,
883
+ validatePaths: true,
884
+ // NEW: Add parent context for nested field resolution
885
+ parentContext: fullData !== contextData ? fullData : undefined,
886
+ });
887
+ if (!evaluationResult.success) {
888
+ return {
889
+ success: false,
890
+ errors: evaluationResult.errors,
891
+ warnings: [],
892
+ data: value,
893
+ };
894
+ }
895
+ // Get the expected schema and condition result
896
+ const expectedSchema = evaluationResult.value;
897
+ const conditionIsTrue = evaluationResult.debugInfo?.finalCondition;
898
+ if (expectedSchema === undefined) {
899
+ // No schema constraint, accept the value
900
+ return {
901
+ success: true,
902
+ errors: [],
903
+ warnings: [],
904
+ data: value,
905
+ };
906
+ }
907
+ // CRITICAL FIX: Handle constant values - VALIDATE user input against expected constant
908
+ if (typeof expectedSchema === "string" &&
909
+ expectedSchema.startsWith("=")) {
910
+ const expectedValue = expectedSchema.slice(1); // Remove the = prefix
911
+ // Handle special constant values
912
+ let actualExpectedValue = expectedValue;
913
+ if (expectedValue === "null") {
914
+ actualExpectedValue = null;
915
+ }
916
+ else if (expectedValue === "true") {
917
+ actualExpectedValue = true;
918
+ }
919
+ else if (expectedValue === "false") {
920
+ actualExpectedValue = false;
921
+ }
922
+ else if (/^\d+(\.\d+)?$/.test(expectedValue)) {
923
+ actualExpectedValue = parseFloat(expectedValue);
924
+ }
925
+ else if (expectedValue.startsWith("[") &&
926
+ expectedValue.endsWith("]")) {
927
+ // Handle array constants like ["USD"] or [1,2,3]
928
+ try {
929
+ actualExpectedValue = JSON.parse(expectedValue);
930
+ }
931
+ catch (error) {
932
+ // If JSON parsing fails, treat as string
933
+ actualExpectedValue = expectedValue;
934
+ }
935
+ }
936
+ else if (expectedValue.startsWith("{") &&
937
+ expectedValue.endsWith("}")) {
938
+ // Handle object constants like {"key": "value"}
939
+ try {
940
+ actualExpectedValue = JSON.parse(expectedValue);
941
+ }
942
+ catch (error) {
943
+ // If JSON parsing fails, treat as string
944
+ actualExpectedValue = expectedValue;
945
+ }
946
+ }
947
+ // FIXED: Validate user input against expected constant value
948
+ // Do NOT override user data - validate it!
949
+ if (!ValidationHelpers.ValidationHelpers.deepEquals(value, actualExpectedValue)) {
950
+ return {
951
+ success: false,
952
+ errors: [
953
+ ErrorHandler.ErrorHandler.createConstantError([], actualExpectedValue, value, expectedValue),
954
+ ],
955
+ warnings: [],
956
+ data: value, // Return original user input, not the expected value
957
+ };
958
+ }
959
+ // User input matches expected constant - validation passes
960
+ return {
961
+ success: true,
962
+ errors: [],
963
+ warnings: [],
964
+ data: value, // Return user's input, not the expected value
965
+ };
966
+ }
967
+ // Handle non-constant string schemas (like "boolean", "string", etc.)
968
+ // For conditionals, validate user input against the expected type
969
+ if (typeof expectedSchema === "string") {
970
+ if (expectedSchema === "boolean") {
971
+ // Validate that user provided a boolean
972
+ if (typeof value !== "boolean") {
973
+ return {
974
+ success: false,
975
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "boolean", value)],
976
+ warnings: [],
977
+ data: value,
978
+ };
979
+ }
980
+ // Keep user's boolean value
981
+ return {
982
+ success: true,
983
+ errors: [],
984
+ warnings: [],
985
+ data: value,
986
+ };
987
+ }
988
+ if (expectedSchema === "string") {
989
+ // Validate that user provided a string
990
+ if (typeof value !== "string") {
991
+ return {
992
+ success: false,
993
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "string", value)],
994
+ warnings: [],
995
+ data: value,
996
+ };
997
+ }
998
+ // Keep user's string value
999
+ return {
1000
+ success: true,
1001
+ errors: [],
1002
+ warnings: [],
1003
+ data: value,
1004
+ };
1005
+ }
1006
+ if (expectedSchema === "number" || expectedSchema === "int") {
1007
+ if (typeof value !== "number") {
1008
+ return {
1009
+ success: false,
1010
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "number", value)],
1011
+ warnings: [],
1012
+ data: value,
1013
+ };
1014
+ }
1015
+ if (expectedSchema === "int" && !Number.isInteger(value)) {
1016
+ return {
1017
+ success: false,
1018
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "integer", value)],
1019
+ warnings: [],
1020
+ data: value,
1021
+ };
1022
+ }
1023
+ return {
1024
+ success: true,
1025
+ errors: [],
1026
+ warnings: [],
1027
+ data: value,
1028
+ };
1029
+ }
1030
+ // Handle array types specially
1031
+ if (expectedSchema.endsWith("[]") || expectedSchema.endsWith("[]?")) {
1032
+ const isOptional = expectedSchema.endsWith("[]?");
1033
+ if (value === null || value === undefined) {
1034
+ if (isOptional) {
1035
+ return {
1036
+ success: true,
1037
+ errors: [],
1038
+ warnings: [],
1039
+ data: value,
1040
+ };
1041
+ }
1042
+ else {
1043
+ return {
1044
+ success: false,
1045
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "null", value)],
1046
+ warnings: [],
1047
+ data: value,
1048
+ };
1049
+ }
1050
+ }
1051
+ if (!Array.isArray(value)) {
1052
+ return {
1053
+ success: false,
1054
+ errors: [ErrorHandler.ErrorHandler.createTypeError([], "array", value)],
1055
+ warnings: [],
1056
+ data: value,
1057
+ };
1058
+ }
1059
+ // FIXED: Validate array elements against the expected type
1060
+ // Extract the element type from the array type (e.g., "number[]" -> "number")
1061
+ const elementType = expectedSchema.replace(/\[\]\??$/, "");
1062
+ // Validate each array element
1063
+ const validatedArray = [];
1064
+ const errors = [];
1065
+ for (let i = 0; i < value.length; i++) {
1066
+ const elementResult = this.validateStringFieldType(elementType, value[i]);
1067
+ if (!elementResult.success) {
1068
+ errors.push(...elementResult.errors.map((error) => ({
1069
+ ...error,
1070
+ path: [i.toString(), ...error.path],
1071
+ })));
1072
+ }
1073
+ else {
1074
+ validatedArray.push(elementResult.data);
1075
+ }
1076
+ }
1077
+ if (errors.length > 0) {
1078
+ return {
1079
+ success: false,
1080
+ errors,
1081
+ warnings: [],
1082
+ data: value,
1083
+ };
1084
+ }
1085
+ return {
1086
+ success: true,
1087
+ errors: [],
1088
+ warnings: [],
1089
+ data: validatedArray,
1090
+ };
1091
+ }
1092
+ return this.validateStringFieldType(expectedSchema, value);
1093
+ }
1094
+ // Accept the value if we can't determine the schema
1095
+ return {
1096
+ success: true,
1097
+ errors: [],
1098
+ warnings: [],
1099
+ data: value,
1100
+ };
1101
+ }
1102
+ catch (error) {
1103
+ // Better error message extraction
1104
+ let errorMessage = "Unknown error";
1105
+ if (error instanceof Error) {
1106
+ errorMessage = error.message;
1107
+ }
1108
+ else if (error && typeof error === "object" && "message" in error) {
1109
+ errorMessage = error.message;
1110
+ }
1111
+ else if (error && typeof error === "object") {
1112
+ errorMessage = JSON.stringify(error);
1113
+ }
1114
+ else {
1115
+ errorMessage = String(error);
1116
+ }
1117
+ return {
1118
+ success: false,
1119
+ errors: [
1120
+ ErrorHandler.ErrorHandler.createConditionalError([], `Conditional validation error: ${errorMessage}`, value),
1121
+ ],
1122
+ warnings: [],
1123
+ data: value,
1124
+ };
1125
+ }
1126
+ }
1127
+ /**
1128
+ * Validate conditional field with full data context
1129
+ */
1130
+ validateConditionalFieldWithContext(conditionalDef, value, fullData) {
1131
+ const result = {
1132
+ success: true,
1133
+ errors: [],
1134
+ warnings: [],
1135
+ data: value,
1136
+ };
1137
+ // Get the field this condition depends on
1138
+ const fieldName = conditionalDef.fieldName;
1139
+ const conditions = conditionalDef.conditions || [];
1140
+ const defaultSchema = conditionalDef.default;
1141
+ // Get the value of the dependent field
1142
+ const dependentFieldValue = fullData[fieldName];
1143
+ // Find the matching condition
1144
+ let schemaToUse = defaultSchema;
1145
+ for (const condition of conditions) {
1146
+ if (this.evaluateCondition(condition, dependentFieldValue)) {
1147
+ schemaToUse = condition.schema;
1148
+ break;
1149
+ }
1150
+ }
1151
+ // If we have a schema to validate against, use it
1152
+ if (schemaToUse) {
1153
+ if (typeof schemaToUse === "string") {
1154
+ return this.validateStringFieldType(schemaToUse, value);
1155
+ }
1156
+ else if (typeof schemaToUse === "object") {
1157
+ return this.validateField("conditional", schemaToUse, value);
1158
+ }
1159
+ }
1160
+ // If no schema found, accept the value
1161
+ return result;
1162
+ }
1163
+ /**
1164
+ * Evaluate a condition against a field value
1165
+ */
1166
+ evaluateCondition(condition, fieldValue) {
1167
+ if (!condition.condition) {
1168
+ return false;
1169
+ }
1170
+ return condition.condition(fieldValue);
1171
+ }
1172
+ /**
1173
+ * Validate conditional field based on other field values (legacy method)
1174
+ *
1175
+ * Note: This method is used when conditional validation is called without
1176
+ * full data context. It provides a fallback validation approach.
1177
+ */
1178
+ validateConditionalField(conditionalDef, value) {
1179
+ const result = {
1180
+ success: true,
1181
+ errors: [],
1182
+ warnings: [],
1183
+ data: value,
1184
+ };
1185
+ // Get the field this condition depends on
1186
+ const conditions = conditionalDef.conditions || [];
1187
+ const defaultSchema = conditionalDef.default;
1188
+ // Since we don't have access to the full data object in this context,
1189
+ // we'll validate against all possible schemas and accept if any pass
1190
+ let validationPassed = false;
1191
+ let lastError = [];
1192
+ // Try to validate against each condition's schema
1193
+ for (const condition of conditions) {
1194
+ if (condition.schema) {
1195
+ try {
1196
+ const conditionResult = this.validateSchemaType(condition.schema, value);
1197
+ if (conditionResult.success) {
1198
+ validationPassed = true;
1199
+ result.data = conditionResult.data;
1200
+ result.warnings.push(...conditionResult.warnings);
1201
+ break; // Found a valid schema, use it
1202
+ }
1203
+ else {
1204
+ lastError = conditionResult.errors;
1205
+ }
1206
+ }
1207
+ catch (error) {
1208
+ // Continue to next condition if this one fails
1209
+ lastError = [
1210
+ ErrorHandler.ErrorHandler.createConditionalError([], `Conditional validation error: ${error instanceof Error ? error.message : String(error)}`, value),
1211
+ ];
1212
+ }
1213
+ }
1214
+ }
1215
+ // If no condition schema worked, try the default schema
1216
+ if (!validationPassed && defaultSchema) {
1217
+ try {
1218
+ const defaultResult = this.validateSchemaType(defaultSchema, value);
1219
+ if (defaultResult.success) {
1220
+ validationPassed = true;
1221
+ result.data = defaultResult.data;
1222
+ result.warnings.push(...defaultResult.warnings);
1223
+ }
1224
+ else {
1225
+ lastError = defaultResult.errors;
1226
+ }
1227
+ }
1228
+ catch (error) {
1229
+ lastError = [
1230
+ ErrorHandler.ErrorHandler.createConditionalError([], `Default schema validation error: ${error instanceof Error ? error.message : String(error)}`, value),
1231
+ ];
1232
+ }
1233
+ }
1234
+ // If no schema validation passed, report the error
1235
+ if (!validationPassed) {
1236
+ result.success = false;
1237
+ result.errors =
1238
+ lastError.length > 0
1239
+ ? lastError
1240
+ : [
1241
+ ErrorHandler.ErrorHandler.createConditionalError([], "No valid conditional schema found", value),
1242
+ ];
1243
+ result.warnings.push("Conditional validation performed without full data context");
1244
+ }
1245
+ return result;
1246
+ }
1247
+ /**
1248
+ * Helper method to validate a value against a schema type
1249
+ */
1250
+ validateSchemaType(schema, value) {
1251
+ if (typeof schema === "string") {
1252
+ return this.validateStringFieldType(schema, value);
1253
+ }
1254
+ else if (typeof schema === "object" && schema !== null) {
1255
+ return this.validateField("conditional", schema, value);
1256
+ }
1257
+ else {
1258
+ return ValidationHelpers.ValidationHelpers.createErrorResult(`Invalid schema type: ${typeof schema}`, value);
1259
+ }
1260
+ }
1261
+ /**
1262
+ * Parse and validate (throws on error)
1263
+ */
1264
+ parse(data) {
1265
+ const result = this.validate(data);
1266
+ if (!result.success) {
1267
+ result.errors.forEach((error) => {
1268
+ throw new Interface.SchemaValidationError(error.message, [error.context?.suggestion || error.code], result.warnings);
1269
+ });
1270
+ }
1271
+ return result.data;
1272
+ }
1273
+ /**
1274
+ * Safe parse (returns result object) - strictly typed input
1275
+ */
1276
+ safeParse(data) {
1277
+ return this.validate(data);
1278
+ }
1279
+ /**
1280
+ * Safe parse with unknown data (for testing invalid inputs)
1281
+ * Use this when you need to test data that might not match the schema
1282
+ */
1283
+ safeParseUnknown(data) {
1284
+ return this.validate(data);
1285
+ }
1286
+ /**
1287
+ * Set schema options
1288
+ */
1289
+ withOptions(opts) {
1290
+ return new InterfaceSchema(this.definition, {
1291
+ ...this.options,
1292
+ ...opts,
1293
+ });
1294
+ }
1295
+ /**
1296
+ * Async validation - returns a promise with validation result
1297
+ */
1298
+ async parseAsync(data) {
1299
+ return new Promise((resolve, reject) => {
1300
+ try {
1301
+ // Use setTimeout to make it truly async
1302
+ setTimeout(() => {
1303
+ try {
1304
+ const result = this.validate(data);
1305
+ if (!result.success) {
1306
+ reject(result.errors.forEach((error) => {
1307
+ throw new Interface.SchemaValidationError(error.message, [error.context?.suggestion || error.code], result.warnings);
1308
+ }));
1309
+ }
1310
+ else {
1311
+ resolve(result.data);
1312
+ }
1313
+ }
1314
+ catch (error) {
1315
+ reject(error);
1316
+ }
1317
+ }, 0);
1318
+ }
1319
+ catch (error) {
1320
+ reject(error);
1321
+ }
1322
+ });
1323
+ }
1324
+ /**
1325
+ * Async safe parse - returns a promise with validation result object
1326
+ */
1327
+ async safeParseAsync(data) {
1328
+ return new Promise((resolve) => {
1329
+ // Use setTimeout to make it truly async
1330
+ setTimeout(() => {
1331
+ try {
1332
+ const result = this.validate(data);
1333
+ resolve(result);
1334
+ }
1335
+ catch (error) {
1336
+ resolve({
1337
+ success: false,
1338
+ errors: [
1339
+ ErrorHandler.ErrorHandler.createSimpleError(`Unexpected validation error: ${error}`),
1340
+ ],
1341
+ warnings: [],
1342
+ data: undefined,
1343
+ });
1344
+ }
1345
+ }, 0);
1346
+ });
1347
+ }
1348
+ /**
1349
+ * Async safe parse with unknown data
1350
+ */
1351
+ async safeParseUnknownAsync(data) {
1352
+ return new Promise((resolve) => {
1353
+ setTimeout(() => {
1354
+ try {
1355
+ const result = this.validate(data);
1356
+ resolve(result);
1357
+ }
1358
+ catch (error) {
1359
+ resolve({
1360
+ success: false,
1361
+ errors: [
1362
+ ErrorHandler.ErrorHandler.createSimpleError(`Unexpected validation error: ${error}`),
1363
+ ],
1364
+ warnings: [],
1365
+ data: undefined,
1366
+ });
1367
+ }
1368
+ }, 0);
1369
+ });
1370
+ }
1371
+ /**
1372
+ * Enable strict mode (no unknown properties allowed)
1373
+ */
1374
+ strict() {
1375
+ return this.withOptions({ strict: true });
1376
+ }
1377
+ /**
1378
+ * Enable loose mode (allow type coercion)
1379
+ */
1380
+ loose() {
1381
+ return this.withOptions({ loose: true });
1382
+ }
1383
+ /**
1384
+ * Allow unknown properties (not strict about extra fields)
1385
+ * Returns a schema that accepts extra properties beyond the defined interface
1386
+ */
1387
+ allowUnknown() {
1388
+ return this.withOptions({ allowUnknown: true });
1389
+ }
1390
+ /**
1391
+ * Set minimum constraints
1392
+ */
1393
+ min(value) {
1394
+ return this.withOptions({
1395
+ min: value,
1396
+ minLength: value,
1397
+ minItems: value,
1398
+ });
1399
+ }
1400
+ /**
1401
+ * Set maximum constraints
1402
+ */
1403
+ max(value) {
1404
+ return this.withOptions({
1405
+ max: value,
1406
+ maxLength: value,
1407
+ maxItems: value,
1408
+ });
1409
+ }
1410
+ /**
1411
+ * Require unique array values
1412
+ */
1413
+ unique() {
1414
+ return this.withOptions({ unique: true });
1415
+ }
1416
+ /**
1417
+ * Set pattern for string validation
1418
+ */
1419
+ pattern(regex) {
1420
+ return this.withOptions({ pattern: regex });
1421
+ }
1422
+ /**
1423
+ * Set default value
1424
+ */
1425
+ default(value) {
1426
+ return this.withOptions({ default: value });
1427
+ }
1428
+ }
1429
+
1430
+ exports.InterfaceSchema = InterfaceSchema;
1431
+ //# sourceMappingURL=InterfaceSchema.js.map