instruction
stringclasses
1 value
input
stringlengths
67
168
output
stringlengths
46
67k
You are a code assistant
Definition of 'dispose' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp
Definition: dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References:
You are a code assistant
Definition of 'debug' in file src/common/log_types.ts in project gitlab-lsp
Definition: debug(message: string, e?: Error): void; info(e: Error): void; info(message: string, e?: Error): void; warn(e: Error): void; warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } export const LOG_LEVEL = { DEBUG: 'debug', INFO: 'info', WARNING: 'warning', ERROR: 'error', } as const; export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL]; References:
You are a code assistant
Definition of 'DidChangeDocumentInActiveEditor' in file src/common/notifications.ts in project gitlab-lsp
Definition: export const DidChangeDocumentInActiveEditor = new NotificationType<DidChangeDocumentInActiveEditorParams>( '$/gitlab/didChangeDocumentInActiveEditor', ); References:
You are a code assistant
Definition of 'HandlesRequest' in file src/common/handler.ts in project gitlab-lsp
Definition: export interface HandlesRequest<P, R, E> { requestHandler: RequestHandler<P, R, E>; } export interface HandlesNotification<P> { notificationHandler: NotificationHandler<P>; } References:
You are a code assistant
Definition of 'sortCheckpoints' in file src/common/graphql/workflow/service.ts in project gitlab-lsp
Definition: sortCheckpoints(checkpoints: LangGraphCheckpoint[]) { return [...checkpoints].sort((a: LangGraphCheckpoint, b: LangGraphCheckpoint) => { const parsedCheckpointA = JSON.parse(a.checkpoint); const parsedCheckpointB = JSON.parse(b.checkpoint); return new Date(parsedCheckpointA.ts).getTime() - new Date(parsedCheckpointB.ts).getTime(); }); } getStatus(checkpoints: LangGraphCheckpoint[]): string { const startingCheckpoint: LangGraphCheckpoint = { checkpoint: '{ "channel_values": { "status": "Starting" }}', }; const lastCheckpoint = checkpoints.at(-1) || startingCheckpoint; const checkpoint = JSON.parse(lastCheckpoint.checkpoint); return checkpoint?.channel_values?.status; } async pollWorkflowEvents(id: string, messageBus: MessageBus): Promise<void> { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise<void> => { try { const checkpoints: LangGraphCheckpoint[] = await this.getWorkflowEvents(workflowId); messageBus.sendNotification('workflowCheckpoints', checkpoints); const status = this.getStatus(checkpoints); messageBus.sendNotification('workflowStatus', status); // If the status is Completed, we dont call the next setTimeout and polling stops if (status !== 'Completed') { timeout = setTimeout(poll, 3000); } else { clearTimeout(timeout); } } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } }; await poll(); } async getWorkflowEvents(id: string): Promise<LangGraphCheckpoint[]> { try { const data: DuoWorkflowEventConnectionType = await this.#apiClient.fetchFromApi({ type: 'graphql', query: GET_WORKFLOW_EVENTS_QUERY, variables: { workflowId: id }, }); return this.sortCheckpoints(data?.duoWorkflowEvents?.nodes || []); } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } } } References:
You are a code assistant
Definition of 'Greet3' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp
Definition: class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References: - src/tests/fixtures/intent/empty_function/ruby.rb:34
You are a code assistant
Definition of 'DefaultDocumentTransformerService' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; constructor(documents: LsTextDocuments, secretRedactor: SecretRedactor) { this.#documents = documents; this.#transformers.push(secretRedactor); } get(uri: string) { return this.#documents.get(uri); } getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined { const doc = this.get(uri); if (doc === undefined) { return undefined; } return this.transform(getDocContext(doc, position, workspaceFolders, completionContext)); } transform(context: IDocContext): IDocContext { return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context); } } export function getDocContext( document: TextDocument, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext { let prefix: string; if (completionContext?.selectedCompletionInfo) { const { selectedCompletionInfo } = completionContext; const range = sanitizeRange(selectedCompletionInfo.range); prefix = `${document.getText({ start: document.positionAt(0), end: range.start, })}${selectedCompletionInfo.text}`; } else { prefix = document.getText({ start: document.positionAt(0), end: position }); } const suffix = document.getText({ start: position, end: document.positionAt(document.getText().length), }); const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders); const fileRelativePath = getRelativePath(document.uri, workspaceFolder); return { prefix, suffix, fileRelativePath, position, uri: document.uri, languageId: document.languageId, workspaceFolder, }; } References:
You are a code assistant
Definition of 'WEBVIEW_TITLE' in file packages/webview_duo_workflow/src/contract.ts in project gitlab-lsp
Definition: export const WEBVIEW_TITLE = 'GitLab Duo Workflow'; export type DuoWorkflowMessages = CreatePluginMessageMap<{ webviewToPlugin: { notifications: { startWorkflow: { goal: string; image: string; }; stopWorkflow: []; openUrl: { url: string; }; }; }; pluginToWebview: { notifications: { workflowCheckpoints: LangGraphCheckpoint[]; workflowError: string; workflowStarted: string; workflowStatus: string; }; }; }>; References:
You are a code assistant
Definition of 'PLATFORM_ORIGIN' in file packages/webview_duo_chat/src/plugin/port/chat/constants.ts in project gitlab-lsp
Definition: export const PLATFORM_ORIGIN = 'vs_code_extension'; References:
You are a code assistant
Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp
Definition: constructor(client: GitLabApiClient) { this.#client = client; } account: Account = { id: 'https://gitlab.com|16918910', instanceUrl: 'https://gitlab.com', } as Partial<Account> as Account; fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { return this.#client.fetchFromApi(request); } connectToCable(): Promise<Cable> { return this.#client.connectToCable(); } getUserAgentHeader(): Record<string, string> { return {}; } } export class ChatPlatformForAccount extends ChatPlatform implements GitLabPlatformForAccount { readonly type = 'account' as const; project: undefined; } export class ChatPlatformForProject extends ChatPlatform implements GitLabPlatformForProject { readonly type = 'project' as const; project: GitLabProject = { gqlId: 'gid://gitlab/Project/123456', restId: 0, name: '', description: '', namespaceWithPath: '', webUrl: '', }; } References:
You are a code assistant
Definition of 'isLanguageSupported' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp
Definition: isLanguageSupported(languageId: string): boolean; onLanguageChange(listener: () => void): Disposable; } export const SupportedLanguagesService = createInterfaceId<SupportedLanguagesService>( 'SupportedLanguagesService', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set<string>; #supportedLanguages: Set<string>; #configService: ConfigService; #eventEmitter = new EventEmitter(); constructor(configService: ConfigService) { this.#enabledLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES); this.#supportedLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES); this.#configService = configService; this.#configService.onConfigChange(() => this.#update()); } #getConfiguredLanguages() { const languages: SupportedLanguagesUpdateParam = {}; const additionalLanguages = this.#configService.get( 'client.codeCompletion.additionalLanguages', ); if (Array.isArray(additionalLanguages)) { languages.allow = additionalLanguages.map(this.#normalizeLanguageIdentifier); } else { log.warn( 'Failed to parse user-configured Code Suggestions languages. Code Suggestions will still work for the default languages.', ); } const disabledSupportedLanguages = this.#configService.get( 'client.codeCompletion.disabledSupportedLanguages', ); if (Array.isArray(disabledSupportedLanguages)) { languages.deny = disabledSupportedLanguages; } else { log.warn( 'Invalid configuration for disabled Code Suggestions languages. All default languages remain enabled.', ); } return languages; } #update() { const { allow = [], deny = [] } = this.#getConfiguredLanguages(); const newSet: Set<string> = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES); for (const language of allow) { newSet.add(language.trim()); } for (const language of deny) { newSet.delete(language); } if (newSet.size === 0) { log.warn('All languages have been disabled for Code Suggestions.'); } const previousEnabledLanguages = this.#enabledLanguages; this.#enabledLanguages = newSet; if (!isEqual(previousEnabledLanguages, this.#enabledLanguages)) { this.#triggerChange(); } } isLanguageSupported(languageId: string) { return this.#supportedLanguages.has(languageId); } isLanguageEnabled(languageId: string) { return this.#enabledLanguages.has(languageId); } onLanguageChange(listener: () => void): Disposable { this.#eventEmitter.on('languageChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('languageChange'); } #normalizeLanguageIdentifier(language: string) { return language.trim().toLowerCase().replace(/^\./, ''); } } References:
You are a code assistant
Definition of 'sendNotification' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: sendNotification<T extends KeysWithOptionalValues<TNotifications>>(type: T): void; sendNotification<T extends keyof TNotifications>(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener<TNotifications extends NotificationMap> { onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'sendInitialized' in file src/tests/int/lsp_client.ts in project gitlab-lsp
Definition: public async sendInitialized(options?: InitializedParams | undefined): Promise<void> { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType<InitializedParams>('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise<void> { const defaults = createFakePartial<ChangeConfigOptions>({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType<DidChangeConfigurationParams>( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType<DidOpenTextDocumentParams>('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise<void> { const params = { textDocument: { uri, }, }; const request = new NotificationType<DidCloseTextDocumentParams>('textDocument/didClose'); await this.#connection.sendNotification(request, params); } /** * Send LSP 'textDocument/didChange' using Full sync method notification * * @param uri File URL. Should include the workspace path in the url * @param version Change version (incrementing from 0) * @param text Full contents of the file */ public async sendTextDocumentDidChangeFull( uri: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType<DidChangeTextDocumentParams>('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise<CompletionItem[] | CompletionList | null> { const params: CompletionParams = { textDocument: { uri, }, position: { line, character, }, context: { triggerKind: 1, // invoked }, }; const request = new RequestType1< CompletionParams, CompletionItem[] | CompletionList | null, void >('textDocument/completion'); const result = await this.#connection.sendRequest(request, params); return result; } public async sendDidChangeDocumentInActiveEditor(uri: string): Promise<void> { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise<WebviewMetadata[]> { const result = await this.#connection.sendRequest<WebviewMetadata[]>( '$/gitlab/webview-metadata', ); return result; } } References:
You are a code assistant
Definition of 'sendNotification' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: sendNotification<T extends keyof TNotifications>(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener<TNotifications extends NotificationMap> { onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'isCursorAfterEmptyPythonFunction' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp
Definition: static isCursorAfterEmptyPythonFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { if (languageName !== 'python') return false; const pythonQuery = treeSitterLanguage.query(`[ (function_definition) (class_definition) ] @function`); const captures = pythonQuery.captures(tree.rootNode); if (captures.length === 0) return false; // Check if any function or class body is empty and cursor is after it return captures.some((capture) => { const bodyNode = capture.node.childForFieldName('body'); return ( bodyNode?.childCount === 0 && EmptyFunctionResolver.#isCursorRightAfterNode(cursorPosition, capture.node.endPosition) ); }); } } let emptyFunctionResolver: EmptyFunctionResolver; export function getEmptyFunctionResolver(): EmptyFunctionResolver { if (!emptyFunctionResolver) { emptyFunctionResolver = new EmptyFunctionResolver(); } return emptyFunctionResolver; } References:
You are a code assistant
Definition of 'ChatRecordType' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp
Definition: type ChatRecordType = | 'general' | 'explainCode' | 'generateTests' | 'refactorCode' | 'newConversation'; type GitLabChatRecordAttributes = { chunkId?: number | null; type?: ChatRecordType; role: ChatRecordRole; content?: string; contentHtml?: string; requestId?: string; state?: ChatRecordState; errors?: string[]; timestamp?: string; extras?: { sources: object[]; }; }; export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial<GitLabChatRecordAttributes>) { const convertedAttributes = attributes as Partial<GitLabChatRecord>; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:46 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:96 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:16
You are a code assistant
Definition of 'buildContext' in file src/common/advanced_context/context_resolvers/advanced_context_resolver.ts in project gitlab-lsp
Definition: abstract buildContext({ documentContext, }: { documentContext: IDocContext; }): AsyncGenerator<ContextResolution>; } References:
You are a code assistant
Definition of 'Repository' in file src/common/git/repository.ts in project gitlab-lsp
Definition: export class Repository { workspaceFolder: WorkspaceFolder; uri: URI; configFileUri: URI; #files: Map<string, RepositoryFile>; #ignoreManager: IgnoreManager; constructor({ configFileUri, workspaceFolder, uri, ignoreManager, }: { workspaceFolder: WorkspaceFolder; uri: RepositoryUri; configFileUri: URI; ignoreManager: IgnoreManager; }) { this.workspaceFolder = workspaceFolder; this.uri = uri; this.configFileUri = configFileUri; this.#files = new Map(); this.#ignoreManager = ignoreManager; } async addFilesAndLoadGitIgnore(files: URI[]): Promise<void> { log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`); await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath)); for (const file of files) { if (!this.#ignoreManager.isIgnored(file.fsPath)) { this.#files.set(file.toString(), { uri: file, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(file.toString(), { uri: file, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } } isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map<string, RepositoryFile> { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References: - src/common/git/repository_service.ts:270
You are a code assistant
Definition of 'Subscription' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp
Definition: interface Subscription<T> { listener: Listener<T>; filter?: FilterFunction<T>; } export class MessageBus<TMessageMap extends Record<string, unknown>> implements Disposable { #subscriptions = new Map<keyof TMessageMap, Set<Subscription<unknown>>>(); public subscribe<K extends keyof TMessageMap>( messageType: K, listener: Listener<TMessageMap[K]>, filter?: FilterFunction<TMessageMap[K]>, ): Disposable { const subscriptions = this.#subscriptions.get(messageType) ?? new Set<Subscription<unknown>>(); const subscription: Subscription<unknown> = { listener: listener as Listener<unknown>, filter: filter as FilterFunction<unknown> | undefined, }; subscriptions.add(subscription); this.#subscriptions.set(messageType, subscriptions); return { dispose: () => { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { targetSubscriptions.delete(subscription); if (targetSubscriptions.size === 0) { this.#subscriptions.delete(messageType); } } }, }; } public publish<K extends keyof TMessageMap>(messageType: K, data: TMessageMap[K]): void { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { Array.from(targetSubscriptions).forEach((subscription) => { const { listener, filter } = subscription as Subscription<TMessageMap[K]>; if (!filter || filter(data)) { listener(data); } }); } } public hasListeners<K extends keyof TMessageMap>(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount<K extends keyof TMessageMap>(messageType: K): number { return this.#subscriptions.get(messageType)?.size ?? 0; } public clear(): void { this.#subscriptions.clear(); } public dispose(): void { this.clear(); } } References:
You are a code assistant
Definition of 'CompletionRequest' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp
Definition: export interface CompletionRequest { textDocument: TextDocumentIdentifier; position: Position; token: CancellationToken; inlineCompletionContext?: InlineCompletionContext; } export class DefaultSuggestionService { readonly #suggestionClientPipeline: SuggestionClientPipeline; #configService: ConfigService; #api: GitLabApiClient; #tracker: TelemetryTracker; #connection: Connection; #documentTransformerService: DocumentTransformerService; #circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests'); #subscriptions: Disposable[] = []; #suggestionsCache: SuggestionsCache; #treeSitterParser: TreeSitterParser; #duoProjectAccessChecker: DuoProjectAccessChecker; #featureFlagService: FeatureFlagService; #postProcessorPipeline = new PostProcessorPipeline(); constructor({ telemetryTracker, configService, api, connection, documentTransformerService, featureFlagService, treeSitterParser, duoProjectAccessChecker, }: SuggestionServiceOptions) { this.#configService = configService; this.#api = api; this.#tracker = telemetryTracker; this.#connection = connection; this.#documentTransformerService = documentTransformerService; this.#suggestionsCache = new SuggestionsCache(this.#configService); this.#treeSitterParser = treeSitterParser; this.#featureFlagService = featureFlagService; const suggestionClient = new FallbackClient( new DirectConnectionClient(this.#api, this.#configService), new DefaultSuggestionClient(this.#api), ); this.#suggestionClientPipeline = new SuggestionClientPipeline([ clientToMiddleware(suggestionClient), createTreeSitterMiddleware({ treeSitterParser, getIntentFn: getIntent, }), ]); this.#subscribeToCircuitBreakerEvents(); this.#duoProjectAccessChecker = duoProjectAccessChecker; } completionHandler = async ( { textDocument, position }: CompletionParams, token: CancellationToken, ): Promise<CompletionItem[]> => { log.debug('Completion requested'); const suggestionOptions = await this.#getSuggestionOptions({ textDocument, position, token }); if (suggestionOptions.find(isStream)) { log.warn( `Completion response unexpectedly contained streaming response. Streaming for completion is not supported. Please report this issue.`, ); } return completionOptionMapper(suggestionOptions.filter(isTextSuggestion)); }; #getSuggestionOptions = async ( request: CompletionRequest, ): Promise<SuggestionOptionOrStream[]> => { const { textDocument, position, token, inlineCompletionContext: context } = request; const suggestionContext = this.#documentTransformerService.getContext( textDocument.uri, position, this.#configService.get('client.workspaceFolders') ?? [], context, ); if (!suggestionContext) { return []; } const cachedSuggestions = this.#useAndTrackCachedSuggestions( textDocument, position, suggestionContext, context?.triggerKind, ); if (context?.triggerKind === InlineCompletionTriggerKind.Invoked) { const options = await this.#handleNonStreamingCompletion(request, suggestionContext); options.unshift(...(cachedSuggestions ?? [])); (cachedSuggestions ?? []).forEach((cs) => this.#tracker.updateCodeSuggestionsContext(cs.uniqueTrackingId, { optionsCount: options.length, }), ); return options; } if (cachedSuggestions) { return cachedSuggestions; } // debounce await waitMs(SUGGESTIONS_DEBOUNCE_INTERVAL_MS); if (token.isCancellationRequested) { log.debug('Debounce triggered for completion'); return []; } if ( context && shouldRejectCompletionWithSelectedCompletionTextMismatch( context, this.#documentTransformerService.get(textDocument.uri), ) ) { return []; } const additionalContexts = await this.#getAdditionalContexts(suggestionContext); // right now we only support streaming for inlineCompletion // if the context is present, we know we are handling inline completion if ( context && this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.StreamCodeGenerations) ) { const intentResolution = await this.#getIntent(suggestionContext); if (intentResolution?.intent === 'generation') { return this.#handleStreamingInlineCompletion( suggestionContext, intentResolution.commentForCursor?.content, intentResolution.generationType, additionalContexts, ); } } return this.#handleNonStreamingCompletion(request, suggestionContext, additionalContexts); }; inlineCompletionHandler = async ( params: InlineCompletionParams, token: CancellationToken, ): Promise<InlineCompletionList> => { log.debug('Inline completion requested'); const options = await this.#getSuggestionOptions({ textDocument: params.textDocument, position: params.position, token, inlineCompletionContext: params.context, }); return inlineCompletionOptionMapper(params, options); }; async #handleStreamingInlineCompletion( context: IDocContext, userInstruction?: string, generationType?: GenerationType, additionalContexts?: AdditionalContext[], ): Promise<StartStreamOption[]> { if (this.#circuitBreaker.isOpen()) { log.warn('Stream was not started as the circuit breaker is open.'); return []; } const streamId = uniqueId('code-suggestion-stream-'); const uniqueTrackingId = generateUniqueTrackingId(); setTimeout(() => { log.debug(`Starting to stream (id: ${streamId})`); const streamingHandler = new DefaultStreamingHandler({ api: this.#api, circuitBreaker: this.#circuitBreaker, connection: this.#connection, documentContext: context, parser: this.#treeSitterParser, postProcessorPipeline: this.#postProcessorPipeline, streamId, tracker: this.#tracker, uniqueTrackingId, userInstruction, generationType, additionalContexts, }); streamingHandler.startStream().catch((e: Error) => log.error('Failed to start streaming', e)); }, 0); return [{ streamId, uniqueTrackingId }]; } async #handleNonStreamingCompletion( request: CompletionRequest, documentContext: IDocContext, additionalContexts?: AdditionalContext[], ): Promise<SuggestionOption[]> { const uniqueTrackingId: string = generateUniqueTrackingId(); try { return await this.#getSuggestions({ request, uniqueTrackingId, documentContext, additionalContexts, }); } catch (e) { if (isFetchError(e)) { this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: e.status }); } this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); this.#circuitBreaker.error(); log.error('Failed to get code suggestions!', e); return []; } } /** * FIXME: unify how we get code completion and generation * so we don't have duplicate intent detection (see `tree_sitter_middleware.ts`) * */ async #getIntent(context: IDocContext): Promise<IntentResolution | undefined> { try { const treeAndLanguage = await this.#treeSitterParser.parseFile(context); if (!treeAndLanguage) { return undefined; } return await getIntent({ treeAndLanguage, position: context.position, prefix: context.prefix, suffix: context.suffix, }); } catch (error) { log.error('Failed to parse with tree sitter', error); return undefined; } } #trackShowIfNeeded(uniqueTrackingId: string) { if ( !canClientTrackEvent( this.#configService.get('client.telemetry.actions'), TRACKING_EVENTS.SHOWN, ) ) { /* If the Client can detect when the suggestion is shown in the IDE, it will notify the Server. Otherwise the server will assume that returned suggestions are shown and tracks the event */ this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); } } async #getSuggestions({ request, uniqueTrackingId, documentContext, additionalContexts, }: { request: CompletionRequest; uniqueTrackingId: string; documentContext: IDocContext; additionalContexts?: AdditionalContext[]; }): Promise<SuggestionOption[]> { const { textDocument, position, token } = request; const triggerKind = request.inlineCompletionContext?.triggerKind; log.info('Suggestion requested.'); if (this.#circuitBreaker.isOpen()) { log.warn('Code suggestions were not requested as the circuit breaker is open.'); return []; } if (!this.#configService.get('client.token')) { return []; } // Do not send a suggestion if content is less than 10 characters const contentLength = (documentContext?.prefix?.length || 0) + (documentContext?.suffix?.length || 0); if (contentLength < 10) { return []; } if (!isAtOrNearEndOfLine(documentContext.suffix)) { return []; } // Creates the suggestion and tracks suggestion_requested this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, triggerKind, additionalContexts, }); /** how many suggestion options should we request from the API */ const optionsCount: OptionsCount = triggerKind === InlineCompletionTriggerKind.Invoked ? MANUAL_REQUEST_OPTIONS_COUNT : 1; const suggestionsResponse = await this.#suggestionClientPipeline.getSuggestions({ document: documentContext, projectPath: this.#configService.get('client.projectPath'), optionsCount, additionalContexts, }); this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { model: suggestionsResponse?.model, status: suggestionsResponse?.status, optionsCount: suggestionsResponse?.choices?.length, isDirectConnection: suggestionsResponse?.isDirectConnection, }); if (suggestionsResponse?.error) { throw new Error(suggestionsResponse.error); } this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED); this.#circuitBreaker.success(); const areSuggestionsNotProvided = !suggestionsResponse?.choices?.length || suggestionsResponse?.choices.every(({ text }) => !text?.length); const suggestionOptions = (suggestionsResponse?.choices || []).map((choice, index) => ({ ...choice, index, uniqueTrackingId, lang: suggestionsResponse?.model?.lang, })); const processedChoices = await this.#postProcessorPipeline.run({ documentContext, input: suggestionOptions, type: 'completion', }); this.#suggestionsCache.addToSuggestionCache({ request: { document: textDocument, position, context: documentContext, additionalContexts, }, suggestions: processedChoices, }); if (token.isCancellationRequested) { this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); return []; } if (areSuggestionsNotProvided) { this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); return []; } this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { suggestionOptions }); this.#trackShowIfNeeded(uniqueTrackingId); return processedChoices; } dispose() { this.#subscriptions.forEach((subscription) => subscription?.dispose()); } #subscribeToCircuitBreakerEvents() { this.#subscriptions.push( this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)), ); this.#subscriptions.push( this.#circuitBreaker.onClose(() => this.#connection.sendNotification(API_RECOVERY_NOTIFICATION), ), ); } #useAndTrackCachedSuggestions( textDocument: TextDocumentIdentifier, position: Position, documentContext: IDocContext, triggerKind?: InlineCompletionTriggerKind, ): SuggestionOption[] | undefined { const suggestionsCache = this.#suggestionsCache.getCachedSuggestions({ document: textDocument, position, context: documentContext, }); if (suggestionsCache?.options?.length) { const { uniqueTrackingId, lang } = suggestionsCache.options[0]; const { additionalContexts } = suggestionsCache; this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, source: SuggestionSource.cache, triggerKind, suggestionOptions: suggestionsCache?.options, language: lang, additionalContexts, }); this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED); this.#trackShowIfNeeded(uniqueTrackingId); return suggestionsCache.options.map((option, index) => ({ ...option, index })); } return undefined; } async #getAdditionalContexts(documentContext: IDocContext): Promise<AdditionalContext[]> { let additionalContexts: AdditionalContext[] = []; const advancedContextEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextEnabled) { const advancedContext = await getAdvancedContext({ documentContext, dependencies: { duoProjectAccessChecker: this.#duoProjectAccessChecker }, }); additionalContexts = advancedContextToRequestBody(advancedContext); } return additionalContexts; } } References: - src/common/suggestion/suggestion_service.ts:324 - src/common/suggestion/suggestion_service.ts:193 - src/common/suggestion/suggestion_service.ts:389
You are a code assistant
Definition of 'EmitterState' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp
Definition: enum EmitterState { STARTED, STOPPING, STOPPED, } export class Emitter { #trackingQueue: PayloadBuilder[] = []; #callback: SendEventCallback; #timeInterval: number; #maxItems: number; #currentState: EmitterState; #timeout: NodeJS.Timeout | undefined; constructor(timeInterval: number, maxItems: number, callback: SendEventCallback) { this.#maxItems = maxItems; this.#timeInterval = timeInterval; this.#callback = callback; this.#currentState = EmitterState.STOPPED; } add(data: PayloadBuilder) { this.#trackingQueue.push(data); if (this.#trackingQueue.length >= this.#maxItems) { this.#drainQueue().catch(() => {}); } } async #drainQueue(): Promise<void> { if (this.#trackingQueue.length > 0) { const copyOfTrackingQueue = this.#trackingQueue.map((e) => e); this.#trackingQueue = []; await this.#callback(copyOfTrackingQueue); } } start() { this.#timeout = setTimeout(async () => { await this.#drainQueue(); if (this.#currentState !== EmitterState.STOPPING) { this.start(); } }, this.#timeInterval); this.#currentState = EmitterState.STARTED; } async stop() { this.#currentState = EmitterState.STOPPING; if (this.#timeout) { clearTimeout(this.#timeout); } this.#timeout = undefined; await this.#drainQueue(); } } References: - src/common/tracking/snowplow/emitter.ts:20
You are a code assistant
Definition of 'shouldRejectCompletionWithSelectedCompletionTextMismatch' in file src/common/suggestion/suggestion_filter.ts in project gitlab-lsp
Definition: export function shouldRejectCompletionWithSelectedCompletionTextMismatch( context: InlineCompletionContext, document?: TextDocument, ): boolean { if (!context.selectedCompletionInfo || !document) { return false; } const currentText = document.getText(sanitizeRange(context.selectedCompletionInfo.range)); const selectedText = context.selectedCompletionInfo.text; return !selectedText.startsWith(currentText); } References: - src/common/suggestion/suggestion_filter.test.ts:64 - src/common/suggestion/suggestion_filter.test.ts:47 - src/common/suggestion/suggestion_filter.test.ts:89 - src/common/suggestion/suggestion_service.ts:240
You are a code assistant
Definition of 'onDuoProjectCacheUpdate' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId<DuoProjectAccessCache>('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map<WorkspaceFolderUri, DuoProject[]>; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map<WorkspaceFolderUri, DuoProject[]>(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise<DuoProject[]> { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise<GitlabRemoteAndFileUri[]> { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise<GitlabRemoteAndFileUri[]> { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce<string[]>((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:
You are a code assistant
Definition of 'get' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: get(uri: string) { return this.#documents.get(uri); } getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined { const doc = this.get(uri); if (doc === undefined) { return undefined; } return this.transform(getDocContext(doc, position, workspaceFolders, completionContext)); } transform(context: IDocContext): IDocContext { return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context); } } export function getDocContext( document: TextDocument, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext { let prefix: string; if (completionContext?.selectedCompletionInfo) { const { selectedCompletionInfo } = completionContext; const range = sanitizeRange(selectedCompletionInfo.range); prefix = `${document.getText({ start: document.positionAt(0), end: range.start, })}${selectedCompletionInfo.text}`; } else { prefix = document.getText({ start: document.positionAt(0), end: position }); } const suffix = document.getText({ start: position, end: document.positionAt(document.getText().length), }); const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders); const fileRelativePath = getRelativePath(document.uri, workspaceFolder); return { prefix, suffix, fileRelativePath, position, uri: document.uri, languageId: document.languageId, workspaceFolder, }; } References: - src/common/utils/headers_to_snowplow_options.ts:21 - src/common/config_service.ts:134 - src/common/utils/headers_to_snowplow_options.ts:12 - src/common/utils/headers_to_snowplow_options.ts:20 - src/common/utils/headers_to_snowplow_options.ts:22
You are a code assistant
Definition of 'SuggestionClientPipeline' in file src/common/suggestion_client/suggestion_client_pipeline.ts in project gitlab-lsp
Definition: export class SuggestionClientPipeline implements SuggestionClient { #middlewares: SuggestionClientMiddleware[]; #pipeline: SuggestionClientFn; constructor(middlewares: SuggestionClientMiddleware[]) { this.#middlewares = [...middlewares]; this.#pipeline = this.#buildPipeline(); } use(middleware: SuggestionClientMiddleware) { this.#middlewares.push(middleware); this.#pipeline = this.#buildPipeline(); } #buildPipeline() { return this.#middlewares.reduce<SuggestionClientFn>( (acc, middleware) => { return (x: SuggestionContext) => { return middleware(x, acc); }; }, () => Promise.reject( new Error(`[SuggestionClientPipeline] Reached end of the pipeline without resolution!`), ), ); } getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined> { return this.#pipeline(context); } } References: - src/common/suggestion/suggestion_service.ts:165 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:55 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:101 - src/common/suggestion/suggestion_service.ts:115 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:34
You are a code assistant
Definition of 'Credentials' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp
Definition: export interface Credentials { instanceUrl: string; token: string; } interface AccountBase extends Credentials { username: string; id: string; } export interface TokenAccount extends AccountBase { type: 'token'; } export interface OAuthAccount extends AccountBase { type: 'oauth'; scopes: string[]; refreshToken: string; expiresAtTimestampInSeconds: number; } export type Account = TokenAccount | OAuthAccount; export const serializeAccountSafe = (account: Account) => JSON.stringify(account, ['instanceUrl', 'id', 'username', 'scopes']); export const makeAccountId = (instanceUrl: string, userId: string | number) => `${instanceUrl}|${userId}`; export const extractUserId = (accountId: string) => accountId.split('|').pop(); References:
You are a code assistant
Definition of 'inlineCompletionOptionMapper' in file src/common/utils/suggestion_mappers.ts in project gitlab-lsp
Definition: export const inlineCompletionOptionMapper = ( params: InlineCompletionParams, options: SuggestionOptionOrStream[], ): InlineCompletionList => ({ items: options.map((option) => { if (isStream(option)) { // the streaming item is empty and only indicates to the client that streaming started return { insertText: '', command: { title: 'Start streaming', command: START_STREAMING_COMMAND, arguments: [option.streamId, option.uniqueTrackingId], }, }; } const completionInfo = params.context.selectedCompletionInfo; let rangeDiff = 0; if (completionInfo) { const range = sanitizeRange(completionInfo.range); rangeDiff = range.end.character - range.start.character; } return { insertText: completionInfo ? `${completionInfo.text.substring(rangeDiff)}${option.text}` : option.text, range: Range.create(params.position, params.position), command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId, getOptionTrackingIndex(option)], }, }; }), }); References: - src/common/utils/suggestion_mapper.test.ts:65 - src/common/utils/suggestion_mapper.test.ts:100 - src/common/suggestion/suggestion_service.ts:283
You are a code assistant
Definition of 'commentQueries' in file src/common/tree_sitter/comments/comment_queries.ts in project gitlab-lsp
Definition: export const commentQueries = { bash: bashCommentQuery, c: cCommentQuery, cpp: cppCommentQuery, c_sharp: csharpCommentQuery, css: cssCommentQuery, go: goCommentQuery, // hcl: hclCommentQuery, html: htmlCommentQuery, java: javaCommentQuery, javascript: javascriptCommentQuery, json: jsonCommentQuery, kotlin: kotlinCommentQuery, powershell: powershellCommentQuery, python: pythonCommentQuery, rust: rustCommentQuery, ruby: rubyCommentQuery, scala: scalaCommentQuery, // sql: sqlCommentQuery, typescript: typescriptCommentQuery, tsx: typescriptCommentQuery, vue: vueCommentQuery, yaml: yamlCommentQuery, } satisfies Record<TreeSitterLanguageName, string>; References:
You are a code assistant
Definition of 'getMessageBus' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus_provider.ts in project gitlab-lsp
Definition: getMessageBus<TMessages extends MessageMap>(webviewId: string): MessageBus<TMessages> | null { if (!webviewId) { return null; } const socketUri = getSocketUri(webviewId); const socket = io(socketUri); const bus = new SocketIoMessageBus<TMessages>(socket); return bus; } } References:
You are a code assistant
Definition of 'handleWorkspaceFilesUpdate' in file src/common/git/repository_service.ts in project gitlab-lsp
Definition: async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:
You are a code assistant
Definition of 'onClose' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:
You are a code assistant
Definition of 'getGitLabEnvironment' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp
Definition: async getGitLabEnvironment(): Promise<GitLabEnvironment> { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:
You are a code assistant
Definition of 'getWebviewMetadata' in file src/tests/int/lsp_client.ts in project gitlab-lsp
Definition: public async getWebviewMetadata(): Promise<WebviewMetadata[]> { const result = await this.#connection.sendRequest<WebviewMetadata[]>( '$/gitlab/webview-metadata', ); return result; } } References:
You are a code assistant
Definition of 'constructor' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp
Definition: constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References:
You are a code assistant
Definition of 'publish' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp
Definition: async publish<K extends keyof MessagesToClient>( type: K, message: MessagesToClient[K], ): Promise<void> { const connectionId = buildConnectionId({ webviewId: message.webviewId, webviewInstanceId: message.webviewInstanceId, }); const connection = this.#connections.get(connectionId); if (!connection) { this.#logger?.error(`No active socket found for ID ${connectionId}`); return; } switch (type) { case 'webview_instance_notification': connection.emit(SOCKET_NOTIFICATION_CHANNEL, { type: message.type, payload: message.payload, }); return; case 'webview_instance_request': connection.emit(SOCKET_REQUEST_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_request']).requestId, }); return; case 'webview_instance_response': connection.emit(SOCKET_RESPONSE_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_response']).requestId, }); return; default: this.#logger?.error(`Unknown message type ${type}`); } } on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } dispose() { this.#messageEmitter.removeAllListeners(); for (const connection of this.#connections.values()) { connection.disconnect(); } this.#connections.clear(); } } References:
You are a code assistant
Definition of 'isSmallFile' in file src/common/tree_sitter/small_files.ts in project gitlab-lsp
Definition: export function isSmallFile(textContent: string, totalCommentLines: number): boolean { const minLinesOfCode = 5; // threshold to determine whether a source code file is considered 'small' const totalNonEmptyLines = getTotalNonEmptyLines(textContent); return totalNonEmptyLines - totalCommentLines < minLinesOfCode; } References: - src/common/tree_sitter/intent_resolver.ts:77 - src/common/tree_sitter/small_files.test.ts:11
You are a code assistant
Definition of 'WEB_IDE_AUTH_PROVIDER_ID' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp
Definition: export const WEB_IDE_AUTH_PROVIDER_ID = 'gitlab-web-ide'; export const WEB_IDE_AUTH_SCOPE = 'api'; // region: Mediator commands ------------------------------------------- export const COMMAND_FETCH_FROM_API = `gitlab-web-ide.mediator.fetch-from-api`; export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`; export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; export const COMMAND_GET_CONFIG = `gitlab-web-ide.mediator.get-config`; // Return type from `COMMAND_FETCH_BUFFER_FROM_API` export interface VSCodeBuffer { readonly buffer: Uint8Array; } // region: Shared configuration ---------------------------------------- export interface InteropConfig { projectPath: string; gitlabUrl: string; } // region: API types --------------------------------------------------- /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the _TReturnType */ export interface PostRequest<_TReturnType> { type: 'rest'; method: 'POST'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; body?: unknown; headers?: Record<string, string>; } /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the _TReturnType */ interface GetRequestBase<_TReturnType> { method: 'GET'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; searchParams?: Record<string, string>; headers?: Record<string, string>; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase<Uint8Array> { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record<string, unknown>; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; // The interface of the VSCode mediator command COMMAND_FETCH_FROM_API // Will throw ResponseError if HTTP response status isn't 200 export type fetchFromApi = <_TReturnType>( request: ApiRequest<_TReturnType>, ) => Promise<_TReturnType>; // The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API // Will throw ResponseError if HTTP response status isn't 200 export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>; /* API exposed by the Web IDE extension * See https://code.visualstudio.com/api/references/vscode-api#extensions */ export interface WebIDEExtension { isTelemetryEnabled: () => boolean; projectPath: string; gitlabUrl: string; } export interface ResponseError extends Error { status: number; body?: unknown; } References:
You are a code assistant
Definition of 'DefaultAiContextAggregator' in file src/common/ai_context_management_2/ai_context_aggregator.ts in project gitlab-lsp
Definition: export class DefaultAiContextAggregator { #AiFileContextProvider: AiFileContextProvider; #AiContextPolicyManager: AiContextPolicyManager; constructor( aiFileContextProvider: AiFileContextProvider, aiContextPolicyManager: AiContextPolicyManager, ) { this.#AiFileContextProvider = aiFileContextProvider; this.#AiContextPolicyManager = aiContextPolicyManager; } async getContextForQuery(query: AiContextQuery): Promise<AiContextItem[]> { switch (query.providerType) { case 'file': { const providerItems = await this.#AiFileContextProvider.getProviderItems( query.query, query.workspaceFolders, ); const contextItems = await Promise.all( providerItems.map((providerItem) => this.#providerItemToContextItem(providerItem)), ); return contextItems; } default: return []; } } async #providerItemToContextItem(providerItem: AiContextProviderItem): Promise<AiContextItem> { if (providerItem.providerType === 'file') { const { fileUri, workspaceFolder, providerType, subType, repositoryFile } = providerItem; const policyResult = await this.#AiContextPolicyManager.runPolicies(providerItem); return { id: fileUri.toString(), isEnabled: policyResult.allowed, info: { project: repositoryFile?.repositoryUri.fsPath, disabledReasons: policyResult.reasons, relFilePath: repositoryFile ? this.#getBasePath(fileUri, parseURIString(workspaceFolder.uri)) : undefined, }, name: Utils.basename(fileUri), type: providerType, subType, }; } throw new Error('Unknown provider type'); } #getBasePath(targetUri: URI, baseUri: URI): string { const targetPath = targetUri.fsPath; const basePath = baseUri.fsPath; return targetPath.replace(basePath, '').replace(/^[/\\]+/, ''); } } References:
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp
Definition: def greet puts "Hello #{@name}" end end class Greet3 end def generate_greetings end def greet_generator yield 'Hello' end References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21
You are a code assistant
Definition of 'isSocketNotificationMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp
Definition: export function isSocketNotificationMessage( message: unknown, ): message is SocketNotificationMessage { return ( typeof message === 'object' && message !== null && 'type' in message && typeof message.type === 'string' ); } export function isSocketRequestMessage(message: unknown): message is SocketIoRequestMessage { return ( typeof message === 'object' && message !== null && 'requestId' in message && typeof message.requestId === 'string' && 'type' in message && typeof message.type === 'string' ); } export function isSocketResponseMessage(message: unknown): message is SocketResponseMessage { return ( typeof message === 'object' && message !== null && 'requestId' in message && typeof message.requestId === 'string' ); } References: - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:68
You are a code assistant
Definition of 'TestProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestProcessor()); const invalidInput = { invalid: 'input' }; await expect( pipeline.run({ documentContext: mockContext, input: invalidInput as unknown as StreamingCompletionResponse, type: 'invalid' as 'stream', }), ).rejects.toThrow('Unexpected type in pipeline processing'); }); }); References: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:191
You are a code assistant
Definition of 'LsFetch' in file src/common/fetch.ts in project gitlab-lsp
Definition: export interface LsFetch { initialize(): Promise<void>; destroy(): Promise<void>; fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; get(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; post(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>; } export const LsFetch = createInterfaceId<LsFetch>('LsFetch'); export class FetchBase implements LsFetch { updateRequestInit(method: string, init?: RequestInit): RequestInit { if (typeof init === 'undefined') { // eslint-disable-next-line no-param-reassign init = { method }; } else { // eslint-disable-next-line no-param-reassign init.method = method; } return init; } async initialize(): Promise<void> {} async destroy(): Promise<void> {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return fetch(input, init); } async *streamFetch( /* eslint-disable @typescript-eslint/no-unused-vars */ _url: string, _body: string, _headers: FetchHeaders, /* eslint-enable @typescript-eslint/no-unused-vars */ ): AsyncGenerator<string, void, void> { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References: - src/node/duo_workflow/desktop_workflow_runner.test.ts:22 - src/common/tracking/snowplow/snowplow.ts:48 - src/common/tracking/snowplow_tracker.test.ts:70 - src/common/tracking/snowplow/snowplow.ts:69 - src/common/tracking/snowplow_tracker.ts:150 - src/common/api.test.ts:34 - src/common/api.ts:127 - src/node/duo_workflow/desktop_workflow_runner.ts:53 - src/common/tracking/snowplow/snowplow.ts:57 - src/common/api.ts:135 - src/node/duo_workflow/desktop_workflow_runner.ts:47 - src/common/tracking/snowplow_tracker.ts:159
You are a code assistant
Definition of 'DefaultConfigService' in file src/common/config_service.ts in project gitlab-lsp
Definition: export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/tracking/instance_tracker.test.ts:36 - src/common/tracking/snowplow_tracker.test.ts:75 - src/common/secret_redaction/redactor.test.ts:24 - src/common/core/handlers/initialize_handler.test.ts:20 - src/common/config_service.test.ts:9 - src/common/advanced_context/advanced_context_service.test.ts:41 - src/common/connection.test.ts:49 - src/common/message_handler.test.ts:98 - src/common/suggestion/supported_languages_service.test.ts:12 - src/common/suggestion/suggestion_service.test.ts:462 - src/common/feature_state/project_duo_acces_check.test.ts:30 - src/common/core/handlers/did_change_workspace_folders_handler.test.ts:17 - src/common/suggestion_client/direct_connection_client.test.ts:38 - src/browser/tree_sitter/index.test.ts:17 - src/common/api.test.ts:482 - src/common/feature_state/supported_language_check.test.ts:31 - src/common/suggestion/suggestion_service.test.ts:191 - src/common/api.test.ts:82 - src/common/security_diagnostics_publisher.test.ts:47 - src/node/duo_workflow/desktop_workflow_runner.test.ts:27 - src/common/suggestion/suggestions_cache.test.ts:46 - src/common/suggestion/suggestions_cache.test.ts:43 - src/common/message_handler.test.ts:212 - src/common/config_service.test.ts:6
You are a code assistant
Definition of 'IWorkflowSettings' in file src/common/config_service.ts in project gitlab-lsp
Definition: export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record<string, boolean>; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter<IConfig>; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter<IConfig>; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial<IConfig>): void; } export const ConfigService = createInterfaceId<ConfigService>('ConfigService'); @Injectable(ConfigService, []) export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:73
You are a code assistant
Definition of 'NegativeIndexError' in file packages/lib-pkg-2/src/fast_fibonacci_solver.ts in project gitlab-lsp
Definition: export const NegativeIndexError = new Error('Index must be non-negative'); export class FastFibonacciSolver implements FibonacciSolver { #memo: Map<number, number> = new Map(); #lastComputedIndex: number = 1; constructor() { this.#memo.set(0, 0); this.#memo.set(1, 1); } solve(index: number): number { if (index < 0) { throw NegativeIndexError; } if (this.#memo.has(index)) { return this.#memo.get(index) as number; } let a = this.#memo.get(this.#lastComputedIndex - 1) as number; let b = this.#memo.get(this.#lastComputedIndex) as number; for (let i = this.#lastComputedIndex + 1; i <= index; i++) { const nextValue = a + b; a = b; b = nextValue; this.#memo.set(i, nextValue); } this.#lastComputedIndex = index; return this.#memo.get(index) as number; } } References:
You are a code assistant
Definition of 'transform' in file src/common/secret_redaction/index.ts in project gitlab-lsp
Definition: transform(context: IDocContext): IDocContext { if (this.#configService.get('client.codeCompletion.enableSecretRedaction')) { return { prefix: this.redactSecrets(context.prefix), suffix: this.redactSecrets(context.suffix), fileRelativePath: context.fileRelativePath, position: context.position, uri: context.uri, languageId: context.languageId, workspaceFolder: context.workspaceFolder, }; } return context; } redactSecrets(raw: string): string { return this.#rules.reduce((redacted: string, rule: IGitleaksRule) => { return this.#redactRuleSecret(redacted, rule); }, raw); } #redactRuleSecret(str: string, rule: IGitleaksRule): string { if (!rule.compiledRegex) return str; if (!this.#keywordHit(rule, str)) { return str; } const matches = [...str.matchAll(rule.compiledRegex)]; return matches.reduce((redacted: string, match: RegExpMatchArray) => { const secret = match[rule.secretGroup ?? 0]; return redacted.replace(secret, '*'.repeat(secret.length)); }, str); } #keywordHit(rule: IGitleaksRule, raw: string) { if (!rule.keywords?.length) { return true; } for (const keyword of rule.keywords) { if (raw.toLowerCase().includes(keyword)) { return true; } } return false; } } References:
You are a code assistant
Definition of 'LspClient' in file src/tests/int/lsp_client.ts in project gitlab-lsp
Definition: export class LspClient { #childProcess: ChildProcessWithoutNullStreams; #connection: MessageConnection; #gitlabToken: string; #gitlabBaseUrl: string = 'https://gitlab.com'; public childProcessConsole: string[] = []; /** * Spawn language server and create an RPC connection. * * @param gitlabToken GitLab PAT to use for code suggestions */ constructor(gitlabToken: string) { this.#gitlabToken = gitlabToken; const command = process.env.LSP_COMMAND ?? 'node'; const args = process.env.LSP_ARGS?.split(' ') ?? ['./out/node/main-bundle.js', '--stdio']; console.log(`Running LSP using command \`${command} ${args.join(' ')}\` `); const file = command === 'node' ? args[0] : command; expect(file).not.toBe(undefined); expect({ file, exists: fs.existsSync(file) }).toEqual({ file, exists: true }); this.#childProcess = spawn(command, args); this.#childProcess.stderr.on('data', (chunk: Buffer | string) => { const chunkString = chunk.toString('utf8'); this.childProcessConsole = this.childProcessConsole.concat(chunkString.split('\n')); process.stderr.write(chunk); }); // Use stdin and stdout for communication: this.#connection = createMessageConnection( new StreamMessageReader(this.#childProcess.stdout), new StreamMessageWriter(this.#childProcess.stdin), ); this.#connection.listen(); this.#connection.onError(function (err) { console.error(err); expect(err).not.toBeTruthy(); }); } /** * Make sure to call this method to shutdown the LS rpc connection */ public dispose() { this.#connection.end(); } /** * Send the LSP 'initialize' message. * * @param initializeParams Provide custom values that override defaults. Merged with defaults. * @returns InitializeResponse object */ public async sendInitialize( initializeParams?: CustomInitializeParams, ): Promise<InitializeResult> { const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams }; const request = new RequestType<InitializeParams, InitializeResult, InitializeError>( 'initialize', ); const response = await this.#connection.sendRequest(request, params); return response; } /** * Send the LSP 'initialized' notification */ public async sendInitialized(options?: InitializedParams | undefined): Promise<void> { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType<InitializedParams>('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise<void> { const defaults = createFakePartial<ChangeConfigOptions>({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType<DidChangeConfigurationParams>( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType<DidOpenTextDocumentParams>('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise<void> { const params = { textDocument: { uri, }, }; const request = new NotificationType<DidCloseTextDocumentParams>('textDocument/didClose'); await this.#connection.sendNotification(request, params); } /** * Send LSP 'textDocument/didChange' using Full sync method notification * * @param uri File URL. Should include the workspace path in the url * @param version Change version (incrementing from 0) * @param text Full contents of the file */ public async sendTextDocumentDidChangeFull( uri: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType<DidChangeTextDocumentParams>('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise<CompletionItem[] | CompletionList | null> { const params: CompletionParams = { textDocument: { uri, }, position: { line, character, }, context: { triggerKind: 1, // invoked }, }; const request = new RequestType1< CompletionParams, CompletionItem[] | CompletionList | null, void >('textDocument/completion'); const result = await this.#connection.sendRequest(request, params); return result; } public async sendDidChangeDocumentInActiveEditor(uri: string): Promise<void> { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise<WebviewMetadata[]> { const result = await this.#connection.sendRequest<WebviewMetadata[]>( '$/gitlab/webview-metadata', ); return result; } } References: - src/tests/int/snowplow_tracker.test.ts:7 - src/tests/int/advanced_context.test.ts:6 - src/tests/int/suggestion.test.ts:9 - src/tests/int/lsp_client.test.ts:5 - src/tests/int/webview.test.ts:6 - src/tests/int/test_utils.ts:46 - src/tests/int/advanced_context.test.ts:9 - src/tests/int/tree_sitter_loaded.test.ts:7 - src/tests/int/snowplow_tracker.test.ts:38
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp
Definition: def greet(self): ... class Greet3: ... def greet3(name): class Greet4: def __init__(self, name): def greet(self): class Greet3: References: - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21 - src/tests/fixtures/intent/empty_function/ruby.rb:20
You are a code assistant
Definition of 'WebviewInstanceDestroyedEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: export type WebviewInstanceDestroyedEventData = WebviewAddress; export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo; export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler<T> { (payload: T): void; } export interface TransportListener { on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable; } export interface TransportPublisher { publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void>; } export interface Transport extends TransportListener, TransportPublisher {} References: - packages/lib_webview_transport/src/types.ts:41
You are a code assistant
Definition of 'IStartWorkflowParams' in file src/common/message_handler.ts in project gitlab-lsp
Definition: export interface IStartWorkflowParams { goal: string; image: string; } export const waitMs = (msToWait: number) => new Promise((resolve) => { setTimeout(resolve, msToWait); }); /* CompletionRequest represents LS client's request for either completion or inlineCompletion */ export interface CompletionRequest { textDocument: TextDocumentIdentifier; position: Position; token: CancellationToken; inlineCompletionContext?: InlineCompletionContext; } export class MessageHandler { #configService: ConfigService; #tracker: TelemetryTracker; #connection: Connection; #circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests'); #subscriptions: Disposable[] = []; #duoProjectAccessCache: DuoProjectAccessCache; #featureFlagService: FeatureFlagService; #workflowAPI: WorkflowAPI | undefined; #virtualFileSystemService: VirtualFileSystemService; constructor({ telemetryTracker, configService, connection, featureFlagService, duoProjectAccessCache, virtualFileSystemService, workflowAPI = undefined, }: MessageHandlerOptions) { this.#configService = configService; this.#tracker = telemetryTracker; this.#connection = connection; this.#featureFlagService = featureFlagService; this.#workflowAPI = workflowAPI; this.#subscribeToCircuitBreakerEvents(); this.#virtualFileSystemService = virtualFileSystemService; this.#duoProjectAccessCache = duoProjectAccessCache; } didChangeConfigurationHandler = async ( { settings }: ChangeConfigOptions = { settings: {} }, ): Promise<void> => { this.#configService.merge({ client: settings, }); // update Duo project access cache await this.#duoProjectAccessCache.updateCache({ baseUrl: this.#configService.get('client.baseUrl') ?? '', workspaceFolders: this.#configService.get('client.workspaceFolders') ?? [], }); await this.#virtualFileSystemService.initialize( this.#configService.get('client.workspaceFolders') ?? [], ); }; telemetryNotificationHandler = async ({ category, action, context, }: ITelemetryNotificationParams) => { if (category === CODE_SUGGESTIONS_CATEGORY) { const { trackingId, optionId } = context; if ( trackingId && canClientTrackEvent(this.#configService.get('client.telemetry.actions'), action) ) { switch (action) { case TRACKING_EVENTS.ACCEPTED: if (optionId) { this.#tracker.updateCodeSuggestionsContext(trackingId, { acceptedOption: optionId }); } this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.ACCEPTED); break; case TRACKING_EVENTS.REJECTED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.REJECTED); break; case TRACKING_EVENTS.CANCELLED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.CANCELLED); break; case TRACKING_EVENTS.SHOWN: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.SHOWN); break; case TRACKING_EVENTS.NOT_PROVIDED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.NOT_PROVIDED); break; default: break; } } } }; onShutdownHandler = () => { this.#subscriptions.forEach((subscription) => subscription?.dispose()); }; #subscribeToCircuitBreakerEvents() { this.#subscriptions.push( this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)), ); this.#subscriptions.push( this.#circuitBreaker.onClose(() => this.#connection.sendNotification(API_RECOVERY_NOTIFICATION), ), ); } async #sendWorkflowErrorNotification(message: string) { await this.#connection.sendNotification(WORKFLOW_MESSAGE_NOTIFICATION, { message, type: 'error', }); } startWorkflowNotificationHandler = async ({ goal, image }: IStartWorkflowParams) => { const duoWorkflow = this.#featureFlagService.isClientFlagEnabled( ClientFeatureFlags.DuoWorkflow, ); if (!duoWorkflow) { await this.#sendWorkflowErrorNotification(`The Duo Workflow feature is not enabled`); return; } if (!this.#workflowAPI) { await this.#sendWorkflowErrorNotification('Workflow API is not configured for the LSP'); return; } try { await this.#workflowAPI?.runWorkflow(goal, image); } catch (e) { log.error('Error in running workflow', e); await this.#sendWorkflowErrorNotification(`Error occurred while running workflow ${e}`); } }; } References: - src/common/message_handler.ts:187
You are a code assistant
Definition of 'DefaultVirtualFileSystemService' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp
Definition: export class DefaultVirtualFileSystemService { #directoryWalker: DirectoryWalker; #emitter = new EventEmitter(); constructor(directoryWalker: DirectoryWalker) { this.#directoryWalker = directoryWalker; } #handleFileChange: FileChangeHandler = (event, workspaceFolder, filePath) => { const fileUri = fsPathToUri(filePath); this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFileUpdate, { event, fileUri, workspaceFolder, }); }; async initialize(workspaceFolders: WorkspaceFolder[]): Promise<void> { await Promise.all( workspaceFolders.map(async (workspaceFolder) => { const files = await this.#directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, }); this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFilesUpdate, { files, workspaceFolder, }); this.#directoryWalker.setupFileWatcher(workspaceFolder, this.#handleFileChange); }), ); } #emitFileSystemEvent<T extends VirtualFileSystemEvents>( eventType: T, data: FileSystemEventMap[T], ) { this.#emitter.emit(FILE_SYSTEM_EVENT_NAME, eventType, data); } onFileSystemEvent(listener: FileSystemEventListener) { this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener), }; } } References: - src/common/git/repository_service.ts:30 - src/common/workspace/workspace_service.ts:20 - src/common/git/repository_service.ts:28 - src/common/workspace/workspace_service.ts:26
You are a code assistant
Definition of 'IsManagedEventFilter' in file packages/lib_webview/src/setup/transport/utils/event_filters.ts in project gitlab-lsp
Definition: export type IsManagedEventFilter = <TEvent extends { webviewInstanceId: WebviewInstanceId }>( event: TEvent, ) => boolean; export const createIsManagedFunc = (managedInstances: ManagedInstances): IsManagedEventFilter => <TEvent extends { webviewInstanceId: WebviewInstanceId }>(event: TEvent) => managedInstances.has(event.webviewInstanceId); References: - packages/lib_webview/src/setup/transport/utils/event_filters.ts:9 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.ts:9
You are a code assistant
Definition of 'delete' in file src/common/fetch.ts in project gitlab-lsp
Definition: async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References:
You are a code assistant
Definition of 'TransportPublisher' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: export interface TransportPublisher { publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void>; } export interface Transport extends TransportListener, TransportPublisher {} References:
You are a code assistant
Definition of 'RepositoryMap' in file src/common/git/repository_service.ts in project gitlab-lsp
Definition: type RepositoryMap = Map<RepositoryUri, Repository>; export type RepositoryService = typeof DefaultRepositoryService.prototype; export const RepositoryService = createInterfaceId<RepositoryService>('RepositoryService'); @Injectable(RepositoryService, [VirtualFileSystemService]) export class DefaultRepositoryService { #virtualFileSystemService: DefaultVirtualFileSystemService; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map<WorkspaceFolderUri, RepositoryMap> = new Map(); #workspaceRepositoryTries: Map<WorkspaceFolderUri, RepositoryTrie> = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References: - src/common/git/repository_service.ts:241 - src/common/git/repository_service.ts:175
You are a code assistant
Definition of 'GitLabChatRecordAttributes' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp
Definition: type GitLabChatRecordAttributes = { chunkId?: number | null; type?: ChatRecordType; role: ChatRecordRole; content?: string; contentHtml?: string; requestId?: string; state?: ChatRecordState; errors?: string[]; timestamp?: string; extras?: { sources: object[]; }; }; export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial<GitLabChatRecordAttributes>) { const convertedAttributes = attributes as Partial<GitLabChatRecord>; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:67 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:81
You are a code assistant
Definition of 'AdvancedContextService' in file src/common/advanced_context/advanced_context_service.ts in project gitlab-lsp
Definition: export interface AdvancedContextService {} export const AdvancedContextService = createInterfaceId<AdvancedContextService>('AdvancedContextService'); @Injectable(AdvancedContextService, [ ConfigService, LsConnection, DocumentService, DocumentTransformerService, SupportedLanguagesService, ]) export class DefaultAdvancedContextService implements AdvancedContextService { #configService: ConfigService; #documentTransformer: DocumentTransformerService; #supportedLanguagesService: SupportedLanguagesService; constructor( configService: ConfigService, connection: LsConnection, documentService: DocumentService, documentTransformer: DocumentTransformerService, supportedLanguagesService: SupportedLanguagesService, ) { this.#configService = configService; this.#documentTransformer = documentTransformer; this.#supportedLanguagesService = supportedLanguagesService; const subscription = documentService.onDocumentChange(async ({ document }, handlerType) => { await this.#updateAdvancedContext(document, handlerType); }); connection.onShutdown(() => subscription.dispose()); } /** * Currently updates the LRU cache with the most recently accessed files in the workspace. * We only update the advanced context for supported languages. We also ensure to run * documents through the `DocumentTransformer` to ensure the secret redaction is applied. */ async #updateAdvancedContext( document: TextDocument, handlerType: TextDocumentChangeListenerType, ) { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); // eslint-disable-next-line default-case switch (handlerType) { case TextDocumentChangeListenerType.onDidClose: { // We don't check if the language is supported for `onDidClose` because we want // always attempt to delete the file from the cache. const fileDeleted = lruCache.deleteFile(document.uri); if (fileDeleted) { log.debug(`Advanced Context: File ${document.uri} was deleted from the LRU cache`); } else { log.debug(`Advanced Context: File ${document.uri} was not found in the LRU cache`); } break; } case TextDocumentChangeListenerType.onDidChangeContent: case TextDocumentChangeListenerType.onDidSave: case TextDocumentChangeListenerType.onDidOpen: case TextDocumentChangeListenerType.onDidSetActive: { const languageEnabled = this.#supportedLanguagesService.isLanguageEnabled( document.languageId, ); if (!languageEnabled) { return; } const context = this.#documentTransformer.getContext( document.uri, { line: 0, character: 0 }, this.#configService.get().client.workspaceFolders ?? [], undefined, ); if (!context) { log.debug(`Advanced Context: document context for ${document.uri} was not found`); return; } lruCache.updateFile(context); log.debug(`Advanced Context: uri ${document.uri} was updated in the MRU cache`); break; } } } } References:
You are a code assistant
Definition of 'onApiReconfigured' in file src/common/api.ts in project gitlab-lsp
Definition: onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:
You are a code assistant
Definition of 'TokenCheckResponse' in file src/common/api.ts in project gitlab-lsp
Definition: export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:
You are a code assistant
Definition of 'isEnabled' in file src/common/tracking/tracking_types.ts in project gitlab-lsp
Definition: isEnabled(): boolean; setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker'); References:
You are a code assistant
Definition of 'SimpleFibonacciSolver' in file packages/lib-pkg-1/src/simple_fibonacci_solver.ts in project gitlab-lsp
Definition: export class SimpleFibonacciSolver implements FibonacciSolver { solve(index: number): number { if (index <= 1) return index; return this.solve(index - 1) + this.solve(index - 2); } } References: - packages/webview-chat/src/app/index.ts:10 - packages/lib-pkg-1/src/simple_fibonacci_solver.test.ts:4 - packages/lib-pkg-1/src/simple_fibonacci_solver.test.ts:7
You are a code assistant
Definition of 'warn' in file src/common/log_types.ts in project gitlab-lsp
Definition: warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } export const LOG_LEVEL = { DEBUG: 'debug', INFO: 'info', WARNING: 'warning', ERROR: 'error', } as const; export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL]; References:
You are a code assistant
Definition of 'getStreamingCodeSuggestions' in file src/common/api.ts in project gitlab-lsp
Definition: getStreamingCodeSuggestions(request: CodeSuggestionRequest): AsyncGenerator<string, void, void>; fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>; connectToCable(): Promise<ActionCableCable>; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId<GitLabApiClient>('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:
You are a code assistant
Definition of 'FILE_INFO' in file src/common/test_utils/mocks.ts in project gitlab-lsp
Definition: export const FILE_INFO: IDocContext = { fileRelativePath: 'example.ts', prefix: 'const x = 10;', suffix: 'console.log(x);', position: { line: 0, character: 13, }, uri: 'file:///example.ts', languageId: 'javascript', }; export const CODE_SUGGESTIONS_RESPONSE: CodeSuggestionResponse = { choices: [ { text: 'choice1', uniqueTrackingId: 'ut1' }, { text: 'choice2', uniqueTrackingId: 'ut2' }, ], status: 200, }; export const INITIALIZE_PARAMS: CustomInitializeParams = { clientInfo: { name: 'Visual Studio Code', version: '1.82.0', }, capabilities: { textDocument: { completion: {}, inlineCompletion: {} } }, rootUri: '/', initializationOptions: {}, processId: 1, }; export const EMPTY_COMPLETION_CONTEXT: IDocContext = { prefix: '', suffix: '', fileRelativePath: 'test.js', position: { line: 0, character: 0, }, uri: 'file:///example.ts', languageId: 'javascript', }; export const SHORT_COMPLETION_CONTEXT: IDocContext = { prefix: 'abc', suffix: 'def', fileRelativePath: 'test.js', position: { line: 0, character: 3, }, uri: 'file:///example.ts', languageId: 'typescript', }; export const LONG_COMPLETION_CONTEXT: IDocContext = { prefix: 'abc 123', suffix: 'def 456', fileRelativePath: 'test.js', position: { line: 0, character: 7, }, uri: 'file:///example.ts', languageId: 'typescript', }; const textDocument: TextDocumentIdentifier = { uri: '/' }; const position: Position = { line: 0, character: 0 }; export const COMPLETION_PARAMS: TextDocumentPositionParams = { textDocument, position }; References:
You are a code assistant
Definition of 'AiContextQuery' in file src/common/ai_context_management_2/ai_context_aggregator.ts in project gitlab-lsp
Definition: export type AiContextQuery = { query: string; providerType: 'file'; textDocument?: TextDocument; workspaceFolders: WorkspaceFolder[]; }; @Injectable(AiContextAggregator, [AiFileContextProvider, AiContextPolicyManager]) export class DefaultAiContextAggregator { #AiFileContextProvider: AiFileContextProvider; #AiContextPolicyManager: AiContextPolicyManager; constructor( aiFileContextProvider: AiFileContextProvider, aiContextPolicyManager: AiContextPolicyManager, ) { this.#AiFileContextProvider = aiFileContextProvider; this.#AiContextPolicyManager = aiContextPolicyManager; } async getContextForQuery(query: AiContextQuery): Promise<AiContextItem[]> { switch (query.providerType) { case 'file': { const providerItems = await this.#AiFileContextProvider.getProviderItems( query.query, query.workspaceFolders, ); const contextItems = await Promise.all( providerItems.map((providerItem) => this.#providerItemToContextItem(providerItem)), ); return contextItems; } default: return []; } } async #providerItemToContextItem(providerItem: AiContextProviderItem): Promise<AiContextItem> { if (providerItem.providerType === 'file') { const { fileUri, workspaceFolder, providerType, subType, repositoryFile } = providerItem; const policyResult = await this.#AiContextPolicyManager.runPolicies(providerItem); return { id: fileUri.toString(), isEnabled: policyResult.allowed, info: { project: repositoryFile?.repositoryUri.fsPath, disabledReasons: policyResult.reasons, relFilePath: repositoryFile ? this.#getBasePath(fileUri, parseURIString(workspaceFolder.uri)) : undefined, }, name: Utils.basename(fileUri), type: providerType, subType, }; } throw new Error('Unknown provider type'); } #getBasePath(targetUri: URI, baseUri: URI): string { const targetPath = targetUri.fsPath; const basePath = baseUri.fsPath; return targetPath.replace(basePath, '').replace(/^[/\\]+/, ''); } } References: - src/common/ai_context_management_2/ai_context_aggregator.ts:36 - src/common/connection_service.ts:105
You are a code assistant
Definition of 'constructor' in file src/common/webview/webview_resource_location_service.test.ts in project gitlab-lsp
Definition: constructor(private uri: string) {} getUri(): string { return this.uri; } } describe('WebviewLocationService', () => { let service: WebviewLocationService; const TEST_URI_1 = 'http://example.com'; const TEST_URI_2 = 'file:///foo/bar'; const TEST_WEBVIEW_ID: WebviewId = 'webview-1' as WebviewId; beforeEach(() => { service = new WebviewLocationService(); }); describe('resolveUris', () => { it('should resolve URIs from multiple providers', () => { const provider1 = new MockWebviewUriProvider(TEST_URI_1); const provider2 = new MockWebviewUriProvider(TEST_URI_2); service.register(provider1); service.register(provider2); const uris = service.resolveUris(TEST_WEBVIEW_ID); expect(uris).toEqual([TEST_URI_1, TEST_URI_2]); }); it('should return an empty array if no providers are registered', () => { const uris = service.resolveUris(TEST_WEBVIEW_ID); expect(uris).toEqual([]); }); it('should not register the same provider multiple times', () => { const provider = new MockWebviewUriProvider(TEST_URI_1); service.register(provider); service.register(provider); const uris = service.resolveUris(TEST_WEBVIEW_ID); expect(uris).toEqual([TEST_URI_1]); }); }); }); References:
You are a code assistant
Definition of 'c' in file packages/lib_di/src/index.test.ts in project gitlab-lsp
Definition: c(): string; } const A = createInterfaceId<A>('A'); const B = createInterfaceId<B>('B'); const C = createInterfaceId<C>('C'); @Injectable(A, []) class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId<object>('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance<object>)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) class AImpl2 implements A { a = () => 'hello'; } expect(() => container.instantiate(AImpl, AImpl2)).toThrow( /The following interface IDs were used multiple times 'A' \(classes: AImpl,AImpl2\)/, ); }); it('detects duplicate id with pre-existing instance', () => { const aInstance = new AImpl(); const a = brandInstance(A, aInstance); container.addInstances(a); expect(() => container.instantiate(AImpl)).toThrow(/classes are clashing/); }); it('detects missing dependencies', () => { expect(() => container.instantiate(BImpl)).toThrow( /Class BImpl \(interface B\) depends on interfaces \[A]/, ); }); it('it uses existing instances as dependencies', () => { const aInstance = new AImpl(); const a = brandInstance(A, aInstance); container.addInstances(a); container.instantiate(BImpl); expect(container.get(B).b()).toBe('B(a)'); }); it("detects classes what aren't decorated with @Injectable", () => { class AImpl2 implements A { a = () => 'hello'; } expect(() => container.instantiate(AImpl2)).toThrow( /Classes \[AImpl2] are not decorated with @Injectable/, ); }); it('detects circular dependencies', () => { @Injectable(A, [C]) class ACircular implements A { a = () => 'hello'; constructor(c: C) { // eslint-disable-next-line no-unused-expressions c; } } expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow( /Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./, ); }); // this test ensures that we don't store any references to the classes and we instantiate them only once it('does not instantiate classes from previous instantiate call', () => { let globCount = 0; @Injectable(A, []) class Counter implements A { counter = globCount; constructor() { globCount++; } a = () => this.counter.toString(); } container.instantiate(Counter); container.instantiate(BImpl); expect(container.get(A).a()).toBe('0'); }); }); describe('get', () => { it('returns an instance of the interfaceId', () => { container.instantiate(AImpl); expect(container.get(A)).toBeInstanceOf(AImpl); }); it('throws an error for missing dependency', () => { container.instantiate(); expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/); }); }); }); References: - src/tests/fixtures/intent/ruby_comments.rb:16
You are a code assistant
Definition of 'WebViewInitialStateInterface' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp
Definition: export interface WebViewInitialStateInterface { slashCommands: GitlabChatSlashCommand[]; } export type Messages = CreatePluginMessageMap<{ pluginToWebview: { notifications: { newRecord: Record; updateRecord: Record; setLoadingState: boolean; cleanChat: undefined; }; }; webviewToPlugin: { notifications: { onReady: undefined; cleanChat: undefined; newPrompt: { record: { content: string; }; }; trackFeedback: { data?: { extendedTextFeedback: string | null; feedbackChoices: Array<string> | null; }; }; }; }; pluginToExtension: { notifications: { showErrorMessage: { message: string; }; }; }; }>; References:
You are a code assistant
Definition of 'deleteFile' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp
Definition: deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:
You are a code assistant
Definition of 'success' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: success() { this.#errorCount = 0; this.#close(); } onOpen(listener: () => void): Disposable { this.#eventEmitter.on('open', listener); return { dispose: () => this.#eventEmitter.removeListener('open', listener) }; } onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:
You are a code assistant
Definition of 'DO_NOT_SHOW_CODE_SUGGESTIONS_VERSION_WARNING' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp
Definition: export const DO_NOT_SHOW_CODE_SUGGESTIONS_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits export const MINIMUM_CODE_SUGGESTIONS_VERSION = '16.8.0'; export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits export const MINIMUM_VERSION = '16.1.0'; export const REQUEST_TIMEOUT_MILLISECONDS = 25000; // Webview IDs export const DUO_WORKFLOW_WEBVIEW_ID = 'duo-workflow'; export const DUO_CHAT_WEBVIEW_ID = 'chat'; References:
You are a code assistant
Definition of 'AiContextManager' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp
Definition: export const AiContextManager = createInterfaceId<AiContextManager>('AiContextManager'); @Injectable(AiContextManager, [AiContextFileRetriever]) export class DefaultAiContextManager { #fileRetriever: AiContextFileRetriever; constructor(fileRetriever: AiContextFileRetriever) { this.#fileRetriever = fileRetriever; } #items: Map<string, AiContextItem> = new Map(); addItem(item: AiContextItem): boolean { if (this.#items.has(item.id)) { return false; } this.#items.set(item.id, item); return true; } removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise<AiContextItemWithContent[]> { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References: - src/common/connection_service.ts:67 - src/common/connection_service.ts:57
You are a code assistant
Definition of 'CreateWorkflowResponse' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp
Definition: interface CreateWorkflowResponse { id: string; } const DuoWorkflowAPIService = createInterfaceId<WorkflowAPI>('WorkflowAPI'); @Injectable(DuoWorkflowAPIService, [ConfigService, LsFetch, GitLabApiClient]) export class DesktopWorkflowRunner implements WorkflowAPI { #dockerSocket?: string; #folders?: WorkspaceFolder[]; #fetch: LsFetch; #api: GitLabApiClient; #projectPath: string | undefined; constructor(configService: ConfigService, fetch: LsFetch, api: GitLabApiClient) { this.#fetch = fetch; this.#api = api; configService.onConfigChange((config) => this.#reconfigure(config)); } #reconfigure(config: IConfig) { this.#dockerSocket = config.client.duoWorkflowSettings?.dockerSocket; this.#folders = config.client.workspaceFolders || []; this.#projectPath = config.client.projectPath; } async runWorkflow(goal: string, image: string): Promise<string> { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise<string> { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise<void> { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise<void> { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise<string> { const response = await this.#api?.fetchFromApi<CreateWorkflowResponse>({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise<GenerateTokenResponse> { const token = await this.#api?.fetchFromApi<GenerateTokenResponse>({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References:
You are a code assistant
Definition of 'account' in file packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts in project gitlab-lsp
Definition: export const account: Account = { username: 'foobar', id: 'foobar', type: 'token', instanceUrl: 'gitlab-instance.xx', token: 'foobar-token', }; export const createFakeCable = () => createFakePartial<Cable>({ subscribe: jest.fn(), disconnect: jest.fn(), }); export const gitlabPlatformForAccount: GitLabPlatformForAccount = { type: 'account', account, project: undefined, fetchFromApi: createFakeFetchFromApi(), connectToCable: async () => createFakeCable(), getUserAgentHeader: () => ({}), }; References:
You are a code assistant
Definition of 'isEnabled' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp
Definition: isEnabled(): boolean { return Boolean(this.#options.enabled); } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ) { if (this.#circuitBreaker.isOpen()) { return; } const { language, isStreaming } = context; // Only auto-reject if client is set up to track accepted and not rejected events. if ( canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) && !canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED) ) { this.rejectOpenedSuggestions(); } setTimeout(() => { if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) { this.#codeSuggestionsContextMap.delete(uniqueTrackingId); this.#codeSuggestionStates.delete(uniqueTrackingId); } }, GC_TIME); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { is_streaming: isStreaming, language, timestamp: new Date().toISOString(), }); if (this.#isStreamingSuggestion(uniqueTrackingId)) return; this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`); } async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`, ); // Allow state to update to ACCEPTED despite 'allowed transitions' constraint. if (newState !== TRACKING_EVENTS.ACCEPTED) { return; } log.debug( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:
You are a code assistant
Definition of 'Logger' in file packages/lib_logging/src/types.ts in project gitlab-lsp
Definition: export interface Logger { debug(e: Error): void; debug(message: string, e?: Error): void; info(e: Error): void; info(message: string, e?: Error): void; warn(e: Error): void; warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } References: - packages/lib_logging/src/utils/with_prefix.ts:5 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:35 - src/common/graphql/workflow/service.test.ts:16 - packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.test.ts:7 - packages/webview_duo_chat/src/plugin/port/log.ts:3 - packages/lib_webview/src/setup/transport/setup_transport.ts:38 - src/common/webview/extension/extension_connection_message_bus_provider.ts:32 - src/node/setup_http.ts:24 - src/common/webview/extension/handlers/handle_request_message.ts:6 - src/common/graphql/workflow/service.ts:16 - packages/lib_webview/src/setup/transport/setup_transport.ts:11 - packages/lib_webview/src/setup/plugin/webview_controller.ts:35 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:44 - src/common/graphql/workflow/service.ts:18 - src/common/webview/extension/extension_connection_message_bus_provider.ts:18 - src/common/webview/extension/handlers/handle_notification_message.ts:6 - packages/lib_webview/src/setup/setup_webview_runtime.ts:14 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:38 - packages/lib_webview_client/src/bus/resolve_message_bus.ts:8 - packages/lib_webview_client/src/bus/resolve_message_bus.ts:31 - src/node/setup_http.ts:13 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:30 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:36 - packages/lib_logging/src/utils/with_prefix.test.ts:5 - src/common/webview/extension/extension_connection_message_bus_provider.test.ts:10 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:52 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:69 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:28 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:32 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:12 - packages/lib_webview/src/setup/plugin/webview_controller.ts:41
You are a code assistant
Definition of 'hasListeners' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp
Definition: public hasListeners<K extends keyof TMessageMap>(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount<K extends keyof TMessageMap>(messageType: K): number { return this.#subscriptions.get(messageType)?.size ?? 0; } public clear(): void { this.#subscriptions.clear(); } public dispose(): void { this.clear(); } } References:
You are a code assistant
Definition of 'setupTransports' in file packages/lib_webview/src/setup/transport/setup_transport.ts in project gitlab-lsp
Definition: export const setupTransports = ( transports: Transport[], runtimeMessageBus: WebviewRuntimeMessageBus, logger: Logger, ): Disposable => { logger.debug(`Setting up ${transports.length} transports`); const disposables = transports.map((transport) => setupTransport(transport, runtimeMessageBus, logger), ); return { dispose: () => { logger.debug(`Disposing ${disposables.length} transports`); for (const disposable of disposables) { disposable.dispose(); } logger.debug('All transports disposed'); }, }; }; References: - packages/lib_webview/src/setup/setup_webview_runtime.ts:23
You are a code assistant
Definition of 'AdvancedContextResolverFactory' in file src/common/advanced_context/advanced_context_factory.ts in project gitlab-lsp
Definition: type AdvancedContextResolverFactory = () => AdvancedContextResolver; const advancedContextResolverFactories: AdvancedContextResolverFactory[] = [ OpenTabsResolver.getInstance, ]; export const getAdvancedContext = async ({ documentContext, dependencies: { duoProjectAccessChecker }, }: { documentContext: IDocContext; dependencies: { duoProjectAccessChecker: DuoProjectAccessChecker }; }): Promise<ContextResolution[]> => { try { const resolvers = advancedContextResolverFactories.map((factory) => factory()); const resolutions: ContextResolution[] = []; for (const resolver of resolvers) { // eslint-disable-next-line no-await-in-loop for await (const resolution of resolver.buildContext({ documentContext })) { resolutions.push(resolution); } } const filteredResolutions = await filterContextResolutions({ contextResolutions: resolutions, documentContext, dependencies: { duoProjectAccessChecker }, byteSizeLimit: CODE_SUGGESTIONS_REQUEST_BYTE_SIZE_LIMIT, }); log.debug(`Advanced Context Factory: using ${filteredResolutions.length} context resolutions `); return filteredResolutions; } catch (e) { log.error('Advanced Context: Error while getting advanced context', e); return []; } }; /** * Maps `ContextResolution` to the request body format `AdditionalContext`. * Note: We intentionally keep these two separate to avoid coupling the request body * format to the advanced context resolver internal data. */ export function advancedContextToRequestBody( advancedContext: ContextResolution[], ): AdditionalContext[] { return advancedContext.map((ac) => ({ type: ac.type, name: ac.fileRelativePath, content: ac.content, resolution_strategy: ac.strategy, })); } References:
You are a code assistant
Definition of 'notNullOrUndefined' in file src/common/utils/not_null_or_undefined.ts in project gitlab-lsp
Definition: export function notNullOrUndefined<T>(value: T | null | undefined): value is T { return value !== null && value !== undefined; } References: - src/common/utils/create_query_string.ts:8
You are a code assistant
Definition of 'BaseRestRequest' in file src/common/api_types.ts in project gitlab-lsp
Definition: interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; headers?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record<string, unknown>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'POST'; body?: unknown; } /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'GET'; searchParams?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:
You are a code assistant
Definition of 'sendTextDocumentDidChangeFull' in file src/tests/int/lsp_client.ts in project gitlab-lsp
Definition: public async sendTextDocumentDidChangeFull( uri: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType<DidChangeTextDocumentParams>('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise<CompletionItem[] | CompletionList | null> { const params: CompletionParams = { textDocument: { uri, }, position: { line, character, }, context: { triggerKind: 1, // invoked }, }; const request = new RequestType1< CompletionParams, CompletionItem[] | CompletionList | null, void >('textDocument/completion'); const result = await this.#connection.sendRequest(request, params); return result; } public async sendDidChangeDocumentInActiveEditor(uri: string): Promise<void> { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise<WebviewMetadata[]> { const result = await this.#connection.sendRequest<WebviewMetadata[]>( '$/gitlab/webview-metadata', ); return result; } } References:
You are a code assistant
Definition of 'clear' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp
Definition: public clear(): void { this.#subscriptions.clear(); } public dispose(): void { this.clear(); } } References:
You are a code assistant
Definition of 'handleWebviewCreated' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp
Definition: export const handleWebviewCreated = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceCreatedEventData, logger, (message) => { messageEmitter.emit('webview_instance_created', message); }); export const handleWebviewDestroyed = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceDestroyedEventData, logger, (message) => { messageEmitter.emit('webview_instance_destroyed', message); }); export const handleWebviewMessage = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceMessageEventData, logger, (message) => { messageEmitter.emit('webview_instance_notification_received', message); }); export type JsonRpcConnectionTransportProps = { connection: Connection; logger: Logger; notificationRpcMethod?: string; webviewCreatedRpcMethod?: string; webviewDestroyedRpcMethod?: string; }; export class JsonRpcConnectionTransport implements Transport { #messageEmitter = createWebviewTransportEventEmitter(); #connection: Connection; #notificationChannel: string; #webviewCreatedChannel: string; #webviewDestroyedChannel: string; #logger?: Logger; #disposables: Disposable[] = []; constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void> { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:91
You are a code assistant
Definition of 'init' in file src/common/notifier.ts in project gitlab-lsp
Definition: init(notify: NotifyFn<T>): void; } References:
You are a code assistant
Definition of 'DEFAULT_INITIAL_BACKOFF_MS' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: export const DEFAULT_INITIAL_BACKOFF_MS = 1000; export const DEFAULT_MAX_BACKOFF_MS = 60000; export const DEFAULT_BACKOFF_MULTIPLIER = 2; export interface ExponentialBackoffCircuitBreakerOptions { maxErrorsBeforeBreaking?: number; initialBackoffMs?: number; maxBackoffMs?: number; backoffMultiplier?: number; } export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } success() { this.#errorCount = 0; this.#close(); } onOpen(listener: () => void): Disposable { this.#eventEmitter.on('open', listener); return { dispose: () => this.#eventEmitter.removeListener('open', listener) }; } onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:
You are a code assistant
Definition of 'GitLabApiClient' in file src/common/api.ts in project gitlab-lsp
Definition: export interface GitLabApiClient { checkToken(token: string | undefined): Promise<TokenCheckResponse>; getCodeSuggestions(request: CodeSuggestionRequest): Promise<CodeSuggestionResponse | undefined>; getStreamingCodeSuggestions(request: CodeSuggestionRequest): AsyncGenerator<string, void, void>; fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>; connectToCable(): Promise<ActionCableCable>; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId<GitLabApiClient>('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/feature_flags.ts:49 - src/common/connection.ts:23 - packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:12 - src/common/tracking/snowplow_tracker.ts:133 - src/common/suggestion_client/default_suggestion_client.test.ts:20 - src/common/suggestion_client/direct_connection_client.test.ts:23 - src/common/suggestion/streaming_handler.test.ts:30 - src/common/suggestion_client/direct_connection_client.ts:54 - src/common/tracking/snowplow_tracker.ts:162 - packages/webview_duo_chat/src/plugin/chat_platform.ts:16 - src/node/duo_workflow/desktop_workflow_runner.ts:49 - src/common/graphql/workflow/service.ts:14 - src/common/tracking/instance_tracker.ts:31 - src/common/feature_flags.test.ts:12 - src/common/core/handlers/token_check_notifier.ts:14 - src/node/duo_workflow/desktop_workflow_runner.ts:53 - src/common/suggestion/streaming_handler.ts:36 - src/common/core/handlers/token_check_notifier.test.ts:7 - packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:10 - src/common/suggestion/suggestion_service.ts:119 - packages/webview_duo_chat/src/plugin/index.ts:9 - src/common/suggestion_client/direct_connection_client.ts:28 - src/common/suggestion/suggestion_service.ts:79 - packages/webview_duo_chat/src/plugin/chat_platform.ts:14 - src/common/feature_flags.ts:43 - src/common/graphql/workflow/service.test.ts:15 - src/common/suggestion_client/default_suggestion_client.ts:8 - src/common/services/duo_access/project_access_cache.ts:94 - src/common/suggestion_client/default_suggestion_client.ts:6 - src/common/graphql/workflow/service.ts:18 - src/common/tracking/instance_tracker.ts:51
You are a code assistant
Definition of 'ExtensionMessage' in file src/common/webview/extension/utils/extension_message.ts in project gitlab-lsp
Definition: export type ExtensionMessage = { webviewId: WebviewId; type: string; payload: unknown; }; export const isExtensionMessage = (message: unknown): message is ExtensionMessage => { return ( typeof message === 'object' && message !== null && 'webviewId' in message && 'type' in message ); }; References:
You are a code assistant
Definition of 'Greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp
Definition: class Greet3: References: - src/tests/fixtures/intent/empty_function/ruby.rb:34
You are a code assistant
Definition of 'rejectOpenedSuggestions' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp
Definition: rejectOpenedSuggestions() { log.debug(`Snowplow Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } #hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null { const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextFeatureFlagsEnabled) { return Boolean(advancedContexts?.length); } return null; } #getAdvancedContextData({ additionalContexts, documentContext, }: { additionalContexts?: AdditionalContext[]; documentContext?: IDocContext; }) { const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts); const contentAboveCursorSizeBytes = documentContext?.prefix ? getByteSize(documentContext.prefix) : 0; const contentBelowCursorSizeBytes = documentContext?.suffix ? getByteSize(documentContext.suffix) : 0; const contextItems: ContextItem[] | null = additionalContexts?.map((item) => ({ file_extension: item.name.split('.').pop() || '', type: item.type, resolution_strategy: item.resolution_strategy, byte_size: item?.content ? getByteSize(item.content) : 0, })) ?? null; const totalContextSizeBytes = contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0; return { totalContextSizeBytes, contentAboveCursorSizeBytes, contentBelowCursorSizeBytes, contextItems, hasAdvancedContext, }; } static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null { let isInvoked = null; if (triggerKind === InlineCompletionTriggerKind.Invoked) { isInvoked = true; } else if (triggerKind === InlineCompletionTriggerKind.Automatic) { isInvoked = false; } return isInvoked; } } References:
You are a code assistant
Definition of 'DefaultConnectionService' in file src/common/connection_service.ts in project gitlab-lsp
Definition: export class DefaultConnectionService implements ConnectionService { #connection: LsConnection; #aiContextAggregator: AiContextAggregator; #aiContextManager: AiContextManager; constructor( connection: LsConnection, tokenCheckNotifier: TokenCheckNotifier, initializeHandler: InitializeHandler, didChangeWorkspaceFoldersHandler: DidChangeWorkspaceFoldersHandler, securityDiagnosticsPublisher: SecurityDiagnosticsPublisher, documentService: DocumentService, aiContextAggregator: AiContextAggregator, aiContextManager: AiContextManager, featureStateManager: FeatureStateManager, ) { this.#connection = connection; this.#aiContextAggregator = aiContextAggregator; this.#aiContextManager = aiContextManager; // request handlers connection.onInitialize(initializeHandler.requestHandler); // notifiers this.#initializeNotifier(TokenCheckNotificationType, tokenCheckNotifier); this.#initializeNotifier(FeatureStateChangeNotificationType, featureStateManager); // notification handlers connection.onNotification(DidChangeDocumentInActiveEditor, documentService.notificationHandler); connection.onNotification( DidChangeWorkspaceFoldersNotification.method, didChangeWorkspaceFoldersHandler.notificationHandler, ); // diagnostics publishers this.#initializeDiagnosticsPublisher(securityDiagnosticsPublisher); // custom handlers this.#setupAiContextHandlers(); } #initializeNotifier<T>(method: NotificationType<T>, notifier: Notifier<T>) { notifier.init(createNotifyFn(this.#connection, method)); } #initializeDiagnosticsPublisher(publisher: DiagnosticsPublisher) { publisher.init(createDiagnosticsPublisherFn(this.#connection)); } #setupAiContextHandlers() { this.#connection.onRequest('$/gitlab/ai-context/query', async (query: AiContextQuery) => { log.info(`recieved search query ${JSON.stringify(query)}`); const results = await this.#aiContextAggregator.getContextForQuery(query); log.info(`got back ${results.length}`); return results; }); this.#connection.onRequest('$/gitlab/ai-context/add', async (item: AiContextItem) => { log.info(`recieved context item add request ${JSON.stringify(item)}`); return this.#aiContextManager.addItem(item); }); this.#connection.onRequest('$/gitlab/ai-context/remove', async (id: string) => { log.info(`recieved context item add request ${JSON.stringify(id)}`); return this.#aiContextManager.removeItem(id); }); this.#connection.onRequest('$/gitlab/ai-context/current-items', async () => { const currentItems = this.#aiContextManager.currentItems(); log.info(`returning ${currentItems.length} current items`); return currentItems; }); this.#connection.onRequest('$/gitlab/ai-context/retrieve', async () => { const items = await this.#aiContextManager.retrieveItems(); log.info(`retrieved ${items.length} current items`); return items; }); } } References:
You are a code assistant
Definition of 'WebviewPlugin' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp
Definition: export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep<PluginMessageMap> = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc<CreatePluginMessageMap<TWebviewPluginMessageMap>>; }; References: - src/common/webview/webview_metadata_provider.test.ts:37 - src/common/webview/webview_metadata_provider.test.ts:42
You are a code assistant
Definition of 'constructor' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp
Definition: constructor(duoProjectPolicy: DuoProjectPolicy) { this.#policies.push(duoProjectPolicy); } async runPolicies(aiContextProviderItem: AiContextProviderItem) { const results = await Promise.all( this.#policies.map(async (policy) => { return policy.isAllowed(aiContextProviderItem); }), ); const disallowedResults = results.filter((result) => !result.allowed); if (disallowedResults.length > 0) { const reasons = disallowedResults.map((result) => result.reason).filter(Boolean); return { allowed: false, reasons: reasons as string[] }; } return { allowed: true }; } } References:
You are a code assistant
Definition of 'init' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp
Definition: init(callback: DiagnosticsPublisherFn): void { this.#publish = callback; } async #runSecurityScan(document: TextDocument) { try { if (!this.#publish) { throw new Error('The DefaultSecurityService has not been initialized. Call init first.'); } if (!this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.RemoteSecurityScans)) { return; } if (!this.#opts?.enabled) { return; } if (!this.#opts) { return; } const url = this.#opts.serviceUrl ?? DEFAULT_SCANNER_SERVICE_URL; if (url === '') { return; } const content = document.getText(); const fileName = UriUtils.basename(URI.parse(document.uri)); const formData = new FormData(); const blob = new Blob([content]); formData.append('file', blob, fileName); const request = { method: 'POST', headers: { Accept: 'application/json', }, body: formData, }; log.debug(`Executing request to url="${url}" with contents of "${fileName}"`); const response = await fetch(url, request); await handleFetchError(response, 'security scan'); const json = await response.json(); const { vulnerabilities: vulns } = json; if (vulns == null || !Array.isArray(vulns)) { return; } const diagnostics: Diagnostic[] = vulns.map((vuln: Vulnerability) => { let message = `${vuln.name}\n\n${vuln.description.substring(0, 200)}`; if (vuln.description.length > 200) { message += '...'; } const severity = vuln.severity === 'high' ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning; // TODO: Use a more precise range when it's available from the service. return { message, range: { start: { line: vuln.location.start_line - 1, character: 0, }, end: { line: vuln.location.end_line, character: 0, }, }, severity, source: 'gitlab_security_scan', }; }); await this.#publish({ uri: document.uri, diagnostics, }); } catch (error) { log.warn('SecurityScan: failed to run security scan', error); } } } References:
You are a code assistant
Definition of 'handleWorkspaceFileUpdate' in file src/common/git/repository_service.ts in project gitlab-lsp
Definition: async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:
You are a code assistant
Definition of 'RequestMap' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'sendRequest' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: sendRequest<T extends keyof TMessages['outbound']['requests'] & string>( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise<ExtractRequestResult<TMessages['outbound']['requests'][T]>> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult<TMessages['outbound']['requests'][T]>) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification<T extends keyof TMessages['inbound']['notifications'] & string>( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest<T extends keyof TMessages['inbound']['requests'] & string>( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise<ExtractRequestResult<TMessages['inbound']['requests'][T]>>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:
You are a code assistant
Definition of 'SuggestionOptionOrStream' in file src/common/api.ts in project gitlab-lsp
Definition: export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/utils/suggestion_mappers.ts:13 - src/common/utils/suggestion_mappers.ts:15
You are a code assistant
Definition of 'TreeSitterLanguageName' in file src/common/tree_sitter/languages.ts in project gitlab-lsp
Definition: export type TreeSitterLanguageName = | 'bash' | 'c' | 'cpp' | 'c_sharp' | 'css' | 'go' | 'html' | 'java' | 'javascript' | 'json' | 'kotlin' | 'powershell' | 'python' | 'ruby' | 'rust' | 'scala' | 'typescript' | 'tsx' | 'vue' | 'yaml'; export interface TreeSitterLanguageInfo { name: TreeSitterLanguageName; extensions: string[]; wasmPath: string; nodeModulesPath?: string; } References: - src/common/tree_sitter/comments/comment_resolver.ts:53 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:15 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:125 - src/common/tree_sitter/comments/comment_resolver.ts:25 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:44 - src/common/tree_sitter/comments/comment_resolver.ts:140 - src/common/tree_sitter/comments/comment_resolver.test.ts:242 - src/common/tree_sitter/languages.ts:24
You are a code assistant
Definition of 'ISnowplowClientContext' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp
Definition: interface ISnowplowClientContext { schema: string; data: { ide_name?: string | null; ide_vendor?: string | null; ide_version?: string | null; extension_name?: string | null; extension_version?: string | null; language_server_version?: string | null; }; } const DEFAULT_SNOWPLOW_OPTIONS = { appId: 'gitlab_ide_extension', timeInterval: 5000, maxItems: 10, }; export const EVENT_VALIDATION_ERROR_MSG = `Telemetry event context is not valid - event won't be tracked.`; export class SnowplowTracker implements TelemetryTracker { #snowplow: Snowplow; #ajv = new Ajv({ strict: false }); #configService: ConfigService; #api: GitLabApiClient; #options: ITelemetryOptions = { enabled: true, baseUrl: SAAS_INSTANCE_URL, trackingUrl: DEFAULT_TRACKING_ENDPOINT, // the list of events that the client can track themselves actions: [], }; #clientContext: ISnowplowClientContext = { schema: 'iglu:com.gitlab/ide_extension_version/jsonschema/1-1-0', data: {}, }; #codeSuggestionStates = new Map<string, TRACKING_EVENTS>(); #lsFetch: LsFetch; #featureFlagService: FeatureFlagService; #gitlabRealm: GitlabRealm = GitlabRealm.saas; #codeSuggestionsContextMap = new Map<string, ISnowplowCodeSuggestionContext>(); constructor( lsFetch: LsFetch, configService: ConfigService, featureFlagService: FeatureFlagService, api: GitLabApiClient, ) { this.#configService = configService; this.#configService.onConfigChange((config) => this.#reconfigure(config)); this.#api = api; const trackingUrl = DEFAULT_TRACKING_ENDPOINT; this.#lsFetch = lsFetch; this.#configService = configService; this.#featureFlagService = featureFlagService; this.#snowplow = Snowplow.getInstance(this.#lsFetch, { ...DEFAULT_SNOWPLOW_OPTIONS, endpoint: trackingUrl, enabled: this.isEnabled.bind(this), }); this.#options.trackingUrl = trackingUrl; this.#ajv.addMetaSchema(SnowplowMetaSchema); } isEnabled(): boolean { return Boolean(this.#options.enabled); } async #reconfigure(config: IConfig) { const { baseUrl } = config.client; const trackingUrl = config.client.telemetry?.trackingUrl; const enabled = config.client.telemetry?.enabled; const actions = config.client.telemetry?.actions; if (typeof enabled !== 'undefined') { this.#options.enabled = enabled; if (enabled === false) { log.warn(`Snowplow Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`); } else if (enabled === true) { log.info(`Snowplow Telemetry: ${TELEMETRY_ENABLED_MSG}`); } } if (baseUrl) { this.#options.baseUrl = baseUrl; this.#gitlabRealm = baseUrl.endsWith(SAAS_INSTANCE_URL) ? GitlabRealm.saas : GitlabRealm.selfManaged; } if (trackingUrl && this.#options.trackingUrl !== trackingUrl) { await this.#snowplow.stop(); this.#snowplow.destroy(); this.#snowplow = Snowplow.getInstance(this.#lsFetch, { ...DEFAULT_SNOWPLOW_OPTIONS, endpoint: trackingUrl, enabled: this.isEnabled.bind(this), }); } if (actions) { this.#options.actions = actions; } this.#setClientContext({ extension: config.client.telemetry?.extension, ide: config.client.telemetry?.ide, }); } #setClientContext(context: IClientContext) { this.#clientContext.data = { ide_name: context?.ide?.name ?? null, ide_vendor: context?.ide?.vendor ?? null, ide_version: context?.ide?.version ?? null, extension_name: context?.extension?.name ?? null, extension_version: context?.extension?.version ?? null, language_server_version: lsVersion ?? null, }; } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ) { const { documentContext, source = SuggestionSource.network, language, isStreaming, triggerKind, optionsCount, additionalContexts, isDirectConnection, } = context; const { gitlab_instance_id, gitlab_global_user_id, gitlab_host_name, gitlab_saas_duo_pro_namespace_ids, } = this.#configService.get('client.snowplowTrackerOptions') ?? {}; if (source === SuggestionSource.cache) { log.debug(`Snowplow Telemetry: Retrieved suggestion from cache`); } else { log.debug(`Snowplow Telemetry: Received request to create a new suggestion`); } // Only auto-reject if client is set up to track accepted and not rejected events. if ( canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) && !canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED) ) { this.rejectOpenedSuggestions(); } setTimeout(() => { if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) { this.#codeSuggestionsContextMap.delete(uniqueTrackingId); this.#codeSuggestionStates.delete(uniqueTrackingId); } }, GC_TIME); const advancedContextData = this.#getAdvancedContextData({ additionalContexts, documentContext, }); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { schema: 'iglu:com.gitlab/code_suggestions_context/jsonschema/3-5-0', data: { suffix_length: documentContext?.suffix.length ?? 0, prefix_length: documentContext?.prefix.length ?? 0, gitlab_realm: this.#gitlabRealm, model_engine: null, model_name: null, language: language ?? null, api_status_code: null, debounce_interval: source === SuggestionSource.cache ? 0 : SUGGESTIONS_DEBOUNCE_INTERVAL_MS, suggestion_source: source, gitlab_global_user_id: gitlab_global_user_id ?? null, gitlab_host_name: gitlab_host_name ?? null, gitlab_instance_id: gitlab_instance_id ?? null, gitlab_saas_duo_pro_namespace_ids: gitlab_saas_duo_pro_namespace_ids ?? null, gitlab_instance_version: this.#api.instanceVersion ?? null, is_streaming: isStreaming ?? false, is_invoked: SnowplowTracker.#isCompletionInvoked(triggerKind), options_count: optionsCount ?? null, has_advanced_context: advancedContextData.hasAdvancedContext, is_direct_connection: isDirectConnection ?? null, total_context_size_bytes: advancedContextData.totalContextSizeBytes, content_above_cursor_size_bytes: advancedContextData.contentAboveCursorSizeBytes, content_below_cursor_size_bytes: advancedContextData.contentBelowCursorSizeBytes, context_items: advancedContextData.contextItems, }, }); this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Snowplow Telemetry: Could not track telemetry', e), ); log.debug(`Snowplow Telemetry: New suggestion ${uniqueTrackingId} has been requested`); } // FIXME: the set and update context methods have similar logic and they should have to grow linearly with each new attribute // the solution might be some generic update method used by both public updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ) { const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate; if (context) { if (model) { context.data.language = model.lang ?? null; context.data.model_engine = model.engine ?? null; context.data.model_name = model.name ?? null; context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null; context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null; context.data.context_tokens_sent = model.tokens_consumption_metadata?.context_tokens_sent ?? null; context.data.context_tokens_used = model.tokens_consumption_metadata?.context_tokens_used ?? null; } if (status) { context.data.api_status_code = status; } if (optionsCount) { context.data.options_count = optionsCount; } if (isDirectConnection !== undefined) { context.data.is_direct_connection = isDirectConnection; } if (acceptedOption) { context.data.accepted_option = acceptedOption; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { if (!this.isEnabled()) { return; } const event: StructuredEvent = { category: CODE_SUGGESTIONS_CATEGORY, action: eventType, label: uniqueTrackingId, }; try { const contexts: SelfDescribingJson[] = [this.#clientContext]; const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId); if (codeSuggestionContext) { contexts.push(codeSuggestionContext); } const suggestionContextValid = this.#ajv.validate( CodeSuggestionContextSchema, codeSuggestionContext?.data, ); if (!suggestionContextValid) { log.warn(EVENT_VALIDATION_ERROR_MSG); log.debug(JSON.stringify(this.#ajv.errors, null, 2)); return; } const ideExtensionContextValid = this.#ajv.validate( IdeExtensionContextSchema, this.#clientContext?.data, ); if (!ideExtensionContextValid) { log.warn(EVENT_VALIDATION_ERROR_MSG); log.debug(JSON.stringify(this.#ajv.errors, null, 2)); return; } await this.#snowplow.trackStructEvent(event, contexts); } catch (error) { log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error); } } public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const isStreaming = Boolean( this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming, ); const allowedTransitions = isStreaming ? streamingSuggestionStateGraph.get(state) : nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `Snowplow Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`, ); // Allow state to update to ACCEPTED despite 'allowed transitions' constraint. if (newState !== TRACKING_EVENTS.ACCEPTED) { return; } log.debug( `Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Snowplow Telemetry: Could not track telemetry', e), ); log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } rejectOpenedSuggestions() { log.debug(`Snowplow Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } #hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null { const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextFeatureFlagsEnabled) { return Boolean(advancedContexts?.length); } return null; } #getAdvancedContextData({ additionalContexts, documentContext, }: { additionalContexts?: AdditionalContext[]; documentContext?: IDocContext; }) { const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts); const contentAboveCursorSizeBytes = documentContext?.prefix ? getByteSize(documentContext.prefix) : 0; const contentBelowCursorSizeBytes = documentContext?.suffix ? getByteSize(documentContext.suffix) : 0; const contextItems: ContextItem[] | null = additionalContexts?.map((item) => ({ file_extension: item.name.split('.').pop() || '', type: item.type, resolution_strategy: item.resolution_strategy, byte_size: item?.content ? getByteSize(item.content) : 0, })) ?? null; const totalContextSizeBytes = contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0; return { totalContextSizeBytes, contentAboveCursorSizeBytes, contentBelowCursorSizeBytes, contextItems, hasAdvancedContext, }; } static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null { let isInvoked = null; if (triggerKind === InlineCompletionTriggerKind.Invoked) { isInvoked = true; } else if (triggerKind === InlineCompletionTriggerKind.Automatic) { isInvoked = false; } return isInvoked; } } References: - src/common/tracking/snowplow_tracker.ts:143