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 | 5x 5x | import { IProviderAdapter, ProviderConfig } from './IProviderAdapter.js'; import { WorkItem, CreateWorkItemData, UpdateWorkItemData, WorkItemFilter, WorkItemExport, WorkItemImport, MigrationResult, ProviderCapabilities, LinkType, } from '../types/index.js'; /** * Base adapter implementation with common functionality * Provides default implementations and utility methods for concrete adapters */ export abstract class BaseAdapter implements IProviderAdapter { protected config!: ProviderConfig; protected initialized = false; abstract initialize(config: ProviderConfig): Promise<void>; abstract validateConnection(): Promise<boolean>; abstract getWorkItem(id: string): Promise<WorkItem>; abstract listWorkItems(filter: WorkItemFilter): Promise<WorkItem[]>; abstract createWorkItem(data: CreateWorkItemData): Promise<WorkItem>; abstract updateWorkItem(id: string, updates: UpdateWorkItemData): Promise<WorkItem>; abstract deleteWorkItem(id: string): Promise<void>; abstract search(query: string): Promise<WorkItem[]>; abstract executeQuery(query: string): Promise<WorkItem[]>; abstract getCapabilities(): ProviderCapabilities; // Default implementations for optional features async linkWorkItems(_parent: string, _child: string, _linkType: LinkType): Promise<void> { await Promise.resolve(); throw new Error(`Link management not supported by ${this.config.id}`); } async unlinkWorkItems(_parent: string, _child: string): Promise<void> { await Promise.resolve(); throw new Error(`Link management not supported by ${this.config.id}`); } async bulkCreate(items: CreateWorkItemData[]): Promise<WorkItem[]> { // Default implementation: sequential creation const results: WorkItem[] = []; for (const item of items) { try { const created = await this.createWorkItem(item); results.push(created); } catch (error) { console.error(`Failed to create work item: ${item.title}`, error); throw error; } } return results; } async bulkUpdate(updates: Map<string, UpdateWorkItemData>): Promise<WorkItem[]> { // Default implementation: sequential updates const results: WorkItem[] = []; for (const [id, updateData] of updates) { try { const updated = await this.updateWorkItem(id, updateData); results.push(updated); } catch (error) { console.error(`Failed to update work item: ${id}`, error); throw error; } } return results; } async exportWorkItems(ids: string[]): Promise<WorkItemExport[]> { const exports: WorkItemExport[] = []; for (const id of ids) { try { const workItem = await this.getWorkItem(id); const exported: WorkItemExport = { id: workItem.id, provider: workItem.provider, type: workItem.type, title: workItem.title, description: workItem.description, state: workItem.state, assignees: workItem.assignees, labels: workItem.labels, milestone: workItem.milestone, iteration: workItem.iteration, priority: workItem.priority, createdAt: workItem.createdAt, updatedAt: workItem.updatedAt, providerFields: workItem.providerFields, relationships: { parent: workItem.parent?.id, children: workItem.children?.map((c) => c.id) ?? [], blocks: workItem.blocks?.map((b) => b.id) ?? [], blockedBy: workItem.blockedBy?.map((b) => b.id) ?? [], relatedTo: workItem.relatedTo?.map((r) => r.id) ?? [], }, }; exports.push(exported); } catch (error) { console.error(`Failed to export work item: ${id}`, error); } } return exports; } async importWorkItems(imports: WorkItemImport[]): Promise<MigrationResult> { const result: MigrationResult = { successful: 0, failed: [], mapping: new Map(), }; for (const importItem of imports) { try { const created = await this.createWorkItem({ type: importItem.type, title: importItem.title, description: importItem.description, assignees: importItem.assignees, labels: importItem.labels, priority: importItem.priority, customFields: importItem.customFields, }); result.successful++; result.mapping.set(importItem.title, created.id); // Use title as temporary key } catch (error) { result.failed.push({ id: importItem.title, reason: error instanceof Error ? error.message : String(error), }); } } return result; } // Utility methods for concrete adapters /** * Check if adapter has been initialized */ protected ensureInitialized(): void { if (!this.initialized) { throw new Error(`Adapter ${this.config.id || 'unknown'} not initialized`); } } /** * Create HTTP headers with authentication */ protected createAuthHeaders(): Record<string, string> { return { Authorization: `Bearer ${this.config.token}`, 'Content-Type': 'application/json', 'User-Agent': 'Project-Nexus-MCP/1.0', }; } /** * Handle common HTTP errors */ protected handleHttpError(response: Response, context: string): never { if (response.status === 401) { throw new Error(`Authentication failed for ${this.config.id}: Invalid token`); } else if (response.status === 403) { throw new Error(`Access denied for ${this.config.id}: Insufficient permissions`); } else if (response.status === 404) { throw new Error(`Resource not found in ${context}`); } else if (response.status >= 500) { throw new Error(`Server error (${response.status}) in ${context}`); } else { throw new Error(`HTTP ${response.status} error in ${context}: ${response.statusText}`); } } /** * Retry logic with exponential backoff */ protected async withRetry<T>( operation: () => Promise<T>, maxAttempts: number = 3, baseDelay: number = 1000, ): Promise<T> { let lastError: Error | null = null; for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await operation(); } catch (error) { lastError = error instanceof Error ? error : new Error(String(error)); if (attempt === maxAttempts) { break; } // Don't retry auth errors if ( lastError.message.includes('Authentication failed') || lastError.message.includes('Access denied') ) { break; } // Exponential backoff const delay = baseDelay * Math.pow(2, attempt - 1); await new Promise((resolve) => setTimeout(resolve, delay)); } } throw lastError ?? new Error('Operation failed after retries'); } /** * Validate required fields for work item creation */ protected validateCreateData(data: CreateWorkItemData): void { if (!data.title.trim()) { throw new Error('Title is required'); } } /** * Sanitize and validate work item data */ protected sanitizeWorkItem(item: Partial<WorkItem>): Partial<WorkItem> { return { ...item, title: item.title?.trim(), description: item.description?.trim() ?? '', labels: Array.isArray(item.labels) ? [...new Set(item.labels)] : [], }; } } /** * Provider capabilities detection utility */ export class CapabilityDetector { private constructor() { // Utility class - prevent instantiation } /** * Detect GitLab capabilities based on license/version */ static detectGitLabCapabilities(_version?: string, license?: string): ProviderCapabilities { const isPremium = license?.includes('Premium') ?? license?.includes('Ultimate') ?? false; return { supportsEpics: isPremium, supportsIterations: isPremium, supportsMilestones: true, supportsMultipleAssignees: isPremium, supportsConfidential: true, supportsWeight: true, supportsTimeTracking: true, supportsCustomFields: false, maxAssignees: isPremium ? 100 : 1, hierarchyLevels: isPremium ? 3 : 2, customWorkItemTypes: ['issue', 'task', 'incident', 'test_case'], }; } /** * Detect GitHub capabilities */ static detectGitHubCapabilities(): ProviderCapabilities { return { supportsEpics: false, // Can simulate with parent issues supportsIterations: false, // Can use milestones supportsMilestones: true, supportsMultipleAssignees: true, supportsConfidential: false, supportsWeight: false, supportsTimeTracking: false, supportsCustomFields: true, // Through Projects Beta maxAssignees: 10, hierarchyLevels: 2, customWorkItemTypes: ['issue'], }; } /** * Detect Azure DevOps capabilities based on process template */ static detectAzureCapabilities( process: 'agile' | 'scrum' | 'basic' = 'agile', ): ProviderCapabilities { const workItemTypes = { agile: ['Epic', 'Feature', 'User Story', 'Task', 'Bug', 'Test Case'], scrum: ['Epic', 'Feature', 'Product Backlog Item', 'Task', 'Bug', 'Test Case'], basic: ['Epic', 'Issue', 'Task'], }; return { supportsEpics: true, supportsIterations: true, supportsMilestones: false, // Use iterations instead supportsMultipleAssignees: false, supportsConfidential: false, // Use Area Path security supportsWeight: false, supportsTimeTracking: true, supportsCustomFields: true, maxAssignees: 1, hierarchyLevels: process === 'basic' ? 3 : 4, customWorkItemTypes: workItemTypes[process], }; } } |