All files / src/abstraction EnhancedWorkItemsManager.ts

97.35% Statements 147/151
80.95% Branches 85/105
100% Functions 19/19
98.63% Lines 144/146

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 4442x 2x 2x 2x                                         2x 46x 46x 46x                       29x 29x 29x 29x   29x 5x     29x 35x   34x     34x 34x   34x 5x 5x 2x   5x     29x   29x     29x     28x 28x 28x   28x 1x     1x 1x 1x             29x 5x 5x 5x 5x   5x 2x       29x                     3x 3x     3x 1x 1x 1x                   2x 2x 6x 6x 1x   5x               3x                     4x   4x 2x 2x   1x       4x             4x 4x   4x   2x 2x   1x             3x                         2x 2x   2x   2x 2x   1x             1x                         3x 2x 2x   2x   2x 2x   1x               2x 2x 1x 1x 1x     2x             3x   3x 4x 4x 3x   1x           3x                               4x 4x   4x 4x   4x 2x           2x 2x     2x                       2x 1x   1x           1x                   1x             2x 2x   2x 1x     1x               29x 29x   29x                       34x   25x   7x   1x   1x         33x   25x   6x   1x   1x         32x   25x   1x   6x         31x   1x   30x         31x   6x   25x           21x 13x 13x       8x 7x         8x      
import { WorkItemsManager } from './WorkItemsManager.js';
import { AdapterFactory } from '../adapters/AdapterFactory.js';
import { DefaultMigrationPipeline } from '../adapters/MigrationPipeline.js';
import {
  validateProviderConfig,
  logConfigurationStatus,
  ConfigValidationResult,
} from '../utils/configValidator.js';
import {
  WorkItem,
  CreateWorkItemData,
  UpdateWorkItemData,
  WorkItemFilter,
  WorkItemExport,
  MigrationResult,
  Provider,
  ProviderCapabilities,
} from '../types/index.js';
import { IProviderAdapter, ProviderConfig } from '../adapters/IProviderAdapter.js';
 
/**
 * Enhanced WorkItemsManager that integrates both the legacy MCP approach
 * and the new adapter system for maximum compatibility and functionality
 */
export class EnhancedWorkItemsManager extends WorkItemsManager {
  private adapters = new Map<string, IProviderAdapter>();
  private migrationPipeline = new DefaultMigrationPipeline();
  private configValidationResults: ConfigValidationResult[] = [];
 
  /**
   * Initialize adapters for providers that support the new adapter system
   * Gracefully skips providers with missing configuration
   */
  async initializeAdapters(options: { silent?: boolean } = {}): Promise<{
    initialized: number;
    skipped: number;
    failed: number;
    results: ConfigValidationResult[];
  }> {
    let initialized = 0;
    let skipped = 0;
    let failed = 0;
    this.configValidationResults = [];
 
    if (!options.silent) {
      console.log('\nšŸ”§ Initializing Provider Adapters...');
    }
 
    for (const providerInstance of this.providerManager.getAllProviders()) {
      if (providerInstance.status !== 'connected') continue;
 
      const providerId = providerInstance.id as Provider;
 
      // Validate configuration first
      const configResult = validateProviderConfig(providerId);
      this.configValidationResults.push(configResult);
 
      if (!configResult.isValid) {
        skipped++;
        if (!options.silent) {
          console.log(`āš ļø  Skipped ${providerId}: ${configResult.reason}`);
        }
        continue;
      }
 
      try {
        // Create adapter configuration from provider instance
        const adapterConfig = this.createAdapterConfig(providerInstance);
 
        // Create and initialize adapter
        const adapter = await AdapterFactory.createAndInitialize(providerId, adapterConfig);
 
        // Store adapter with key
        const key = providerId;
        this.adapters.set(key, adapter);
        initialized++;
 
        if (!options.silent) {
          console.log(`āœ… Initialized ${providerId} adapter`);
        }
      } catch (error) {
        failed++;
        Eif (!options.silent) {
          console.log(
            `āŒ Failed to initialize ${providerId} adapter: ${error instanceof Error ? error.message : String(error)}`,
          );
        }
      }
    }
 
    if (!options.silent) {
      console.log(`\nšŸ“Š Adapter Initialization Summary:`);
      console.log(`   āœ… Initialized: ${initialized}`);
      console.log(`   āš ļø  Skipped: ${skipped}`);
      console.log(`   āŒ Failed: ${failed}`);
 
      if (skipped > 0) {
        logConfigurationStatus(this.configValidationResults);
      }
    }
 
    return { initialized, skipped, failed, results: this.configValidationResults };
  }
 
  /**
   * Check configuration status for all providers
   */
  getConfigurationStatus(): {
    configured: string[];
    missing: Array<{ provider: string; reason: string }>;
    total: number;
  } {
    const configured: string[] = [];
    const missing: Array<{ provider: string; reason: string }> = [];
 
    // If we have cached results, use them
    if (this.configValidationResults.length > 0) {
      this.configValidationResults.forEach((result) => {
        if (result.isValid) {
          configured.push(result.provider);
        } else E{
          missing.push({
            provider: result.provider,
            reason: result.reason ?? 'Unknown configuration issue',
          });
        }
      });
    } else {
      // Otherwise, validate all known providers on-demand
      const providers: Provider[] = ['github', 'gitlab', 'azure'];
      providers.forEach((provider) => {
        const result = validateProviderConfig(provider);
        if (result.isValid) {
          configured.push(result.provider);
        } else {
          missing.push({
            provider: result.provider,
            reason: result.reason ?? 'Unknown configuration issue',
          });
        }
      });
    }
 
    return {
      configured,
      missing,
      total: configured.length + missing.length,
    };
  }
 
  /**
   * Get capabilities for all connected providers
   */
  getProviderCapabilities(): Map<string, ProviderCapabilities> {
    const capabilities = new Map<string, ProviderCapabilities>();
 
    for (const [key, adapter] of this.adapters) {
      try {
        capabilities.set(key, adapter.getCapabilities());
      } catch (error) {
        console.error(`Failed to get capabilities for ${key}:`, error);
      }
    }
 
    return capabilities;
  }
 
  /**
   * Create work item using adapter system (preferred) or fallback to legacy
   */
  async createWorkItemEnhanced(project: string, data: CreateWorkItemData): Promise<WorkItem> {
    const provider = this.detectProviderFromProject(project);
    const adapter = this.getAdapterForProvider(provider);
 
    if (adapter) {
      // Use new adapter system
      try {
        return await adapter.createWorkItem(data);
      } catch (error) {
        console.error(
          `Adapter creation failed, falling back to legacy: ${error instanceof Error ? error.message : String(error)}`,
        );
      }
    }
 
    // Fallback to legacy system
    return await this.createWorkItem(project, {
      title: data.title,
      description: data.description,
      type: data.type,
      labels: data.labels,
      priority: data.priority,
    });
  }
 
  /**
   * Update work item using adapter system (preferred) or fallback to legacy
   */
  async updateWorkItemEnhanced(id: string, updates: UpdateWorkItemData): Promise<WorkItem> {
    const [provider] = id.split(':');
    const adapter = this.getAdapterForProvider(provider);
 
    Eif (adapter) {
      // Use new adapter system
      try {
        return await adapter.updateWorkItem(id, updates);
      } catch (error) {
        console.error(
          `Adapter update failed, falling back to legacy: ${error instanceof Error ? error.message : String(error)}`,
        );
      }
    }
 
    // Fallback to legacy system
    return await this.updateWorkItem(id, {
      title: updates.title,
      description: updates.description,
      state: updates.state,
      labels: updates.labels,
      priority: updates.priority,
    });
  }
 
  /**
   * List work items using adapter system (preferred) or fallback to legacy
   */
  async listWorkItemsEnhanced(project?: string, filter?: WorkItemFilter): Promise<WorkItem[]> {
    if (project) {
      const provider = this.detectProviderFromProject(project);
      const adapter = this.getAdapterForProvider(provider);
 
      Eif (adapter && filter) {
        // Use new adapter system
        try {
          return await adapter.listWorkItems(filter);
        } catch (error) {
          console.error(
            `Adapter listing failed, falling back to legacy: ${error instanceof Error ? error.message : String(error)}`,
          );
        }
      }
    }
 
    // Fallback to legacy system
    const legacyFilters: Record<string, unknown> = {};
    if (filter) {
      Eif (filter.state && filter.state !== 'all') legacyFilters.status = filter.state;
      Iif (filter.assignee) legacyFilters.assignee = filter.assignee;
      Iif (filter.labels) legacyFilters.labels = filter.labels;
    }
 
    return await this.listWorkItems(project, legacyFilters);
  }
 
  /**
   * Search across all providers using adapter system
   */
  async searchWorkItems(query: string): Promise<WorkItem[]> {
    const results: WorkItem[] = [];
 
    for (const [key, adapter] of this.adapters) {
      try {
        const providerResults = await adapter.search(query);
        results.push(...providerResults);
      } catch (error) {
        console.error(
          `Search failed for ${key}: ${error instanceof Error ? error.message : String(error)}`,
        );
      }
    }
 
    return results;
  }
 
  /**
   * Migrate work items between providers using the new migration pipeline
   */
  async migrateWorkItems(
    sourceProject: string,
    targetProject: string,
    _workItemIds: string[],
    options: {
      preserveIds?: boolean;
      mapUsers?: Map<string, string>;
      dryRun?: boolean;
    } = {},
  ): Promise<MigrationResult> {
    const sourceProvider = this.detectProviderFromProject(sourceProject);
    const targetProvider = this.detectProviderFromProject(targetProject);
 
    const sourceAdapter = this.getAdapterForProvider(sourceProvider);
    const targetAdapter = this.getAdapterForProvider(targetProvider);
 
    if (!sourceAdapter || !targetAdapter) {
      throw new Error(
        `Migration requires both source (${sourceProvider}) and target (${targetProvider}) adapters`,
      );
    }
 
    // Phase 1: Extract
    const filter: WorkItemFilter = {}; // Would be configured based on workItemIds
    const exported = await this.migrationPipeline.extract(sourceAdapter, filter);
 
    // Phase 2: Transform
    const transformResult = await this.migrationPipeline.transform(
      exported,
      targetProvider as Provider,
      {
        preserveIds: options.preserveIds ?? true,
        mapUsers: options.mapUsers ?? new Map<string, string>(),
        mapLabels: new Map(),
        handleMissingFields: 'metadata',
        customFieldMapping: {},
      },
    );
 
    if (options.dryRun) {
      return {
        successful: transformResult.items.length,
        failed: transformResult.errors.map((error) => ({ id: 'dry-run', reason: error })),
        mapping: new Map(),
      };
    }
 
    // Phase 3: Load
    const migrationResult = await this.migrationPipeline.load(
      targetAdapter,
      transformResult.items,
      {
        batchSize: 10,
        continueOnError: true,
        dryRun: false,
      },
    );
 
    return migrationResult;
  }
 
  /**
   * Export work items for backup or analysis
   */
  async exportWorkItems(project: string, filter?: WorkItemFilter): Promise<WorkItemExport[]> {
    const provider = this.detectProviderFromProject(project);
    const adapter = this.getAdapterForProvider(provider);
 
    if (!adapter) {
      throw new Error(`Export requires adapter for provider: ${provider}`);
    }
 
    return await this.migrationPipeline.extract(adapter, filter ?? {});
  }
 
  private createAdapterConfig(providerInstance: {
    id: string;
    config: { name?: string };
  }): ProviderConfig {
    // Extract configuration from environment or provider config
    const baseUrl = this.getProviderBaseUrl(providerInstance.id);
    const token = this.getProviderToken(providerInstance.id);
 
    return {
      id: providerInstance.id,
      name: providerInstance.config.name ?? providerInstance.id,
      apiUrl: baseUrl,
      token: token,
      organization: this.getProviderOrganization(providerInstance.id),
      project: this.getProviderProject(providerInstance.id),
      group: this.getProviderGroup(providerInstance.id),
    };
  }
 
  private getProviderBaseUrl(providerId: string): string {
    switch (providerId) {
      case 'github':
        return 'https://api.github.com';
      case 'gitlab':
        return process.env.GITLAB_URL ?? 'https://gitlab.com/api/v4';
      case 'azure':
        return 'https://dev.azure.com';
      default:
        return '';
    }
  }
 
  private getProviderToken(providerId: string): string {
    switch (providerId) {
      case 'github':
        return process.env.GITHUB_TOKEN ?? 'test_token';
      case 'gitlab':
        return process.env.GITLAB_TOKEN ?? 'test_token';
      case 'azure':
        return process.env.AZURE_TOKEN ?? 'test_token';
      default:
        return 'test_token';
    }
  }
 
  private getProviderOrganization(providerId: string): string | undefined {
    switch (providerId) {
      case 'github':
        return process.env.GITHUB_ORG;
      case 'azure':
        return process.env.AZURE_ORG;
      default:
        return undefined;
    }
  }
 
  private getProviderProject(providerId: string): string | undefined {
    switch (providerId) {
      case 'azure':
        return process.env.AZURE_PROJECT;
      default:
        return undefined;
    }
  }
 
  private getProviderGroup(providerId: string): string | undefined {
    switch (providerId) {
      case 'gitlab':
        return process.env.GITLAB_GROUP;
      default:
        return undefined;
    }
  }
 
  private getAdapterForProvider(provider: string): IProviderAdapter | null {
    // Try exact match first
    if (this.adapters.has(provider)) {
      const adapter = this.adapters.get(provider);
      Eif (adapter) return adapter;
    }
 
    // Try to find adapter by provider type
    for (const [key, adapter] of this.adapters) {
      Iif (key.startsWith(provider + ':') || key === provider) {
        return adapter;
      }
    }
 
    return null;
  }
}