/** * Core types and interfaces for the FortifyJS Schema system */ /** * Rich validation error with detailed information */ interface ValidationError { /** Field path where the error occurred (e.g., ['user', 'profile', 'email']) */ path: string[]; /** Human-readable error message */ message: string; /** Error code for programmatic handling */ code: string; /** Expected value or type */ expected: string; /** Actual received value */ received: any; /** Type of the received value */ receivedType: string; /** Additional context or suggestions */ context?: { suggestion?: string; allowedValues?: any[]; constraints?: Record; }; } /** * Schema validation result with rich error information */ interface SchemaValidationResult { success: boolean; data?: T; errors: ValidationError[]; warnings: string[]; } /** * Base schema configuration options */ interface BaseSchemaOptions { optional?: boolean; nullable?: boolean; default?: any; } /** * String schema validation options */ interface StringSchemaOptions extends BaseSchemaOptions { minLength?: number; maxLength?: number; pattern?: RegExp; format?: "email" | "url" | "uuid" | "phone" | "slug" | "username"; } /** * Number schema validation options */ interface NumberSchemaOptions extends BaseSchemaOptions { min?: number; max?: number; integer?: boolean; positive?: boolean; precision?: number; } /** * Boolean schema validation options */ interface BooleanSchemaOptions extends BaseSchemaOptions { strict?: boolean; } /** * Array schema validation options */ interface ArraySchemaOptions extends BaseSchemaOptions { minLength?: number; maxLength?: number; unique?: boolean; } /** * Object schema validation options */ interface ObjectSchemaOptions extends BaseSchemaOptions { strict?: boolean; allowUnknown?: boolean; } /** * Schema type definitions */ type SchemaType = "string" | "number" | "boolean" | "array" | "object" | "date" | "any"; /** * Schema definition for object properties */ type SchemaDefinition = { [key: string]: SchemaConfig; }; /** * Complete schema configuration */ interface SchemaConfig { type: SchemaType; options?: BaseSchemaOptions; elementSchema?: SchemaConfig; properties?: SchemaDefinition; validator?: (value: any) => void; } /** * Constant value wrapper to distinguish from string types */ interface ConstantValue { const: string | number | boolean; } /** * Union value wrapper for proper type inference */ interface UnionValue { union: T; } /** * Optional constant value wrapper */ interface OptionalConstantValue { const: string | number | boolean; optional: true; } /** * Optional schema interface wrapper */ interface OptionalSchemaInterface { optional: true; schema: SchemaInterface; } /** * Schema definition using TypeScript-like interface syntax */ interface SchemaInterface { [key: string]: SchemaFieldType | ConstantValue | OptionalConstantValue | SchemaInterface | SchemaInterface[] | any; } /** * Field type definitions using string literals and objects */ type SchemaFieldType = "string" | "string?" | "number" | "number?" | "boolean" | "boolean?" | "date" | "date?" | "any" | "any?" | "email" | "email?" | "url" | "url?" | "uuid" | "uuid?" | "phone" | "phone?" | "slug" | "slug?" | "username" | "username?" | "ip" | "ip?" | "json" | "json?" | "json.fast" | "json.fast?" | "json.secure" | "json.secure?" | "password" | "password?" | "text" | "text?" | "hexcolor" | "hexcolor?" | "base64" | "base64?" | "jwt" | "jwt?" | "semver" | "semver?" | "object" | "object?" | "int" | "int?" | "positive" | "positive?" | "float" | "float?" | "string[]" | "string[]?" | "number[]" | "number[]?" | "boolean[]" | "boolean[]?" | "int[]" | "int[]?" | "email[]" | "email[]?" | "url[]" | "url[]?" | "ip[]" | "ip[]?" | "json[]" | "json[]?" | "json.fast[]" | "json.fast[]?" | "password[]" | "password[]?" | "text[]" | "text[]?" | "object[]" | "object[]?" | "hexcolor[]" | "hexcolor[]?" | "base64[]" | "base64[]?" | "jwt[]" | "jwt[]?" | "semver[]" | "semver[]?" | string | ConstantValue | OptionalConstantValue | UnionValue | SchemaInterface | SchemaInterface[] | OptionalSchemaInterface; /** * Schema validation options for fine-tuning */ interface SchemaOptions { minLength?: number; maxLength?: number; pattern?: RegExp; min?: number; max?: number; precision?: number; minItems?: number; maxItems?: number; unique?: boolean; strict?: boolean; allowUnknown?: boolean; required?: boolean; default?: any; loose?: boolean; enablePerformanceMonitoring?: boolean; enableOptimizations?: boolean; cacheValidation?: boolean; skipOptimization?: boolean; } type AllowUnknownSchema = T & Record; /** * TypeScript Interface-like Schema Definition System * * Allows defining schemas using TypeScript-like syntax with string literals * that feel natural and are much easier to read and write. */ /** * Interface Schema class for TypeScript-like schema definitions */ declare class InterfaceSchema { private definition; private options; private compiledFields; private schemaKeys; private ConditionalParser; private compiledValidator?; private schemaComplexity; private isOptimized; private precompiledValidator?; private optimizationLevel; constructor(definition: SchemaInterface, options?: SchemaOptions); /** * Check if a field type uses conditional syntax using secure regex pattern */ private isConditionalSyntax; /** * Apply performance optimizations based on schema characteristics */ private applyOptimizations; /** * Create precompiled validator for maximum speed * SAFETY: Now includes recursion protection and cycle detection */ private createPrecompiledValidator; /** * Check if schema has nested conditional fields * CRITICAL FIX: This prevents precompilation for schemas with nested conditionals */ private hasNestedConditionalFields; /** * Check if schema has nested required fields (! syntax) * CRITICAL FIX: This prevents precompilation for schemas with nested required fields */ private hasNestedRequiredFields; /** * Check if schema has custom error messages (--> syntax) * CRITICAL FIX: This prevents precompilation for schemas with custom error messages */ private hasCustomErrorMessages; /** * Calculate schema complexity score */ private calculateComplexity; /** * Calculate maximum nesting depth to avoid optimization bugs */ private calculateMaxNestingDepth; /** * Pre-compile schema for faster validation */ private precompileSchema; /** * Validate data against the interface schema - ULTRA-OPTIMIZED version */ private validate; /** * Standard validation method (original implementation) */ private validateStandard; /** * Validate pre-compiled string field for maximum performance */ private validatePrecompiledStringField; /** * Validate individual field */ private validateField; /** * Validate string-based field types - optimized version */ private validateStringFieldType; /** * Validate basic types with constraints */ private validateBasicType; /** * Validate nested object with full data context for conditional field resolution * CRITICAL FIX: This method ensures nested conditional validation has access to parent context */ private validateNestedObjectWithContext; /** * Validate enhanced conditional field using our new AST-based system * FIXED: Now properly handles nested context for field resolution */ private validateEnhancedConditionalField; /** * Validate conditional field with full data context */ private validateConditionalFieldWithContext; /** * Evaluate a condition against a field value */ private evaluateCondition; /** * Validate conditional field based on other field values (legacy method) * * Note: This method is used when conditional validation is called without * full data context. It provides a fallback validation approach. */ private validateConditionalField; /** * Helper method to validate a value against a schema type */ private validateSchemaType; /** * Parse and validate (throws on error) */ parse(data: T): T; /** * Safe parse (returns result object) - strictly typed input */ safeParse(data: T): SchemaValidationResult; /** * Safe parse with unknown data (for testing invalid inputs) * Use this when you need to test data that might not match the schema */ safeParseUnknown(data: unknown): SchemaValidationResult; /** * Set schema options */ withOptions(opts: SchemaOptions): InterfaceSchema; /** * Async validation - returns a promise with validation result */ parseAsync(data: T): Promise; /** * Async safe parse - returns a promise with validation result object */ safeParseAsync(data: T): Promise>; /** * Async safe parse with unknown data */ safeParseUnknownAsync(data: unknown): Promise>; /** * Enable strict mode (no unknown properties allowed) */ strict(): InterfaceSchema; /** * Enable loose mode (allow type coercion) */ loose(): InterfaceSchema; /** * Allow unknown properties (not strict about extra fields) * Returns a schema that accepts extra properties beyond the defined interface */ allowUnknown(): InterfaceSchema>; /** * Set minimum constraints */ min(value: number): InterfaceSchema; /** * Set maximum constraints */ max(value: number): InterfaceSchema; /** * Require unique array values */ unique(): InterfaceSchema; /** * Set pattern for string validation */ pattern(regex: RegExp): InterfaceSchema; /** * Set default value */ default(value: any): InterfaceSchema; } /** * Unified TypeScript Type Inference System * * Combines core schema type inference with advanced conditional analysis. * This is the single source of truth for all TypeScript type operations. */ /** * Core type mapping for basic field types */ type CoreTypeMap = { string: string; number: number; boolean: boolean; date: Date; any: any; email: string; url: string; uuid: string; phone: string; slug: string; username: string; int: number; integer: number; positive: number; negative: number; float: number; double: number; unknown: unknown; void: undefined; null: null; undefined: undefined; }; /** * Strip custom error message helper (handles both "type --> msg" and "type--> msg") */ type StripCustomError = T extends `${infer Base} --> ${string}` ? Base : T extends `${infer Base}--> ${string}` ? Base : T extends `${infer Base}-->${string}` ? Base : T; /** * Extract base type from field type string (removes constraints and modifiers) */ type ExtractBaseType = StripCustomError extends infer Stripped ? Stripped extends T ? T extends `${infer Base}(${string})` ? Base : T extends `${infer Base}?` ? Base : T extends `${infer Base}[]` ? Base : T extends `${infer Base}[]?` ? Base : T extends `${infer Base}!` ? Base : T extends `(${infer Content})?` ? Content : T extends `(${infer Content})` ? Content : T : ExtractBaseType : T; /** * Check if field type is optional */ type IsOptional = StripCustomError extends infer Stripped ? Stripped extends string ? Stripped extends `${string}?` ? true : false : false : false; /** * Check if field type is an array */ type IsArray = T extends `${string}[]` | `${string}[]?` ? true : false; /** * Extract element type from array type, handling parentheses */ type ExtractElementType = T extends `${infer Element}[]` ? Element extends `(${infer UnionContent})` ? UnionContent : Element : T extends `${infer Element}[]?` ? Element extends `(${infer UnionContent})` ? UnionContent : Element : T; /** * Map field type string to TypeScript type */ type MapFieldType = IsArray extends true ? Array>> : T extends `record<${infer K}, ${infer V}>` ? Record extends string | number | symbol ? MapFieldType : string, MapFieldType> : T extends `Record<${infer K}, ${infer V}>` ? Record extends string | number | symbol ? MapFieldType : string, MapFieldType> : T extends `when ${string} *? ${string}` ? InferConditionalType : ExtractBaseType extends `${string}|${string}` ? ParseUnionType> : T extends `=${infer Value}?` ? Value | undefined : T extends `=${infer Value}` ? Value : ExtractBaseType extends keyof CoreTypeMap ? CoreTypeMap[ExtractBaseType] : any; /** * Utility type to trim whitespace from string literal types */ type Trim = T extends ` ${infer Rest}` ? Trim : T extends `${infer Rest} ` ? Trim : T; /** * Parse union type string into union of literal types */ type ParseUnionType = T extends `(${infer Content})` ? ParseUnionType> : T extends `${infer First}|${infer Rest}` ? Trim | ParseUnionType : Trim; /** * Handle optional fields */ type HandleOptional = IsOpt extends true ? T | undefined : T; /** * Infer type for a single field */ type InferFieldType$1 = T extends string ? HandleOptional, IsOptional> : T extends ConstantValue ? T["const"] : T extends OptionalConstantValue ? T["const"] | undefined : T extends UnionValue & { optional: true; } ? U[number] | undefined : T extends UnionValue ? U[number] : T extends OptionalSchemaInterface ? InferSchemaType | undefined : T extends readonly [infer U] ? Array> : T extends Array ? Array> : T extends object ? InferSchemaType : any; /** * Main type inference for schema interfaces * FIXED: Handle optional properties correctly in nested objects */ type InferSchemaType = { [K in keyof T as T[K] extends string ? IsOptional extends true ? never : K : K]: InferFieldType$1; } & { [K in keyof T as T[K] extends string ? IsOptional extends true ? K : never : never]?: InferFieldType$1; }; type InferConditionalType = T extends `${string} *? ${infer Then} : ${infer Else}` ? Then extends `=${infer ThenValue}` ? Else extends `=${infer ElseValue}` ? ThenValue | ElseValue : ThenType | ElseType : ThenType | ElseType : ThenType | ElseType; /** * Enhanced schema modification utilities - transform, combine, and manipulate schemas */ declare class Mod { /** * Safely access schema internals with proper typing */ private static getSchemaInternals; /** * Merge multiple schemas into a single schema * @example * ```typescript * const UserSchema = Interface({ id: "number", name: "string" }); * const ProfileSchema = Interface({ bio: "string?", avatar: "url?" }); * * const MergedSchema = Mod.merge(UserSchema, ProfileSchema); * // Result: { id: number, name: string, bio?: string, avatar?: string } * ``` */ static merge(schema1: InterfaceSchema, schema2: InterfaceSchema): InterfaceSchema; /** * Merge multiple schemas with conflict resolution * @example * ```typescript * const schema1 = Interface({ id: "number", name: "string" }); * const schema2 = Interface({ id: "uuid", email: "email" }); * * const merged = Mod.mergeDeep(schema1, schema2, "second"); // id becomes "uuid" * ``` */ static mergeDeep(schema1: InterfaceSchema, schema2: InterfaceSchema, strategy?: "first" | "second" | "merge"): InterfaceSchema; /** * Pick specific fields from a schema */ static pick(schema: InterfaceSchema, keys: K[]): InterfaceSchema>; /** * Omit specific fields from a schema */ static omit(schema: InterfaceSchema, keys: K[]): InterfaceSchema>; /** * Make all fields in a schema optional */ static partial(schema: InterfaceSchema): InterfaceSchema>; /** * Make all fields in a schema required */ static required(schema: InterfaceSchema): InterfaceSchema>; /** * Make specific fields optional in a schema without modifying field types * * This method allows you to selectively make certain fields optional while keeping * all other fields required. It's particularly useful when you want to create * flexible versions of strict schemas for different use cases (e.g., partial updates, * form validation, API endpoints with optional parameters). * * The method works with both primitive types and nested objects, properly handling * the optional nature at the validation level while maintaining type safety. * * @param schema - The source schema to modify * @param keys - Array of field names to make optional * @returns A new schema with specified fields made optional * * @example Making primitive fields optional * ```typescript * const UserSchema = Interface({ * id: "number", * name: "string", * email: "email", * phone: "string" * }); * * const FlexibleUserSchema = Mod.makeOptional(UserSchema, ["email", "phone"]); * * // Now accepts both: * FlexibleUserSchema.parse({ id: 1, name: "John" }); // ✅ email and phone optional * FlexibleUserSchema.parse({ id: 1, name: "John", email: "john@example.com" }); // ✅ * ``` * * @example Making nested objects optional * ```typescript * const ProfileSchema = Interface({ * id: "number", * name: "string", * preferences: { * theme: "light|dark", * notifications: "boolean", * language: "en|es|fr" * }, * settings: { * privacy: "public|private", * newsletter: "boolean" * } * }); * * const FlexibleProfileSchema = Mod.makeOptional(ProfileSchema, ["preferences", "settings"]); * * // Now accepts: * FlexibleProfileSchema.parse({ id: 1, name: "John" }); // ✅ nested objects optional * FlexibleProfileSchema.parse({ * id: 1, * name: "John", * preferences: { theme: "dark", notifications: true, language: "en" } * }); // ✅ * ``` * * @example Use case: API endpoints with optional parameters * ```typescript * const CreateUserSchema = Interface({ * name: "string", * email: "email", * password: "string", * role: "admin|user|moderator", * department: "string", * startDate: "date" * }); * * // For user registration (minimal required fields) * const RegisterSchema = Mod.makeOptional(CreateUserSchema, ["role", "department", "startDate"]); * * // For admin creation (all fields required) * const AdminCreateSchema = CreateUserSchema; * * // For profile updates (most fields optional) * const UpdateProfileSchema = Mod.makeOptional(CreateUserSchema, ["password", "role", "department", "startDate"]); * ``` */ static makeOptional(schema: InterfaceSchema, keys: K[]): InterfaceSchema & Partial>>; /** * Extend a schema with additional fields */ static extend(schema: InterfaceSchema, extension: U): InterfaceSchema>; /** * Create a deep partial version of a schema (makes ALL fields optional recursively) * * Unlike the regular `partial()` method which only makes top-level fields optional, * `deepPartial()` recursively traverses the entire schema structure and makes every * field at every nesting level optional. This is particularly useful for update * operations, patch APIs, or form validation where users might only provide * partial data at any level of nesting. * * @param schema - The source schema to make deeply partial * @returns A new schema where all fields at all levels are optional * * @example Basic deep partial transformation * ```typescript * const UserSchema = Interface({ * id: "number", * name: "string", * profile: { * bio: "string", * avatar: "string", * social: { * twitter: "string", * linkedin: "string" * } * } * }); * * const DeepPartialSchema = Mod.deepPartial(UserSchema); * * // All of these are now valid: * DeepPartialSchema.parse({}); // ✅ Everything optional * DeepPartialSchema.parse({ id: 1 }); // ✅ Only id provided * DeepPartialSchema.parse({ * profile: { * bio: "Developer" * } * }); // ✅ Partial nested data * DeepPartialSchema.parse({ * profile: { * social: { * twitter: "@john" * } * } * }); // ✅ Deep nested partial data * ``` * * @example Use case: API PATCH endpoints * ```typescript * const ArticleSchema = Interface({ * id: "number", * title: "string", * content: "string", * metadata: { * tags: "string[]", * category: "string", * seo: { * title: "string", * description: "string", * keywords: "string[]" * } * }, * author: { * id: "number", * name: "string" * } * }); * * // For PATCH /articles/:id - allow partial updates at any level * const PatchArticleSchema = Mod.deepPartial(ArticleSchema); * * // Users can update just the SEO title: * PatchArticleSchema.parse({ * metadata: { * seo: { * title: "New SEO Title" * } * } * }); // ✅ * ``` * * @example Difference from regular partial() * ```typescript * const NestedSchema = Interface({ * user: { * name: "string", * email: "email" * } * }); * * const RegularPartial = Mod.partial(NestedSchema); * // Type: { user?: { name: string, email: string } } * // user is optional, but if provided, name and email are required * * const DeepPartial = Mod.deepPartial(NestedSchema); * // Type: { user?: { name?: string, email?: string } } * // user is optional, and if provided, name and email are also optional * ``` */ static deepPartial(schema: InterfaceSchema): InterfaceSchema>; /** * Transform field types using a mapper function * @example * ```typescript * const UserSchema = Interface({ id: "number", name: "string" }); * const StringifiedSchema = Mod.transform(UserSchema, (type) => * type.replace("number", "string") * ); * // Result: { id: string, name: string } * ``` */ static transform(schema: InterfaceSchema, mapper: (fieldType: string, fieldName: string) => string): InterfaceSchema; /** * Rename fields in a schema * @example * ```typescript * const UserSchema = Interface({ user_id: "number", user_name: "string" }); * const RenamedSchema = Mod.rename(UserSchema, { * user_id: "id", * user_name: "name" * }); * // Result: { id: number, name: string } * ``` */ static rename(schema: InterfaceSchema, fieldMap: Record): InterfaceSchema; /** * Create a schema with default values that are automatically applied during validation * * This method allows you to specify default values that will be automatically applied * to fields when they are missing or undefined in the input data. This is particularly * useful for API endpoints, form processing, and configuration objects where you want * to ensure certain fields always have sensible default values. * * Default values are applied during the validation process, so they don't modify the * original schema definition but are included in the validated output. * * @param schema - The source schema to add defaults to * @param defaultValues - Object mapping field names to their default values * @returns A new schema that applies default values during validation * * @example Basic default values * ```typescript * const UserSchema = Interface({ * id: "number", * name: "string", * role: "string?", * active: "boolean?", * createdAt: "date?" * }); * * const UserWithDefaults = Mod.defaults(UserSchema, { * role: "user", * active: true, * createdAt: new Date() * }); * * const result = UserWithDefaults.parse({ * id: 1, * name: "John Doe" * // role, active, and createdAt will be filled with defaults * }); * * console.log(result.data); * // { * // id: 1, * // name: "John Doe", * // role: "user", * // active: true, * // createdAt: 2023-12-01T10:30:00.000Z * // } * ``` * * @example API configuration with defaults * ```typescript * const ApiConfigSchema = Interface({ * host: "string", * port: "number?", * timeout: "number?", * retries: "number?", * ssl: "boolean?", * compression: "boolean?" * }); * * const ApiConfigWithDefaults = Mod.defaults(ApiConfigSchema, { * port: 3000, * timeout: 5000, * retries: 3, * ssl: false, * compression: true * }); * * // Users only need to provide the host * const config = ApiConfigWithDefaults.parse({ * host: "api.example.com" * }); * // All other fields get sensible defaults * ``` * * @example Form processing with defaults * ```typescript * const ProfileFormSchema = Interface({ * name: "string", * email: "email", * theme: "string?", * notifications: "boolean?", * language: "string?" * }); * * const ProfileWithDefaults = Mod.defaults(ProfileFormSchema, { * theme: "light", * notifications: true, * language: "en" * }); * * // Form submissions get defaults for unchecked/unselected fields * const profile = ProfileWithDefaults.parse({ * name: "Jane Smith", * email: "jane@example.com" * // theme, notifications, language get defaults * }); * ``` * * @example Conditional defaults based on environment * ```typescript * const AppConfigSchema = Interface({ * environment: "development|staging|production", * debug: "boolean?", * logLevel: "string?", * cacheEnabled: "boolean?" * }); * * const isDevelopment = process.env.NODE_ENV === "development"; * * const AppConfigWithDefaults = Mod.defaults(AppConfigSchema, { * debug: isDevelopment, * logLevel: isDevelopment ? "debug" : "info", * cacheEnabled: !isDevelopment * }); * ``` */ static defaults(schema: InterfaceSchema, defaultValues: Record): InterfaceSchema; /** * Create a strict version of a schema that rejects any additional properties * * By default, Fortify Schema ignores extra properties in the input data (they're * simply not included in the validated output). The `strict()` method changes this * behavior to actively reject any properties that aren't defined in the schema, * making validation fail with an error. * * This is useful for APIs where you want to ensure clients aren't sending * unexpected data, form validation where extra fields indicate errors, or * configuration parsing where unknown options should be flagged. * * @param schema - The source schema to make strict * @returns A new schema that rejects additional properties * * @example Basic strict validation * ```typescript * const UserSchema = Interface({ * id: "number", * name: "string", * email: "email" * }); * * const StrictUserSchema = Mod.strict(UserSchema); * * // This will succeed * StrictUserSchema.parse({ * id: 1, * name: "John", * email: "john@example.com" * }); // ✅ * * // This will fail due to extra property * StrictUserSchema.parse({ * id: 1, * name: "John", * email: "john@example.com", * age: 30 // ❌ Error: Unexpected properties: age * }); * ``` * * @example API endpoint validation * ```typescript * const CreatePostSchema = Interface({ * title: "string", * content: "string", * tags: "string[]?", * published: "boolean?" * }); * * const StrictCreatePostSchema = Mod.strict(CreatePostSchema); * * // Protect against typos or malicious extra data * app.post('/posts', (req, res) => { * const result = StrictCreatePostSchema.safeParse(req.body); * * if (!result.success) { * return res.status(400).json({ * error: "Invalid request data", * details: result.errors * }); * } * * // Guaranteed to only contain expected fields * const post = result.data; * }); * ``` * * @example Configuration validation * ```typescript * const DatabaseConfigSchema = Interface({ * host: "string", * port: "number", * username: "string", * password: "string", * database: "string" * }); * * const StrictDatabaseConfig = Mod.strict(DatabaseConfigSchema); * * // Catch configuration typos early * const config = StrictDatabaseConfig.parse({ * host: "localhost", * port: 5432, * username: "admin", * password: "secret", * database: "myapp", * connectionTimeout: 5000 // ❌ Error: Unknown config option * }); * ``` * * @example Comparison with default behavior * ```typescript * const Schema = Interface({ name: "string" }); * const StrictSchema = Mod.strict(Schema); * * const input = { name: "John", extra: "ignored" }; * * // Default behavior: extra properties ignored * const defaultResult = Schema.parse(input); * console.log(defaultResult); // { name: "John" } - extra property ignored * * // Strict behavior: extra properties cause error * const strictResult = StrictSchema.safeParse(input); * console.log(strictResult.success); // false * console.log(strictResult.errors); // [{ message: "Unexpected properties: extra" }] * ``` */ static strict(schema: InterfaceSchema): InterfaceSchema; /** * Create a passthrough version of a schema that preserves additional properties * * By default, Fortify Schema ignores extra properties in the input data (they're * not included in the validated output). The `passthrough()` method changes this * behavior to explicitly include all additional properties in the validated result, * effectively making the schema more permissive. * * This is useful for proxy APIs, data transformation pipelines, or situations * where you want to validate known fields while preserving unknown ones for * later processing or forwarding to other systems. * * @param schema - The source schema to make passthrough * @returns A new schema that includes additional properties in the output * * @example Basic passthrough behavior * ```typescript * const UserSchema = Interface({ * id: "number", * name: "string", * email: "email" * }); * * const PassthroughUserSchema = Mod.passthrough(UserSchema); * * const result = PassthroughUserSchema.parse({ * id: 1, * name: "John", * email: "john@example.com", * age: 30, // Extra property * department: "IT" // Extra property * }); * * console.log(result); * // { * // id: 1, * // name: "John", * // email: "john@example.com", * // age: 30, // ✅ Preserved * // department: "IT" // ✅ Preserved * // } * ``` * * @example API proxy with validation * ```typescript * const KnownUserFieldsSchema = Interface({ * id: "number", * name: "string", * email: "email", * role: "admin|user|moderator" * }); * * const ProxyUserSchema = Mod.passthrough(KnownUserFieldsSchema); * * // Validate known fields while preserving unknown ones * app.post('/users/proxy', (req, res) => { * const result = ProxyUserSchema.safeParse(req.body); * * if (!result.success) { * return res.status(400).json({ * error: "Invalid known fields", * details: result.errors * }); * } * * // Forward to another service with all data preserved * const response = await externalAPI.createUser(result.data); * res.json(response); * }); * ``` * * @example Data transformation pipeline * ```typescript * const CoreDataSchema = Interface({ * timestamp: "date", * userId: "number", * action: "string" * }); * * const FlexibleDataSchema = Mod.passthrough(CoreDataSchema); * * // Process events with varying additional metadata * function processEvent(rawEvent: unknown) { * const result = FlexibleDataSchema.safeParse(rawEvent); * * if (!result.success) { * throw new Error("Invalid core event structure"); * } * * const event = result.data; * * // Core fields are validated and typed * console.log(`User ${event.userId} performed ${event.action} at ${event.timestamp}`); * * // Additional metadata is preserved for downstream processing * if ('metadata' in event) { * processMetadata(event.metadata); * } * * return event; // All data preserved * } * ``` * * @example Comparison with default and strict behavior * ```typescript * const Schema = Interface({ name: "string" }); * const PassthroughSchema = Mod.passthrough(Schema); * const StrictSchema = Mod.strict(Schema); * * const input = { name: "John", extra: "data", more: "fields" }; * * // Default: extra properties ignored * const defaultResult = Schema.parse(input); * console.log(defaultResult); // { name: "John" } * * // Passthrough: extra properties included * const passthroughResult = PassthroughSchema.parse(input); * console.log(passthroughResult); // { name: "John", extra: "data", more: "fields" } * * // Strict: extra properties cause error * const strictResult = StrictSchema.safeParse(input); * console.log(strictResult.success); // false * ``` */ static passthrough(schema: InterfaceSchema): InterfaceSchema>; /** * Create a schema that accepts null values for all fields * @example * ```typescript * const UserSchema = Interface({ id: "number", name: "string" }); * const NullableSchema = Mod.nullable(UserSchema); * // Result: { id: number | null, name: string | null } * ``` */ static nullable(schema: InterfaceSchema): InterfaceSchema<{ [K in keyof T]: T[K] | null; }>; /** * Get comprehensive metadata and statistics about a schema * * This method analyzes a schema and returns detailed information about its structure, * including field counts, types, and other useful metadata. This is particularly * useful for debugging, documentation generation, schema analysis tools, or * building dynamic UIs based on schema structure. * * @param schema - The schema to analyze * @returns Object containing detailed schema metadata * * @example Basic schema analysis * ```typescript * const UserSchema = Interface({ * id: "number", * name: "string", * email: "email?", * profile: { * bio: "string?", * avatar: "string" * }, * tags: "string[]?" * }); * * const info = Mod.info(UserSchema); * console.log(info); * // { * // fieldCount: 5, * // requiredFields: 3, * // optionalFields: 2, * // types: ["number", "string", "email?", "object", "string[]?"], * // fields: ["id", "name", "email", "profile", "tags"] * // } * ``` * * @example Using info for documentation generation * ```typescript * function generateSchemaDoc(schema: InterfaceSchema, name: string) { * const info = Mod.info(schema); * * return ` * ## ${name} Schema * * **Fields:** ${info.fieldCount} total (${info.requiredFields} required, ${info.optionalFields} optional) * * **Field Types:** * ${info.fields.map((field, i) => `- ${field}: ${info.types[i]}`).join('\n')} * `; * } * * const doc = generateSchemaDoc(UserSchema, "User"); * console.log(doc); * ``` * * @example Schema complexity analysis * ```typescript * function analyzeSchemaComplexity(schema: InterfaceSchema) { * const info = Mod.info(schema); * * const complexity = { * simple: info.fieldCount <= 5, * hasOptionalFields: info.optionalFields > 0, * hasArrays: info.types.some(type => type.includes('[]')), * hasNestedObjects: info.types.includes('object'), * typeVariety: new Set(info.types.map(type => * type.replace(/\?|\[\]/g, '') * )).size * }; * * return complexity; * } * * const complexity = analyzeSchemaComplexity(UserSchema); * console.log(complexity); * // { * // simple: false, * // hasOptionalFields: true, * // hasArrays: true, * // hasNestedObjects: true, * // typeVariety: 4 * // } * ``` * * @example Dynamic form generation * ```typescript * function generateFormFields(schema: InterfaceSchema) { * const info = Mod.info(schema); * * return info.fields.map((fieldName, index) => { * const fieldType = info.types[index]; * const isRequired = !fieldType.includes('?'); * const baseType = fieldType.replace(/\?|\[\]/g, ''); * * return { * name: fieldName, * type: baseType, * required: isRequired, * isArray: fieldType.includes('[]'), * inputType: getInputType(baseType) // Custom function * }; * }); * } * * function getInputType(type: string): string { * switch (type) { * case 'string': return 'text'; * case 'number': return 'number'; * case 'email': return 'email'; * case 'date': return 'date'; * case 'boolean': return 'checkbox'; * default: return 'text'; * } * } * * const formFields = generateFormFields(UserSchema); * ``` * * @example Schema validation and testing * ```typescript * function validateSchemaStructure(schema: InterfaceSchema) { * const info = Mod.info(schema); * const issues: string[] = []; * * if (info.fieldCount === 0) { * issues.push("Schema has no fields"); * } * * if (info.requiredFields === 0) { * issues.push("Schema has no required fields"); * } * * if (info.fieldCount > 20) { * issues.push("Schema might be too complex (>20 fields)"); * } * * const unknownTypes = info.types.filter(type => * !['string', 'number', 'boolean', 'date', 'email', 'object'].some(known => * type.replace(/\?|\[\]/g, '').includes(known) * ) * ); * * if (unknownTypes.length > 0) { * issues.push(`Unknown types found: ${unknownTypes.join(', ')}`); * } * * return { * valid: issues.length === 0, * issues, * info * }; * } * ``` */ static info(schema: InterfaceSchema): { fieldCount: number; requiredFields: number; optionalFields: number; types: string[]; fields: string[]; }; /** * Clone a schema with optional modifications * @example * ```typescript * const UserSchema = Interface({ id: "number", name: "string" }); * const ClonedSchema = Mod.clone(UserSchema, { preserveOptions: true }); * ``` */ static clone(schema: InterfaceSchema, options?: { preserveOptions?: boolean; }): InterfaceSchema; } type DeepPartial = { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P]; }; /** * Helper class for creating schema values */ declare class Make { /** * Create a constant value (safer than using raw values) * @example * ```typescript * const schema = Interface({ * status: Make.const("pending"), * version: Make.const(1.0), * enabled: Make.const(true) * }); * ``` */ static const(value: T): ConstantValue & { const: T; }; /** * Create a union type (multiple allowed values) with proper type inference * @example * ```typescript * const schema = Interface({ * status: Make.union("pending", "accepted", "rejected"), * priority: Make.union("low", "medium", "high") * }); * ``` */ static union(...values: T): UnionValue; /** * Create an optional union type with proper type inference * @example * ```typescript * const schema = Interface({ * status: Make.unionOptional("pending", "accepted", "rejected") * }); * ``` */ static unionOptional(...values: T): UnionValue & { optional: true; }; } /** * TypeScript Interface-like Schema System * * The most intuitive way to define schemas - just like TypeScript interfaces! * * @example * ```typescript * import { Interface as IF} from "fortify-schema"; * * // Define schema like a TypeScript interface * const UserSchema = IF({ * id: "number", * email: "email", * name: "string", * age: "number?", // Optional * isActive: "boolean?", // Optional * tags: "string[]?", // Optional array * role: "admin", // Constant value * profile: { // Nested object * bio: "string?", * avatar: "url?" * } * }); * * // Validate data * const result = UserSchema.safeParse(userData); * ``` */ /** * Create a schema using TypeScript interface-like syntax with full type inference * * @param definition - Schema definition using TypeScript-like syntax * @param options - Optional validation options * @returns InterfaceSchema instance with inferred types * * @example Basic Usage * ```typescript * const UserSchema = Interface({ * id: "number", * email: "email", * name: "string", * age: "number?", * isActive: "boolean?", * tags: "string[]?" * }); * * // result is fully typed as: * // SchemaValidationResult<{ * // id: number; * // email: string; * // name: string; * // age?: number; * // isActive?: boolean; * // tags?: string[]; * // }> * const result = UserSchema.safeParse(data); * ``` * * @example With Constraints * ```typescript * const UserSchema = Interface({ * username: "string(3,20)", // 3-20 characters * age: "number(18,120)", // 18-120 years * tags: "string[](1,10)?", // 1-10 tags, optional * }); * ``` * * @example Nested Objects * ```typescript * const OrderSchema = Interface({ * id: "number", * customer: { * name: "string", * email: "email", * address: { * street: "string", * city: "string", * zipCode: "string" * } * }, * items: [{ * name: "string", * price: "number", * quantity: "int" * }] * }); * ``` */ declare function Interface(definition: T, options?: SchemaOptions): InterfaceSchema>; /** * Type helper for inferring TypeScript types from schema definitions * * @example * ```typescript * const UserSchema = Interface({ * id: "number", * email: "email", * name: "string", * age: "number?", * tags: "string[]?" * }); * * // Infer the TypeScript type * type User = InferType; * // User = { * // id: number; * // email: string; * // name: string; * // age?: number; * // tags?: string[]; * // } * ``` */ type InferType> = T extends InterfaceSchema ? U : never; /** * Available field types for schema definitions */ declare const FieldTypes: { readonly STRING: "string"; readonly STRING_OPTIONAL: "string?"; readonly NUMBER: "number"; readonly NUMBER_OPTIONAL: "number?"; readonly BOOLEAN: "boolean"; readonly BOOLEAN_OPTIONAL: "boolean?"; readonly DATE: "date"; readonly DATE_OPTIONAL: "date?"; readonly ANY: "any"; readonly ANY_OPTIONAL: "any?"; readonly EMAIL: "email"; readonly EMAIL_OPTIONAL: "email?"; readonly URL: "url"; readonly URL_OPTIONAL: "url?"; readonly UUID: "uuid"; readonly UUID_OPTIONAL: "uuid?"; readonly PHONE: "phone"; readonly PHONE_OPTIONAL: "phone?"; readonly SLUG: "slug"; readonly SLUG_OPTIONAL: "slug?"; readonly USERNAME: "username"; readonly USERNAME_OPTIONAL: "username?"; readonly INT: "int"; readonly INT_OPTIONAL: "int?"; readonly POSITIVE: "positive"; readonly POSITIVE_OPTIONAL: "positive?"; readonly FLOAT: "float"; readonly FLOAT_OPTIONAL: "float?"; readonly STRING_ARRAY: "string[]"; readonly STRING_ARRAY_OPTIONAL: "string[]?"; readonly NUMBER_ARRAY: "number[]"; readonly NUMBER_ARRAY_OPTIONAL: "number[]?"; readonly BOOLEAN_ARRAY: "boolean[]"; readonly BOOLEAN_ARRAY_OPTIONAL: "boolean[]?"; readonly INT_ARRAY: "int[]"; readonly INT_ARRAY_OPTIONAL: "int[]?"; readonly EMAIL_ARRAY: "email[]"; readonly EMAIL_ARRAY_OPTIONAL: "email[]?"; readonly URL_ARRAY: "url[]"; readonly URL_ARRAY_OPTIONAL: "url[]?"; readonly RECORD_STRING_ANY: "record"; readonly RECORD_STRING_ANY_OPTIONAL: "record?"; readonly RECORD_STRING_STRING: "record"; readonly RECORD_STRING_STRING_OPTIONAL: "record?"; readonly RECORD_STRING_NUMBER: "record"; readonly RECORD_STRING_NUMBER_OPTIONAL: "record?"; }; /** * Quick schema creation helpers */ declare const QuickSchemas: { /** * User schema with common fields */ User: InterfaceSchema>; /** * API response schema */ APIResponse: InterfaceSchema>; /** * Pagination schema */ Pagination: InterfaceSchema>; /** * Address schema */ Address: InterfaceSchema>; /** * Contact info schema */ Contact: InterfaceSchema>; }; /** * OpenAPI Converter - Convert schemas to OpenAPI specifications * * This module provides utilities to convert Fortify Schema definitions * to OpenAPI 3.0 specifications for API documentation. */ /** * OpenAPI converter for schema definitions */ declare class OpenAPIConverter { /** * Convert a schema to OpenAPI format */ static convertSchema(schema: SchemaInterface): OpenAPISchemaObject; /** * Convert a single field to OpenAPI property */ private static convertField; /** * Convert string-based field definitions */ private static convertStringField; /** * Convert object field definitions */ private static convertObjectField; /** * Parse string constraints from string(min,max) format */ private static parseStringConstraints; /** * Generate complete OpenAPI specification */ static generateOpenAPISpec(schema: SchemaInterface, options: OpenAPISpecOptions): OpenAPISpecification; /** * Generate schema reference for use in OpenAPI paths */ static generateSchemaReference(schemaName: string): OpenAPIReference; /** * Generate request body specification */ static generateRequestBody(schema: SchemaInterface, options?: RequestBodyOptions): OpenAPIRequestBody; /** * Generate response specification */ static generateResponse(schema: SchemaInterface, options?: ResponseOptions): OpenAPIResponse; } /** * Type definitions */ interface OpenAPISchemaObject { type: string; properties?: Record; required?: string[]; items?: any; format?: string; pattern?: string; minimum?: number; maximum?: number; exclusiveMinimum?: boolean; exclusiveMaximum?: boolean; minLength?: number; maxLength?: number; minItems?: number; maxItems?: number; } interface OpenAPISpecOptions { title: string; version: string; description?: string; schemaName?: string; servers?: string[]; paths?: Record; } interface OpenAPISpecification { openapi: string; info: { title: string; version: string; description?: string; }; servers?: Array<{ url: string; }>; components: { schemas: Record; }; paths: Record; } interface OpenAPIReference { $ref: string; } interface RequestBodyOptions { description?: string; required?: boolean; examples?: Record; } interface OpenAPIRequestBody { description: string; required: boolean; content: Record; }>; } interface ResponseOptions { description?: string; examples?: Record; headers?: Record; } interface OpenAPIResponse { description: string; content: Record; }>; headers?: Record; } /** * TypeScript Generator - Generate TypeScript type definitions from schemas * * This module provides utilities to convert Fortify Schema definitions * to TypeScript type definitions and interfaces. */ /** * TypeScript code generator for schema definitions */ declare class TypeScriptGenerator$1 { /** * Generate TypeScript interface from schema */ static generateInterface(schema: SchemaInterface, options?: TypeScriptOptions): string; /** * Extract field definitions from schema object */ private static extractFieldDefinitions; /** * Generate interface definition */ private static generateInterfaceDefinition; /** * Generate type alias definition */ private static generateTypeDefinition; /** * Convert schema field to TypeScript type */ private static convertToTypeScript; /** * Convert string-based field to TypeScript type */ private static convertStringToTypeScript; /** * Convert object to TypeScript type */ private static convertObjectToTypeScript; /** * Check if field is optional */ private static isOptionalField; /** * Generate utility types for schema */ static generateUtilityTypes(schema: SchemaInterface, baseName: string): string; /** * Generate validation function types */ static generateValidationTypes(baseName: string): string; /** * Generate complete TypeScript module */ static generateModule(schema: SchemaInterface, options: ModuleOptions): string; /** * Generate JSDoc comments for schema fields */ static generateJSDoc(schema: SchemaInterface): Record; /** * Generate JSDoc for a single field */ private static generateFieldJSDoc; } /** * Type definitions */ interface TypeScriptOptions { exportName?: string; namespace?: string; exportType?: "interface" | "type"; } interface ModuleOptions { moduleName?: string; exportName?: string; includeUtilities?: boolean; includeValidation?: boolean; header?: string; } /** * Validation Engine - Core validation logic for schema extensions * * This module provides the core validation engine that powers all schema extensions. * It acts as a bridge between extensions and the main validation system, delegating * actual validation to the TypeValidators module to avoid duplication. */ /** * Core validation engine for schema validation */ declare class ValidationEngine { /** * Validate a value against a schema field definition * Delegates to TypeValidators for actual validation logic */ static validateField(fieldSchema: any, value: any): ValidationFieldResult; /** * Validate against string-based schema definitions * Uses TypeValidators for consistent validation logic */ private static validateStringSchema; /** * Validate against object schema definitions */ private static validateObjectSchema; /** * Validate entire object against schema */ static validateObject(schema: SchemaInterface, data: any): ValidationResult$1; } /** * Type definitions */ interface ValidationFieldResult { isValid: boolean; errors: string[]; } interface ValidationResult$1 { isValid: boolean; data: any; errors: Record; timestamp: Date; } /** * Type definitions */ interface DocumentationOptions { title?: string; description?: string; examples?: boolean; interactive?: boolean; } interface InteractiveOptions { title?: string; theme?: "light" | "dark"; showExamples?: boolean; allowTesting?: boolean; } interface Documentation { markdown: string; html: string; openapi: OpenAPISpec; json: any; examples: any[]; } interface InteractiveDocumentation { html: string; css: string; javascript: string; } interface OpenAPISpec { openapi: string; info: { title: string; version: string; }; servers?: Array<{ url: string; }>; components: { schemas: Record; }; } /** * Type definitions */ interface ValidationResult { isValid: boolean; data: any; errors: Record; timestamp: Date; } interface FieldValidationResult { field: string; value: any; isValid: boolean; errors: string[]; } interface ValidationStats { totalValidated: number; validCount: number; invalidCount: number; errorRate: number; startTime: Date; } type InferFieldType = T extends "string" ? string : T extends "string?" ? string | undefined : T extends "number" ? number : T extends "number?" ? number | undefined : T extends "boolean" ? boolean : T extends "boolean?" ? boolean | undefined : T extends "string[]" ? string[] : T extends "string[]?" ? string[] | undefined : T extends "number[]" ? number[] : T extends "number[]?" ? number[] | undefined : T extends "boolean[]" ? boolean[] : T extends "boolean[]?" ? boolean[] | undefined : T extends `${string}|${string}` ? string : any; type ConditionalResult = { __conditional: true; __inferredType: InferFieldType | InferFieldType; }; /** * Builder for the "else" part of conditional validation with TypeScript inference * This class is returned after calling .then() and provides the .else() method */ declare class ConditionalElse { private builder; private condition; private thenSchema; constructor(builder: ConditionalBuilder, condition: (value: any) => boolean, thenSchema: TThen); /** * Specify the schema to use when the condition is false */ else(elseSchema: TElse): ConditionalResult; /** * Alias for else() - for backward compatibility */ default(defaultSchema: TElse): ConditionalResult; /** * Build without else clause (same as calling .else(undefined)) */ build(): any; } /** * Builder for the "then" part of conditional validation with TypeScript inference */ declare class ConditionalThen { private builder; private condition; constructor(builder: ConditionalBuilder, condition: (value: any) => boolean); then(schema: T): ConditionalElse; } /** * Builder for single field conditional validation with TypeScript inference */ declare class ConditionalBuilder { private fieldName; private conditions; private defaultSchema; constructor(fieldName: string); /** * Check if field equals specific value */ is(value: any): ConditionalThen; /** * Check if field does not equal specific value */ isNot(value: any): ConditionalThen; /** * Check if field exists (not null/undefined) */ exists(): ConditionalThen; /** * Check if field matches pattern */ matches(pattern: RegExp): ConditionalThen; /** * Check if field is in array of values */ in(values: any[]): ConditionalThen; /** * Custom condition function */ when(condition: (value: any) => boolean): ConditionalThen; addCondition(condition: (value: any) => boolean, schema: any): this; default(schema: any): any; build(): any; } /** * Builder for multi-field "then" part */ declare class MultiConditionalThen { private builder; private conditions; constructor(builder: MultiConditionalBuilder, conditions: Record); then(schema: any): MultiConditionalElse; } /** * Builder for multi-field "else" part */ declare class MultiConditionalElse { private thenSchema; private elseSchema; constructor(thenSchema: any, elseSchema: any); else(schema: any): any; } /** * Custom validator builder */ declare class CustomValidator { private validator; constructor(validator: (data: any) => { valid: true; } | { error: string; }); build(): any; } /** * Builder for multi-field conditional validation */ declare class MultiConditionalBuilder { private fieldNames; private matchConditions; constructor(fieldNames: string[]); match(conditions: Record): MultiConditionalThen; } /** * Conditional Validation - dependent field validation * * This module provides powerful conditional validation where fields can depend * on other fields' values, making complex business logic validation simple. */ /** * Conditional validation utilities */ declare const When: { /** * Create conditional validation based on another field's value * * @example * ```typescript * const UserSchema = Interface({ * accountType: Make.union("free", "premium", "enterprise"), * maxProjects: When.field("accountType").is("free").then("int(1,3)") * .is("premium").then("int(1,50)") * .is("enterprise").then("int(1,)") * .default("int(1,1)"), * * paymentMethod: When.field("accountType").isNot("free").then("string").else("string?"), * billingAddress: When.field("paymentMethod").exists().then({ * street: "string", * city: "string", * country: "string(2,2)" * }).else("any?") * }); * ``` */ field(fieldName: string): ConditionalBuilder; /** * Create validation that depends on multiple fields * * @example * ```typescript * const OrderSchema = Interface({ * orderType: Make.union("pickup", "delivery"), * address: "string?", * deliveryFee: "number?", * * // Complex conditional validation * ...When.fields(["orderType", "address"]).match({ * orderType: "delivery", * address: (val) => val && val.length > 0 * }).then({ * deliveryFee: "number(0,)" // Required for delivery with address * }).else({ * deliveryFee: "number?" // Optional otherwise * }) * }); * ``` */ fields(fieldNames: string[]): MultiConditionalBuilder; /** * Create custom validation logic * * @example * ```typescript * const EventSchema = Interface({ * startDate: "date", * endDate: "date", * * // Custom validation: endDate must be after startDate * ...When.custom((data) => { * if (data.endDate <= data.startDate) { * return { error: "End date must be after start date" }; * } * return { valid: true }; * }) * }); * ``` */ custom(validator: (data: any) => { valid: true; } | { error: string; }): CustomValidator; }; /** * Smart Schema Inference - TypeScript type-to-schema conversion * * This module provides automatic schema generation from TypeScript types, * making schema definition even more seamless. */ /** * Smart inference utilities for automatic schema generation */ declare const Smart: { /** * Infer schema from TypeScript interface using runtime reflection * * @example * ```typescript * interface User { * id: number; * email: string; * name?: string; * } * * // Use with sample data that matches your interface * const UserSchema = Smart.fromType({ * id: 1, * email: "user@example.com", * name: "John Doe" * }); * // Generates: Interface({ id: "positive", email: "email", name: "string?" }) * ``` */ fromType(sampleData: T): SchemaInterface; /** * Infer schema from sample data with intelligent type detection * * @example * ```typescript * const sampleUser = { * id: 1, * email: "user@example.com", * name: "John Doe", * tags: ["developer", "typescript"] * }; * * const UserSchema = Smart.fromSample(sampleUser); * // Generates: Interface({ id: "positive", email: "email", name: "string", tags: "string[]" }) * ``` */ fromSample(sample: any): SchemaInterface; /** * Infer field type from value with smart detection */ inferFieldType(value: any): string; /** * Smart format detection utilities */ isEmail(str: string): boolean; isUrl(str: string): boolean; isUuid(str: string): boolean; isPhone(str: string): boolean; /** * Generate schema from JSON Schema (migration helper) * * @example * ```typescript * const jsonSchema = { * type: "object", * properties: { * id: { type: "number" }, * email: { type: "string", format: "email" } * } * }; * * const schema = Smart.fromJsonSchema(jsonSchema); * ``` */ fromJsonSchema(jsonSchema: any): SchemaInterface; convertJsonSchemaProperty(prop: any): string; }; /** * Live validator for real-time validation */ declare class LiveValidator { private schema; private currentData; private currentErrors; private listeners; private fieldListeners; constructor(schema: SchemaInterface); /** * Validate a single field in real-time */ validateField(fieldName: string, value: any): FieldValidationResult; /** * Validate all current data */ validateAll(): ValidationResult; /** * Listen for validation changes */ onValidation(listener: (result: ValidationResult) => void): void; /** * Listen for specific field validation */ onFieldValidation(fieldName: string, listener: (result: FieldValidationResult) => void): void; /** * Get current validation state */ get isValid(): boolean; get errors(): Record; get data(): any; private notifyListeners; } /** * Form validator with DOM integration */ declare class FormValidator extends LiveValidator { private boundFields; private autoValidationEnabled; private submitListeners; /** * Bind a form field for automatic validation (Node.js compatible) */ bindField(fieldName: string, element: any): void; /** * Enable automatic validation on input changes (Node.js compatible) */ enableAutoValidation(): void; /** * Listen for form submission */ onSubmit(listener: (isValid: boolean, data: any, errors: Record) => void): void; /** * Trigger form validation (typically on submit) */ submit(): void; private setupFieldListeners; } /** * Enhanced Stream Validator with full EventEmitter-like interface * Supports all standard stream methods (.on, .emit, .pipe, etc.) * Synchronized with InterfaceSchema modules */ declare class StreamValidator { private schema; private validListeners; private invalidListeners; private statsListeners; private eventListeners; private onceListeners; private isPaused; private isDestroyed; private dataQueue; private transformers; private filters; private mappers; private stats; constructor(schema: SchemaInterface); /** * Generic event listener (EventEmitter-like interface) */ on(event: string, listener: (...args: any[]) => void): this; /** * One-time event listener */ once(event: string, listener: (...args: any[]) => void): this; /** * Remove event listener */ off(event: string, listener?: (...args: any[]) => void): this; /** * Emit event to all listeners */ emit(event: string, ...args: any[]): boolean; /** * Enhanced validate method with stream control and InterfaceSchema sync */ validate(data: any): void; private _processData; private _formatErrors; private _applyTransformations; private _passesFilters; /** * Listen for valid data */ onValid(listener: (data: any) => void): void; /** * Listen for invalid data */ onInvalid(listener: (data: any, errors: Record) => void): void; /** * Listen for validation statistics */ onStats(listener: (stats: ValidationStats) => void): void; /** * Get current validation statistics */ getStats(): ValidationStats; private updateStats; /** * Add data transformer to pipeline */ transform(transformer: (data: any) => any): this; /** * Add data filter to pipeline */ filter(predicate: (data: any) => boolean): this; /** * Add data mapper to pipeline */ map(mapper: (data: any) => any): this; /** * Pipe data to another stream validator */ pipe(destination: StreamValidator): StreamValidator; /** * Pause the stream (queue incoming data) */ pause(): this; /** * Resume the stream (process queued data) */ resume(): this; /** * Destroy the stream (cleanup and prevent further use) */ destroy(): this; /** * Check if stream is destroyed */ get destroyed(): boolean; /** * Check if stream is paused */ get paused(): boolean; /** * Get queue length */ get queueLength(): number; } /** * Real-time Validation - live validation system * * This module provides real-time validation with reactive updates, * perfect for forms and live data validation. * * Uses modular validation engine for consistent validation logic. */ /** * Real-time validation utilities */ declare const Live: { /** * Create a reactive validator that validates in real-time * * @example * ```typescript * const UserSchema = Interface({ * email: "email", * username: "string(3,20)", * password: "string(8,)" * }); * * const liveValidator = Live.validator(UserSchema); * * // Listen for validation changes * liveValidator.onValidation((result) => { * console.log('Validation result:', result); * updateUI(result); * }); * * // Validate field by field * liveValidator.validateField('email', 'user@example.com'); * liveValidator.validateField('username', 'johndoe'); * * // Get current state * console.log(liveValidator.isValid); // true/false * console.log(liveValidator.errors); // Current errors * ``` */ validator(schema: SchemaInterface): LiveValidator; /** * Create a form validator with field-level validation * * @example * ```typescript * const formValidator = Live.form(UserSchema); * * // Bind to form fields * formValidator.bindField('email', emailInput); * formValidator.bindField('username', usernameInput); * * // Auto-validation on input * formValidator.enableAutoValidation(); * * // Submit validation * formValidator.onSubmit((isValid, data, errors) => { * if (isValid) { * submitForm(data); * } else { * showErrors(errors); * } * }); * ``` */ form(schema: SchemaInterface): FormValidator; /** * Create a stream validator for continuous data validation * * @example * ```typescript * const streamValidator = Live.stream(DataSchema); * * // Validate streaming data * dataStream.subscribe((data) => { * streamValidator.validate(data); * }); * * // Handle validation results * streamValidator.onValid((data) => { * processValidData(data); * }); * * streamValidator.onInvalid((data, errors) => { * logInvalidData(data, errors); * }); * ``` */ stream(schema: SchemaInterface): StreamValidator; }; /** * Auto documentation utilities */ declare const Docs: { /** * Generate comprehensive documentation from schema * * @example * ```typescript * const UserSchema = Interface({ * id: "uuid", * email: "email", * name: "string(2,50)", * age: "int(18,120)?", * role: Make.union("user", "admin", "moderator") * }); * * const documentation = Docs.generate(UserSchema, { * title: "User API", * description: "User management endpoints", * examples: true, * interactive: true * }); * * console.log(documentation.markdown); * console.log(documentation.html); * console.log(documentation.openapi); * ``` */ generate(schema: SchemaInterface, options?: DocumentationOptions): Documentation; /** * Generate OpenAPI specification from schema * * @example * ```typescript * const openApiSpec = Docs.openapi(UserSchema, { * title: "User API", * version: "1.0.0", * servers: ["https://api.example.com"] * }); * ``` */ openapi(schema: SchemaInterface, options: OpenAPISpecOptions): OpenAPISpecification; /** * Generate TypeScript type definitions * * @example * ```typescript * const typeDefinitions = Docs.typescript(UserSchema, { * exportName: "User", * namespace: "API" * }); * * // Generates: * // export interface User { * // id: string; * // email: string; * // name: string; * // age?: number; * // role: "user" | "admin" | "moderator"; * // } * ``` */ typescript(schema: SchemaInterface, options?: TypeScriptOptions): string; /** * Generate interactive documentation with live examples * * @example * ```typescript * const interactiveDocs = Docs.interactive(UserSchema, { * title: "User Schema Playground", * theme: "dark", * showExamples: true, * allowTesting: true * }); * * document.body.innerHTML = interactiveDocs.html; * ``` */ interactive(schema: SchemaInterface, options?: InteractiveOptions): InteractiveDocumentation; }; /** * TypeScript generator */ declare class TypeScriptGenerator { private schema; private options; constructor(schema: SchemaInterface, options: TypeScriptOptions); generate(): string; private convertToTypeScript; } /** * Extensions Bundle * * All extensions in one convenient object for easy access */ declare const Extensions: { Smart: { fromSample: (sample: any) => SchemaInterface; fromJsonSchema: (jsonSchema: any) => SchemaInterface; fromType: (sampleData: T) => SchemaInterface; }; When: { field: (fieldName: string) => ConditionalBuilder; custom: (validator: (data: any) => { valid: true; } | { error: string; }) => CustomValidator; }; Live: { validator: (schema: SchemaInterface) => LiveValidator; stream: (schema: SchemaInterface) => StreamValidator; }; Docs: { generate: (schema: SchemaInterface, options?: DocumentationOptions) => Documentation; typescript: (schema: SchemaInterface, options?: TypeScriptOptions) => string; openapi: (schema: SchemaInterface, options: OpenAPISpecOptions) => OpenAPISpecification; }; Utils: { ValidationEngine: typeof ValidationEngine; OpenAPIConverter: typeof OpenAPIConverter; TypeScriptGenerator: typeof TypeScriptGenerator$1; }; }; /** * Quick access to most commonly used extensions */ declare const Quick: { fromSample: (sample: any) => SchemaInterface; fromJsonSchema: (jsonSchema: any) => SchemaInterface; when: (fieldName: string) => ConditionalBuilder; live: (schema: SchemaInterface) => LiveValidator; stream: (schema: SchemaInterface) => StreamValidator; docs: (schema: SchemaInterface, options?: DocumentationOptions) => Documentation; typescript: (schema: SchemaInterface, options?: TypeScriptOptions) => string; openapi: (schema: SchemaInterface, options: OpenAPISpecOptions) => OpenAPISpecification; }; interface OptimizationRecommendation { type: 'cache' | 'precompile' | 'restructure' | 'hotpath' | 'memory'; priority: 'low' | 'medium' | 'high' | 'critical'; description: string; estimatedImprovement: number; implementation: () => Promise; } interface PerformanceProfile { averageDuration: number; p95Duration: number; p99Duration: number; throughput: number; cacheHitRate: number; memoryUsage: number; bottlenecks: string[]; recommendations: OptimizationRecommendation[]; } interface PerformanceThresholds { slowOperationMs: number; criticalOperationMs: number; minCacheHitRate: number; maxMemoryMB: number; autoOptimizeThreshold: number; } /** * Smart Performance Monitor & Auto-Optimizer * * Monitors validation performance in real-time and automatically * applies optimizations based on usage patterns and bottlenecks. */ declare class PerformanceMonitor { private static metrics; private static readonly MAX_METRICS; private static readonly ANALYSIS_INTERVAL; private static readonly CLEANUP_INTERVAL; private static readonly thresholds; private static isMonitoring; private static analysisTimer?; private static cleanupTimer?; private static optimizationHistory; private static optimizationCallbacks; /** * Start performance monitoring */ static startMonitoring(customThresholds?: Partial): void; /** * Stop performance monitoring */ static stopMonitoring(): void; /** * Register optimization callback */ static registerOptimization(type: string, callback: () => Promise): void; /** * Record a validation operation */ static recordOperation(operationId: string, duration: number, schemaComplexity: number, cacheHit?: boolean, optimizationApplied?: string): void; /** * Analyze performance and generate recommendations */ static analyzePerformance(): PerformanceProfile; /** * Get performance report */ static getPerformanceReport(): { profile: PerformanceProfile; optimizationHistory: typeof PerformanceMonitor.optimizationHistory; totalMetrics: number; monitoringStatus: boolean; thresholds: PerformanceThresholds; }; /** * Clear performance data */ static clearData(): void; /** * Private methods */ private static performAnalysis; private static calculatePerformanceProfile; private static identifyBottlenecks; private static generateRecommendations; private static autoApplyOptimizations; private static applyOptimization; private static executeOptimization; private static handleOperationResult; private static handleCriticalPerformance; private static optimizeCache; private static optimizeMemory; /** * Get current memory usage in MB */ private static getMemoryUsage; private static precompileSchemas; private static optimizeHotPaths; /** * Get schema definitions for operations from integrated schema registry */ private static getSchemaDefinitionsForOperations; /** * Get the global schema registry (integrates with existing Interface schemas) */ private static getSchemaRegistry; private static schemaRegistry; /** * Infer schema structure from historical validation metrics */ private static inferSchemaFromMetrics; /** * Generate schema based on operation ID patterns */ private static generateSchemaFromPattern; /** * Create optimized validator for hot path with real implementation */ private static createHotPathValidator; private static hotPathValidators; /** * Generate sample data for schema pre-warming */ private static generateSampleData; /** * Generate sample value for a field type */ private static generateSampleValue; /** * Generate test data for hot path warming */ private static generateHotPathTestData; private static cleanupOldMetrics; private static getRecentMetrics; private static groupBy; private static countOperations; private static getEmptyProfile; } export { Docs, Extensions, FieldTypes, Interface, InterfaceSchema, Live, Make, Mod, PerformanceMonitor, Quick, QuickSchemas, Smart, TypeScriptGenerator, When }; export type { ArraySchemaOptions, BooleanSchemaOptions, ConstantValue, InferType, NumberSchemaOptions, ObjectSchemaOptions, SchemaConfig, SchemaFieldType, SchemaInterface, SchemaOptions, SchemaType, SchemaValidationResult, StringSchemaOptions };