All files / src/services SchemaIntrospector.ts

97.87% Statements 92/94
92.06% Branches 58/63
94.73% Functions 18/19
97.75% Lines 87/89

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  43x 43x                                                                                                                 155x 155x 155x       27x 27x 117x 116x 116x 155x   1x       116x 1x   116x   27x                 43x                                                                               43x   38x     38x       33x 3x     30x 30x   30x 27x     29x 91x     27x     27x   117x                 27x 114x               27x 27x 91x     27x             27x           27x   3x         3x                                   3x         13x 1x   12x       18x 1x     17x 17x 12x       5x 1x   4x 1x   3x 1x     2x       7x 9x       3x 1x   2x       4x 1x     3x   3x 5x 4x                 4x 4x   4x 4x                 3x       4x   4x   8x 4x 4x   4x   4x 2x 2x 2x         4x                     1x       8x       2x      
import { GraphQLClient } from '../graphql/client';
import { gql } from 'graphql-tag';
import { logDebug, logInfo, logWarn } from '../logger';
 
export interface FieldInfo {
  name: string;
  type: {
    name: string | null;
    kind: string;
    ofType?: {
      name: string | null;
      kind: string;
    } | null;
  };
}
 
export interface TypeInfo {
  name: string;
  fields: FieldInfo[] | null;
  enumValues?: Array<{ name: string; description?: string }> | null;
}
 
/** A field of an output type: the named type it resolves to and its argument names. */
export interface IndexedField {
  type: string;
  args: ReadonlySet<string>;
}
 
/**
 * Every type the instance's GraphQL schema declares, with its fields (output
 * types) or input fields (input objects). Types without either (unions, enums,
 * scalars) map to an empty field map so their existence can still be checked.
 */
export type SchemaFieldIndex = ReadonlyMap<string, ReadonlyMap<string, IndexedField>>;
 
export interface SchemaInfo {
  workItemWidgetTypes: string[];
  typeDefinitions: Map<string, TypeInfo>;
  availableFeatures: Set<string>;
  /** Absent when introspection failed; callers then cannot adapt to the schema. */
  fieldIndex?: SchemaFieldIndex;
}
 
interface IntrospectionTypeRef {
  name: string | null;
  kind: string;
  ofType?: IntrospectionTypeRef | null;
}
 
interface IntrospectionType {
  name: string;
  kind: string;
  fields?: Array<FieldInfo & { args?: Array<{ name: string }> }> | null;
  inputFields?: Array<{ name: string }> | null;
  enumValues?: Array<{ name: string; description?: string }> | null;
}
 
/** Named type at the bottom of a NON_NULL/LIST wrapper chain. */
function namedType(ref: IntrospectionTypeRef | null | undefined): string {
  let current = ref;
  while (current && !current.name) current = current.ofType;
  return current?.name ?? '';
}
 
function buildFieldIndex(types: IntrospectionType[]): SchemaFieldIndex {
  const index = new Map<string, Map<string, IndexedField>>();
  for (const type of types) {
    if (!type.name) continue;
    const fields = new Map<string, IndexedField>();
    for (const field of type.fields ?? []) {
      fields.set(field.name, {
        type: namedType(field.type),
        args: new Set((field.args ?? []).map((arg) => arg.name)),
      });
    }
    // Input object fields, so handlers can tell which mutation inputs exist.
    for (const inputField of type.inputFields ?? []) {
      fields.set(inputField.name, { type: '', args: new Set() });
    }
    index.set(type.name, fields);
  }
  return index;
}
 
interface IntrospectionResult {
  __schema: {
    types: IntrospectionType[];
  };
}
 
const INTROSPECTION_QUERY = gql`
  query IntrospectSchema {
    __schema {
      types {
        name
        kind
        fields {
          name
          args {
            name
          }
          type {
            name
            kind
            ofType {
              name
              kind
              ofType {
                name
                kind
                ofType {
                  name
                  kind
                }
              }
            }
          }
        }
        inputFields {
          name
        }
        enumValues {
          name
          description
        }
      }
    }
  }
`;
 
export class SchemaIntrospector {
  private client: GraphQLClient;
  private cachedSchema: SchemaInfo | null = null;
 
  constructor(client: GraphQLClient) {
    this.client = client;
  }
 
  public async introspectSchema(): Promise<SchemaInfo> {
    if (this.cachedSchema) {
      return this.cachedSchema;
    }
 
    try {
      logDebug('Introspecting GitLab GraphQL schema...');
 
      const result = await this.client.request<IntrospectionResult>(INTROSPECTION_QUERY);
      const types = result.__schema.types;
 
      // Extract WorkItem widget types
      const workItemWidgetType = types.find((type) => type.name === 'WorkItemWidgetType');
      const workItemWidgetTypes = workItemWidgetType?.enumValues?.map((value) => value.name) ?? [];
 
      // Build type definitions map
      const typeDefinitions = new Map<string, TypeInfo>();
 
      // Focus on WorkItem-related types
      const relevantTypes = types.filter(
        (type) =>
          type.name &&
          (type.name.startsWith('WorkItem') ||
            type.name.includes('Widget') ||
            type.name === 'AwardEmoji' ||
            type.name === 'Milestone' ||
            type.name === 'User' ||
            type.name === 'Label'),
      );
 
      for (const type of relevantTypes) {
        typeDefinitions.set(type.name, {
          name: type.name,
          fields: type.fields ?? null,
          enumValues: type.enumValues ?? null,
        });
      }
 
      // Determine available features based on widget types
      const availableFeatures = new Set<string>();
      for (const widgetType of workItemWidgetTypes) {
        availableFeatures.add(widgetType);
      }
 
      this.cachedSchema = {
        workItemWidgetTypes,
        typeDefinitions,
        availableFeatures,
        fieldIndex: buildFieldIndex(types),
      };
 
      logInfo('GraphQL schema introspection completed', {
        widgetTypes: workItemWidgetTypes.length,
        typeDefinitions: typeDefinitions.size,
        features: availableFeatures.size,
      });
 
      return this.cachedSchema;
    } catch (error) {
      logWarn('Schema introspection failed, using fallback schema info', {
        err: error as Error,
      });
 
      // Provide fallback schema info when introspection fails
      this.cachedSchema = {
        workItemWidgetTypes: [
          'ASSIGNEES',
          'LABELS',
          'MILESTONE',
          'DESCRIPTION',
          'START_AND_DUE_DATE',
          'WEIGHT',
          'TIME_TRACKING',
          'HEALTH_STATUS',
          'COLOR',
          'NOTIFICATIONS',
          'NOTES',
        ],
        typeDefinitions: new Map(),
        availableFeatures: new Set(['workItems', 'epics', 'issues']),
      };
 
      return this.cachedSchema;
    }
  }
 
  public isWidgetTypeAvailable(widgetType: string): boolean {
    if (!this.cachedSchema) {
      throw new Error('Schema not introspected yet. Call introspectSchema() first.');
    }
    return this.cachedSchema.availableFeatures.has(widgetType);
  }
 
  public getFieldsForType(typeName: string): FieldInfo[] {
    if (!this.cachedSchema) {
      throw new Error('Schema not introspected yet. Call introspectSchema() first.');
    }
 
    const typeInfo = this.cachedSchema.typeDefinitions.get(typeName);
    if (typeInfo?.fields) {
      return typeInfo.fields;
    }
 
    // Fallback field information for common widget types when full schema unavailable
    if (typeName === 'WorkItemWidgetAssignees') {
      return [{ name: 'assignees', type: { name: 'UserConnection', kind: 'OBJECT' } }];
    }
    if (typeName === 'WorkItemWidgetLabels') {
      return [{ name: 'labels', type: { name: 'LabelConnection', kind: 'OBJECT' } }];
    }
    if (typeName === 'WorkItemWidgetMilestone') {
      return [{ name: 'milestone', type: { name: 'Milestone', kind: 'OBJECT' } }];
    }
 
    return [];
  }
 
  public hasField(typeName: string, fieldName: string): boolean {
    const fields = this.getFieldsForType(typeName);
    return fields.some((field) => field.name === fieldName);
  }
 
  public getAvailableWidgetTypes(): string[] {
    if (!this.cachedSchema) {
      throw new Error('Schema not introspected yet. Call introspectSchema() first.');
    }
    return this.cachedSchema.workItemWidgetTypes;
  }
 
  public generateSafeWidgetQuery(requestedWidgets: string[]): string {
    if (!this.cachedSchema) {
      throw new Error('Schema not introspected yet. Call introspectSchema() first.');
    }
 
    const safeWidgets: string[] = [];
 
    for (const widget of requestedWidgets) {
      if (this.isWidgetTypeAvailable(widget)) {
        const widgetTypeName = `WorkItemWidget${
          widget.charAt(0) +
          widget
            .slice(1)
            .toLowerCase()
            .replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase())
        }`;
 
        // Generate safe field selections for this widget
        const fields = this.getFieldsForType(widgetTypeName);
        const safeFields = this.generateSafeFieldSelections(fields);
 
        Eif (safeFields.length > 0) {
          safeWidgets.push(`
            ... on ${widgetTypeName} {
              ${safeFields.join('\n              ')}
            }
          `);
        }
      }
    }
 
    return safeWidgets.join('\n');
  }
 
  private generateSafeFieldSelections(fields: FieldInfo[]): string[] {
    const safeFields: string[] = [];
 
    for (const field of fields) {
      // Skip complex fields that require sub-selections for now
      if (field.type.kind === 'SCALAR' || field.type.kind === 'ENUM') {
        safeFields.push(field.name);
      } else Eif (field.type.kind === 'OBJECT' && field.name !== 'type') {
        // Add basic object fields with simple sub-selections
        Iif (field.name === 'milestone') {
          safeFields.push(`${field.name} { id title state }`);
        } else if (field.name === 'assignees' || field.name === 'participants') {
          safeFields.push(`${field.name} { nodes { id username } }`);
        } else Eif (field.name === 'labels') {
          safeFields.push(`${field.name} { nodes { id title color } }`);
        }
      }
    }
 
    return safeFields;
  }
 
  /**
   * Populate the internal cache from externally-provided SchemaInfo.
   * Used when ConnectionManager restores introspection data from its caches
   * (introspectionCache or InstanceRegistry) so that callers who access
   * the SchemaIntrospector directly (e.g. DynamicWorkItemsQuery) see the
   * same widget/type data without a redundant GraphQL introspection call.
   */
  public rehydrate(schema: SchemaInfo): void {
    this.cachedSchema = schema;
  }
 
  public getCachedSchema(): SchemaInfo | null {
    return this.cachedSchema;
  }
 
  public clearCache(): void {
    this.cachedSchema = null;
  }
}