A sophisticated 1700+ line parser for Formedible form definitions with advanced security sanitization, complex Zod expression parsing, AI-friendly error reporting, automatic schema inference, and support for all 24+ field types with location-aware debugging.
npx shadcn@latest add https://formedible.dev/r/formedible-parser.json
import { FormedibleParser } from '@/components/formedible-parser';// Main parsing method - supports JSON, JS objects, and Zod expressionsconst formDefinition = `{title: "Advanced Contact Form",fields: [{name: "email",type: "email",label: "Email Address",required: true},{name: "rating",type: "rating",label: "Service Rating",ratingConfig: { max: 5, allowHalf: true, icon: "star" }},{name: "feedback",type: "textarea",label: "Detailed Feedback",textareaConfig: { rows: 4, maxLength: 500, showWordCount: true }}],schema: "z.object({ email: z.string().email(), rating: z.number().optional(), feedback: z.string().optional() })"}`;try {// Parse with default optionsconst parsedConfig = FormedibleParser.parse(formDefinition);console.log('Parsed successfully:', parsedConfig);} catch (error) {console.error('Enhanced error info:', error.message);// Shows detailed AI-friendly error messages with fixes}
// Complex field configurations with nested objectsconst complexFormConfig = `{title: "Team Registration Form",fields: [{name: "teamLead",type: "object",label: "Team Lead Information",objectConfig: {title: "Team Lead Details",collapsible: true,layout: "vertical",fields: [{ name: "name", type: "text", label: "Full Name", required: true },{ name: "email", type: "email", label: "Email", required: true },{ name: "phone", type: "phone", label: "Phone Number", phoneConfig: { defaultCountry: "US" } }]}},{name: "teamMembers",type: "array",label: "Team Members",arrayConfig: {itemType: "object",itemLabel: "Team Member",minItems: 1,maxItems: 10,sortable: true,objectConfig: {fields: [{ name: "name", type: "text", label: "Name", required: true },{ name: "role", type: "select", label: "Role", options: ["Developer", "Designer", "Manager"] },{ name: "skills", type: "multiSelect", label: "Skills", options: ["React", "TypeScript", "Node.js", "Python"] }]}}}]}`;const parsedConfig = FormedibleParser.parse(complexFormConfig);
// Advanced Zod parsing with nested expressions and chained methodsconst zodFormConfig = `{title: "User Registration with Complex Validation",fields: [{name: "email",type: "email",label: "Email Address",required: true},{name: "password",type: "password",label: "Password",passwordConfig: { showToggle: true, strengthMeter: true }},{name: "confirmPassword",type: "password",label: "Confirm Password"}],// Complex chained Zod expressions are parsed correctlyschema: "z.object({email: z.string().email().min(1, 'Required'),password: z.string().min(8).regex(/[A-Z]/, 'Must contain uppercase').regex(/[0-9]/, 'Must contain number'),confirmPassword: z.string()}).refine(data => data.password === data.confirmPassword, { message: 'Passwords must match', path: ['confirmPassword'] })",crossFieldValidation: [{fields: ["password", "confirmPassword"],validator: "passwords-match",message: "Passwords must match exactly"}]}`;const parsedConfig = FormedibleParser.parse(zodFormConfig);
// Enhanced error handling with AI-friendly suggestionsconst invalidConfig = `{fields: [{ name: "email", type: "invalid-type" }, // Invalid field type{ name: "", type: "text" } // Missing name]}`;try {const result = FormedibleParser.parse(invalidConfig);} catch (error) {if (error.name === 'ParserError') {console.log('❌ Error Code:', error.code);console.log('📝 Enhanced message with examples:', error.message);// Shows detailed fix suggestions like:// ✅ Supported field types: text, email, password, url, tel, textarea...// 📝 Example: { name: "email", type: "email", label: "Email Address" }if (error.fieldIndex !== undefined) {console.log('🎯 Error in field #:', error.fieldIndex);}}}// Validation with suggestions - perfect for AI integrationsconst validationResult = FormedibleParser.validateWithSuggestions(invalidConfig);console.log('Is valid:', validationResult.isValid);console.log('Errors:', validationResult.errors);console.log('AI suggestions:', validationResult.suggestions);
// Schema inference and merging capabilitiesconst formDefinition = `{fields: [{ name: "email", type: "email", label: "Email" },{ name: "age", type: "number", label: "Age", min: 18, max: 120 }]}`;// Parse with automatic schema inferenceconst inferenceResult = FormedibleParser.parseWithSchemaInference(formDefinition, {enabled: true,defaultValidation: true,inferFromValues: true});console.log('Parsed config:', inferenceResult.config);console.log('Inferred schema:', inferenceResult.inferredSchema);console.log('Confidence score:', inferenceResult.confidence);// Merge with existing schemasimport { z } from 'zod';const baseSchema = z.object({firstName: z.string(),lastName: z.string()});const mergedConfig = FormedibleParser.mergeSchemas(inferenceResult.config,baseSchema,'extend' // 'extend' | 'override' | 'intersect');// Field type validationconsole.log('Is valid type:', FormedibleParser.isValidFieldType('email')); // trueconsole.log('Supported types:', FormedibleParser.getSupportedFieldTypes()); // All 24 types
// The parser automatically sanitizes dangerous code patternsconst dangerousCode = `{fields: [{name: "email",type: "email",validation: "eval('malicious code')", // ❌ Automatically removedonSubmit: "setTimeout(() => { /* dangerous */ }, 1000)" // ❌ Sanitized}],onSubmit: "fetch('/api/steal-data')" // ❌ Functions not supported in parser mode}`;// Security patterns automatically removed:// - eval, Function, setTimeout, setInterval// - document, window, global, process// - __proto__, constructor, prototype// - Arrow functions and function expressions// - new keyword usageconst safeConfig = FormedibleParser.parse(dangerousCode);// Result: Clean configuration object with dangerous patterns removed// Location-aware error reporting for debuggingtry {FormedibleParser.parse('{ invalid: syntax }');} catch (error) {console.log('Error at line:', error.location?.line);console.log('Error at column:', error.location?.column);console.log('Field context:', error.location?.field);}
// ✅ Main API Methods (all static)FormedibleParser.parse(code, options?) // Main parsing methodFormedibleParser.parseWithSchemaInference(code, options?) // With schema inferenceFormedibleParser.validateWithSuggestions(code) // AI-friendly validationFormedibleParser.mergeSchemas(config, baseSchema, strategy) // Schema mergingFormedibleParser.isValidFieldType(type) // Field type validationFormedibleParser.getSupportedFieldTypes() // Get all supported typesFormedibleParser.validateConfig(config) // Validate config object// ✅ Supported merge strategies'extend' // Add missing fields from base schema'override' // Replace schema completely'intersect' // Keep only fields that exist in both// ✅ All 24 supported field typesconst fieldTypes = FormedibleParser.getSupportedFieldTypes();console.log(fieldTypes);// ['text', 'email', 'password', 'url', 'tel', 'textarea', 'select',// 'checkbox', 'switch', 'number', 'date', 'slider', 'file', 'rating',// 'phone', 'colorPicker', 'location', 'duration', 'multiSelect',// 'autocomplete', 'masked', 'object', 'array', 'radio']
The formedible-parser is a sophisticated 1700+ line implementation with advanced security sanitization, complex Zod expression parsing, schema inference, AI-friendly error reporting, and comprehensive validation for all 24+ field types. Perfect for AI integrations and enterprise applications.