All files / src/lib/api-docs openapi-import.ts

87.04% Statements 450/517
77.66% Branches 80/103
90% Functions 9/10
87.04% Lines 450/517

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 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 5181x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                     1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 3x 10x   10x 1x 10x 1x 10x 5x 10x 10x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 5x 5x 5x 5x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 8x 8x 8x 1x 1x 1x 1x 1x 8x 8x 8x 4x 4x 4x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x 2x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 9x 9x 9x 9x 9x 11x 11x 11x 11x 11x 11x 11x 11x 11x 12x 12x     12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 11x 11x 11x 11x 11x 11x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 11x 9x 9x 9x 9x 9x 9x 11x 11x 11x 9x 9x 11x 11x 12x 11x 11x 12x 1x 1x 12x 11x 9x 9x 9x 9x 9x 9x 11x 1x 1x 1x 11x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 10x 10x 10x 10x 10x 5x 5x 10x 10x 10x 10x 10x 5x 1x 1x 5x 4x 4x 4x 4x 4x 4x 5x 5x 5x 10x 5x 5x 5x 10x 5x 5x 5x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 6x 6x 1x 1x 6x 6x 3x 3x 6x 6x 6x 4x     4x 4x 4x     4x 4x 1x 1x 4x 4x 4x 1x 1x 4x 4x     4x 4x 6x 6x 6x 6x 6x  
/**
 * OpenAPI Import Utility
 *
 * Converts OpenAPI 3.x specifications to the internal API registry format.
 * Supports importing from Swagger/OpenAPI JSON and YAML files.
 */
 
import {
  ApiRegistry,
  ApiCategory,
  ApiEndpoint,
  ApiParameter,
  ApiBodyField,
  ApiRequestBody,
  ApiResponseSchema,
  HttpMethod,
  OpenAPISpec } from '@/types/api-docs';
 
interface OpenAPIImportResult {
  success: boolean;
  registry: ApiRegistry | null;
  errors: string[];
  warnings: string[];
}
 
/**
 * Parse YAML string to JSON
 * Simple implementation without external dependencies
 */
function parseYaml(yaml: string): unknown {
  // Basic YAML to JSON conversion
  // For full YAML support, consider using js-yaml library
  try {
    // Try parsing as JSON first (some "YAML" files are actually JSON)
    return JSON.parse(yaml);
  } catch {
    // Basic YAML parsing for common patterns
    const lines = yaml.split('\n');
    const result: Record<string, unknown> = {};
    const stack: Array<{ obj: Record<string, unknown>; indent: number }> = [
      { obj: result, indent: -1 },
    ];

    for (const line of lines) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith('#')) continue;

      const indent = line.search(/\S/);
      const match = trimmed.match(/^([^:]+):\s*(.*)$/);

      if (match) {
        const [, key, value] = match;

        // Pop stack to find correct parent
        while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
          stack.pop();
        }

        const parent = stack[stack.length - 1].obj;

        if (value && value !== '|' && value !== '>') {
          // Simple value
          let parsedValue: unknown = value;
          if (value === 'true') parsedValue = true;
          else if (value === 'false') parsedValue = false;
          else if (value === 'null') parsedValue = null;
          else if (/^-?\d+$/.test(value)) parsedValue = parseInt(value);
          else if (/^-?\d+\.\d+$/.test(value)) parsedValue = parseFloat(value);
          else if (value.startsWith('"') && value.endsWith('"')) {
            parsedValue = value.slice(1, -1);
          } else if (value.startsWith("'") && value.endsWith("'")) {
            parsedValue = value.slice(1, -1);
          }

          parent[key.trim()] = parsedValue;
        } else {
          // Nested object
          const newObj: Record<string, unknown> = {};
          parent[key.trim()] = newObj;
          stack.push({ obj: newObj, indent });
        }
      }
    }

    return result;
  }
}
 
/**
 * Convert OpenAPI type to internal type
 */
function convertType(
  schema: { type?: string; items?: unknown; format?: string } | undefined
): 'string' | 'number' | 'boolean' | 'object' | 'array' {
  if (!schema || !schema.type) return 'string';
 
  switch (schema.type) {
    case 'integer':
    case 'number':
      return 'number';
    case 'boolean':
      return 'boolean';
    case 'array':
      return 'array';
    case 'object':
      return 'object';
    default:
      return 'string';
  }
}
 
/**
 * Convert OpenAPI parameter to internal parameter
 */
function convertParameter(param: {
  name: string;
  in: string;
  required?: boolean;
  description?: string;
  schema?: { type?: string; enum?: string[]; example?: unknown };
}): ApiParameter {
  return {
    name: param.name,
    type: convertType(param.schema),
    required: param.required || false,
    description: param.description || '',
    example: param.schema?.example as string | number | boolean | undefined,
    enum: param.schema?.enum,
    location: param.in as 'path' | 'query' | 'header'};
}
 
/**
 * Convert OpenAPI schema properties to body fields
 */
function convertSchemaToFields(
  schema: {
    type?: string;
    properties?: Record<string, unknown>;
    required?: string[];
    items?: unknown;
  } | undefined
): ApiBodyField[] {
  if (!schema?.properties) return [];
 
  const required = schema.required || [];
  const fields: ApiBodyField[] = [];
 
  for (const [name, propSchema] of Object.entries(schema.properties)) {
    const prop = propSchema as {
      type?: string;
      description?: string;
      example?: unknown;
      enum?: string[];
      properties?: Record<string, unknown>;
      items?: unknown;
      required?: string[];
    };
 
    const field: ApiBodyField = {
      name,
      type: convertType(prop),
      required: required.includes(name),
      description: prop.description || '',
      example: prop.example,
      enum: prop.enum};
 
    // Handle nested objects
    if (prop.type === 'object' && prop.properties) {
      field.nested = convertSchemaToFields(prop);
    }
 
    // Handle array items
    if (prop.type === 'array' && prop.items) {
      const items = prop.items as { type?: string; properties?: Record<string, unknown> };
      if (items.properties) {
        field.nested = convertSchemaToFields(items);
      }
    }
 
    fields.push(field);
  }
 
  return fields;
}
 
/**
 * Convert OpenAPI request body to internal request body
 */
function convertRequestBody(
  requestBody: {
    required?: boolean;
    description?: string;
    content?: Record<
      string,
      { schema?: unknown; example?: unknown }
    >;
  } | undefined
): ApiRequestBody | undefined {
  if (!requestBody?.content) return undefined;
 
  const contentTypes = Object.keys(requestBody.content);
  const contentType = contentTypes.includes('application/json')
    ? 'application/json'
    : contentTypes[0];
 
  const mediaType = requestBody.content[contentType];
  const schema = mediaType?.schema as {
    type?: string;
    properties?: Record<string, unknown>;
    required?: string[];
  } | undefined;
 
  return {
    contentType: contentType as 'application/json' | 'multipart/form-data',
    description: requestBody.description,
    fields: convertSchemaToFields(schema),
    example: mediaType?.example as Record<string, unknown> | undefined};
}
 
/**
 * Convert OpenAPI responses to internal response schemas
 */
function convertResponses(
  responses: Record<
    string,
    {
      description?: string;
      content?: Record<string, { schema?: unknown; example?: unknown }>;
    }
  > | undefined
): ApiResponseSchema[] {
  if (!responses) return [];
 
  const result: ApiResponseSchema[] = [];
 
  for (const [statusCode, response] of Object.entries(responses)) {
    const status = parseInt(statusCode);
    if (isNaN(status)) continue;
 
    const schema: ApiResponseSchema = {
      status,
      description: response.description || ''};
 
    // Get content
    if (response.content) {
      const contentType = Object.keys(response.content)[0];
      const mediaType = response.content[contentType];
 
      schema.contentType = contentType;
      schema.example = mediaType?.example;
 
      const schemaObj = mediaType?.schema as {
        type?: string;
        properties?: Record<string, unknown>;
        required?: string[];
      } | undefined;
      schema.fields = convertSchemaToFields(schemaObj);
    }
 
    result.push(schema);
  }
 
  // Sort by status code
  result.sort((a, b) => a.status - b.status);
 
  return result;
}
 
/**
 * Generate a unique ID for an endpoint
 */
function generateEndpointId(method: string, path: string): string {
  const cleanPath = path
    .replace(/[{}]/g, '')
    .replace(/\//g, '-')
    .replace(/^-|-$/g, '')
    .toLowerCase();
 
  return `${method.toLowerCase()}-${cleanPath}`;
}
 
/**
 * Import an OpenAPI specification
 */
export function importOpenAPI(
  specContent: string,
  format: 'json' | 'yaml' = 'json'
): OpenAPIImportResult {
  const errors: string[] = [];
  const warnings: string[] = [];
 
  try {
    // Parse the specification
    const spec = (
      format === 'yaml' ? parseYaml(specContent) : JSON.parse(specContent)
    ) as OpenAPISpec;
 
    // Validate OpenAPI version
    if (!spec.openapi?.startsWith('3.')) {
      errors.push(`Unsupported OpenAPI version: ${spec.openapi}. Only 3.x is supported.`);
      return { success: false, registry: null, errors, warnings };
    }
 
    // Create registry
    const registry: ApiRegistry = {
      version: spec.info.version,
      title: spec.info.title,
      description: spec.info.description || '',
      baseUrl: spec.servers?.[0]?.url || '',
      categories: []};
 
    // Group endpoints by tag
    const categoryMap = new Map<string, ApiCategory>();
 
    for (const [path, pathItem] of Object.entries(spec.paths || {})) {
      for (const [method, operation] of Object.entries(pathItem)) {
        // Skip non-HTTP methods
        if (!['get', 'post', 'put', 'patch', 'delete'].includes(method)) {
          continue;
        }
 
        const op = operation as {
          summary?: string;
          description?: string;
          operationId?: string;
          tags?: string[];
          parameters?: Array<{
            name: string;
            in: string;
            required?: boolean;
            description?: string;
            schema?: { type?: string; enum?: string[]; example?: unknown };
          }>;
          requestBody?: {
            required?: boolean;
            description?: string;
            content?: Record<string, { schema?: unknown; example?: unknown }>;
          };
          responses?: Record<
            string,
            {
              description?: string;
              content?: Record<string, { schema?: unknown; example?: unknown }>;
            }
          >;
          security?: Array<Record<string, string[]>>;
        };
 
        const tags = op.tags || ['default'];
        const primaryTag = tags[0];
 
        // Create or get category
        if (!categoryMap.has(primaryTag)) {
          categoryMap.set(primaryTag, {
            id: primaryTag.toLowerCase().replace(/\s+/g, '-'),
            name: primaryTag,
            description: `${primaryTag} endpoints`,
            endpoints: []});
        }
 
        const category = categoryMap.get(primaryTag)!;
 
        // Create endpoint
        const endpoint: ApiEndpoint = {
          id: op.operationId || generateEndpointId(method, path),
          method: method.toUpperCase() as HttpMethod,
          path: path.replace(/{(\w+)}/g, '{$1}'), // Ensure consistent parameter format
          summary: op.summary || `${method.toUpperCase()} ${path}`,
          description: op.description,
          category: primaryTag,
          tags: tags.slice(1),
          parameters: op.parameters?.map(convertParameter),
          requestBody: convertRequestBody(op.requestBody),
          responses: convertResponses(op.responses),
          requiresAuth: !!op.security && op.security.length > 0,
          adminOnly: tags.some(t =>
            t.toLowerCase().includes('admin') || t.toLowerCase().includes('management')
          )};
 
        category.endpoints.push(endpoint);
      }
    }
 
    // Convert map to array and sort
    registry.categories = Array.from(categoryMap.values());
    registry.categories.sort((a, b) => a.name.localeCompare(b.name));
 
    // Sort endpoints within each category
    for (const category of registry.categories) {
      category.endpoints.sort((a, b) => a.path.localeCompare(b.path));
    }
 
    // Add warnings for missing data
    for (const category of registry.categories) {
      for (const endpoint of category.endpoints) {
        if (!endpoint.description) {
          warnings.push(`Endpoint ${endpoint.id} has no description`);
        }
        if (endpoint.responses.length === 0) {
          warnings.push(`Endpoint ${endpoint.id} has no response definitions`);
        }
      }
    }
 
    return {
      success: true,
      registry,
      errors,
      warnings};
  } catch (error) {
    errors.push(`Failed to parse specification: ${error instanceof Error ? error.message : 'Unknown error'}`);
    return { success: false, registry: null, errors, warnings };
  }
}
 
/**
 * Merge imported registry with existing registry
 */
export function mergeRegistries(
  existing: ApiRegistry,
  imported: ApiRegistry,
  options: {
    overwriteExisting?: boolean;
    preserveCustomFields?: boolean;
  } = {}
): ApiRegistry {
  const { overwriteExisting = false, preserveCustomFields = true } = options;
 
  const result: ApiRegistry = {
    ...existing,
    categories: [...existing.categories]};
 
  for (const importedCategory of imported.categories) {
    const existingCategory = result.categories.find(
      c => c.id === importedCategory.id
    );
 
    if (existingCategory) {
      // Merge endpoints
      for (const importedEndpoint of importedCategory.endpoints) {
        const existingEndpoint = existingCategory.endpoints.find(
          e => e.id === importedEndpoint.id
        );
 
        if (existingEndpoint) {
          if (overwriteExisting) {
            // Replace entirely
            Object.assign(existingEndpoint, importedEndpoint);
          } else if (preserveCustomFields) {
            // Merge, preferring existing custom fields
            Object.assign(existingEndpoint, {
              ...importedEndpoint,
              description: existingEndpoint.description || importedEndpoint.description,
              tags: existingEndpoint.tags || importedEndpoint.tags});
          }
        } else {
          existingCategory.endpoints.push(importedEndpoint);
        }
      }
    } else {
      result.categories.push(importedCategory);
    }
  }
 
  return result;
}
 
/**
 * Validate an imported registry
 */
export function validateImportedRegistry(
  registry: ApiRegistry
): { valid: boolean; issues: string[] } {
  const issues: string[] = [];
 
  if (!registry.title) {
    issues.push('Registry is missing a title');
  }
 
  if (!registry.version) {
    issues.push('Registry is missing a version');
  }
 
  if (registry.categories.length === 0) {
    issues.push('Registry has no categories');
  }
 
  const endpointIds = new Set<string>();
  for (const category of registry.categories) {
    if (!category.id) {
      issues.push(`Category is missing an ID: ${category.name}`);
    }
 
    for (const endpoint of category.endpoints) {
      if (!endpoint.id) {
        issues.push(`Endpoint is missing an ID in category ${category.name}`);
      }
 
      if (endpointIds.has(endpoint.id)) {
        issues.push(`Duplicate endpoint ID: ${endpoint.id}`);
      }
      endpointIds.add(endpoint.id);
 
      if (!endpoint.path) {
        issues.push(`Endpoint ${endpoint.id} is missing a path`);
      }
 
      if (!endpoint.method) {
        issues.push(`Endpoint ${endpoint.id} is missing a method`);
      }
    }
  }
 
  return {
    valid: issues.length === 0,
    issues};
}