All files / src/store openApiStore.ts

86.3% Statements 334/387
73.97% Branches 54/73
92.85% Functions 13/14
86.3% Lines 334/387

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 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 5691x 1x 1x                                                                                                                                                                                           1x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x   2x       2x 14x 14x 14x 14x   2x 27x 27x     27x 6x 6x   6x 18x 18x 18x 6x 18x   12x 12x 18x 18x 6x   6x 6x 6x 6x 6x 6x     12x 12x 12x 12x 27x   2x 30x 30x                                                   30x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x     15x 15x 15x 15x 15x 15x 15x 15x 15x   15x 30x 30x 30x 30x   2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 14x 14x 15x 15x 15x 2x 2x 15x 15x     15x 15x 15x 15x 15x 15x 15x 15x 5x 5x 15x 15x 15x 15x 15x 15x 15x 15x   15x 15x   2x 15x 14x 14x 1x 1x 2x 1x 1x 15x   2x   6x 6x   6x 6x 2x 2x 2x 2x 2x 2x   6x 1x 1x 1x                 1x 1x   6x 2x 2x 2x 2x 2x   6x 1x 1x 1x 1x 1x   6x   6x   6x 6x 6x   2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 15x     15x 5x 6x 6x 5x 5x     15x     15x 15x                         15x     15x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15x     15x 9x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 9x 9x     15x                     15x     15x 15x 15x 15x 15x 15x     15x 15x         15x     15x 15x     15x 15x     15x     15x 15x 15x     15x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   15x     15x 15x   2x 10x 11x   11x 11x 11x   11x 11x 11x 11x     11x 5x 5x     11x 1x 1x     11x 5x 5x   11x 11x 10x   10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x   2x 2x 2x 2x 2x 2x 2x 2x   2x 1x 1x     1x 1x 1x     1x 1x 1x 1x     1x 1x 1x 1x 1x   2x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 2x   1x
import fs from 'fs';
import path from 'path';
import { stringify } from 'yaml';
import type {
  OpenAPI,
  OpenAPIV3_1
} from 'openapi-types';
 
interface SecurityInfo {
  type: 'apiKey' | 'oauth2' | 'http' | 'openIdConnect';
  scheme?: 'bearer' | 'basic' | 'digest';
  name?: string;
  in?: 'header' | 'query' | 'cookie';
  flows?: {
    implicit?: {
      authorizationUrl: string;
      scopes: Record<string, string>;
    };
    authorizationCode?: {
      authorizationUrl: string;
      tokenUrl: string;
      scopes: Record<string, string>;
    };
    clientCredentials?: {
      tokenUrl: string;
      scopes: Record<string, string>;
    };
    password?: {
      tokenUrl: string;
      scopes: Record<string, string>;
    };
  };
  openIdConnectUrl?: string;
}
 
interface RequestInfo {
  query: Record<string, string>;
  body: any;
  contentType: string;
  headers?: Record<string, string>;
  security?: SecurityInfo[];
}
 
interface ResponseInfo {
  status: number;
  body: any;
  contentType: string;
  headers?: Record<string, string>;
}
 
interface EndpointInfo {
  path: string;
  method: string;
  responses: {
    [key: number]: OpenAPIV3_1.ResponseObject;
  };
  parameters: OpenAPIV3_1.ParameterObject[];
  requestBody?: OpenAPIV3_1.RequestBodyObject;
  security?: OpenAPIV3_1.SecurityRequirementObject[];
}
 
interface HAREntry {
  startedDateTime: string;
  time: number;
  request: {
    method: string;
    url: string;
    httpVersion: string;
    headers: Array<{ name: string; value: string }>;
    queryString: Array<{ name: string; value: string }>;
    postData?: {
      mimeType: string;
      text: string;
    };
  };
  response: {
    status: number;
    statusText: string;
    httpVersion: string;
    headers: Array<{ name: string; value: string }>;
    content: {
      size: number;
      mimeType: string;
      text: string;
    };
  };
}
 
type PathItemObject = {
  [method: string]: OpenAPIV3_1.OperationObject;
};
 
type PathsObject = {
  [path: string]: PathItemObject;
};
 
class OpenAPIStore {
  private endpoints: Map<string, EndpointInfo>;
  private harEntries: HAREntry[];
  private targetUrl: string;
  private examples: Map<any, any[]>;
  private schemaCache: Map<string, OpenAPIV3_1.SchemaObject[]>;
  private securitySchemes: Map<string, OpenAPIV3_1.SecuritySchemeObject>;
 
  constructor(targetUrl: string = 'http://localhost:8080') {
    this.endpoints = new Map();
    this.harEntries = [];
    this.targetUrl = targetUrl;
    this.examples = new Map();
    this.schemaCache = new Map();
    this.securitySchemes = new Map();
  }
 
  public setTargetUrl(url: string): void {
    this.targetUrl = url;
  }
 
  public clear(): void {
    this.endpoints.clear();
    this.harEntries = [];
    this.examples.clear();
  }
 
  private deepMergeSchemas(schemas: OpenAPIV3_1.SchemaObject[]): OpenAPIV3_1.SchemaObject {
    if (schemas.length === 0) return { type: 'object' };
    if (schemas.length === 1) return schemas[0];
 
    // If all schemas are objects, merge their properties
    if (schemas.every(s => s.type === 'object')) {
      const mergedProperties: Record<string, OpenAPIV3_1.SchemaObject> = {};
      const mergedRequired: string[] = [];
 
      schemas.forEach(schema => {
        if (schema.properties) {
          Object.entries(schema.properties).forEach(([key, value]) => {
            if (!mergedProperties[key]) {
              mergedProperties[key] = value;
            } else {
              // If property exists, merge its schemas
              mergedProperties[key] = this.deepMergeSchemas([mergedProperties[key], value]);
            }
          });
        }
      });
 
      return {
        type: 'object',
        properties: mergedProperties,
        example: schemas[0].example // Keep the first example
      };
    }
 
    // If schemas are different types, use oneOf
    return {
      type: 'object',
      oneOf: schemas
    };
  }
 
  private generateJsonSchema(obj: any): OpenAPIV3_1.SchemaObject {
    if (obj === null) return { type: 'null' };
    if (Array.isArray(obj)) {
      if (obj.length === 0) return { type: 'array', items: { type: 'object' } };
      
      // Generate schemas for all items
      const itemSchemas = obj.map(item => this.generateJsonSchema(item));
      
      // If all items have the same schema, use that
      if (itemSchemas.every(s => JSON.stringify(s) === JSON.stringify(itemSchemas[0]))) {
        return {
          type: 'array',
          items: itemSchemas[0],
          example: obj
        };
      }
      
      // If items have different schemas, use oneOf
      return {
        type: 'array',
        items: {
          type: 'object',
          oneOf: itemSchemas
        },
        example: obj
      };
    }
    
    if (typeof obj === 'object') {
      const properties: Record<string, OpenAPIV3_1.SchemaObject> = {};
      for (const [key, value] of Object.entries(obj)) {
        properties[key] = this.generateJsonSchema(value);
      }
      return {
        type: 'object',
        properties,
        example: obj
      };
    }
    
    // Map JavaScript types to OpenAPI types
    const typeMap: Record<string, OpenAPIV3_1.NonArraySchemaObjectType> = {
      'string': 'string',
      'number': 'number',
      'boolean': 'boolean',
      'bigint': 'integer',
      'symbol': 'string',
      'undefined': 'string',
      'function': 'string'
    };
    
    return { 
      type: typeMap[typeof obj] || 'string',
      example: obj
    };
  }
 
  private recordHAREntry(
    path: string,
    method: string,
    request: RequestInfo,
    response: ResponseInfo
  ): void {
    const now = new Date();
    const entry: HAREntry = {
      startedDateTime: now.toISOString(),
      time: 0,
      request: {
        method: method.toUpperCase(),
        url: `http://localhost:3000${path}${this.buildQueryString(request.query)}`,
        httpVersion: 'HTTP/1.1',
        headers: Object.entries(request.headers || {})
          .map(([name, value]) => ({ 
            name: name.toLowerCase(), // Normalize header names
            value: String(value) // Ensure value is a string
          })),
        queryString: Object.entries(request.query || {})
          .map(([name, value]) => ({ 
            name, 
            value: String(value) // Ensure value is a string
          })),
        postData: request.body ? {
          mimeType: request.contentType,
          text: JSON.stringify(request.body)
        } : undefined
      },
      response: {
        status: response.status,
        statusText: response.status === 200 ? 'OK' : 'Error',
        httpVersion: 'HTTP/1.1',
        headers: Object.entries(response.headers || {})
          .map(([name, value]) => ({ 
            name: name.toLowerCase(), // Normalize header names
            value: String(value) // Ensure value is a string
          })),
        content: {
          size: response.body ? JSON.stringify(response.body).length : 0,
          mimeType: response.contentType || 'application/json',
          text: response.body ? JSON.stringify(response.body) : ''
        }
      }
    };
 
    this.harEntries.push(entry);
  }
 
  private buildQueryString(query: Record<string, string>): string {
    if (!query || Object.keys(query).length === 0) {
      return '';
    }
    const params = new URLSearchParams();
    Object.entries(query).forEach(([key, value]) => {
      params.append(key, value);
    });
    return `?${params.toString()}`;
  }
 
  private addSecurityScheme(security: SecurityInfo): string {
    // Use a consistent name based on the type with an underscore suffix
    const schemeName = `${security.type}_`;
    let scheme: OpenAPIV3_1.SecuritySchemeObject;
 
    switch (security.type) {
      case 'apiKey':
        scheme = {
          type: 'apiKey',
          name: security.name || 'X-API-Key',
          in: security.in || 'header'
        };
        break;
 
      case 'oauth2':
        scheme = {
          type: 'oauth2',
          flows: security.flows || {
            implicit: {
              authorizationUrl: 'https://example.com/oauth/authorize',
              scopes: {
                'read': 'Read access',
                'write': 'Write access'
              }
            }
          }
        };
        break;
 
      case 'http':
        scheme = {
          type: 'http',
          scheme: security.scheme || 'bearer'
        };
        break;
 
      case 'openIdConnect':
        scheme = {
          type: 'openIdConnect',
          openIdConnectUrl: security.openIdConnectUrl || 'https://example.com/.well-known/openid-configuration'
        };
        break;
 
      default:
        throw new Error(`Unsupported security type: ${security.type}`);
    }
 
    this.securitySchemes.set(schemeName, scheme);
    return schemeName;
  }
 
  public recordEndpoint(
    path: string,
    method: string,
    request: RequestInfo,
    response: ResponseInfo
  ): void {
    const key = `${method}:${path}`;
    const endpoint: EndpointInfo = this.endpoints.get(key) || {
      path,
      method,
      responses: {},
      parameters: [],
      requestBody: method.toLowerCase() === 'get' ? undefined : {
        required: false,
        content: {}
      }
    };
 
    // Add security schemes if present
    if (request.security) {
      endpoint.security = request.security.map(security => {
        const schemeName = this.addSecurityScheme(security);
        return { [schemeName]: ['read'] }; // Add default scope
      });
    }
 
    // Convert path parameters to OpenAPI format
    const openApiPath = path.replace(/:(\w+)/g, '{$1}');
 
    // Add path parameters
    const pathParams = path.match(/:(\w+)/g) || [];
    pathParams.forEach(param => {
      const paramName = param.slice(1);
      if (!endpoint.parameters.some(p => p.name === paramName)) {
        endpoint.parameters.push({
          name: paramName,
          in: 'path',
          required: true,
          schema: {
            type: 'string',
            example: paramName // Use the parameter name as an example
          }
        });
      }
    });
 
    // Add query parameters and headers
    Object.entries(request.query).forEach(([key, value]) => {
      if (!endpoint.parameters.some(p => p.name === key)) {
        endpoint.parameters.push({
          name: key,
          in: 'query',
          required: false,
          schema: {
            type: 'string',
            example: value
          }
        });
      }
    });
 
    // Add request headers as parameters
    if (request.headers) {
      Object.entries(request.headers).forEach(([name, value]) => {
        if (!endpoint.parameters.some(p => p.name === name)) {
          endpoint.parameters.push({
            name: name,
            in: 'header',
            required: false,
            schema: {
              type: 'string',
              example: value
            }
          });
        }
      });
    }
 
    // Add request body schema if present and not a GET request
    if (request.body && method.toLowerCase() !== 'get') {
      const contentType = request.contentType || 'application/json';
      if (endpoint.requestBody && !endpoint.requestBody.content[contentType]) {
        const schema = this.generateJsonSchema(request.body);
        endpoint.requestBody.content[contentType] = {
          schema
        };
      }
    }
 
    // Add response schema
    const responseContentType = response.contentType || 'application/json';
    
    // Initialize response object if it doesn't exist
    if (!endpoint.responses[response.status]) {
      endpoint.responses[response.status] = {
        description: `Response for ${method.toUpperCase()} ${path}`,
        content: {}
      };
    }
 
    // Ensure content object exists
    const responseObj = endpoint.responses[response.status];
    if (!responseObj.content) {
      responseObj.content = {};
    }
 
    // Generate schema for the current response
    const currentSchema = this.generateJsonSchema(response.body);
    
    // Get existing schemas for this endpoint and status code
    const schemaKey = `${key}:${response.status}:${responseContentType}`;
    const existingSchemas = this.schemaCache.get(schemaKey) || [];
    
    // Add the current schema to the cache
    existingSchemas.push(currentSchema);
    this.schemaCache.set(schemaKey, existingSchemas);
    
    // Merge all schemas for this endpoint and status code
    const mergedSchema = this.deepMergeSchemas(existingSchemas);
 
    // Update the content with the merged schema
    responseObj.content[responseContentType] = {
      schema: mergedSchema
    };
 
    // Add response headers
    if (response.headers && Object.keys(response.headers).length > 0) {
      endpoint.responses[response.status].headers = Object.entries(response.headers).reduce((acc, [name, value]) => {
        acc[name] = {
          schema: {
            type: 'string',
            example: value
          },
          description: `Response header ${name}`
        };
        return acc;
      }, {} as NonNullable<OpenAPIV3_1.ResponseObject['headers']>);
    }
 
    this.endpoints.set(key, endpoint);
 
    // Record in HAR
    this.recordHAREntry(path, method, request, response);
  }
 
  public getOpenAPISpec(): OpenAPIV3_1.Document {
    const paths = Array.from(this.endpoints.entries()).reduce<Required<PathsObject>>((acc, [key, info]) => {
      const [method, path] = key.split(':');
      
      if (!acc[path]) {
        acc[path] = {} as Required<PathItemObject>;
      }
      
      const operation: OpenAPIV3_1.OperationObject = {
        summary: `${method.toUpperCase()} ${path}`,
        responses: info.responses,
      };
 
      // Only include parameters if there are any
      if (info.parameters.length > 0) {
        operation.parameters = info.parameters;
      }
 
      // Only include requestBody if it exists
      if (info.requestBody) {
        operation.requestBody = info.requestBody;
      }
 
      // Add security if it exists
      if (info.security) {
        operation.security = info.security;
      }
 
      acc[path][method] = operation;
      return acc;
    }, {});
 
    const spec: OpenAPIV3_1.Document = {
      openapi: '3.1.0',
      info: {
        title: 'Generated API Documentation',
        version: '1.0.0',
        description: 'Automatically generated API documentation from proxy traffic',
      },
      servers: [{
        url: this.targetUrl,
      }],
      paths,
      components: {
        securitySchemes: Object.fromEntries(this.securitySchemes)
      }
    };
 
    return spec;
  }
 
  public getOpenAPISpecAsYAML(): string {
    const spec = this.getOpenAPISpec();
    return stringify(spec, {
      indent: 2,
      simpleKeys: true,
      strict: true
    });
  }
 
  public saveOpenAPISpec(outputDir: string): void {
    const spec = this.getOpenAPISpec();
    const yamlSpec = this.getOpenAPISpecAsYAML();
 
    // Ensure output directory exists
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }
 
    // Save JSON spec
    fs.writeFileSync(
      path.join(outputDir, 'openapi.json'),
      JSON.stringify(spec, null, 2)
    );
 
    // Save YAML spec
    fs.writeFileSync(
      path.join(outputDir, 'openapi.yaml'),
      yamlSpec
    );
  }
 
  public generateHAR(): any {
    return {
      log: {
        version: '1.2',
        creator: {
          name: 'Arbiter',
          version: '1.0.0',
        },
        entries: this.harEntries,
      },
    };
  }
}
 
export const openApiStore = new OpenAPIStore();