Angular Modernizer
    Preparing search index...

    Parser Orchestrator

    Coordinates parser selection and fallback mechanisms for resilient parsing across different project types. Automatically selects the best parser based on project characteristics and falls back gracefully on failures.

    Architecture:

    ProjectContext → ParserOrchestrator → selectParser() → ParserStrategy
    ↓
    [StandardParser, EnhancedParser]
    ↓
    Cache (>80% hit rate)

    Selection Algorithm:

    1. Check cache for previous selection
    2. Filter parsers that can handle project (canHandle() == true)
    3. Select parser with highest reliability score
    4. Cache selection for future use
    5. Log decision for feedback system

    Fallback Algorithm:

    1. Try primary parser (from selectParser())
    2. On failure, try each alternative parser in order
    3. Log fallback attempts and results
    4. Throw if all parsers fail
    import { ParserOrchestrator } from '@angular-modernizer/core';
    import { Project } from 'ts-morph';

    const project = new Project({ tsConfigFilePath: './tsconfig.json' });
    const orchestrator = new ParserOrchestrator(project);

    // Define project context
    const context: ProjectContext = {
    projectRoot: '/path/to/project',
    hasCustomDecorators: true,
    hasPathAliases: true,
    hasComplexConstructors: false,
    angularVersion: '17.0.0'
    };

    // Auto-select best parser
    const parser = await orchestrator.selectParser(context);
    console.info(`Selected: ${parser.name}`); // 'enhanced'

    // Parse with automatic fallback
    const result = await orchestrator.parseWithFallback(
    'src/app/component.ts',
    fileContent,
    context
    );
    console.info(`Parsed by: ${result.parserUsed}`);
    // If primary parser fails, orchestrator tries alternatives
    try {
    const result = await orchestrator.parseWithFallback(file, content, context);
    if (result.fallbackUsed) {
    console.warn(`Primary parser failed, used ${result.parserUsed}`);
    result.failedParsers?.forEach(({ parserName, error }) => {
    console.error(`${parserName}: ${error}`);
    });
    }
    } catch (error) {
    console.error('All parsers failed:', error);
    }
    Index

    Constructors

    • Initialize the Parser Orchestrator.

      Registers available parser strategies:

      • StandardParserStrategy (0.95 reliability for standard projects)
      • EnhancedParserStrategy (0.6-0.8 reliability for complex projects)

      Strategies are ordered by preference (StandardParser first for performance).

      Parameters

      • project: Project

        ts-morph Project instance for parsing

      • Optionaloptions: { verboseLogging?: boolean }

        Configuration options

      Returns ParserOrchestrator

      const project = new Project({ tsConfigFilePath: './tsconfig.json' });
      const orchestrator = new ParserOrchestrator(project, {
      verboseLogging: true
      });

    Methods

    • Clear the parser selection cache.

      Useful for testing or forcing re-evaluation of parser selection.

      Returns void

      orchestrator.clearCache();
      // Next selectParser() call will re-evaluate
    • Get cache statistics for monitoring.

      Returns { cacheHits: number; hitRate: number; size: number; totalSelections: number }

      Cache statistics object

      • cacheHits: number

        Selections answered from the cache.

      • hitRate: number

        cacheHits / totalSelections (0 to 1; 0 without selections).

      • size: number

        Number of cached parser selections.

      • totalSelections: number

        Number of recorded parser selections.

      const stats = orchestrator.getCacheStats();
      console.info(`Cache size: ${stats.size}`);
      console.info(`Hit rate: ${(stats.hitRate * 100).toFixed(1)}%`);
    • Get the name of the currently selected parser strategy.

      Returns 'none' if no parser has been selected yet.

      Returns string

      Parser strategy name or 'none'

      await orchestrator.selectParser(context);
      console.info(orchestrator.getSelectedStrategy()); // 'enhanced'
    • Get parser selection history for feedback analysis.

      Limited to last 100 selections to prevent memory leaks.

      Returns ParserSelectionDecision[]

      Array of parser selection decisions

      const history = orchestrator.getSelectionHistory();
      console.info(`Total selections: ${history.length}`);
      console.info(`Cache hit rate: ${history.filter(h => h.fromCache).length / history.length}`);
      history.forEach(decision => {
      console.info(`${decision.timestamp}: ${decision.selectedParser} (${decision.reliability})`);
      });
    • Get all registered parser strategies.

      Returns ParserStrategy[]

      Array of registered parser strategies

      const strategies = orchestrator.getStrategies();
      strategies.forEach(s => {
      console.info(`${s.name}: can handle = ${s.canHandle(context)}`);
      });
    • Parse a file with automatic fallback on failure.

      Fallback algorithm:

      1. Try primary parser (from selectParser())
      2. On failure, log error and try each alternative parser
      3. Return first successful parse result with metadata
      4. Throw if all parsers fail

      Resilience: Gracefully degrades to alternative parsers on failure Performance: No overhead unless primary parser fails

      Parameters

      • file: string

        File path to parse

      • content: string

        File content to parse

      • projectContext: ParserProjectContext

        Project characteristics

      Returns Promise<ParseWithFallbackResult>

      Promise resolving to parse result with fallback metadata

      Error if all parsers fail

      const result = await orchestrator.parseWithFallback(file, content, context);
      console.info(`Parsed by: ${result.parserUsed}`); // 'enhanced'
      console.info(`Fallback used: ${result.fallbackUsed}`); // false
      console.info(`Errors: ${result.ast.errors.length}`); // 0
      // If EnhancedParser fails, StandardParser used as fallback
      const result = await orchestrator.parseWithFallback(file, content, context);
      if (result.fallbackUsed) {
      console.warn(`Primary parser failed, using ${result.parserUsed}`);
      result.failedParsers?.forEach(({ parserName, error }) => {
      console.error(`${parserName} failed: ${error}`);
      });
      }
    • Select the best parser for the given project context.

      Selection algorithm:

      1. Check cache for previous selection
      2. Filter parsers that can handle the project (canHandle() == true)
      3. Select parser with highest reliability score
      4. Cache selection for future use
      5. Log decision for feedback system

      Performance:

      • Cached selection: <1ms
      • New selection: <5ms
      • Cache hit rate: >80% in typical usage

      Parameters

      Returns Promise<ParserStrategy>

      Promise resolving to selected ParserStrategy

      Error if no parser can handle the project

      const context: ProjectContext = {
      projectRoot: '/app',
      hasCustomDecorators: false,
      hasPathAliases: false,
      hasComplexConstructors: false,
      angularVersion: '17.0.0'
      };
      const parser = await orchestrator.selectParser(context);
      console.info(parser.name); // 'standard'
      console.info(parser.getReliability(context)); // 0.95
      const context: ProjectContext = {
      projectRoot: '/app',
      hasCustomDecorators: true,
      hasPathAliases: true,
      hasComplexConstructors: false,
      angularVersion: '16.0.0'
      };
      const parser = await orchestrator.selectParser(context);
      console.info(parser.name); // 'enhanced'
      console.info(parser.getReliability(context)); // 0.65
    • Transform an AST with the selected parser.

      Delegates to the currently selected parser's transform method.

      Parameters

      Returns Promise<ParserTransformResult>

      Promise resolving to transformation result

      const parseResult = await orchestrator.parseWithFallback(file, content, context);
      const transformResult = await orchestrator.transform(parseResult.ast, rules);
      console.info(`Modified: ${transformResult.modified}`);
      console.info(`Parser: ${transformResult.metadata?.parserStrategy}`);