instruction
stringclasses
1 value
input
stringlengths
67
168
output
stringlengths
46
67k
You are a code assistant
Definition of 'sendRequest' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp
Definition: async sendRequest(type: Method, payload?: unknown): Promise<never> { const requestId = generateRequestId(); this.#logger.debug(`Sending request: ${type}, ID: ${requestId}`); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestHandle = this.#pendingResponseEvents.register( requestId, (message: ResponseMessage) => { if (message.success) { resolve(message.payload as PromiseLike<never>); } else { reject(new Error(message.reason)); } clearTimeout(timeout); pendingRequestHandle.dispose(); }, ); this.#runtimeMessageBus.publish('plugin:request', { ...this.#address, requestId, type, payload, }); timeout = setTimeout(() => { pendingRequestHandle.dispose(); this.#logger.debug(`Request with ID: ${requestId} timed out`); reject(new Error('Request timed out')); }, 10000); }); } onRequest(type: Method, handler: Handler): Disposable { return this.#requestEvents.register(type, (requestId: RequestId, payload: unknown) => { try { const result = handler(payload); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: true, payload: result, }); } catch (error) { this.#logger.error(`Error handling request of type ${type}:`, error as Error); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: false, reason: (error as Error).message, }); } }); } dispose(): void { this.#eventSubscriptions.dispose(); this.#notificationEvents.dispose(); this.#requestEvents.dispose(); this.#pendingResponseEvents.dispose(); } } References:
You are a code assistant
Definition of 'getCommentForCursor' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp
Definition: getCommentForCursor({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): CommentResolution | undefined { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return undefined; } const comments = query.captures(tree.rootNode).map((capture) => { return { start: capture.node.startPosition, end: capture.node.endPosition, content: capture.node.text, capture, }; }); const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition); if (commentAtCursor) { // No need to further check for isPositionInNode etc. as cursor is directly on the comment return { commentAtCursor }; } const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition); if (!commentAboveCursor) { return undefined; } const commentParentNode = commentAboveCursor.capture.node.parent; if (!commentParentNode) { return undefined; } if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) { return undefined; } const directChildren = commentParentNode.children; for (const child of directChildren) { const hasNodeBetweenCursorAndComment = child.startPosition.row > commentAboveCursor.capture.node.endPosition.row && child.startPosition.row <= cursorPosition.row; if (hasNodeBetweenCursorAndComment) { return undefined; } } return { commentAboveCursor }; } static #isPositionInNode(position: Point, node: SyntaxNode): boolean { return position.row >= node.startPosition.row && position.row <= node.endPosition.row; } static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter((comment) => comment.end.row < cursorPosition.row), ); } static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter( (comment) => comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row, ), ); } static #getLastComment(comments: Comment[]): Comment | undefined { return comments.sort((a, b) => b.end.row - a.end.row)[0]; } /** * Returns the total number of lines that are comments in a parsed syntax tree. * Uses a Set because we only want to count each line once. * @param {Object} params - Parameters for counting comment lines. * @param {TreeSitterLanguageName} params.languageName - The name of the programming language. * @param {Tree} params.tree - The syntax tree to analyze. * @param {Language} params.treeSitterLanguage - The Tree-sitter language instance. * @returns {number} - The total number of unique lines containing comments. */ getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set<number>(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:
You are a code assistant
Definition of 'streamFetch' in file src/node/fetch.ts in project gitlab-lsp
Definition: async *streamFetch( url: string, body: string, headers: FetchHeaders, ): AsyncGenerator<string, void, void> { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream<Uint8Array>, ): AsyncGenerator<string, void, void> { for await (const chunk of stream) { buffer += decoder.decode(chunk); yield buffer; } } const response: Response = await this.fetch(url, { method: 'POST', headers, body, }); await handleFetchError(response, 'Code Suggestions Streaming'); if (response.body) { // Note: Using (node:stream).ReadableStream as it supports async iterators yield* readStream(response.body as ReadableStream); } } #createHttpsAgent(): https.Agent { const agentOptions = { ...this.#agentOptions, keepAlive: true, }; log.debug( `fetch: https agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(agentOptions), )}.`, ); return new https.Agent(agentOptions); } #createProxyAgent(): ProxyAgent { log.debug( `fetch: proxy agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(this.#agentOptions), )}.`, ); return new ProxyAgent(this.#agentOptions); } async #fetchLogged(input: RequestInfo | URL, init: LsRequestInit): Promise<Response> { const start = Date.now(); const url = this.#extractURL(input); if (init.agent === httpAgent) { log.debug(`fetch: request for ${url} made with http agent.`); } else { const type = init.agent === this.#proxy ? 'proxy' : 'https'; log.debug(`fetch: request for ${url} made with ${type} agent.`); } try { const resp = await fetch(input, init); const duration = Date.now() - start; log.debug(`fetch: request to ${url} returned HTTP ${resp.status} after ${duration} ms`); return resp; } catch (e) { const duration = Date.now() - start; log.debug(`fetch: request to ${url} threw an exception after ${duration} ms`); log.error(`fetch: request to ${url} failed with:`, e); throw e; } } #getAgent(input: RequestInfo | URL): ProxyAgent | https.Agent | http.Agent { if (this.#proxy) { return this.#proxy; } if (input.toString().startsWith('https://')) { return this.#httpsAgent; } return httpAgent; } #extractURL(input: RequestInfo | URL): string { if (input instanceof URL) { return input.toString(); } if (typeof input === 'string') { return input; } return input.url; } #sanitizeAgentOptions(agentOptions: LsAgentOptions) { const { ca, cert, key, ...options } = agentOptions; return { ...options, ...(ca ? { ca: '<hidden>' } : {}), ...(cert ? { cert: '<hidden>' } : {}), ...(key ? { key: '<hidden>' } : {}), }; } } References:
You are a code assistant
Definition of 'getSocketEventHandler' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts in project gitlab-lsp
Definition: function getSocketEventHandler(socket: jest.Mocked<Socket>, eventName: SocketEvents): Function { const [, handler] = socket.on.mock.calls.find((call) => call[0] === eventName)!; return handler; } References: - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:91 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:147 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:129
You are a code assistant
Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { 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:
You are a code assistant
Definition of 'DefaultCodeSuggestionsSupportedLanguageCheck' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp
Definition: export class DefaultCodeSuggestionsSupportedLanguageCheck implements StateCheck { #documentService: DocumentService; #isLanguageEnabled = false; #isLanguageSupported = false; #supportedLanguagesService: SupportedLanguagesService; #currentDocument?: TextDocument; #stateEmitter = new EventEmitter(); constructor( documentService: DocumentService, supportedLanguagesService: SupportedLanguagesService, ) { this.#documentService = documentService; this.#supportedLanguagesService = supportedLanguagesService; this.#documentService.onDocumentChange((event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#updateWithDocument(event.document); } }); this.#supportedLanguagesService.onLanguageChange(() => this.#update()); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } #updateWithDocument(document: TextDocument) { this.#currentDocument = document; this.#update(); } get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References: - src/common/feature_state/supported_language_check.test.ts:50
You are a code assistant
Definition of 'updateCodeSuggestionsContext' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp
Definition: 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 'processCompletion' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestStreamProcessor()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test processed', done: false }); }); test('should process completion input correctly', async () => { class TestCompletionProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { 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:
You are a code assistant
Definition of 'getTotalNonEmptyLines' in file src/common/tree_sitter/small_files.ts in project gitlab-lsp
Definition: function getTotalNonEmptyLines(textContent: string): number { return textContent.split('\n').filter((line) => line.trim() !== '').length; } 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/small_files.ts:7
You are a code assistant
Definition of 'constructor' in file src/common/webview/extension/extension_connection_message_bus_provider.ts in project gitlab-lsp
Definition: constructor({ connection, logger, notificationRpcMethod = DEFAULT_NOTIFICATION_RPC_METHOD, requestRpcMethod = DEFAULT_REQUEST_RPC_METHOD, }: ExtensionConnectionMessageBusProviderProps) { this.#connection = connection; this.#logger = withPrefix(logger, '[ExtensionConnectionMessageBusProvider]'); this.#rpcMethods = { notification: notificationRpcMethod, request: requestRpcMethod, }; this.#handlers = { notification: new ExtensionMessageHandlerRegistry(), request: new ExtensionMessageHandlerRegistry(), }; this.#setupConnectionSubscriptions(); } getMessageBus<T extends MessageMap>(webviewId: WebviewId): MessageBus<T> { return new ExtensionConnectionMessageBus({ webviewId, connection: this.#connection, rpcMethods: this.#rpcMethods, handlers: this.#handlers, }); } dispose(): void { this.#disposables.dispose(); } #setupConnectionSubscriptions() { this.#disposables.add( this.#connection.onNotification( this.#rpcMethods.notification, handleNotificationMessage(this.#notificationHandlers, this.#logger), ), ); this.#disposables.add( this.#connection.onRequest( this.#rpcMethods.request, handleRequestMessage(this.#requestHandlers, this.#logger), ), ); } } References:
You are a code assistant
Definition of 'CompositeDisposable' in file packages/lib_disposable/src/composite_disposable.ts in project gitlab-lsp
Definition: export class CompositeDisposable implements Disposable { #disposables: Set<Disposable> = new Set(); get size() { return this.#disposables.size; } add(...disposables: Disposable[]): void { for (const disposable of disposables) { this.#disposables.add(disposable); } } dispose(): void { for (const disposable of this.#disposables) { disposable.dispose(); } this.#disposables.clear(); } } References: - packages/lib_disposable/src/composite_disposable.test.ts:10 - packages/lib_webview/src/setup/transport/setup_transport.ts:17 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:24 - packages/lib_webview/src/setup/plugin/webview_controller.ts:98 - packages/lib_disposable/src/composite_disposable.test.ts:5 - packages/webview_duo_chat/src/plugin/chat_controller.ts:17 - src/common/webview/extension/extension_connection_message_bus_provider.ts:38 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:22 - packages/lib_webview/src/setup/plugin/webview_controller.ts:17 - packages/lib_webview/src/setup/plugin/webview_controller.ts:33
You are a code assistant
Definition of 'LsTextDocuments' in file src/common/external_interfaces.ts in project gitlab-lsp
Definition: export const LsTextDocuments = createInterfaceId<LsTextDocuments>('LsTextDocuments'); References: - src/common/document_transformer_service.ts:79 - src/common/document_transformer_service.ts:81
You are a code assistant
Definition of 'handle' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp
Definition: async handle(key: TKey, ...args: Parameters<THandler>): Promise<ReturnType<THandler>> { const hash = this.#hashFunc(key); return this.#basicRegistry.handle(hash, ...args); } dispose() { this.#basicRegistry.dispose(); } } References:
You are a code assistant
Definition of 'DefaultDuoProjectAccessCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: 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: - src/common/services/duo_access/project_access_cache.test.ts:157 - src/common/services/duo_access/project_access_cache.test.ts:53 - src/common/services/duo_access/project_access_cache.test.ts:125 - src/common/services/duo_access/project_access_cache.test.ts:88
You are a code assistant
Definition of 'GitLabApiClient' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp
Definition: export interface GitLabApiClient { fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>; connectToCable(): Promise<Cable>; } References: - 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 - 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
You are a code assistant
Definition of 'fetchFromApi' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp
Definition: 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: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11 - packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10
You are a code assistant
Definition of 'CodeSuggestionsSupportedLanguageCheck' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp
Definition: export interface CodeSuggestionsSupportedLanguageCheck extends StateCheck {} export const CodeSuggestionsSupportedLanguageCheck = createInterfaceId<CodeSuggestionsSupportedLanguageCheck>('CodeSuggestionsSupportedLanguageCheck'); @Injectable(CodeSuggestionsSupportedLanguageCheck, [DocumentService, SupportedLanguagesService]) export class DefaultCodeSuggestionsSupportedLanguageCheck implements StateCheck { #documentService: DocumentService; #isLanguageEnabled = false; #isLanguageSupported = false; #supportedLanguagesService: SupportedLanguagesService; #currentDocument?: TextDocument; #stateEmitter = new EventEmitter(); constructor( documentService: DocumentService, supportedLanguagesService: SupportedLanguagesService, ) { this.#documentService = documentService; this.#supportedLanguagesService = supportedLanguagesService; this.#documentService.onDocumentChange((event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#updateWithDocument(event.document); } }); this.#supportedLanguagesService.onLanguageChange(() => this.#update()); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } #updateWithDocument(document: TextDocument) { this.#currentDocument = document; this.#update(); } get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References: - src/common/feature_state/supported_language_check.test.ts:22 - src/common/feature_state/feature_state_manager.ts:28
You are a code assistant
Definition of 'LsConnection' in file src/common/external_interfaces.ts in project gitlab-lsp
Definition: export type LsConnection = Connection; export const LsConnection = createInterfaceId<LsConnection>('LsConnection'); export type LsTextDocuments = TextDocuments<TextDocument>; export const LsTextDocuments = createInterfaceId<LsTextDocuments>('LsTextDocuments'); References: - src/common/advanced_context/advanced_context_service.ts:34 - src/common/connection_service.ts:60 - src/common/connection_service.ts:53 - src/common/connection_service.ts:34 - src/common/connection_service.ts:38
You are a code assistant
Definition of 'AccountBase' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp
Definition: 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 'EnabledCallback' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp
Definition: export type EnabledCallback = () => boolean; export type SnowplowOptions = { appId: string; endpoint: string; timeInterval: number; maxItems: number; enabled: EnabledCallback; }; /** * Adds the 'stm' parameter with the current time to the payload * Stringify all payload values * @param payload - The payload which will be mutated */ function preparePayload(payload: Payload): Record<string, string> { const stringifiedPayload: Record<string, string> = {}; Object.keys(payload).forEach((key) => { stringifiedPayload[key] = String(payload[key]); }); stringifiedPayload.stm = new Date().getTime().toString(); return stringifiedPayload; } export class Snowplow { /** Disable sending events when it's not possible. */ disabled: boolean = false; #emitter: Emitter; #lsFetch: LsFetch; #options: SnowplowOptions; #tracker: TrackerCore; static #instance?: Snowplow; // eslint-disable-next-line no-restricted-syntax private constructor(lsFetch: LsFetch, options: SnowplowOptions) { this.#lsFetch = lsFetch; this.#options = options; this.#emitter = new Emitter( this.#options.timeInterval, this.#options.maxItems, this.#sendEvent.bind(this), ); this.#emitter.start(); this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) }); } public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise<void> { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to "gl" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with "js-*"" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise<void> { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References: - src/common/tracking/snowplow/snowplow.ts:22
You are a code assistant
Definition of 'isLanguageEnabled' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp
Definition: 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 'updateSuggestionState' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'ManagedInstances' in file packages/lib_webview/src/setup/transport/utils/event_filters.ts in project gitlab-lsp
Definition: export type ManagedInstances = Set<WebviewInstanceId>; 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_transport_event_handlers.ts:10 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:10
You are a code assistant
Definition of 'DefaultDirectoryWalker' in file src/common/services/fs/dir.ts in project gitlab-lsp
Definition: export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise<URI[]> { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References:
You are a code assistant
Definition of 'SuggestionClientMiddleware' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp
Definition: export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType<SuggestionClientFn>; References: - src/common/suggestion_client/suggestion_client_pipeline.test.ts:39 - src/common/suggestion_client/tree_sitter_middleware.test.ts:19 - src/common/suggestion_client/tree_sitter_middleware.ts:12 - src/common/suggestion_client/client_to_middleware.ts:4 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:36 - src/common/suggestion_client/suggestion_client_pipeline.ts:19
You are a code assistant
Definition of 'NotificationMessage' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp
Definition: export type NotificationMessage = WebviewAddress & { type: string; payload?: unknown; }; export type RequestMessage = NotificationMessage & { requestId: string; }; export type SuccessfulResponse = WebviewAddress & { requestId: string; success: true; type: string; payload?: unknown; }; export type FailedResponse = WebviewAddress & { requestId: string; success: false; reason: string; type: string; }; export type ResponseMessage = SuccessfulResponse | FailedResponse; export type Messages = { 'webview:connect': WebviewAddress; 'webview:disconnect': WebviewAddress; 'webview:notification': NotificationMessage; 'webview:request': RequestMessage; 'webview:response': ResponseMessage; 'plugin:notification': NotificationMessage; 'plugin:request': RequestMessage; 'plugin:response': ResponseMessage; }; export class WebviewRuntimeMessageBus extends MessageBus<Messages> {} References: - packages/lib_webview/src/events/webview_runtime_message_bus.ts:35 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:32
You are a code assistant
Definition of 'WebviewId' in file packages/lib_webview_plugin/src/types.ts in project gitlab-lsp
Definition: export type WebviewId = string & { readonly _type: 'WebviewId' }; /** * Represents a unique identifier for instances of a webview. */ export type WebviewInstanceId = string & { readonly _type: 'WebviewInstanceId' }; export type WebviewAddress = { webviewId: WebviewId; webviewInstanceId: WebviewInstanceId; }; export type WebviewMessageBusManagerHandler<T extends MessageMap> = ( webviewInstanceId: WebviewInstanceId, messageBus: MessageBus<T>, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; export interface WebviewConnection<T extends MessageMap> { broadcast: <TMethod extends keyof T['outbound']['notifications'] & string>( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) => void; onInstanceConnected: (handler: WebviewMessageBusManagerHandler<T>) => void; } References: - src/common/webview/extension/extension_connection_message_bus.ts:8 - src/node/webview/handlers/webview_handler.test.ts:14 - src/common/webview/webview_resource_location_service.ts:20 - packages/lib_webview_transport/src/types.ts:5 - packages/lib_webview_plugin/src/types.ts:17 - src/common/webview/extension/utils/extension_message_handler_registry.ts:5 - src/common/webview/extension/extension_connection_message_bus_provider.ts:62 - src/common/webview/webview_resource_location_service.ts:6 - packages/lib_webview/src/setup/plugin/webview_controller.ts:38 - packages/lib_webview/src/setup/plugin/utils/filters.ts:4 - src/node/webview/http_access_info_provider.ts:12 - src/node/webview/webview_fastify_middleware.ts:21 - packages/lib_webview/src/setup/plugin/webview_controller.ts:25 - src/node/webview/handlers/webview_handler.ts:28 - src/node/webview/routes/webview_routes.ts:11 - src/node/webview/handlers/webview_handler.ts:7 - src/common/webview/webview_metadata_provider.test.ts:12 - packages/lib_webview_transport_socket_io/src/types.ts:4 - packages/lib_webview/src/types.ts:5 - src/common/webview/webview_metadata_provider.ts:5 - packages/lib_webview_plugin/src/webview_plugin.ts:62 - packages/lib_webview/src/setup/plugin/utils/filters.ts:5 - src/common/webview/extension/extension_connection_message_bus.ts:17 - src/common/webview/webview_resource_location_service.test.ts:17 - src/common/webview/webview_metadata_provider.test.ts:8 - src/node/webview/handlers/webview_handler.ts:11 - src/common/webview/extension/utils/extension_message.ts:4
You are a code assistant
Definition of 'ICodeSuggestionModel' in file src/common/tracking/tracking_types.ts in project gitlab-lsp
Definition: export interface ICodeSuggestionModel { lang: string; engine: string; name: string; tokens_consumption_metadata?: { input_tokens?: number; output_tokens?: number; context_tokens_sent?: number; context_tokens_used?: number; }; } export interface TelemetryTracker { 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: - src/common/tracking/tracking_types.ts:12 - src/common/tracking/snowplow_tracker.test.ts:337 - src/common/tracking/instance_tracker.test.ts:171 - src/common/api.ts:66
You are a code assistant
Definition of 'IntentDetectionExamples' in file src/node/tree_sitter/test_examples/intent_detection/types.ts in project gitlab-lsp
Definition: export type IntentDetectionExamples = { completion: Array<SuggestionContext>; generation: Array<SuggestionContext>; }; References: - src/node/tree_sitter/test_examples/intent_detection/java.ts:4 - src/node/tree_sitter/test_examples/intent_detection/go.ts:4 - src/node/tree_sitter/test_examples/intent_detection/python.ts:4 - src/node/tree_sitter/test_examples/intent_detection/ruby.ts:4 - src/node/tree_sitter/test_examples/intent_detection/javascript.ts:4 - src/node/tree_sitter/test_examples/intent_detection/typescript.ts:4
You are a code assistant
Definition of 'listenerCount' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp
Definition: 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 'initialize' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp
Definition: def initialize(name) @name = name end 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:25 - src/tests/fixtures/intent/empty_function/ruby.rb:17
You are a code assistant
Definition of 'API_PULLING' in file packages/webview_duo_chat/src/plugin/port/chat/api/pulling.ts in project gitlab-lsp
Definition: export const API_PULLING = { interval: 5000, maxRetries: 10, }; export const pullHandler = async <T>( handler: () => Promise<T | undefined>, retry = API_PULLING.maxRetries, ): Promise<T | undefined> => { if (retry <= 0) { log.debug('Pull handler: no retries left, exiting without return value.'); return undefined; } log.debug(`Pull handler: pulling, ${retry - 1} retries left.`); const response = await handler(); if (response) return response; await waitForMs(API_PULLING.interval); return pullHandler(handler, retry - 1); }; References:
You are a code assistant
Definition of 'sendTextDocumentCompletion' in file src/tests/int/lsp_client.ts in project gitlab-lsp
Definition: 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 'getDocContext' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: 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/document_transformer_service.test.ts:79 - src/common/document_transformer_service.test.ts:46 - src/common/document_transformer_service.test.ts:53 - src/common/document_transformer_service.ts:100
You are a code assistant
Definition of 'constructor' in file src/common/suggestion_client/direct_connection_client.ts in project gitlab-lsp
Definition: constructor(api: GitLabApiClient, configService: ConfigService) { this.#api = api; this.#configService = configService; this.#api.onApiReconfigured(({ isInValidState }) => { this.#connectionDetails = undefined; this.#isValidApi = isInValidState; this.#directConnectionCircuitBreaker.success(); // resets the circuit breaker // TODO: fetch the direct connection details https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/239 }); } #fetchDirectConnectionDetails = async () => { if (this.#connectionDetailsCircuitBreaker.isOpen()) { return; } let details; try { details = await this.#api.fetchFromApi<IDirectConnectionDetails>({ type: 'rest', method: 'POST', path: '/code_suggestions/direct_access', supportedSinceInstanceVersion: { version: '17.2.0', resourceName: 'get direct connection details', }, }); } catch (e) { // 401 indicates that the user has GitLab Duo disabled and shout result in longer periods of open circuit if (isFetchError(e) && e.status === 401) { this.#connectionDetailsCircuitBreaker.megaError(); } else { this.#connectionDetailsCircuitBreaker.error(); } log.info( `Failed to fetch direct connection details from GitLab instance. Code suggestion requests will be sent to your GitLab instance. Error ${e}`, ); } this.#connectionDetails = details; this.#configService.merge({ client: { snowplowTrackerOptions: transformHeadersToSnowplowOptions(details?.headers) }, }); }; async #fetchUsingDirectConnection<T>(request: CodeSuggestionRequest): Promise<T> { if (!this.#connectionDetails) { throw new Error('Assertion error: connection details are undefined'); } const suggestionEndpoint = `${this.#connectionDetails.base_url}/v2/completions`; const start = Date.now(); const response = await fetch(suggestionEndpoint, { method: 'post', body: JSON.stringify(request), keepalive: true, headers: { ...this.#connectionDetails.headers, Authorization: `Bearer ${this.#connectionDetails.token}`, 'X-Gitlab-Authentication-Type': 'oidc', 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), 'Content-Type': ' application/json', }, signal: AbortSignal.timeout(5 * SECOND), }); await handleFetchError(response, 'Direct Connection for code suggestions'); const data = await response.json(); const end = Date.now(); log.debug(`Direct connection (${suggestionEndpoint}) suggestion fetched in ${end - start}ms`); return data; } async getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined> { // TODO we would like to send direct request only for intent === COMPLETION // however, currently we are not certain that the intent is completion // when we finish the following two issues, we can be certain that the intent is COMPLETION // // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/173 // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/247 if (context.intent === GENERATION) { return undefined; } if (!this.#isValidApi) { return undefined; } if (this.#directConnectionCircuitBreaker.isOpen()) { return undefined; } if (!this.#connectionDetails || areExpired(this.#connectionDetails)) { this.#fetchDirectConnectionDetails().catch( (e) => log.error(`#fetchDirectConnectionDetails error: ${e}`), // this makes eslint happy, the method should never throw ); return undefined; } try { const response = await this.#fetchUsingDirectConnection<SuggestionResponse>( createV2Request(context, this.#connectionDetails.model_details), ); return response && { ...response, isDirectConnection: true }; } catch (e) { this.#directConnectionCircuitBreaker.error(); log.warn( 'Direct connection for code suggestions failed. Code suggestion requests will be sent to your GitLab instance.', e, ); } return undefined; } } References:
You are a code assistant
Definition of 'onDocumentChange' in file src/common/document_service.ts in project gitlab-lsp
Definition: onDocumentChange(listener: TextDocumentChangeListener) { this.#emitter.on(DOCUMENT_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(DOCUMENT_CHANGE_EVENT_NAME, listener), }; } } References:
You are a code assistant
Definition of 'warn' in file src/common/log.ts in project gitlab-lsp
Definition: warn(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError); } error(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError); } } // TODO: rename the export and replace usages of `log` with `Log`. export const log = new Log(); References:
You are a code assistant
Definition of 'isFetchError' in file src/common/fetch_error.ts in project gitlab-lsp
Definition: export function isFetchError(object: unknown): object is FetchError { return object instanceof FetchError; } export const stackToArray = (stack: string | undefined): string[] => (stack ?? '').split('\n'); export interface ResponseError extends Error { status: number; body?: unknown; } const getErrorType = (body: string): string | unknown => { try { const parsedBody = JSON.parse(body); return parsedBody?.error; } catch { return undefined; } }; const isInvalidTokenError = (response: Response, body?: string) => Boolean(response.status === 401 && body && getErrorType(body) === 'invalid_token'); const isInvalidRefresh = (response: Response, body?: string) => Boolean(response.status === 400 && body && getErrorType(body) === 'invalid_grant'); export class FetchError extends Error implements ResponseError, DetailedError { response: Response; #body?: string; constructor(response: Response, resourceName: string, body?: string) { let message = `Fetching ${resourceName} from ${response.url} failed`; if (isInvalidTokenError(response, body)) { message = `Request for ${resourceName} failed because the token is expired or revoked.`; } if (isInvalidRefresh(response, body)) { message = `Request to refresh token failed, because it's revoked or already refreshed.`; } super(message); this.response = response; this.#body = body; } get status() { return this.response.status; } isInvalidToken(): boolean { return ( isInvalidTokenError(this.response, this.#body) || isInvalidRefresh(this.response, this.#body) ); } get details() { const { message, stack } = this; return { message, stack: stackToArray(stack), response: { status: this.response.status, headers: this.response.headers, body: this.#body, }, }; } } export class TimeoutError extends Error { constructor(url: URL | RequestInfo) { const timeoutInSeconds = Math.round(REQUEST_TIMEOUT_MILLISECONDS / 1000); super( `Request to ${extractURL(url)} timed out after ${timeoutInSeconds} second${timeoutInSeconds === 1 ? '' : 's'}`, ); } } export class InvalidInstanceVersionError extends Error {} References: - src/common/suggestion/streaming_handler.ts:177 - src/common/suggestion/suggestion_service.ts:338 - src/common/suggestion_client/direct_connection_client.ts:83 - src/common/fetch_error.test.ts:44 - src/common/fetch_error.test.ts:50
You are a code assistant
Definition of 'getProviderItems' in file src/common/ai_context_management_2/providers/ai_context_provider.ts in project gitlab-lsp
Definition: getProviderItems( query: string, workspaceFolder: WorkspaceFolder[], ): Promise<AiContextProviderItem[]>; } References:
You are a code assistant
Definition of 'AdditionalContext' in file src/common/api_types.ts in project gitlab-lsp
Definition: 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 'size' in file packages/lib_disposable/src/composite_disposable.ts in project gitlab-lsp
Definition: get size() { return this.#disposables.size; } add(...disposables: Disposable[]): void { for (const disposable of disposables) { this.#disposables.add(disposable); } } dispose(): void { for (const disposable of this.#disposables) { disposable.dispose(); } this.#disposables.clear(); } } References:
You are a code assistant
Definition of 'addInstances' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: addInstances(...instances: BrandedInstance<object>[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map<string, ClassWithDependencies>(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get<T>(id: InterfaceId<T>): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References:
You are a code assistant
Definition of 'constructor' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp
Definition: constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = emptyFunctionQueries[language]; if (!queryString) { log.warn(`No empty function query found for: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ isCursorInEmptyFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return false; } const emptyBodyPositions = query.captures(tree.rootNode).map((capture) => { return EmptyFunctionResolver.#findEmptyBodyPosition(capture.node); }); const cursorInsideInOneOfTheCaptures = emptyBodyPositions.some( (emptyBody) => EmptyFunctionResolver.#isValidBodyPosition(emptyBody) && EmptyFunctionResolver.#isCursorInsideNode( cursorPosition, emptyBody.startPosition, emptyBody.endPosition, ), ); return ( cursorInsideInOneOfTheCaptures || EmptyFunctionResolver.isCursorAfterEmptyPythonFunction({ languageName, tree, treeSitterLanguage, cursorPosition, }) ); } static #isCursorInsideNode( cursorPosition: Point, startPosition: Point, endPosition: Point, ): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorAfterNodeStart = cursorRow > startPosition.row || (cursorRow === startPosition.row && cursorColumn >= startPosition.column); const isCursorBeforeNodeEnd = cursorRow < endPosition.row || (cursorRow === endPosition.row && cursorColumn <= endPosition.column); return isCursorAfterNodeStart && isCursorBeforeNodeEnd; } static #isCursorRightAfterNode(cursorPosition: Point, endPosition: Point): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorRightAfterNode = cursorRow - endPosition.row === 1 || (cursorRow === endPosition.row && cursorColumn > endPosition.column); return isCursorRightAfterNode; } static #findEmptyBodyPosition(node: SyntaxNode): { startPosition?: Point; endPosition?: Point } { const startPosition = node.lastChild?.previousSibling?.endPosition; const endPosition = node.lastChild?.startPosition; return { startPosition, endPosition }; } static #isValidBodyPosition(arg: { startPosition?: Point; endPosition?: Point; }): arg is { startPosition: Point; endPosition: Point } { return !isUndefined(arg.startPosition) && !isUndefined(arg.endPosition); } 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 'CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: export const CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId } ) { requestId errors } } `, defaultVariables: {}, }; export const CHAT_INPUT_TEMPLATE_17_3_AND_LATER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String $platformOrigin: String! ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId platformOrigin: $platformOrigin } ) { requestId errors } } `, defaultVariables: { platformOrigin: PLATFORM_ORIGIN, }, }; export type AiActionResponseType = { aiAction: { requestId: string; errors: string[] }; }; export const AI_MESSAGES_QUERY = gql` query getAiMessages($requestIds: [ID!], $roles: [AiMessageRole!]) { aiMessages(requestIds: $requestIds, roles: $roles) { nodes { requestId role content contentHtml timestamp errors extras { sources } } } } `; type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise<AiActionResponseType> { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise<AiMessage> { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise<AiActionResponseType> { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> { const request: GraphQLRequest<AiMessagesResponseType> = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise<AiActionResponseType> { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest<AiActionResponseType> = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise<ChatInputTemplate> { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:
You are a code assistant
Definition of 'hasbinSync' in file src/tests/int/hasbin.ts in project gitlab-lsp
Definition: export function hasbinSync(bin: string) { return getPaths(bin).some(fileExistsSync); } export function hasbinAll(bins: string[], done: (result: boolean) => void) { async.every(bins, hasbin.async, done); } export function hasbinAllSync(bins: string[]) { return bins.every(hasbin.sync); } export function hasbinSome(bins: string[], done: (result: boolean) => void) { async.some(bins, hasbin.async, done); } export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/["]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } export function fileExists(filePath: string, done: (result: boolean) => void) { stat(filePath, function (error, stat) { if (error) { return done(false); } done(stat.isFile()); }); } export function fileExistsSync(filePath: string) { try { return statSync(filePath).isFile(); } catch (error) { return false; } } References: - src/tests/int/fetch.test.ts:91
You are a code assistant
Definition of 'Container' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: export class Container { #instances = new Map<string, unknown>(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been "branded" by the `brandInstance` method */ addInstances(...instances: BrandedInstance<object>[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map<string, ClassWithDependencies>(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get<T>(id: InterfaceId<T>): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - src/node/main.ts:92 - packages/lib_di/src/index.test.ts:50 - packages/lib_di/src/index.test.ts:53 - src/browser/main.ts:65
You are a code assistant
Definition of 'constructor' in file src/common/fetch_error.ts in project gitlab-lsp
Definition: constructor(url: URL | RequestInfo) { const timeoutInSeconds = Math.round(REQUEST_TIMEOUT_MILLISECONDS / 1000); super( `Request to ${extractURL(url)} timed out after ${timeoutInSeconds} second${timeoutInSeconds === 1 ? '' : 's'}`, ); } } export class InvalidInstanceVersionError extends Error {} References:
You are a code assistant
Definition of 'buildConnectionId' in file packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts in project gitlab-lsp
Definition: export function buildConnectionId( webviewInstanceInfo: WebviewInstanceInfo, ): WebviewSocketConnectionId { return `${webviewInstanceInfo.webviewId}:${webviewInstanceInfo.webviewInstanceId}` as WebviewSocketConnectionId; } References: - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:63 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:132
You are a code assistant
Definition of 'getWorkspaceFiles' in file src/common/workspace/workspace_service.ts in project gitlab-lsp
Definition: getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References:
You are a code assistant
Definition of 'onRequest' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp
Definition: onRequest(type: Method, handler: Handler): Disposable { return this.#requestEvents.register(type, (requestId: RequestId, payload: unknown) => { try { const result = handler(payload); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: true, payload: result, }); } catch (error) { this.#logger.error(`Error handling request of type ${type}:`, error as Error); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: false, reason: (error as Error).message, }); } }); } dispose(): void { this.#eventSubscriptions.dispose(); this.#notificationEvents.dispose(); this.#requestEvents.dispose(); this.#pendingResponseEvents.dispose(); } } References:
You are a code assistant
Definition of 'setupFileWatcher' in file src/common/services/fs/dir.ts in project gitlab-lsp
Definition: setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler): void; } export const DirectoryWalker = createInterfaceId<DirectoryWalker>('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise<URI[]> { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References:
You are a code assistant
Definition of 'initialize' in file src/node/fetch.ts in project gitlab-lsp
Definition: async initialize(): Promise<void> { // Set http_proxy and https_proxy environment variables // which will then get picked up by the ProxyAgent and // used. try { const proxy = await getProxySettings(); if (proxy?.http) { process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`; log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`); } if (proxy?.https) { process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`; log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`); } if (!proxy?.http && !proxy?.https) { log.debug(`fetch: Detected no proxy settings`); } } catch (err) { log.warn('Unable to load proxy settings', err); } if (this.#userProxy) { log.debug(`fetch: Detected user proxy ${this.#userProxy}`); process.env.http_proxy = this.#userProxy; process.env.https_proxy = this.#userProxy; } if (process.env.http_proxy || process.env.https_proxy) { log.info( `fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`, ); this.#proxy = this.#createProxyAgent(); } this.#initialized = true; } async destroy(): Promise<void> { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { if (!this.#initialized) { throw new Error('LsFetch not initialized. Make sure LsFetch.initialize() was called.'); } try { return await this.#fetchLogged(input, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MILLISECONDS), ...init, agent: this.#getAgent(input), }); } catch (e) { if (hasName(e) && e.name === 'AbortError') { throw new TimeoutError(input); } throw e; } } updateAgentOptions({ ignoreCertificateErrors, ca, cert, certKey }: FetchAgentOptions): void { let fileOptions = {}; try { fileOptions = { ...(ca ? { ca: fs.readFileSync(ca) } : {}), ...(cert ? { cert: fs.readFileSync(cert) } : {}), ...(certKey ? { key: fs.readFileSync(certKey) } : {}), }; } catch (err) { log.error('Error reading https agent options from file', err); } const newOptions: LsAgentOptions = { rejectUnauthorized: !ignoreCertificateErrors, ...fileOptions, }; if (isEqual(newOptions, this.#agentOptions)) { // new and old options are the same, nothing to do return; } this.#agentOptions = newOptions; this.#httpsAgent = this.#createHttpsAgent(); if (this.#proxy) { this.#proxy = this.#createProxyAgent(); } } async *streamFetch( url: string, body: string, headers: FetchHeaders, ): AsyncGenerator<string, void, void> { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream<Uint8Array>, ): AsyncGenerator<string, void, void> { for await (const chunk of stream) { buffer += decoder.decode(chunk); yield buffer; } } const response: Response = await this.fetch(url, { method: 'POST', headers, body, }); await handleFetchError(response, 'Code Suggestions Streaming'); if (response.body) { // Note: Using (node:stream).ReadableStream as it supports async iterators yield* readStream(response.body as ReadableStream); } } #createHttpsAgent(): https.Agent { const agentOptions = { ...this.#agentOptions, keepAlive: true, }; log.debug( `fetch: https agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(agentOptions), )}.`, ); return new https.Agent(agentOptions); } #createProxyAgent(): ProxyAgent { log.debug( `fetch: proxy agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(this.#agentOptions), )}.`, ); return new ProxyAgent(this.#agentOptions); } async #fetchLogged(input: RequestInfo | URL, init: LsRequestInit): Promise<Response> { const start = Date.now(); const url = this.#extractURL(input); if (init.agent === httpAgent) { log.debug(`fetch: request for ${url} made with http agent.`); } else { const type = init.agent === this.#proxy ? 'proxy' : 'https'; log.debug(`fetch: request for ${url} made with ${type} agent.`); } try { const resp = await fetch(input, init); const duration = Date.now() - start; log.debug(`fetch: request to ${url} returned HTTP ${resp.status} after ${duration} ms`); return resp; } catch (e) { const duration = Date.now() - start; log.debug(`fetch: request to ${url} threw an exception after ${duration} ms`); log.error(`fetch: request to ${url} failed with:`, e); throw e; } } #getAgent(input: RequestInfo | URL): ProxyAgent | https.Agent | http.Agent { if (this.#proxy) { return this.#proxy; } if (input.toString().startsWith('https://')) { return this.#httpsAgent; } return httpAgent; } #extractURL(input: RequestInfo | URL): string { if (input instanceof URL) { return input.toString(); } if (typeof input === 'string') { return input; } return input.url; } #sanitizeAgentOptions(agentOptions: LsAgentOptions) { const { ca, cert, key, ...options } = agentOptions; return { ...options, ...(ca ? { ca: '<hidden>' } : {}), ...(cert ? { cert: '<hidden>' } : {}), ...(key ? { key: '<hidden>' } : {}), }; } } References: - src/tests/fixtures/intent/empty_function/ruby.rb:17 - src/tests/fixtures/intent/empty_function/ruby.rb:25
You are a code assistant
Definition of 'versionRequest' in file packages/webview_duo_chat/src/plugin/port/gilab/check_version.ts in project gitlab-lsp
Definition: export const versionRequest: ApiRequest<GitLabVersionResponse> = { type: 'rest', method: 'GET', path: '/version', }; References:
You are a code assistant
Definition of 'constructor' in file src/node/fetch.ts in project gitlab-lsp
Definition: constructor(userProxy?: string) { super(); this.#agentOptions = { rejectUnauthorized: true, }; this.#userProxy = userProxy; this.#httpsAgent = this.#createHttpsAgent(); } async initialize(): Promise<void> { // Set http_proxy and https_proxy environment variables // which will then get picked up by the ProxyAgent and // used. try { const proxy = await getProxySettings(); if (proxy?.http) { process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`; log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`); } if (proxy?.https) { process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`; log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`); } if (!proxy?.http && !proxy?.https) { log.debug(`fetch: Detected no proxy settings`); } } catch (err) { log.warn('Unable to load proxy settings', err); } if (this.#userProxy) { log.debug(`fetch: Detected user proxy ${this.#userProxy}`); process.env.http_proxy = this.#userProxy; process.env.https_proxy = this.#userProxy; } if (process.env.http_proxy || process.env.https_proxy) { log.info( `fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`, ); this.#proxy = this.#createProxyAgent(); } this.#initialized = true; } async destroy(): Promise<void> { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { if (!this.#initialized) { throw new Error('LsFetch not initialized. Make sure LsFetch.initialize() was called.'); } try { return await this.#fetchLogged(input, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MILLISECONDS), ...init, agent: this.#getAgent(input), }); } catch (e) { if (hasName(e) && e.name === 'AbortError') { throw new TimeoutError(input); } throw e; } } updateAgentOptions({ ignoreCertificateErrors, ca, cert, certKey }: FetchAgentOptions): void { let fileOptions = {}; try { fileOptions = { ...(ca ? { ca: fs.readFileSync(ca) } : {}), ...(cert ? { cert: fs.readFileSync(cert) } : {}), ...(certKey ? { key: fs.readFileSync(certKey) } : {}), }; } catch (err) { log.error('Error reading https agent options from file', err); } const newOptions: LsAgentOptions = { rejectUnauthorized: !ignoreCertificateErrors, ...fileOptions, }; if (isEqual(newOptions, this.#agentOptions)) { // new and old options are the same, nothing to do return; } this.#agentOptions = newOptions; this.#httpsAgent = this.#createHttpsAgent(); if (this.#proxy) { this.#proxy = this.#createProxyAgent(); } } async *streamFetch( url: string, body: string, headers: FetchHeaders, ): AsyncGenerator<string, void, void> { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream<Uint8Array>, ): AsyncGenerator<string, void, void> { for await (const chunk of stream) { buffer += decoder.decode(chunk); yield buffer; } } const response: Response = await this.fetch(url, { method: 'POST', headers, body, }); await handleFetchError(response, 'Code Suggestions Streaming'); if (response.body) { // Note: Using (node:stream).ReadableStream as it supports async iterators yield* readStream(response.body as ReadableStream); } } #createHttpsAgent(): https.Agent { const agentOptions = { ...this.#agentOptions, keepAlive: true, }; log.debug( `fetch: https agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(agentOptions), )}.`, ); return new https.Agent(agentOptions); } #createProxyAgent(): ProxyAgent { log.debug( `fetch: proxy agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(this.#agentOptions), )}.`, ); return new ProxyAgent(this.#agentOptions); } async #fetchLogged(input: RequestInfo | URL, init: LsRequestInit): Promise<Response> { const start = Date.now(); const url = this.#extractURL(input); if (init.agent === httpAgent) { log.debug(`fetch: request for ${url} made with http agent.`); } else { const type = init.agent === this.#proxy ? 'proxy' : 'https'; log.debug(`fetch: request for ${url} made with ${type} agent.`); } try { const resp = await fetch(input, init); const duration = Date.now() - start; log.debug(`fetch: request to ${url} returned HTTP ${resp.status} after ${duration} ms`); return resp; } catch (e) { const duration = Date.now() - start; log.debug(`fetch: request to ${url} threw an exception after ${duration} ms`); log.error(`fetch: request to ${url} failed with:`, e); throw e; } } #getAgent(input: RequestInfo | URL): ProxyAgent | https.Agent | http.Agent { if (this.#proxy) { return this.#proxy; } if (input.toString().startsWith('https://')) { return this.#httpsAgent; } return httpAgent; } #extractURL(input: RequestInfo | URL): string { if (input instanceof URL) { return input.toString(); } if (typeof input === 'string') { return input; } return input.url; } #sanitizeAgentOptions(agentOptions: LsAgentOptions) { const { ca, cert, key, ...options } = agentOptions; return { ...options, ...(ca ? { ca: '<hidden>' } : {}), ...(cert ? { cert: '<hidden>' } : {}), ...(key ? { key: '<hidden>' } : {}), }; } } References:
You are a code assistant
Definition of 'DuoProjectAccessCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: 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: - src/common/services/duo_access/project_access_checker.test.ts:11 - src/common/feature_state/project_duo_acces_check.ts:44 - src/common/services/duo_access/project_access_checker.ts:20 - src/common/message_handler.ts:38 - src/common/connection.ts:34 - src/common/services/duo_access/project_access_checker.ts:22 - src/common/message_handler.ts:81
You are a code assistant
Definition of 'OAuthAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp
Definition: 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 'isWebviewInstanceDestroyedEventData' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp
Definition: export const isWebviewInstanceDestroyedEventData: MessageValidator< WebviewInstanceDestroyedEventData > = (message: unknown): message is WebviewInstanceDestroyedEventData => isWebviewAddress(message); export const isWebviewInstanceMessageEventData: MessageValidator< WebviewInstanceNotificationEventData > = (message: unknown): message is WebviewInstanceNotificationEventData => isWebviewAddress(message) && 'type' in message; References:
You are a code assistant
Definition of 'TokenCheckNotificationType' in file src/common/notifications.ts in project gitlab-lsp
Definition: export const TokenCheckNotificationType = new NotificationType<TokenCheckNotificationParams>( TOKEN_CHECK_NOTIFICATION, ); // TODO: once the following clients are updated: // // - JetBrains: https://gitlab.com/gitlab-org/editor-extensions/gitlab-jetbrains-plugin/-/blob/main/src/main/kotlin/com/gitlab/plugin/lsp/GitLabLanguageServer.kt#L16 // // We should remove the `TextDocument` type from the parameter since it's deprecated export type DidChangeDocumentInActiveEditorParams = TextDocument | DocumentUri; export const DidChangeDocumentInActiveEditor = new NotificationType<DidChangeDocumentInActiveEditorParams>( '$/gitlab/didChangeDocumentInActiveEditor', ); References:
You are a code assistant
Definition of 'DefaultProjectDuoAccessCheck' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp
Definition: export class DefaultProjectDuoAccessCheck implements StateCheck { #subscriptions: Disposable[] = []; #stateEmitter = new EventEmitter(); #hasDuoAccess?: boolean; #duoProjectAccessChecker: DuoProjectAccessChecker; #configService: ConfigService; #currentDocument?: TextDocument; #isEnabledInSettings = true; constructor( documentService: DocumentService, configService: ConfigService, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, ) { this.#configService = configService; this.#duoProjectAccessChecker = duoProjectAccessChecker; this.#subscriptions.push( documentService.onDocumentChange(async (event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#currentDocument = event.document; await this.#checkIfProjectHasDuoAccess(); } }), configService.onConfigChange(async (config) => { this.#isEnabledInSettings = config.client.duo?.enabledWithoutGitlabProject ?? true; await this.#checkIfProjectHasDuoAccess(); }), duoProjectAccessCache.onDuoProjectCacheUpdate(() => this.#checkIfProjectHasDuoAccess()), ); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise<void> { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise<WorkspaceFolder | undefined> { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References: - src/common/feature_state/project_duo_acces_check.test.ts:54
You are a code assistant
Definition of 'InlineSvgPlugin' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp
Definition: export const InlineSvgPlugin = { name: 'inline-svg', transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default ""'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default "data:image/svg+xml;base64,${base64Data}"`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:
You are a code assistant
Definition of 'getAdvancedContext' in file src/common/advanced_context/advanced_context_factory.ts in project gitlab-lsp
Definition: 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: - src/common/suggestion/suggestion_service.ts:550 - src/common/advanced_context/advanced_context_factory.test.ts:75
You are a code assistant
Definition of 'getForSaaSAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp
Definition: getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined>; } References:
You are a code assistant
Definition of 'render' in file packages/webview_duo_workflow/src/app/index.ts in project gitlab-lsp
Definition: render(createElement) { return createElement(App); }, }).$mount(); } References:
You are a code assistant
Definition of 'FileExtension' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp
Definition: type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; /** * Note: We use the language server procotol Ids here because `IDocContext` expects * these Ids (which is passed into `ParseFile`) and because they are unique. * `ParseFile` derives the tree sitter gramamr from the file's extension. * Some grammars apply to multiple extensions, eg. `typescript` applies * to both `.ts` and `.tsx`. */ const testCases: Array<[LanguageServerLanguageId, FileExtension, IntentTestCase[]]> = [ /* [ FIXME: add back support for vue 'vue', '.vue', // ../../fixtures/intent/vue_comments.vue [ ['on_empty_comment', { line: 2, character: 9 }, 'completion'], ['after_empty_comment', { line: 3, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 30, character: 0 }, undefined], // TODO: comments in the Vue `script` are not captured // ['on_comment_in_empty_function', { line: 34, character: 33 }, 'completion'], // ['after_comment_in_empty_function', { line: 35, character: 0 }, 'generation'], ], ], */ [ 'typescript', '.ts', // ../../fixtures/intent/typescript_comments.ts [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/typescriptreact_comments.tsx [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'javascript', '.js', // ../../fixtures/intent/javascript_comments.js [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'javascriptreact', '.jsx', // ../../fixtures/intent/javascriptreact_comments.jsx [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 15, character: 25 }, 'completion'], ['on_jsdoc_comment', { line: 16, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 17, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 31, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 32, character: 0 }, 'generation'], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/ruby_comments.rb [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 9, character: 23 }, 'completion'], ['on_block_comment', { line: 10, character: 4 }, 'completion'], ['after_block_comment', { line: 11, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 21, character: 30 }, 'completion'], ['after_comment_in_empty_function', { line: 22, character: 22 }, 'generation'], ], ], [ 'go', '.go', // ../../fixtures/intent/go_comments.go [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 20, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 24, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 25, character: 0 }, 'generation'], ], ], [ 'java', '.java', // ../../fixtures/intent/java_comments.java [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 14, character: 29 }, 'completion'], ['on_doc_comment', { line: 15, character: 3 }, 'completion'], ['after_doc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/kotlin_comments.kt [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 14, character: 29 }, 'completion'], ['on_doc_comment', { line: 15, character: 3 }, 'completion'], ['after_doc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'rust', '.rs', // ../../fixtures/intent/rust_comments.rs [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 11, character: 25 }, 'completion'], ['on_doc_comment', { line: 12, character: 42 }, 'completion'], ['after_doc_comment', { line: 15, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 26, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 27, character: 0 }, 'generation'], ], ], [ 'yaml', '.yaml', // ../../fixtures/intent/yaml_comments.yaml [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ], ], [ 'html', '.html', // ../../fixtures/intent/html_comments.html [ ['on_empty_comment', { line: 14, character: 12 }, 'completion'], ['after_empty_comment', { line: 15, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 8, character: 91 }, 'completion'], ['after_non_empty_comment', { line: 9, character: 0 }, 'generation'], ['in_block_comment', { line: 18, character: 29 }, 'completion'], ['on_block_comment', { line: 19, character: 7 }, 'completion'], ['after_block_comment', { line: 20, character: 0 }, 'generation'], ['no_comment_large_file', { line: 12, character: 66 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/c_comments.c [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/cpp_comments.cpp [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/c_sharp_comments.cs [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 22 }, 'generation'], ], ], [ 'css', '.css', // ../../fixtures/intent/css_comments.css [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 3, character: 31 }, 'completion'], ['after_non_empty_comment', { line: 4, character: 0 }, 'generation'], ['in_block_comment', { line: 7, character: 23 }, 'completion'], ['on_block_comment', { line: 8, character: 2 }, 'completion'], ['after_block_comment', { line: 9, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ], ], [ 'bash', '.sh', // ../../fixtures/intent/bash_comments.css [ ['on_empty_comment', { line: 4, character: 1 }, 'completion'], ['after_empty_comment', { line: 5, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 2, character: 65 }, 'completion'], ['after_non_empty_comment', { line: 3, character: 0 }, 'generation'], ['no_comment_large_file', { line: 10, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 19, character: 12 }, 'completion'], ['after_comment_in_empty_function', { line: 20, character: 0 }, 'generation'], ], ], [ 'json', '.json', // ../../fixtures/intent/json_comments.css [ ['on_empty_comment', { line: 20, character: 3 }, 'completion'], ['after_empty_comment', { line: 21, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 0, character: 38 }, 'completion'], ['after_non_empty_comment', { line: 1, character: 0 }, 'generation'], ['no_comment_large_file', { line: 10, character: 0 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/scala_comments.scala [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 3 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 12, character: 0 }, undefined], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'powersell', '.ps1', // ../../fixtures/intent/powershell_comments.ps1 [ ['on_empty_comment', { line: 20, character: 3 }, 'completion'], ['after_empty_comment', { line: 21, character: 3 }, 'completion'], ['after_non_empty_comment', { line: 10, character: 0 }, 'generation'], ['after_block_comment', { line: 8, character: 0 }, 'generation'], ['no_comment_large_file', { line: 22, character: 0 }, undefined], ['after_comment_in_empty_function', { line: 26, character: 0 }, 'generation'], ], ], ]; describe.each(testCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `${language}_comments${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('comment'); } }); }); }); describe('Empty Function Intent', () => { type TestType = | 'empty_function_declaration' | 'non_empty_function_declaration' | 'empty_function_expression' | 'non_empty_function_expression' | 'empty_arrow_function' | 'non_empty_arrow_function' | 'empty_method_definition' | 'non_empty_method_definition' | 'empty_class_constructor' | 'non_empty_class_constructor' | 'empty_class_declaration' | 'non_empty_class_declaration' | 'empty_anonymous_function' | 'non_empty_anonymous_function' | 'empty_implementation' | 'non_empty_implementation' | 'empty_closure_expression' | 'non_empty_closure_expression' | 'empty_generator' | 'non_empty_generator' | 'empty_macro' | 'non_empty_macro'; type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:
You are a code assistant
Definition of 'getByteSize' in file src/common/utils/byte_size.ts in project gitlab-lsp
Definition: export function getByteSize(str: string): number { return Buffer.from(str).byteLength; } References: - src/common/tracking/snowplow_tracker.test.ts:601 - src/common/tracking/snowplow_tracker.ts:489 - src/common/advanced_context/advanced_context_filters.ts:72 - src/common/advanced_context/lru_cache.test.ts:9 - src/common/tracking/snowplow_tracker.ts:492 - src/common/tracking/snowplow_tracker.test.ts:587 - src/common/tracking/snowplow_tracker.test.ts:588 - src/common/tracking/snowplow_tracker.test.ts:604 - src/common/tracking/snowplow_tracker.ts:500 - src/common/advanced_context/advanced_context_filters.ts:65 - src/common/advanced_context/lru_cache.ts:43 - src/common/tracking/snowplow_tracker.test.ts:589
You are a code assistant
Definition of 'Vulnerability' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp
Definition: interface Vulnerability { name: string; description: string; severity: string; location: { start_line: number; end_line: number }; } export interface SecurityDiagnosticsPublisher extends DiagnosticsPublisher {} export const SecurityDiagnosticsPublisher = createInterfaceId<SecurityDiagnosticsPublisher>( 'SecurityDiagnosticsPublisher', ); @Injectable(SecurityDiagnosticsPublisher, [FeatureFlagService, ConfigService, DocumentService]) export class DefaultSecurityDiagnosticsPublisher implements SecurityDiagnosticsPublisher { #publish: DiagnosticsPublisherFn | undefined; #opts?: ISecurityScannerOptions; #featureFlagService: FeatureFlagService; constructor( featureFlagService: FeatureFlagService, configService: ConfigService, documentService: DocumentService, ) { this.#featureFlagService = featureFlagService; configService.onConfigChange((config: IConfig) => { this.#opts = config.client.securityScannerOptions; }); documentService.onDocumentChange( async ( event: TextDocumentChangeEvent<TextDocument>, handlerType: TextDocumentChangeListenerType, ) => { if (handlerType === TextDocumentChangeListenerType.onDidSave) { await this.#runSecurityScan(event.document); } }, ); } 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: - src/common/security_diagnostics_publisher.ts:110
You are a code assistant
Definition of 'WebviewInstanceResponseEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: 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:50 - packages/lib_webview_transport/src/types.ts:44
You are a code assistant
Definition of 'Category' in file src/tests/unit/tree_sitter/test_utils.ts in project gitlab-lsp
Definition: export type Category = 'intent'; // add any more languages not in base languages (but supported by tree sitter) export type LanguageServerLanguageId = | (typeof BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES)[number] | 'yaml'; /** * Use this function to get the path of a fixture file. * Pulls from the `src/tests/fixtures` directory. */ export const getFixturePath = (category: Category, filePath: string) => resolve(cwd(), 'src', 'tests', 'fixtures', category, filePath); /** * Use this function to get the test file and tree for a given fixture file * to be used for Tree Sitter testing purposes. */ export const getTreeAndTestFile = async ({ fixturePath, position, languageId, }: { fixturePath: string; position: Position; languageId: LanguageServerLanguageId; }) => { const parser = new DesktopTreeSitterParser(); const fullText = await readFile(fixturePath, 'utf8'); const { prefix, suffix } = splitTextFileForPosition(fullText, position); const documentContext = { uri: fsPathToUri(fixturePath), prefix, suffix, position, languageId, fileRelativePath: resolve(cwd(), fixturePath), workspaceFolder: { uri: 'file:///', name: 'test', }, } satisfies IDocContext; const treeAndLanguage = await parser.parseFile(documentContext); if (!treeAndLanguage) { throw new Error('Failed to parse file'); } return { prefix, suffix, fullText, treeAndLanguage }; }; /** * Mimics the "prefix" and "suffix" according * to the position in the text file. */ export const splitTextFileForPosition = (text: string, position: Position) => { const lines = text.split('\n'); // Ensure the position is within bounds const maxRow = lines.length - 1; const row = Math.min(position.line, maxRow); const maxColumn = lines[row]?.length || 0; const column = Math.min(position.character, maxColumn); // Get the part of the current line before the cursor and after the cursor const prefixLine = lines[row].slice(0, column); const suffixLine = lines[row].slice(column); // Combine lines before the current row for the prefix const prefixLines = lines.slice(0, row).concat(prefixLine); const prefix = prefixLines.join('\n'); // Combine lines after the current row for the suffix const suffixLines = [suffixLine].concat(lines.slice(row + 1)); const suffix = suffixLines.join('\n'); return { prefix, suffix }; }; References: - src/tests/unit/tree_sitter/test_utils.ts:21
You are a code assistant
Definition of 'advancedContextToRequestBody' in file src/common/advanced_context/advanced_context_factory.ts in project gitlab-lsp
Definition: export function advancedContextToRequestBody( advancedContext: ContextResolution[], ): AdditionalContext[] { return advancedContext.map((ac) => ({ type: ac.type, name: ac.fileRelativePath, content: ac.content, resolution_strategy: ac.strategy, })); } References: - src/common/suggestion/suggestion_service.ts:555 - src/common/advanced_context/advanced_context_factory.test.ts:38
You are a code assistant
Definition of 'DocumentTransformerService' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: export interface DocumentTransformerService { get(uri: string): TextDocument | undefined; getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId<DocumentTransformerService>( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) 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: - src/common/advanced_context/advanced_context_service.ts:28 - src/common/suggestion/suggestion_service.ts:81 - src/common/advanced_context/advanced_context_service.ts:36 - src/common/suggestion/suggestion_service.ts:125 - src/common/connection.ts:22
You are a code assistant
Definition of 'checkToken' in file src/common/api.ts in project gitlab-lsp
Definition: 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 'transformIndexHtml' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp
Definition: transformIndexHtml(html) { const doc = NodeHtmlParser.parse(html); const body = doc.querySelector('body'); doc.querySelectorAll('head script').forEach((script) => { script.removeAttribute('type'); script.removeAttribute('crossorigin'); body?.appendChild(script); }); return doc.toString(); }, }; export const HtmlTransformPlugin = { name: 'html-transform', transformIndexHtml(html) { return html.replace('{{ svg placeholder }}', svgSpriteContent); }, }; export const InlineSvgPlugin = { name: 'inline-svg', transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default ""'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default "data:image/svg+xml;base64,${base64Data}"`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:
You are a code assistant
Definition of 'DirectoryWalker' in file src/common/services/fs/dir.ts in project gitlab-lsp
Definition: export const DirectoryWalker = createInterfaceId<DirectoryWalker>('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise<URI[]> { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References: - src/common/services/duo_access/project_access_cache.ts:92 - src/common/services/fs/virtual_file_service.ts:46 - src/common/services/fs/virtual_file_service.ts:42
You are a code assistant
Definition of 'register' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp
Definition: register(key: TKey, handler: THandler): Disposable; handle(key: TKey, ...args: Parameters<THandler>): Promise<ReturnType<THandler>>; dispose(): void; } References:
You are a code assistant
Definition of 'has' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp
Definition: has(key: TKey): boolean; register(key: TKey, handler: THandler): Disposable; handle(key: TKey, ...args: Parameters<THandler>): Promise<ReturnType<THandler>>; dispose(): void; } References:
You are a code assistant
Definition of 'DisposeFunc' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp
Definition: export type DisposeFunc = () => void; /** * Represents a structured message map for a webview plugin. */ export type PluginMessageMap = { extensionToPlugin: MessageDefinitions; pluginToExtension: MessageDefinitions; webviewToPlugin: MessageDefinitions; pluginToWebview: MessageDefinitions; }; /** * Utility type for creating a plugin message map with default values. This utility type helps plugin authors define the message map for their plugins without needing to specify every detail. It ensures that the required message structures are in place and provides sensible defaults for any unspecified parts. * * @template T - The partial message map provided by the plugin author. This type should extend `PartialDeep<WebviewPluginMessageMap>`. */ export type CreatePluginMessageMap<T extends PartialDeep<PluginMessageMap>> = { extensionToPlugin: CreateMessageDefinitions<T['extensionToPlugin']>; pluginToExtension: CreateMessageDefinitions<T['pluginToExtension']>; webviewToPlugin: CreateMessageDefinitions<T['webviewToPlugin']>; pluginToWebview: CreateMessageDefinitions<T['pluginToWebview']>; }; type WebviewPluginSetupParams<T extends PluginMessageMap> = { webview: WebviewConnection<{ inbound: T['webviewToPlugin']; outbound: T['pluginToWebview']; }>; extension: MessageBus<{ inbound: T['extensionToPlugin']; outbound: T['pluginToExtension']; }>; }; /** * The `WebviewPluginSetupFunc` is responsible for setting up the communication between the webview plugin and the extension, as well as between the webview plugin and individual webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. * @param webviewMessageBus - The message bus for communication with individual webview instances. * @param extensionMessageBus - The message bus for communication with the webview host (extension). * @returns An optional function to dispose of resources when the plugin is unloaded. */ type WebviewPluginSetupFunc<T extends PluginMessageMap> = ( context: WebviewPluginSetupParams<T>, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep<PluginMessageMap> = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc<CreatePluginMessageMap<TWebviewPluginMessageMap>>; }; References:
You are a code assistant
Definition of 'canClientTrackEvent' in file src/common/tracking/utils.ts in project gitlab-lsp
Definition: export const canClientTrackEvent = ( actions: Array<{ action: TRACKING_EVENTS }> = [], event: TRACKING_EVENTS, ) => { return actions.some(({ action }) => action === event); }; export const generateUniqueTrackingId = (): string => { return uuidv4(); }; References: - src/common/tracking/snowplow_tracker.ts:270 - src/common/tracking/instance_tracker.ts:97 - src/common/tracking/snowplow_tracker.ts:271 - src/common/message_handler.ts:137 - src/common/tracking/instance_tracker.ts:98 - src/common/suggestion/suggestion_service.ts:372
You are a code assistant
Definition of 'CODE_SUGGESTIONS_REQUEST_BYTE_SIZE_LIMIT' in file src/common/advanced_context/helpers.ts in project gitlab-lsp
Definition: export const CODE_SUGGESTIONS_REQUEST_BYTE_SIZE_LIMIT = 50000; // 50KB /** * This is the maxium byte size of the LRU cache used for Open Tabs */ export const LRU_CACHE_BYTE_SIZE_LIMIT = 24 * 1024 * 1024; // 24MB /** * Determines if the advanced context resolver should be used for code suggestions. * Because the Code Suggestions API has other consumers than the language server, * we gate the advanced context resolver behind a feature flag separately. */ export const shouldUseAdvancedContext = ( featureFlagService: FeatureFlagService, configService: ConfigService, ) => { const isEditorAdvancedContextEnabled = featureFlagService.isInstanceFlagEnabled( InstanceFeatureFlags.EditorAdvancedContext, ); const isGenericContextEnabled = featureFlagService.isInstanceFlagEnabled( InstanceFeatureFlags.CodeSuggestionsContext, ); let isEditorOpenTabsContextEnabled = configService.get('client.openTabsContext'); if (isEditorOpenTabsContextEnabled === undefined) { isEditorOpenTabsContextEnabled = true; } /** * TODO - when we introduce other context resolution strategies, * have `isEditorOpenTabsContextEnabled` only disable the corresponding resolver (`lruResolver`) * https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/298 * https://gitlab.com/groups/gitlab-org/editor-extensions/-/epics/59#note_1981542181 */ return ( isEditorAdvancedContextEnabled && isGenericContextEnabled && isEditorOpenTabsContextEnabled ); }; References:
You are a code assistant
Definition of 'getCodeSuggestions' in file src/common/api.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'SocketIoRequestMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp
Definition: export type SocketIoRequestMessage = { requestId: string; type: string; payload: unknown; }; export type SocketResponseMessage = { requestId: string; type: string; payload: unknown; success: boolean; reason?: string | undefined; }; 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:
You are a code assistant
Definition of 'SOCKET_REQUEST_CHANNEL' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: export const SOCKET_REQUEST_CHANNEL = 'request'; export const SOCKET_RESPONSE_CHANNEL = 'response'; export type SocketEvents = | typeof SOCKET_NOTIFICATION_CHANNEL | typeof SOCKET_REQUEST_CHANNEL | typeof SOCKET_RESPONSE_CHANNEL; export class SocketIoMessageBus<TMessages extends MessageMap> implements MessageBus<TMessages> { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification<T extends keyof TMessages['outbound']['notifications']>( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise<void> { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } 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 'publish' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'dispose' in file src/common/git/ignore_manager.ts in project gitlab-lsp
Definition: dispose(): void { this.#ignoreTrie.dispose(); } } References:
You are a code assistant
Definition of 'GITLAB_ORG_URL' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp
Definition: export const GITLAB_ORG_URL: string = 'https://dev.gitlab.org'; export const GITLAB_DEVELOPMENT_URL: string = 'http://localhost'; export enum GitLabEnvironment { GITLAB_COM = 'production', GITLAB_STAGING = 'staging', GITLAB_ORG = 'org', GITLAB_DEVELOPMENT = 'development', GITLAB_SELF_MANAGED = 'self-managed', } export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise<string | undefined> { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise<GitLabPlatformForAccount | undefined> { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } 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 'runWorkflow' in file packages/lib_workflow_api/src/index.ts in project gitlab-lsp
Definition: runWorkflow(goal: string, image: string): Promise<string>; } References:
You are a code assistant
Definition of 'WebviewPluginSetupFunc' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp
Definition: type WebviewPluginSetupFunc<T extends PluginMessageMap> = ( context: WebviewPluginSetupParams<T>, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep<PluginMessageMap> = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc<CreatePluginMessageMap<TWebviewPluginMessageMap>>; }; References:
You are a code assistant
Definition of 'dispose' in file packages/lib_disposable/src/types.ts in project gitlab-lsp
Definition: dispose(): void; } References:
You are a code assistant
Definition of 'WorkspaceFolderUri' in file src/common/git/repository_service.ts in project gitlab-lsp
Definition: type WorkspaceFolderUri = string; 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:280 - src/common/git/repository_service.ts:245 - src/common/git/repository_service.ts:241
You are a code assistant
Definition of 'SuggestionServiceOptions' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp
Definition: export interface SuggestionServiceOptions { telemetryTracker: TelemetryTracker; configService: ConfigService; api: GitLabApiClient; connection: Connection; documentTransformerService: DocumentTransformerService; treeSitterParser: TreeSitterParser; featureFlagService: FeatureFlagService; duoProjectAccessChecker: DuoProjectAccessChecker; } export interface ITelemetryNotificationParams { category: 'code_suggestions'; action: TRACKING_EVENTS; context: { trackingId: string; optionId?: number; }; } 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 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:150
You are a code assistant
Definition of 'constructor' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp
Definition: constructor(name) {} greet() {} } class Greet2 { constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References:
You are a code assistant
Definition of 'stop' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp
Definition: async stop() { this.#currentState = EmitterState.STOPPING; if (this.#timeout) { clearTimeout(this.#timeout); } this.#timeout = undefined; await this.#drainQueue(); } } References:
You are a code assistant
Definition of 'IClientConfig' in file src/common/config_service.ts in project gitlab-lsp
Definition: 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/message_handler.ts:25 - src/common/message_handler.test.ts:112 - src/common/suggestion/suggestion_service.ts:68 - src/common/config_service.ts:80
You are a code assistant
Definition of 'destroyInstance' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp
Definition: public static destroyInstance(): void { LruCache.#instance = undefined; } get openFiles() { return this.#cache; } #getDocumentSize(context: IDocContext): number { const size = getByteSize(`${context.prefix}${context.suffix}`); return Math.max(1, size); } /** * Update the file in the cache. * Uses lru-cache under the hood. */ updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ 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 'WebviewInstanceMessageBus' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp
Definition: export class WebviewInstanceMessageBus<T extends MessageMap = MessageMap> implements WebviewMessageBus<T>, Disposable { #address: WebviewAddress; #runtimeMessageBus: WebviewRuntimeMessageBus; #eventSubscriptions = new CompositeDisposable(); #notificationEvents = new SimpleRegistry<NotificationHandler>(); #requestEvents = new SimpleRegistry<RequestHandler>(); #pendingResponseEvents = new SimpleRegistry<ResponseHandler>(); #logger: Logger; constructor( webviewAddress: WebviewAddress, runtimeMessageBus: WebviewRuntimeMessageBus, logger: Logger, ) { this.#address = webviewAddress; this.#runtimeMessageBus = runtimeMessageBus; this.#logger = withPrefix( logger, `[WebviewInstanceMessageBus:${webviewAddress.webviewId}:${webviewAddress.webviewInstanceId}]`, ); this.#logger.debug('initializing'); const eventFilter = buildWebviewAddressFilter(webviewAddress); this.#eventSubscriptions.add( this.#runtimeMessageBus.subscribe( 'webview:notification', async (message) => { try { await this.#notificationEvents.handle(message.type, message.payload); } catch (error) { this.#logger.debug( `Failed to handle webview instance notification: ${message.type}`, error instanceof Error ? error : undefined, ); } }, eventFilter, ), this.#runtimeMessageBus.subscribe( 'webview:request', async (message) => { try { await this.#requestEvents.handle(message.type, message.requestId, message.payload); } catch (error) { this.#logger.error(error as Error); } }, eventFilter, ), this.#runtimeMessageBus.subscribe( 'webview:response', async (message) => { try { await this.#pendingResponseEvents.handle(message.requestId, message); } catch (error) { this.#logger.error(error as Error); } }, eventFilter, ), ); this.#logger.debug('initialized'); } sendNotification(type: Method, payload?: unknown): void { this.#logger.debug(`Sending notification: ${type}`); this.#runtimeMessageBus.publish('plugin:notification', { ...this.#address, type, payload, }); } onNotification(type: Method, handler: Handler): Disposable { return this.#notificationEvents.register(type, handler); } async sendRequest(type: Method, payload?: unknown): Promise<never> { const requestId = generateRequestId(); this.#logger.debug(`Sending request: ${type}, ID: ${requestId}`); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestHandle = this.#pendingResponseEvents.register( requestId, (message: ResponseMessage) => { if (message.success) { resolve(message.payload as PromiseLike<never>); } else { reject(new Error(message.reason)); } clearTimeout(timeout); pendingRequestHandle.dispose(); }, ); this.#runtimeMessageBus.publish('plugin:request', { ...this.#address, requestId, type, payload, }); timeout = setTimeout(() => { pendingRequestHandle.dispose(); this.#logger.debug(`Request with ID: ${requestId} timed out`); reject(new Error('Request timed out')); }, 10000); }); } onRequest(type: Method, handler: Handler): Disposable { return this.#requestEvents.register(type, (requestId: RequestId, payload: unknown) => { try { const result = handler(payload); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: true, payload: result, }); } catch (error) { this.#logger.error(`Error handling request of type ${type}:`, error as Error); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: false, reason: (error as Error).message, }); } }); } dispose(): void { this.#eventSubscriptions.dispose(); this.#notificationEvents.dispose(); this.#requestEvents.dispose(); this.#pendingResponseEvents.dispose(); } } References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:16 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:21 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:31 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:335
You are a code assistant
Definition of 'PluginMessageMap' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp
Definition: export type PluginMessageMap = { extensionToPlugin: MessageDefinitions; pluginToExtension: MessageDefinitions; webviewToPlugin: MessageDefinitions; pluginToWebview: MessageDefinitions; }; /** * Utility type for creating a plugin message map with default values. This utility type helps plugin authors define the message map for their plugins without needing to specify every detail. It ensures that the required message structures are in place and provides sensible defaults for any unspecified parts. * * @template T - The partial message map provided by the plugin author. This type should extend `PartialDeep<WebviewPluginMessageMap>`. */ export type CreatePluginMessageMap<T extends PartialDeep<PluginMessageMap>> = { extensionToPlugin: CreateMessageDefinitions<T['extensionToPlugin']>; pluginToExtension: CreateMessageDefinitions<T['pluginToExtension']>; webviewToPlugin: CreateMessageDefinitions<T['webviewToPlugin']>; pluginToWebview: CreateMessageDefinitions<T['pluginToWebview']>; }; type WebviewPluginSetupParams<T extends PluginMessageMap> = { webview: WebviewConnection<{ inbound: T['webviewToPlugin']; outbound: T['pluginToWebview']; }>; extension: MessageBus<{ inbound: T['extensionToPlugin']; outbound: T['pluginToExtension']; }>; }; /** * The `WebviewPluginSetupFunc` is responsible for setting up the communication between the webview plugin and the extension, as well as between the webview plugin and individual webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. * @param webviewMessageBus - The message bus for communication with individual webview instances. * @param extensionMessageBus - The message bus for communication with the webview host (extension). * @returns An optional function to dispose of resources when the plugin is unloaded. */ type WebviewPluginSetupFunc<T extends PluginMessageMap> = ( context: WebviewPluginSetupParams<T>, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep<PluginMessageMap> = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc<CreatePluginMessageMap<TWebviewPluginMessageMap>>; }; References:
You are a code assistant
Definition of 'onDocumentChange' in file src/common/document_service.ts in project gitlab-lsp
Definition: onDocumentChange(listener: TextDocumentChangeListener): Disposable; notificationHandler(params: DidChangeDocumentInActiveEditorParams): void; } export const DocumentService = createInterfaceId<DocumentService>('DocumentsWrapper'); const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange'; export class DefaultDocumentService implements DocumentService, HandlesNotification<DidChangeDocumentInActiveEditorParams> { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments<TextDocument>; constructor(documents: TextDocuments<TextDocument>) { this.#documents = documents; this.#subscriptions.push( documents.onDidOpen(this.#createMediatorListener(TextDocumentChangeListenerType.onDidOpen)), ); documents.onDidChangeContent( this.#createMediatorListener(TextDocumentChangeListenerType.onDidChangeContent), ); documents.onDidClose(this.#createMediatorListener(TextDocumentChangeListenerType.onDidClose)); documents.onDidSave(this.#createMediatorListener(TextDocumentChangeListenerType.onDidSave)); } notificationHandler = (param: DidChangeDocumentInActiveEditorParams) => { const document = isTextDocument(param) ? param : this.#documents.get(param); if (!document) { log.error(`Active editor document cannot be retrieved by URL: ${param}`); return; } const event: TextDocumentChangeEvent<TextDocument> = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent<TextDocument>) => { this.#emitter.emit(DOCUMENT_CHANGE_EVENT_NAME, event, type); }; onDocumentChange(listener: TextDocumentChangeListener) { this.#emitter.on(DOCUMENT_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(DOCUMENT_CHANGE_EVENT_NAME, listener), }; } } References:
You are a code assistant
Definition of 'constructor' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp
Definition: constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = commentQueries[language]; if (!queryString) { log.warn(`No comment query found for language: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is on or directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ getCommentForCursor({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): CommentResolution | undefined { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return undefined; } const comments = query.captures(tree.rootNode).map((capture) => { return { start: capture.node.startPosition, end: capture.node.endPosition, content: capture.node.text, capture, }; }); const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition); if (commentAtCursor) { // No need to further check for isPositionInNode etc. as cursor is directly on the comment return { commentAtCursor }; } const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition); if (!commentAboveCursor) { return undefined; } const commentParentNode = commentAboveCursor.capture.node.parent; if (!commentParentNode) { return undefined; } if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) { return undefined; } const directChildren = commentParentNode.children; for (const child of directChildren) { const hasNodeBetweenCursorAndComment = child.startPosition.row > commentAboveCursor.capture.node.endPosition.row && child.startPosition.row <= cursorPosition.row; if (hasNodeBetweenCursorAndComment) { return undefined; } } return { commentAboveCursor }; } static #isPositionInNode(position: Point, node: SyntaxNode): boolean { return position.row >= node.startPosition.row && position.row <= node.endPosition.row; } static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter((comment) => comment.end.row < cursorPosition.row), ); } static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter( (comment) => comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row, ), ); } static #getLastComment(comments: Comment[]): Comment | undefined { return comments.sort((a, b) => b.end.row - a.end.row)[0]; } /** * Returns the total number of lines that are comments in a parsed syntax tree. * Uses a Set because we only want to count each line once. * @param {Object} params - Parameters for counting comment lines. * @param {TreeSitterLanguageName} params.languageName - The name of the programming language. * @param {Tree} params.tree - The syntax tree to analyze. * @param {Language} params.treeSitterLanguage - The Tree-sitter language instance. * @returns {number} - The total number of unique lines containing comments. */ getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set<number>(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:
You are a code assistant
Definition of 'AiContextItemType' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp
Definition: export type AiContextItemType = 'issue' | 'merge_request' | 'file'; export type AiContextItemSubType = 'open_tab' | 'local_file_search'; export type AiContextItem = { id: string; name: string; isEnabled: boolean; info: AiContextItemInfo; type: AiContextItemType; } & ( | { type: 'issue' | 'merge_request'; subType?: never } | { type: 'file'; subType: AiContextItemSubType } ); export type AiContextItemWithContent = AiContextItem & { content: string; }; References: - src/common/ai_context_management_2/ai_context_item.ts:17
You are a code assistant
Definition of 'constructor' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp
Definition: constructor( featureFlagService: FeatureFlagService, configService: ConfigService, documentService: DocumentService, ) { this.#featureFlagService = featureFlagService; configService.onConfigChange((config: IConfig) => { this.#opts = config.client.securityScannerOptions; }); documentService.onDocumentChange( async ( event: TextDocumentChangeEvent<TextDocument>, handlerType: TextDocumentChangeListenerType, ) => { if (handlerType === TextDocumentChangeListenerType.onDidSave) { await this.#runSecurityScan(event.document); } }, ); } 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 'ResolveMessageBusParams' in file packages/lib_webview_client/src/bus/resolve_message_bus.ts in project gitlab-lsp
Definition: type ResolveMessageBusParams = { webviewId: string; providers?: MessageBusProvider[]; logger?: Logger; }; export function resolveMessageBus<TMessages extends MessageMap>( params: ResolveMessageBusParams, ): MessageBus<TMessages> { const { webviewId } = params; const logger = params.logger || new NullLogger(); const providers = params.providers || getDefaultProviders(); for (const provider of providers) { const bus = getMessageBusFromProviderSafe<TMessages>(webviewId, provider, logger); if (bus) { return bus; } } throw new Error(`Unable to resolve a message bus for webviewId: ${webviewId}`); } function getMessageBusFromProviderSafe<TMessages extends MessageMap>( webviewId: string, provider: MessageBusProvider, logger: Logger, ): MessageBus<TMessages> | null { try { logger.debug(`Trying to resolve message bus from provider: ${provider.name}`); const bus = provider.getMessageBus<TMessages>(webviewId); logger.debug(`Message bus resolved from provider: ${provider.name}`); return bus; } catch (error) { logger.debug('Failed to resolve message bus', error as Error); return null; } } References: - packages/lib_webview_client/src/bus/resolve_message_bus.ts:12