@simonecoelhosfo/optimizely-mcp-server
Version:
Optimizely MCP Server for AI assistants with integrated CLI tools
308 lines • 9.22 kB
TypeScript
/**
* UnifiedFieldResolver - Consolidates all field mapping knowledge for dynamic query resolution
*
* This class represents the core of Phase 3 Intelligent Flattening Architecture.
* It consolidates knowledge from:
* - IntelligentPayloadParser (3,750+ field patterns)
* - ComprehensiveAutoCorrector (platform-specific corrections)
* - FieldMapper (entity-specific mappings)
* - FIELDS.generated (complete schema definitions)
*
* The goal is to handle ANY field variation dynamically without hard-coding.
*/
import { EntityType } from './types.js';
/**
* Context information for field resolution
*/
export interface QueryContext {
/** Primary entity being queried */
primaryEntity: EntityType;
/** Platform context (web vs feature experimentation) */
platform?: 'web' | 'feature' | 'custom';
/** Whether individual array elements are needed (affects flattening strategy) */
needsIndividualElements?: boolean;
/** Additional context filters that might affect resolution */
filters?: Array<{
field: string;
operator: string;
value: any;
}>;
/** Project ID for context-sensitive mappings */
projectId?: string;
}
/**
* Result of field resolution process
*/
export interface ResolvedField {
/** Original input field name as provided */
originalInput: string;
/** Canonical field name after all transformations */
canonicalName: string;
/** Path to access the field (e.g., "$.variations[*].key") */
accessPath: string;
/** Data type of the field */
dataType: 'string' | 'number' | 'boolean' | 'array' | 'object' | 'any';
/** Whether the field represents an array */
isArray: boolean;
/** Whether the field is nested within JSON */
isNested: boolean;
/** Whether this field requires flattening to query individual elements */
requiresFlattening: boolean;
/** SQL accessor expression for this field */
sqlAccessor: string;
/** JSONata expression if complex processing needed */
jsonataExpression?: string;
/** Additional JOIN requirements */
requiredJoins?: string[];
/** Additional WHERE conditions needed */
additionalConditions?: string[];
}
/**
* Result of the complete field resolution process
*/
export interface FieldResolutionResult {
/** Successfully resolved fields */
resolvedFields: ResolvedField[];
/** Fields that could not be resolved */
unresolvedFields: string[];
/** Required database JOINs for the query */
requiredJoins: string[];
/** Required WHERE conditions */
additionalConditions: string[];
/** Whether any fields require array flattening */
requiresFlattening: boolean;
/** Whether JSONata post-processing is needed */
requiresJsonProcessing: boolean;
/** Performance hints for query optimization */
optimizationHints: {
/** Can use simple JSON_EXTRACT without flattening */
canUseSimpleExtract: boolean;
/** Estimated complexity level */
complexityLevel: 'simple' | 'moderate' | 'complex';
/** Expected result size impact */
resultSizeImpact: 'minimal' | 'moderate' | 'significant';
};
}
/**
* Normalization step results
*/
export interface NormalizationResult {
/** Normalized field name */
normalized: string;
/** Applied transformations */
transformations: string[];
/** Confidence level (0-1) */
confidence: number;
}
/**
* Synonym mapping result
*/
export interface SynonymMappingResult {
/** Mapped field name */
mapped: string;
/** Applied synonyms */
synonyms: Array<{
from: string;
to: string;
}>;
/** Context that influenced the mapping */
context: string;
}
/**
* Platform correction result
*/
export interface PlatformCorrectionResult {
/** Corrected field name */
corrected: string;
/** Applied corrections */
corrections: Array<{
type: string;
description: string;
}>;
/** Platform that influenced the correction */
platform: string;
}
/**
* Schema validation result
*/
export interface SchemaValidationResult {
/** Validated field information */
field: {
name: string;
path: string;
type: string;
isArray: boolean;
isNested: boolean;
};
/** Whether validation passed */
isValid: boolean;
/** Validation errors if any */
errors: string[];
/** Suggestions for fixes */
suggestions: string[];
}
/**
* UnifiedFieldResolver - The core field resolution engine
*
* This class implements the 5-step resolution process:
* 1. Normalize field name variations (camelCase, snake_case, etc.)
* 2. Apply synonym mappings (traffic → weight, etc.)
* 3. Apply platform-specific corrections
* 4. Validate against schema
* 5. Determine optimal access strategy
*/
export declare class UnifiedFieldResolver {
private payloadParser;
private fieldMapper;
private fieldsSchema;
private logger;
constructor();
/**
* Resolve a single field reference to database access strategy
*
* @param input - Field name as provided by user/agent
* @param context - Query context for resolution
* @returns Complete field resolution result
*/
resolveField(input: string, context: QueryContext): ResolvedField;
/**
* Resolve multiple fields in batch for optimal performance
*
* @param inputs - Array of field names
* @param context - Query context for resolution
* @returns Batch resolution result
*/
resolveFields(inputs: string[], context: QueryContext): FieldResolutionResult;
/**
* Step 1: Normalize field name variations
* Handles: camelCase ↔ snake_case ↔ PascalCase ↔ kebab-case
*/
private normalizeFieldName;
/**
* Detect the case type of input field
*/
private detectCaseType;
/**
* Calculate confidence score for normalization
*/
private calculateNormalizationConfidence;
/**
* Step 2: Apply synonym mappings
* Handles: traffic → weight, traffic_allocation → percentage_included, etc.
*/
private applySynonymMappings;
/**
* Get critical synonyms that solve the "variations.key does not exist" error
*/
private getCriticalSynonyms;
/**
* Get entity-specific synonym mappings
*/
private getEntitySpecificSynonyms;
/**
* Get platform-specific synonym mappings
*/
private getPlatformSpecificSynonyms;
/**
* Get common field synonyms (lowest priority)
*/
private getCommonSynonyms;
/**
* Step 3: Apply platform-specific corrections
* Handles differences between Web and Feature Experimentation
* Uses ComprehensiveAutoCorrector.autoCorrect() static method
*/
private applyPlatformCorrections;
/**
* Apply manual platform-specific field corrections
*/
private getManualPlatformCorrections;
/**
* Get platform-exclusive field lists
*/
private getPlatformExclusiveFields;
/**
* Get platform-specific field name corrections
*/
private getPlatformFieldCorrections;
/**
* Step 4: Validate against schema
* Ensures the field exists and gets type information
*/
private validateAgainstSchema;
/**
* Get entity schema from FIELDS
*/
private getEntitySchema;
/**
* Normalize entity type for schema lookup
*/
private normalizeEntityForSchema;
/**
* Check if field exists in entity schema
*/
private isFieldInSchema;
/**
* Get field type from schema
*/
private getFieldType;
/**
* Check if field is an array type
*/
private isArrayField;
/**
* Get nested field type for array elements
*/
private getNestedFieldType;
/**
* Find fuzzy matches for field name
*/
private findFuzzyMatches;
/**
* Calculate Levenshtein distance for fuzzy matching
*/
private calculateLevenshteinDistance;
/**
* Get all available fields from schema
*/
private getAvailableFields;
/**
* Step 5: Determine optimal access strategy
* Decides between direct SQL, JSON_EXTRACT, or flattening
*/
private determineAccessStrategy;
/**
* Determine if field requires array flattening
*/
private requiresFlattening;
/**
* Build SQL accessor expression
*/
private buildSQLAccessor;
/**
* Build JSONata expression for complex processing
*/
private buildJsonataExpression;
/**
* Determine required database JOINs
*/
private determineRequiredJoins;
/**
* Determine additional WHERE conditions
*/
private determineAdditionalConditions;
/**
* Normalize data type names
*/
private normalizeDataType;
/**
* Initialize all field mapping systems
* This method integrates existing infrastructure without modifying it
*/
private initializeMappers;
/**
* Get performance optimization hints for query planning
*/
private getOptimizationHints;
}
//# sourceMappingURL=UnifiedFieldResolver.d.ts.map