instruction
stringclasses
1 value
input
stringlengths
67
168
output
stringlengths
46
67k
You are a code assistant
Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp
Definition: constructor(client: GitLabApiClient) { this.#client = client; } async getForActiveProject(): Promise<GitLabPlatformForProject | undefined> { // return new ChatPlatformForProject(this.#client); return undefined; } async getForActiveAccount(): Promise<GitLabPlatformForAccount | undefined> { return new ChatPlatformForAccount(this.#client); } async getForAllAccounts(): Promise<GitLabPlatformForAccount[]> { return [new ChatPlatformForAccount(this.#client)]; } async getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined> { return new ChatPlatformForAccount(this.#client); } } References:
You are a code assistant
Definition of 'DefaultSuggestionService' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp
Definition: 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.test.ts:74 - src/common/connection.ts:37 - src/common/suggestion/suggestion_service.test.ts:207 - src/common/suggestion/suggestion_service.test.ts:478
You are a code assistant
Definition of 'DesktopFileResolver' in file src/node/services/fs/file.ts in project gitlab-lsp
Definition: export class DesktopFileResolver extends EmptyFileResolver { async readFile({ fileUri }: ReadFile): Promise<string> { return readFile(fsPathFromUri(fileUri), 'utf8'); } } References: - src/node/services/fs/file.test.ts:9 - src/node/services/fs/file.test.ts:12
You are a code assistant
Definition of 'dispose' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp
Definition: dispose() { this.#handlers.clear(); } } function resolveError(e: unknown): Error { if (e instanceof Error) { return e; } if (typeof e === 'string') { return new Error(e); } return new Error('Unknown error'); } References:
You are a code assistant
Definition of 'setupEventSubscriptions' in file packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.ts in project gitlab-lsp
Definition: export const setupEventSubscriptions = ( runtimeMessageBus: WebviewRuntimeMessageBus, transport: Transport, isManaged: IsManagedEventFilter, ): Disposable[] => [ runtimeMessageBus.subscribe( 'plugin:notification', async (message) => { await transport.publish('webview_instance_notification', message); }, isManaged, ), runtimeMessageBus.subscribe( 'plugin:request', async (message) => { await transport.publish('webview_instance_request', message); }, isManaged, ), runtimeMessageBus.subscribe( 'plugin:response', async (message) => { await transport.publish('webview_instance_response', message); }, isManaged, ), ]; References: - packages/lib_webview/src/setup/transport/setup_transport.ts:21 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:36 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:45 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:67 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:95 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:26 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:82
You are a code assistant
Definition of 'DesktopWorkflowRunner' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp
Definition: export class DesktopWorkflowRunner implements WorkflowAPI { #dockerSocket?: string; #folders?: WorkspaceFolder[]; #fetch: LsFetch; #api: GitLabApiClient; #projectPath: string | undefined; constructor(configService: ConfigService, fetch: LsFetch, api: GitLabApiClient) { this.#fetch = fetch; this.#api = api; configService.onConfigChange((config) => this.#reconfigure(config)); } #reconfigure(config: IConfig) { this.#dockerSocket = config.client.duoWorkflowSettings?.dockerSocket; this.#folders = config.client.workspaceFolders || []; this.#projectPath = config.client.projectPath; } async runWorkflow(goal: string, image: string): Promise<string> { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise<string> { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise<void> { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise<void> { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise<string> { const response = await this.#api?.fetchFromApi<CreateWorkflowResponse>({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise<GenerateTokenResponse> { const token = await this.#api?.fetchFromApi<GenerateTokenResponse>({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References: - src/node/duo_workflow/desktop_workflow_runner.test.ts:14 - src/node/main.ts:169 - src/node/duo_workflow/desktop_workflow_runner.test.ts:28
You are a code assistant
Definition of 'destroy' in file src/common/fetch.ts in project gitlab-lsp
Definition: async destroy(): Promise<void> {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return fetch(input, init); } async *streamFetch( /* eslint-disable @typescript-eslint/no-unused-vars */ _url: string, _body: string, _headers: FetchHeaders, /* eslint-enable @typescript-eslint/no-unused-vars */ ): AsyncGenerator<string, void, void> { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References:
You are a code assistant
Definition of 'ExponentialBackoffCircuitBreakerOptions' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: export interface ExponentialBackoffCircuitBreakerOptions { maxErrorsBeforeBreaking?: number; initialBackoffMs?: number; maxBackoffMs?: number; backoffMultiplier?: number; } export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } success() { this.#errorCount = 0; this.#close(); } onOpen(listener: () => void): Disposable { this.#eventEmitter.on('open', listener); return { dispose: () => this.#eventEmitter.removeListener('open', listener) }; } onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References: - src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts:40
You are a code assistant
Definition of 'OptionsCount' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp
Definition: export type OptionsCount = 1 | typeof MANUAL_REQUEST_OPTIONS_COUNT; export const GENERATION = 'generation'; export const COMPLETION = 'completion'; export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined>; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType<SuggestionClientFn>; References: - src/common/suggestion_client/suggestion_client.ts:23 - src/common/suggestion/suggestion_service.ts:425
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/go_comments.go in project gitlab-lsp
Definition: func greet(name string) string { return "Hello, " + name + "!" } // This file has more than 5 non-comment lines var a = 1 var b = 2 var c = 3 var d = 4 var e = 5 var f = 6 func (g Greet) greet() { // function to greet the user } References: - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21 - src/tests/fixtures/intent/empty_function/ruby.rb:20
You are a code assistant
Definition of 'CodeSuggestionRequest' in file src/common/api.ts in project gitlab-lsp
Definition: export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/api.ts:291 - src/common/suggestion_client/create_v2_request.ts:7 - src/common/suggestion/streaming_handler.ts:121 - src/common/api.ts:268 - src/common/api.ts:28 - src/common/suggestion_client/direct_connection_client.ts:98 - src/common/api.ts:29
You are a code assistant
Definition of 'ClassWithDependencies' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set<string>(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map<string, ClassWithDependencies>): ClassWithDependencies[] => { const visited = new Set<string>(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance<T extends object> = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = <T extends object>( id: InterfaceId<T>, instance: T, ): BrandedInstance<T> => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ 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:
You are a code assistant
Definition of 'SecretRedactor' in file src/common/secret_redaction/index.ts in project gitlab-lsp
Definition: export const SecretRedactor = createInterfaceId<SecretRedactor>('SecretRedactor'); @Injectable(SecretRedactor, [ConfigService]) export class DefaultSecretRedactor implements SecretRedactor { #rules: IGitleaksRule[] = []; #configService: ConfigService; constructor(configService: ConfigService) { this.#rules = rules.map((rule) => ({ ...rule, compiledRegex: new RegExp(convertToJavaScriptRegex(rule.regex), 'gmi'), })); this.#configService = configService; } transform(context: IDocContext): IDocContext { if (this.#configService.get('client.codeCompletion.enableSecretRedaction')) { return { prefix: this.redactSecrets(context.prefix), suffix: this.redactSecrets(context.suffix), fileRelativePath: context.fileRelativePath, position: context.position, uri: context.uri, languageId: context.languageId, workspaceFolder: context.workspaceFolder, }; } return context; } redactSecrets(raw: string): string { return this.#rules.reduce((redacted: string, rule: IGitleaksRule) => { return this.#redactRuleSecret(redacted, rule); }, raw); } #redactRuleSecret(str: string, rule: IGitleaksRule): string { if (!rule.compiledRegex) return str; if (!this.#keywordHit(rule, str)) { return str; } const matches = [...str.matchAll(rule.compiledRegex)]; return matches.reduce((redacted: string, match: RegExpMatchArray) => { const secret = match[rule.secretGroup ?? 0]; return redacted.replace(secret, '*'.repeat(secret.length)); }, str); } #keywordHit(rule: IGitleaksRule, raw: string) { if (!rule.keywords?.length) { return true; } for (const keyword of rule.keywords) { if (raw.toLowerCase().includes(keyword)) { return true; } } return false; } } References: - src/common/document_transformer_service.ts:81 - src/common/secret_redaction/redactor.test.ts:20 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:18
You are a code assistant
Definition of 'setCodeSuggestionsContext' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp
Definition: public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ) { if (this.#circuitBreaker.isOpen()) { return; } const { language, isStreaming } = context; // Only auto-reject if client is set up to track accepted and not rejected events. if ( canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) && !canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED) ) { this.rejectOpenedSuggestions(); } setTimeout(() => { if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) { this.#codeSuggestionsContextMap.delete(uniqueTrackingId); this.#codeSuggestionStates.delete(uniqueTrackingId); } }, GC_TIME); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { is_streaming: isStreaming, language, timestamp: new Date().toISOString(), }); if (this.#isStreamingSuggestion(uniqueTrackingId)) return; this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`); } async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`, ); // Allow state to update to ACCEPTED despite 'allowed transitions' constraint. if (newState !== TRACKING_EVENTS.ACCEPTED) { return; } log.debug( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:
You are a code assistant
Definition of 'PostRequest' in file src/common/api_types.ts in project gitlab-lsp
Definition: interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'POST'; body?: unknown; } /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'GET'; searchParams?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:
You are a code assistant
Definition of 'TreeSitterParserLoadState' in file src/common/tree_sitter/parser.ts in project gitlab-lsp
Definition: export enum TreeSitterParserLoadState { INIT = 'init', ERRORED = 'errored', READY = 'ready', UNIMPLEMENTED = 'unimplemented', } export type TreeAndLanguage = { tree: Parser.Tree; languageInfo: TreeSitterLanguageInfo; language: Language; }; export abstract class TreeSitterParser { protected loadState: TreeSitterParserLoadState; protected languages: Map<string, TreeSitterLanguageInfo>; protected readonly parsers = new Map<TreeSitterLanguageName, Parser>(); abstract init(): Promise<void>; constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) { this.languages = this.buildTreeSitterInfoByExtMap(languages); this.loadState = TreeSitterParserLoadState.INIT; } get loadStateValue(): TreeSitterParserLoadState { return this.loadState; } async parseFile(context: IDocContext): Promise<TreeAndLanguage | undefined> { const init = await this.#handleInit(); if (!init) { return undefined; } const languageInfo = this.getLanguageInfoForFile(context.fileRelativePath); if (!languageInfo) { return undefined; } const parser = await this.getParser(languageInfo); if (!parser) { log.debug( 'TreeSitterParser: Skipping intent detection using tree-sitter due to missing parser.', ); return undefined; } const tree = parser.parse(`${context.prefix}${context.suffix}`); return { tree, language: parser.getLanguage(), languageInfo, }; } async #handleInit(): Promise<boolean> { try { await this.init(); return true; } catch (err) { log.warn('TreeSitterParser: Error initializing an appropriate tree-sitter parser', err); this.loadState = TreeSitterParserLoadState.ERRORED; } return false; } getLanguageNameForFile(filename: string): TreeSitterLanguageName | undefined { return this.getLanguageInfoForFile(filename)?.name; } async getParser(languageInfo: TreeSitterLanguageInfo): Promise<Parser | undefined> { if (this.parsers.has(languageInfo.name)) { return this.parsers.get(languageInfo.name) as Parser; } try { const parser = new Parser(); const language = await Parser.Language.load(languageInfo.wasmPath); parser.setLanguage(language); this.parsers.set(languageInfo.name, parser); log.debug( `TreeSitterParser: Loaded tree-sitter parser (tree-sitter-${languageInfo.name}.wasm present).`, ); return parser; } catch (err) { this.loadState = TreeSitterParserLoadState.ERRORED; // NOTE: We validate the below is not present in generation.test.ts integration test. // Make sure to update the test appropriately if changing the error. log.warn( 'TreeSitterParser: Unable to load tree-sitter parser due to an unexpected error.', err, ); return undefined; } } getLanguageInfoForFile(filename: string): TreeSitterLanguageInfo | undefined { const ext = filename.split('.').pop(); return this.languages.get(`.${ext}`); } buildTreeSitterInfoByExtMap( languages: TreeSitterLanguageInfo[], ): Map<string, TreeSitterLanguageInfo> { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map<string, TreeSitterLanguageInfo>()); } } References: - src/common/tree_sitter/parser.ts:20 - src/common/tree_sitter/parser.ts:33
You are a code assistant
Definition of 'installLanguage' in file scripts/wasm/build_tree_sitter_wasm.ts in project gitlab-lsp
Definition: async function installLanguage(language: TreeSitterLanguageInfo) { const grammarsDir = resolve(cwd(), 'vendor', 'grammars'); try { await mkdir(grammarsDir, { recursive: true }); if (!language.nodeModulesPath) { console.warn('nodeModulesPath undefined for grammar!'); return; } await execaCommand( `npm run tree-sitter -- build --wasm node_modules/${language.nodeModulesPath}`, ); const wasmLanguageFile = path.join(cwd(), `tree-sitter-${language.name}.wasm`); console.log(`Installed ${language.name} parser successfully.`); await copyFile(wasmLanguageFile, path.join(grammarsDir, `tree-sitter-${language.name}.wasm`)); await execaCommand(`rm ${wasmLanguageFile}`); } catch (error) { console.error(`Error installing ${language.name} parser:`, error); } } async function installLanguages() { const installPromises = TREE_SITTER_LANGUAGES.map(installLanguage); await Promise.all(installPromises); } installLanguages() .then(() => { console.log('Language parsers installed successfully.'); }) .catch((error) => { console.error('Error installing language parsers:', error); }); References:
You are a code assistant
Definition of 'info' in file src/common/log_types.ts in project gitlab-lsp
Definition: info(message: string, e?: Error): void; warn(e: Error): void; warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } export const LOG_LEVEL = { DEBUG: 'debug', INFO: 'info', WARNING: 'warning', ERROR: 'error', } as const; export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL]; References:
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp
Definition: func greet(name string) {} func greet(name string) { fmt.Println(name) } var greet = func(name string) { } var greet = func(name string) { fmt.Println(name) } type Greet struct{} type Greet struct { name string } // empty method declaration func (g Greet) greet() { } // non-empty method declaration func (g Greet) greet() { fmt.Printf("Hello %s\n", g.name) } References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21
You are a code assistant
Definition of 'write' in file src/node/http/utils/create_logger_transport.ts in project gitlab-lsp
Definition: write(chunk, _encoding, callback) { logger[level](chunk.toString()); callback(); }, }); References:
You are a code assistant
Definition of 'WEBVIEW_BASE_PATH' in file src/node/webview/constants.ts in project gitlab-lsp
Definition: export const WEBVIEW_BASE_PATH = path.join(__dirname, '../../../out/webviews/'); References:
You are a code assistant
Definition of 'constructor' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp
Definition: constructor(server: Server, logger?: Logger) { this.#server = server; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#initialize(); } #initialize(): void { this.#logger?.debug('Initializing webview transport'); const namespace = this.#server.of(NAMESPACE_REGEX_PATTERN); namespace.on('connection', (socket) => { const match = socket.nsp.name.match(NAMESPACE_REGEX_PATTERN); if (!match) { this.#logger?.error('Failed to parse namespace for socket connection'); return; } const webviewId = match[1] as WebviewId; const webviewInstanceId = randomUUID() as WebviewInstanceId; const webviewInstanceInfo: WebviewInstanceInfo = { webviewId, webviewInstanceId, }; const connectionId = buildConnectionId(webviewInstanceInfo); this.#connections.set(connectionId, socket); this.#messageEmitter.emit('webview_instance_created', webviewInstanceInfo); socket.on(SOCKET_NOTIFICATION_CHANNEL, (message: unknown) => { if (!isSocketNotificationMessage(message)) { this.#logger?.debug(`[${connectionId}] received notification with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received notification`); this.#messageEmitter.emit('webview_instance_notification_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, }); }); socket.on(SOCKET_REQUEST_CHANNEL, (message: unknown) => { if (!isSocketRequestMessage(message)) { this.#logger?.debug(`[${connectionId}] received request with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received request`); this.#messageEmitter.emit('webview_instance_request_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, requestId: message.requestId, }); }); socket.on(SOCKET_RESPONSE_CHANNEL, (message: unknown) => { if (!isSocketResponseMessage(message)) { this.#logger?.debug(`[${connectionId}] received response with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received response`); this.#messageEmitter.emit('webview_instance_response_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, requestId: message.requestId, success: message.success, reason: message.reason ?? '', }); }); socket.on('error', (error) => { this.#logger?.debug(`[${connectionId}] error`, error); }); socket.on('disconnect', (reason) => { this.#logger?.debug(`[${connectionId}] disconnected with reason: ${reason}`); this.#connections.delete(connectionId); this.#messageEmitter.emit('webview_instance_destroyed', webviewInstanceInfo); }); }); this.#logger?.debug('transport initialized'); } async publish<K extends keyof MessagesToClient>( type: K, message: MessagesToClient[K], ): Promise<void> { const connectionId = buildConnectionId({ webviewId: message.webviewId, webviewInstanceId: message.webviewInstanceId, }); const connection = this.#connections.get(connectionId); if (!connection) { this.#logger?.error(`No active socket found for ID ${connectionId}`); return; } switch (type) { case 'webview_instance_notification': connection.emit(SOCKET_NOTIFICATION_CHANNEL, { type: message.type, payload: message.payload, }); return; case 'webview_instance_request': connection.emit(SOCKET_REQUEST_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_request']).requestId, }); return; case 'webview_instance_response': connection.emit(SOCKET_RESPONSE_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_response']).requestId, }); return; default: this.#logger?.error(`Unknown message type ${type}`); } } on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } dispose() { this.#messageEmitter.removeAllListeners(); for (const connection of this.#connections.values()) { connection.disconnect(); } this.#connections.clear(); } } References:
You are a code assistant
Definition of 'GitLabApiClient' in file src/common/api.ts in project gitlab-lsp
Definition: export const GitLabApiClient = createInterfaceId<GitLabApiClient>('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/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 - 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
You are a code assistant
Definition of 'getSuggestions' in file src/common/suggestion_client/suggestion_client_pipeline.ts in project gitlab-lsp
Definition: getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined> { return this.#pipeline(context); } } References:
You are a code assistant
Definition of 'JsonRpcConnectionTransportProps' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp
Definition: export type JsonRpcConnectionTransportProps = { connection: Connection; logger: Logger; notificationRpcMethod?: string; webviewCreatedRpcMethod?: string; webviewDestroyedRpcMethod?: string; }; export class JsonRpcConnectionTransport implements Transport { #messageEmitter = createWebviewTransportEventEmitter(); #connection: Connection; #notificationChannel: string; #webviewCreatedChannel: string; #webviewDestroyedChannel: string; #logger?: Logger; #disposables: Disposable[] = []; constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void> { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:79
You are a code assistant
Definition of 'WebviewUriProvider' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp
Definition: export interface WebviewUriProvider { getUri(webviewId: WebviewId): Uri; } export interface WebviewUriProviderRegistry { register(provider: WebviewUriProvider): void; } export class WebviewLocationService implements WebviewUriProviderRegistry { #uriProviders = new Set<WebviewUriProvider>(); register(provider: WebviewUriProvider) { this.#uriProviders.add(provider); } resolveUris(webviewId: WebviewId): Uri[] { const uris: Uri[] = []; for (const provider of this.#uriProviders) { uris.push(provider.getUri(webviewId)); } return uris; } } References: - src/common/webview/webview_resource_location_service.ts:16 - src/common/webview/webview_resource_location_service.ts:10
You are a code assistant
Definition of 'buildWebviewIdFilter' in file packages/lib_webview/src/setup/plugin/utils/filters.ts in project gitlab-lsp
Definition: export const buildWebviewIdFilter = (webviewId: WebviewId) => <T extends { webviewId: WebviewId }>(event: T): boolean => { return event.webviewId === webviewId; }; export const buildWebviewAddressFilter = (address: WebviewAddress) => <T extends WebviewAddress>(event: T): boolean => { return ( event.webviewId === address.webviewId && event.webviewInstanceId === address.webviewInstanceId ); }; References: - packages/lib_webview/src/setup/plugin/webview_controller.ts:76
You are a code assistant
Definition of 'TokenCheckNotifier' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp
Definition: export interface TokenCheckNotifier extends Notifier<TokenCheckNotificationParams> {} export const TokenCheckNotifier = createInterfaceId<TokenCheckNotifier>('TokenCheckNotifier'); @Injectable(TokenCheckNotifier, [GitLabApiClient]) export class DefaultTokenCheckNotifier implements TokenCheckNotifier { #notify: NotifyFn<TokenCheckNotificationParams> | undefined; constructor(api: GitLabApiClient) { api.onApiReconfigured(async ({ isInValidState, validationMessage }) => { if (!isInValidState) { if (!this.#notify) { throw new Error( 'The DefaultTokenCheckNotifier has not been initialized. Call init first.', ); } await this.#notify({ message: validationMessage, }); } }); } init(callback: NotifyFn<TokenCheckNotificationParams>) { this.#notify = callback; } } References: - src/common/core/handlers/token_check_notifier.test.ts:8 - src/common/connection_service.ts:61
You are a code assistant
Definition of 'get' in file src/common/fetch.ts in project gitlab-lsp
Definition: get(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; post(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>; } export const LsFetch = createInterfaceId<LsFetch>('LsFetch'); export class FetchBase implements LsFetch { updateRequestInit(method: string, init?: RequestInit): RequestInit { if (typeof init === 'undefined') { // eslint-disable-next-line no-param-reassign init = { method }; } else { // eslint-disable-next-line no-param-reassign init.method = method; } return init; } async initialize(): Promise<void> {} async destroy(): Promise<void> {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return fetch(input, init); } async *streamFetch( /* eslint-disable @typescript-eslint/no-unused-vars */ _url: string, _body: string, _headers: FetchHeaders, /* eslint-enable @typescript-eslint/no-unused-vars */ ): AsyncGenerator<string, void, void> { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References: - src/common/utils/headers_to_snowplow_options.ts:22 - src/common/utils/headers_to_snowplow_options.ts:21 - src/common/config_service.ts:134 - src/common/utils/headers_to_snowplow_options.ts:12 - src/common/utils/headers_to_snowplow_options.ts:20
You are a code assistant
Definition of 'getLanguageServerVersion' in file src/common/utils/get_language_server_version.ts in project gitlab-lsp
Definition: export function getLanguageServerVersion(): string { return '{{GITLAB_LANGUAGE_SERVER_VERSION}}'; } References: - src/node/main.ts:84 - src/common/api.ts:419 - src/browser/main.ts:117 - src/common/suggestion_client/direct_connection_client.ts:112
You are a code assistant
Definition of 'constructor' in file src/common/webview/extension/utils/extension_message_handler_registry.ts in project gitlab-lsp
Definition: constructor() { super((key) => `${key.webviewId}:${key.type}`); } } References:
You are a code assistant
Definition of 'getMetadata' in file src/common/webview/webview_metadata_provider.ts in project gitlab-lsp
Definition: getMetadata(): WebviewMetadata[] { return Array.from(this.#plugins).map((plugin) => ({ id: plugin.id, title: plugin.title, uris: this.#accessInfoProviders.resolveUris(plugin.id), })); } } References:
You are a code assistant
Definition of 'triggerDocumentEvent' in file src/common/feature_state/supported_language_check.test.ts in project gitlab-lsp
Definition: function triggerDocumentEvent( languageId: string, handlerType: TextDocumentChangeListenerType = TextDocumentChangeListenerType.onDidSetActive, ) { const document = createFakePartial<TextDocument>({ languageId }); const event = createFakePartial<TextDocumentChangeEvent<TextDocument>>({ document }); documentEventListener(event, handlerType); } beforeEach(async () => { onDocumentChange.mockImplementation((_listener) => { documentEventListener = _listener; }); configService.set('client.codeCompletion.disabledSupportedLanguages', []); configService.set('client.codeCompletion.additionalLanguages', []); listener.mockReset(); check = new DefaultCodeSuggestionsSupportedLanguageCheck(documents, supportedLanguagesService); disposables.push(check.onChanged(listener)); }); afterEach(() => { while (disposables.length > 0) { disposables.pop()!.dispose(); } }); describe('is updated on "TextDocumentChangeListenerType.onDidSetActive" document change event', () => { it('should NOT be engaged when document language is supported', () => { BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES.forEach((languageId: string) => { triggerDocumentEvent(languageId); expect(check.engaged).toBe(false); expect(check.id).toEqual(expect.any(String)); }); }); it('should NOT be engaged when document language is enabled but not supported', () => { configService.set('client.codeCompletion.additionalLanguages', [mockUnsupportedLanguage]); triggerDocumentEvent(mockUnsupportedLanguage); expect(check.engaged).toBe(false); expect(check.id).toEqual(expect.any(String)); }); it('should be engaged when document language is disabled', () => { const languageId = 'python'; configService.set('client.codeCompletion.disabledSupportedLanguages', [languageId]); triggerDocumentEvent(languageId); expect(check.engaged).toBe(true); expect(check.id).toBe(DISABLED_LANGUAGE); }); it('should be engaged when document language is NOT supported', () => { triggerDocumentEvent(mockUnsupportedLanguage); expect(check.engaged).toBe(true); expect(check.id).toBe(UNSUPPORTED_LANGUAGE); }); }); describe('change event', () => { let initialEngaged: boolean; let initialId: string; beforeEach(() => { initialEngaged = check.engaged; initialId = check.id; }); it('emits after check is updated', () => { listener.mockImplementation(() => { expect(check.engaged).toBe(!initialEngaged); }); triggerDocumentEvent('python'); expect(listener).toHaveBeenCalledTimes(1); }); it('emits when only engaged property changes', () => { triggerDocumentEvent('python'); expect(listener).toHaveBeenCalledTimes(1); expect(check.engaged).toBe(!initialEngaged); expect(check.id).toBe(initialId); }); }); }); References: - src/common/feature_state/project_duo_acces_check.test.ts:117 - src/common/feature_state/supported_language_check.test.ts:109 - src/common/feature_state/project_duo_acces_check.test.ts:134 - src/common/feature_state/supported_language_check.test.ts:81 - src/common/feature_state/project_duo_acces_check.test.ts:96 - src/common/feature_state/project_duo_acces_check.test.ts:106 - src/common/feature_state/supported_language_check.test.ts:115 - src/common/feature_state/supported_language_check.test.ts:72 - src/common/feature_state/supported_language_check.test.ts:88 - src/common/feature_state/supported_language_check.test.ts:63
You are a code assistant
Definition of 'NotifyFn' in file src/common/notifier.ts in project gitlab-lsp
Definition: export type NotifyFn<T> = (data: T) => Promise<void>; export interface Notifier<T> { init(notify: NotifyFn<T>): void; } References:
You are a code assistant
Definition of 'SuccessMessage' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: 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: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:133
You are a code assistant
Definition of 'dispose' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'workflowPluginFactory' in file packages/webview_duo_workflow/src/plugin/index.ts in project gitlab-lsp
Definition: export const workflowPluginFactory = ( graphqlApi: WorkflowGraphQLService, workflowApi: WorkflowAPI, connection: Connection, ): WebviewPlugin<DuoWorkflowMessages> => { return { id: WEBVIEW_ID, title: WEBVIEW_TITLE, setup: ({ webview }) => { webview.onInstanceConnected((_webviewInstanceId, messageBus) => { messageBus.onNotification('startWorkflow', async ({ goal, image }) => { try { const workflowId = await workflowApi.runWorkflow(goal, image); messageBus.sendNotification('workflowStarted', workflowId); await graphqlApi.pollWorkflowEvents(workflowId, messageBus); } catch (e) { const error = e as Error; messageBus.sendNotification('workflowError', error.message); } }); messageBus.onNotification('openUrl', async ({ url }) => { await connection.sendNotification('$/gitlab/openUrl', { url }); }); }); }, }; }; References: - src/node/main.ts:219
You are a code assistant
Definition of 'DefaultDuoProjectPolicy' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp
Definition: export class DefaultDuoProjectPolicy implements AiContextPolicy { constructor(private duoProjectAccessChecker: DuoProjectAccessChecker) {} isAllowed(aiProviderItem: AiContextProviderItem): Promise<{ allowed: boolean; reason?: string }> { const { providerType } = aiProviderItem; switch (providerType) { case 'file': { const { repositoryFile } = aiProviderItem; if (!repositoryFile) { return Promise.resolve({ allowed: true }); } const duoProjectStatus = this.duoProjectAccessChecker.checkProjectStatus( repositoryFile.uri.toString(), repositoryFile.workspaceFolder, ); const enabled = duoProjectStatus === DuoProjectStatus.DuoEnabled || duoProjectStatus === DuoProjectStatus.NonGitlabProject; if (!enabled) { return Promise.resolve({ allowed: false, reason: 'Duo is not enabled for this project' }); } return Promise.resolve({ allowed: true }); } default: { throw new Error(`Unknown provider type ${providerType}`); } } } } References:
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp
Definition: function greet(name) {} function greet2(name) { console.log(name); } const greet3 = function (name) {}; const greet4 = function (name) { console.log(name); }; const greet5 = (name) => {}; const greet6 = (name) => { console.log(name); }; class Greet { constructor(name) {} greet() {} } class Greet2 { name: string; constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21
You are a code assistant
Definition of 'DiagnosticsPublisher' in file src/common/diagnostics_publisher.ts in project gitlab-lsp
Definition: export interface DiagnosticsPublisher { init(publish: DiagnosticsPublisherFn): void; } References: - src/common/connection_service.ts:100
You are a code assistant
Definition of 'sendInitialize' in file src/tests/int/lsp_client.ts in project gitlab-lsp
Definition: public async sendInitialize( initializeParams?: CustomInitializeParams, ): Promise<InitializeResult> { const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams }; const request = new RequestType<InitializeParams, InitializeResult, InitializeError>( 'initialize', ); const response = await this.#connection.sendRequest(request, params); return response; } /** * Send the LSP 'initialized' notification */ public async sendInitialized(options?: InitializedParams | undefined): Promise<void> { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType<InitializedParams>('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise<void> { const defaults = createFakePartial<ChangeConfigOptions>({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType<DidChangeConfigurationParams>( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType<DidOpenTextDocumentParams>('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise<void> { const params = { textDocument: { uri, }, }; const request = new NotificationType<DidCloseTextDocumentParams>('textDocument/didClose'); await this.#connection.sendNotification(request, params); } /** * Send LSP 'textDocument/didChange' using Full sync method notification * * @param uri File URL. Should include the workspace path in the url * @param version Change version (incrementing from 0) * @param text Full contents of the file */ public async sendTextDocumentDidChangeFull( uri: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType<DidChangeTextDocumentParams>('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise<CompletionItem[] | CompletionList | null> { const params: CompletionParams = { textDocument: { uri, }, position: { line, character, }, context: { triggerKind: 1, // invoked }, }; const request = new RequestType1< CompletionParams, CompletionItem[] | CompletionList | null, void >('textDocument/completion'); const result = await this.#connection.sendRequest(request, params); return result; } public async sendDidChangeDocumentInActiveEditor(uri: string): Promise<void> { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise<WebviewMetadata[]> { const result = await this.#connection.sendRequest<WebviewMetadata[]>( '$/gitlab/webview-metadata', ); return result; } } References:
You are a code assistant
Definition of 'ResponseMessage' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp
Definition: 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:37 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:112 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:34 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:13
You are a code assistant
Definition of 'CancelStreaming' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp
Definition: export const CancelStreaming = new NotificationType<StreamWithId>( CANCEL_STREAMING_COMPLETION_NOTIFICATION, ); export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References:
You are a code assistant
Definition of 'handle' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp
Definition: handle(key: TKey, ...args: Parameters<THandler>): Promise<ReturnType<THandler>>; dispose(): void; } References:
You are a code assistant
Definition of 'TOKEN_CHECK_NOTIFICATION' in file src/common/notifications.ts in project gitlab-lsp
Definition: export const TOKEN_CHECK_NOTIFICATION = '$/gitlab/token/check'; export const FEATURE_STATE_CHANGE = '$/gitlab/featureStateChange'; export type FeatureStateNotificationParams = FeatureState[]; export const FeatureStateChangeNotificationType = new NotificationType<FeatureStateNotificationParams>(FEATURE_STATE_CHANGE); export interface TokenCheckNotificationParams { message?: string; } 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 'KeysWithOptionalValues' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: export type KeysWithOptionalValues<T> = { [K in keyof T]: undefined extends T[K] ? K : never; }[keyof T]; /** * Maps notification message types to their corresponding payloads. * @typedef {Record<Method, MessagePayload>} NotificationMap */ export type NotificationMap = Record<Method, MessagePayload>; /** * Interface for publishing notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationPublisher<TNotifications extends NotificationMap> { sendNotification<T extends KeysWithOptionalValues<TNotifications>>(type: T): void; sendNotification<T extends keyof TNotifications>(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener<TNotifications extends NotificationMap> { onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'getWorkflowEvents' in file src/common/graphql/workflow/service.ts in project gitlab-lsp
Definition: async getWorkflowEvents(id: string): Promise<LangGraphCheckpoint[]> { try { const data: DuoWorkflowEventConnectionType = await this.#apiClient.fetchFromApi({ type: 'graphql', query: GET_WORKFLOW_EVENTS_QUERY, variables: { workflowId: id }, }); return this.sortCheckpoints(data?.duoWorkflowEvents?.nodes || []); } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } } } References:
You are a code assistant
Definition of 'engaged' in file src/common/feature_state/feature_state_manager.test.ts in project gitlab-lsp
Definition: get engaged() { return duoProjectAccessCheckEngaged; }, id: DUO_DISABLED_FOR_PROJECT, details: 'DUO is disabled for this project', onChanged: mockOn, }); // the CodeSuggestionStateManager is a top-level service that orchestrates the feature checks and sends out notifications, it doesn't have public API const stateManager = new DefaultFeatureStateManager( supportedLanguageCheck, duoProjectAccessCheck, ); stateManager.init(mockSendNotification); mockSendNotification.mockReset(); }); describe('on check engage', () => { it('should notify the client', async () => { const mockChecksEngagedState = createFakePartial<FeatureState[]>([ { featureId: CODE_SUGGESTIONS, engagedChecks: [ { checkId: UNSUPPORTED_LANGUAGE, details: 'Language is not supported', }, ], }, { featureId: CHAT, engagedChecks: [], }, ]); notifyClient(); expect(mockSendNotification).toHaveBeenCalledWith( expect.arrayContaining(mockChecksEngagedState), ); }); }); describe('on check disengage', () => { const mockNoCheckEngagedState = createFakePartial<FeatureState[]>([ { featureId: CODE_SUGGESTIONS, engagedChecks: [], }, { featureId: CHAT, engagedChecks: [], }, ]); it('should notify the client', () => { languageCheckEngaged = false; notifyClient(); expect(mockSendNotification).toHaveBeenCalledWith(mockNoCheckEngagedState); }); }); }); References:
You are a code assistant
Definition of 'createWebviewTransportEventEmitter' in file packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp
Definition: export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:59 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:34
You are a code assistant
Definition of 'info' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:
You are a code assistant
Definition of 'AiActionResponseType' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: 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 'sendNotification' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: 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 'Comment' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp
Definition: export type Comment = { start: Point; end: Point; content: string; capture: QueryCapture; }; export type CommentResolution = | { commentAtCursor: Comment; commentAboveCursor?: never } | { commentAtCursor?: never; commentAboveCursor: Comment }; export class CommentResolver { protected queryByLanguage: Map<string, Query>; 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: - src/common/tree_sitter/comments/comment_resolver.ts:14 - src/common/tree_sitter/comments/comment_resolver.ts:15 - src/common/tree_sitter/intent_resolver.ts:13 - src/common/tree_sitter/comments/comment_resolver.ts:159
You are a code assistant
Definition of 'LRU_CACHE_BYTE_SIZE_LIMIT' in file src/common/advanced_context/helpers.ts in project gitlab-lsp
Definition: 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 'TreeSitterLanguageInfo' in file src/common/tree_sitter/languages.ts in project gitlab-lsp
Definition: export interface TreeSitterLanguageInfo { name: TreeSitterLanguageName; extensions: string[]; wasmPath: string; nodeModulesPath?: string; } References: - scripts/wasm/build_tree_sitter_wasm.ts:8 - src/common/tree_sitter/parser.ts:78 - src/common/tree_sitter/parser.ts:15
You are a code assistant
Definition of 'build' in file scripts/esbuild/browser.ts in project gitlab-lsp
Definition: async function build() { await esbuild.build(config); } void build(); References: - scripts/esbuild/desktop.ts:41 - scripts/esbuild/common.ts:31 - scripts/esbuild/browser.ts:26
You are a code assistant
Definition of 'init' in file src/common/tree_sitter/parser.test.ts in project gitlab-lsp
Definition: async init() { this.loadState = TreeSitterParserLoadState.READY; } })({ languages }); }); afterEach(() => { jest.resetAllMocks(); }); describe('init', () => { it('should initialize the parser', async () => { await treeSitterParser.init(); expect(treeSitterParser.loadStateValue).toBe(TreeSitterParserLoadState.READY); }); it('should handle initialization error', async () => { treeSitterParser.init = async () => { throw new Error('Initialization error'); }; await treeSitterParser.parseFile({} as IDocContext); expect(treeSitterParser.loadStateValue).toBe(TreeSitterParserLoadState.ERRORED); }); }); describe('parseFile', () => { it('should parse a file with a valid parser', async () => { const iDocContext: IDocContext = { fileRelativePath: 'test.ts', prefix: 'function test() {}', suffix: '', position: { line: 0, character: 0 }, languageId: 'typescript', uri: 'file:///test.ts', }; const parseFn = jest.fn().mockReturnValue({}); const getLanguageFn = jest.fn().mockReturnValue(createFakePartial<Parser.Language>({})); jest.spyOn(treeSitterParser, 'getLanguageInfoForFile').mockReturnValue(languages[0]); jest.spyOn(treeSitterParser, 'getParser').mockResolvedValue( createFakePartial<Parser>({ parse: parseFn, getLanguage: getLanguageFn, }), ); const result = await treeSitterParser.parseFile(iDocContext); expect(parseFn).toHaveBeenCalled(); expect(result).toEqual({ tree: expect.any(Object), language: expect.any(Object), languageInfo: languages[0], }); }); it('should return undefined when no parser is available for the file', async () => { const iDocContext: IDocContext = { fileRelativePath: 'test.txt', prefix: 'Some text', suffix: '', position: { line: 0, character: 0 }, languageId: 'plaintext', uri: 'file:///test.txt', }; const result = await treeSitterParser.parseFile(iDocContext); expect(result).toBeUndefined(); }); }); describe('getParser', () => { it('should return the parser for languageInfo', async () => { // mock namespace Parser.Language (Parser as unknown as Record<string, unknown>).Language = { load: jest.fn().mockResolvedValue({}), }; class FakeParser { setLanguage = jest.fn(); } jest.mocked(Parser).mockImplementation(() => createFakePartial<Parser>(new FakeParser())); const loadSpy = jest.spyOn(Parser.Language, 'load'); const result = await treeSitterParser.getParser({ name: 'typescript', extensions: ['.ts'], wasmPath: '/path/to/tree-sitter-typescript.wasm', nodeModulesPath: '/path/to/node_modules', }); expect(loadSpy).toHaveBeenCalledWith('/path/to/tree-sitter-typescript.wasm'); expect(result).toBeInstanceOf(FakeParser); }); it('should handle parser loading error', async () => { (Parser.Language.load as jest.Mock).mockRejectedValue(new Error('Loading error')); const result = await treeSitterParser.getParser({ name: 'typescript', extensions: ['.ts'], wasmPath: '/path/to/tree-sitter-typescript.wasm', nodeModulesPath: '/path/to/node_modules', }); expect(treeSitterParser.loadStateValue).toBe(TreeSitterParserLoadState.ERRORED); expect(result).toBeUndefined(); }); }); describe('getLanguageNameForFile', () => { it('should return the language name for a given file', () => { const result = treeSitterParser.getLanguageNameForFile('test.ts'); expect(result).toBe('typescript'); }); it('should return undefined when no language is found for a file', () => { const result = treeSitterParser.getLanguageNameForFile('test.txt'); expect(result).toBeUndefined(); }); }); describe('buildTreeSitterInfoByExtMap', () => { it('should build the language info map by extension', () => { const result = treeSitterParser.buildTreeSitterInfoByExtMap(languages); expect(result).toEqual( new Map([ ['.ts', languages[0]], ['.js', languages[1]], ]), ); }); }); }); References:
You are a code assistant
Definition of 'createFastifyHttpServer' in file src/node/http/create_fastify_http_server.ts in project gitlab-lsp
Definition: export const createFastifyHttpServer = async ( props: Partial<CreateFastifyServerProps>, ): Promise<CreateHttpServerResult> => { const { port = 0, plugins = [] } = props; const logger = props.logger && loggerWithPrefix(props.logger, '[HttpServer]:'); const server = fastify({ forceCloseConnections: true, ignoreTrailingSlash: true, logger: createFastifyLogger(logger), }); try { await registerPlugins(server, plugins, logger); const address = await startFastifyServer(server, port, logger); await server.ready(); logger?.info(`server listening on ${address}`); return { address, server, shutdown: async () => { try { await server.close(); logger?.info('server shutdown'); } catch (err) { logger?.error('error during server shutdown', err as Error); } }, }; } catch (err) { logger?.error('error during server setup', err as Error); throw err; } }; const registerPlugins = async ( server: FastifyInstance, plugins: FastifyPluginRegistration[], logger?: ILog, ) => { await Promise.all( plugins.map(async ({ plugin, options }) => { try { await server.register(plugin, options); } catch (err) { logger?.error('Error during plugin registration', err as Error); throw err; } }), ); }; const startFastifyServer = (server: FastifyInstance, port: number, logger?: ILog): Promise<URL> => new Promise((resolve, reject) => { try { server.listen({ port, host: '127.0.0.1' }, (err, address) => { if (err) { logger?.error(err); reject(err); return; } resolve(new URL(address)); }); } catch (error) { reject(error); } }); const createFastifyLogger = (logger?: ILog): FastifyBaseLogger | undefined => logger ? pino(createLoggerTransport(logger)) : undefined; References: - src/node/http/create_fastify_http_server.test.ts:78 - src/node/http/create_fastify_http_server.test.ts:51 - src/node/http/create_fastify_http_server.test.ts:104 - src/node/setup_http.ts:25 - src/node/http/create_fastify_http_server.test.ts:36 - src/node/http/create_fastify_http_server.test.ts:62 - src/node/http/create_fastify_http_server.test.ts:89
You are a code assistant
Definition of 'getCachedSuggestions' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp
Definition: getCachedSuggestions(request: SuggestionCacheContext): SuggestionCache | undefined { if (!this.#getCurrentConfig().enabled) { return undefined; } const currentLine = request.context.prefix.split('\n').at(-1) ?? ''; const key = this.#getSuggestionKey(request); const candidate = this.#cache.get(key); if (!candidate) { return undefined; } const { character } = request.position; if (candidate.timesRetrievedByPosition[character] > 0) { // If cache has already returned this suggestion from the same position before, discard it. this.#cache.delete(key); return undefined; } this.#increaseCacheEntryRetrievedCount(key, character); const options = candidate.suggestions .map((s) => { const currentLength = currentLine.length; const previousLength = candidate.currentLine.length; const diff = currentLength - previousLength; if (diff < 0) { return null; } if ( currentLine.slice(0, previousLength) !== candidate.currentLine || s.text.slice(0, diff) !== currentLine.slice(previousLength) ) { return null; } return { ...s, text: s.text.slice(diff), uniqueTrackingId: generateUniqueTrackingId(), }; }) .filter((x): x is SuggestionOption => Boolean(x)); return { options, additionalContexts: candidate.additionalContexts, }; } } References:
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp
Definition: def greet end end class Greet2 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:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21
You are a code assistant
Definition of 'getLoadState' in file src/browser/tree_sitter/index.ts in project gitlab-lsp
Definition: getLoadState() { return this.loadState; } async init(): Promise<void> { const baseAssetsUrl = this.#configService.get('client.baseAssetsUrl'); this.languages = this.buildTreeSitterInfoByExtMap([ { name: 'bash', extensions: ['.sh', '.bash', '.bashrc', '.bash_profile'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-c', }, { name: 'c', extensions: ['.c'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-c', }, { name: 'cpp', extensions: ['.cpp'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-cpp.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-cpp', }, { name: 'c_sharp', extensions: ['.cs'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-c_sharp.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-c-sharp', }, { name: 'css', extensions: ['.css'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-css.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-css', }, { name: 'go', extensions: ['.go'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-go.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-go', }, { name: 'html', extensions: ['.html'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-html.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-html', }, { name: 'java', extensions: ['.java'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-java.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-java', }, { name: 'javascript', extensions: ['.js'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-javascript.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-javascript', }, { name: 'powershell', extensions: ['.ps1'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-powershell.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-powershell', }, { name: 'python', extensions: ['.py'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-python.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-python', }, { name: 'ruby', extensions: ['.rb'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-ruby.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-ruby', }, // TODO: Parse throws an error - investigate separately // { // name: 'sql', // extensions: ['.sql'], // wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-sql.wasm', baseAssetsUrl), // nodeModulesPath: 'tree-sitter-sql', // }, { name: 'scala', extensions: ['.scala'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-scala.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-scala', }, { name: 'typescript', extensions: ['.ts'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-typescript.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-typescript/typescript', }, // TODO: Parse throws an error - investigate separately // { // name: 'hcl', // terraform, terragrunt // extensions: ['.tf', '.hcl'], // wasmPath: resolveGrammarAbsoluteUrl( // 'vendor/grammars/tree-sitter-hcl.wasm', // baseAssetsUrl, // ), // nodeModulesPath: 'tree-sitter-hcl', // }, { name: 'json', extensions: ['.json'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-json.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-json', }, ]); try { await Parser.init({ locateFile(scriptName: string) { return resolveGrammarAbsoluteUrl(`node/${scriptName}`, baseAssetsUrl); }, }); log.debug('BrowserTreeSitterParser: Initialized tree-sitter parser.'); this.loadState = TreeSitterParserLoadState.READY; } catch (err) { log.warn('BrowserTreeSitterParser: Error initializing tree-sitter parsers.', err); this.loadState = TreeSitterParserLoadState.ERRORED; } } } References:
You are a code assistant
Definition of 'isOpen' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp
Definition: isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:
You are a code assistant
Definition of 'stackToArray' in file src/common/fetch_error.ts in project gitlab-lsp
Definition: 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/fetch_error.ts:68
You are a code assistant
Definition of 'ChatSupportResponseInterface' in file packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts in project gitlab-lsp
Definition: export interface ChatSupportResponseInterface { hasSupportForChat: boolean; platform?: GitLabPlatformForAccount; } export type ChatAvailableResponseType = { currentUser: { duoChatAvailable: boolean; }; }; export async function getChatSupport( platform?: GitLabPlatformForAccount | undefined, ): Promise<ChatSupportResponseInterface> { const request: GraphQLRequest<ChatAvailableResponseType> = { type: 'graphql', query: queryGetChatAvailability, variables: {}, }; const noSupportResponse: ChatSupportResponseInterface = { hasSupportForChat: false }; if (!platform) { return noSupportResponse; } try { const { currentUser: { duoChatAvailable }, } = await platform.fetchFromApi(request); if (duoChatAvailable) { return { hasSupportForChat: duoChatAvailable, platform, }; } return noSupportResponse; } catch (e) { log.error(e as Error); return noSupportResponse; } } References: - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts:33 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:94 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:98 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:19 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:102
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) end def greet end end class Greet2 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:17 - src/tests/fixtures/intent/empty_function/ruby.rb:25
You are a code assistant
Definition of 'sendRequest' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp
Definition: sendRequest<T extends keyof TMessageMap['outbound']['requests'] & string>( type: T, payload?: TMessageMap['outbound']['requests'][T]['params'], ): Promise<ExtractRequestResult<TMessageMap['outbound']['requests'][T]>> { return this.#connection.sendRequest(this.#rpcMethods.request, { webviewId: this.#webviewId, type, payload, }); } async sendNotification<T extends keyof TMessageMap['outbound']['notifications'] & string>( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise<void> { await this.#connection.sendNotification(this.#rpcMethods.notification, { webviewId: this.#webviewId, type, payload, }); } } References:
You are a code assistant
Definition of 'addProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp
Definition: addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run<T extends ProcessorType>({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise<ProcessorInputMap[T]> { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise<ProcessorInputMap[T]>; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise<ProcessorInputMap[T]>; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise<ProcessorInputMap[T]>, ); } } References:
You are a code assistant
Definition of 'setupHttp' in file src/node/setup_http.ts in project gitlab-lsp
Definition: export async function setupHttp( plugins: WebviewPlugin[], uriProviderRegistry: WebviewUriProviderRegistry, transportRegistry: Set<Transport>, logger: Logger, ): Promise<void> { const server = await initializeHttpServer( plugins.map((x) => x.id), logger, ); uriProviderRegistry.register(new WebviewHttpAccessInfoProvider(server.addresses()?.[0])); transportRegistry.add(new SocketIOWebViewTransport(server.io)); } async function initializeHttpServer(webviewIds: WebviewId[], logger: Logger) { const { shutdown: fastifyShutdown, server } = await createFastifyHttpServer({ plugins: [ createFastifySocketIoPlugin(), createWebviewPlugin({ webviewIds, }), { plugin: async (app) => { app.get('/', () => { return { message: 'Hello, world!' }; }); }, }, ], logger, }); const handleGracefulShutdown = async (signal: string) => { logger.info(`Received ${signal}. Shutting down...`); server.io.close(); await fastifyShutdown(); logger.info('Shutdown complete. Exiting process.'); process.exit(0); }; process.on('SIGTERM', handleGracefulShutdown); process.on('SIGINT', handleGracefulShutdown); return server; } References: - src/node/main.ts:226
You are a code assistant
Definition of 'add' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp
Definition: add(data: PayloadBuilder) { this.#trackingQueue.push(data); if (this.#trackingQueue.length >= this.#maxItems) { this.#drainQueue().catch(() => {}); } } async #drainQueue(): Promise<void> { if (this.#trackingQueue.length > 0) { const copyOfTrackingQueue = this.#trackingQueue.map((e) => e); this.#trackingQueue = []; await this.#callback(copyOfTrackingQueue); } } start() { this.#timeout = setTimeout(async () => { await this.#drainQueue(); if (this.#currentState !== EmitterState.STOPPING) { this.start(); } }, this.#timeInterval); this.#currentState = EmitterState.STARTED; } async stop() { this.#currentState = EmitterState.STOPPING; if (this.#timeout) { clearTimeout(this.#timeout); } this.#timeout = undefined; await this.#drainQueue(); } } References:
You are a code assistant
Definition of 'onNotification' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'FibonacciSolver' in file packages/lib-pkg-1/src/types/fibonacci_solver.ts in project gitlab-lsp
Definition: export interface FibonacciSolver { solve: (index: number) => number; } References:
You are a code assistant
Definition of 'onApiReconfigured' in file src/common/api.ts in project gitlab-lsp
Definition: onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; 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 'SocketIoMessageBus' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: 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: - packages/lib_webview_client/src/bus/provider/socket_io_message_bus_provider.ts:18 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:56
You are a code assistant
Definition of 'FeatureFlagService' in file src/common/feature_flags.ts in project gitlab-lsp
Definition: export interface FeatureFlagService { /** * Checks if a feature flag is enabled on the GitLab instance. * @see `IGitLabAPI` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean; /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean; } @Injectable(FeatureFlagService, [GitLabApiClient, ConfigService]) export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map<string, boolean> = new Map(); constructor(api: GitLabApiClient, configService: ConfigService) { this.#api = api; this.#featureFlags = new Map(); this.#configService = configService; this.#api.onApiReconfigured(async ({ isInValidState }) => { if (!isInValidState) return; await this.#updateInstanceFeatureFlags(); }); } /** * Fetches the feature flags from the gitlab instance * and updates the internal state. */ async #fetchFeatureFlag(name: string): Promise<boolean> { try { const result = await this.#api.fetchFromApi<{ featureFlagEnabled: boolean }>({ type: 'graphql', query: INSTANCE_FEATURE_FLAG_QUERY, variables: { name }, }); log.debug(`FeatureFlagService: feature flag ${name} is ${result.featureFlagEnabled}`); return result.featureFlagEnabled; } catch (e) { // FIXME: we need to properly handle graphql errors // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/250 if (e instanceof ClientError) { const fieldDoesntExistError = e.message.match(/field '([^']+)' doesn't exist on type/i); if (fieldDoesntExistError) { // we expect graphql-request to throw an error when the query doesn't exist (eg. GitLab 16.9) // so we debug to reduce noise log.debug(`FeatureFlagService: query doesn't exist`, e.message); } else { log.error(`FeatureFlagService: error fetching feature flag ${name}`, e); } } return false; } } /** * Fetches the feature flags from the gitlab instance * and updates the internal state. */ async #updateInstanceFeatureFlags(): Promise<void> { log.debug('FeatureFlagService: populating feature flags'); for (const flag of Object.values(InstanceFeatureFlags)) { // eslint-disable-next-line no-await-in-loop this.#featureFlags.set(flag, await this.#fetchFeatureFlag(flag)); } } /** * Checks if a feature flag is enabled on the GitLab instance. * @see `GitLabApiClient` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean { return this.#featureFlags.get(name) ?? false; } /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean { const value = this.#configService.get('client.featureFlags')?.[name]; return value ?? false; } } References: - src/common/suggestion/suggestion_service.ts:83 - src/common/tracking/snowplow_tracker.ts:152 - src/common/connection.ts:24 - src/common/message_handler.ts:37 - src/common/security_diagnostics_publisher.ts:40 - src/common/suggestion/suggestion_service.ts:137 - src/common/advanced_context/helpers.ts:21 - src/common/security_diagnostics_publisher.ts:37 - src/common/message_handler.ts:83 - src/common/feature_flags.test.ts:13 - src/common/security_diagnostics_publisher.test.ts:19 - src/common/tracking/snowplow_tracker.ts:161 - src/common/tracking/snowplow_tracker.test.ts:76
You are a code assistant
Definition of 'log' in file packages/webview_duo_chat/src/plugin/port/log.ts in project gitlab-lsp
Definition: export const log: Logger = new NullLogger(); References: - scripts/set_ls_version.js:17 - scripts/commit-lint/lint.js:66 - src/tests/fixtures/intent/empty_function/javascript.js:4 - src/tests/fixtures/intent/empty_function/javascript.js:31 - scripts/commit-lint/lint.js:61 - src/tests/fixtures/intent/empty_function/javascript.js:16 - src/tests/fixtures/intent/empty_function/javascript.js:10
You are a code assistant
Definition of 'DuoChatWebviewMessageBus' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp
Definition: export type DuoChatWebviewMessageBus = MessageBus<{ inbound: Messages['webviewToPlugin']; outbound: Messages['pluginToWebview']; }>; export type DuoChatExtensionMessageBus = MessageBus<{ inbound: Messages['extensionToPlugin']; outbound: Messages['pluginToExtension']; }>; /** * These types are copied from ./src/common/api_types.ts * TODO: move these types to a common package */ // why: `_TReturnType` helps encapsulate the full request type when used with `fetchFromApi` /* eslint @typescript-eslint/no-unused-vars: ["error", { "varsIgnorePattern": "TReturnType" }] */ /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface SupportedSinceInstanceVersion { version: string; resourceName: string; } interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; headers?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record<string, unknown>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'POST'; body?: unknown; } /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'GET'; searchParams?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>; connectToCable(): Promise<Cable>; } References: - packages/webview_duo_chat/src/plugin/chat_controller.ts:21 - packages/webview_duo_chat/src/plugin/chat_controller.ts:15
You are a code assistant
Definition of 'SuccessfulResponse' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler<T> { (payload: T): void; } export interface TransportListener { on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable; } export interface TransportPublisher { publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void>; } export interface Transport extends TransportListener, TransportPublisher {} References:
You are a code assistant
Definition of 'createWebviewTransportEventEmitter' in file packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp
Definition: export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:59 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:34
You are a code assistant
Definition of 'DUO_DISABLED_FOR_PROJECT' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: export const DUO_DISABLED_FOR_PROJECT = 'duo-disabled-for-project' as const; export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const; export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:
You are a code assistant
Definition of 'duoChatPluginFactory' in file packages/webview_duo_chat/src/plugin/index.ts in project gitlab-lsp
Definition: export const duoChatPluginFactory = ({ gitlabApiClient, }: DuoChatPluginFactoryParams): WebviewPlugin<Messages> => ({ id: WEBVIEW_ID, title: WEBVIEW_TITLE, setup: ({ webview, extension }) => { const platformManager = new ChatPlatformManager(gitlabApiClient); const gitlabPlatformManagerForChat = new GitLabPlatformManagerForChat(platformManager); webview.onInstanceConnected((_, webviewMessageBus) => { const controller = new GitLabChatController( gitlabPlatformManagerForChat, webviewMessageBus, extension, ); return { dispose: () => { controller.dispose(); }, }; }); }, }); References: - src/node/main.ts:221
You are a code assistant
Definition of 'buildWebviewRequestHandler' in file src/node/webview/handlers/webview_handler.ts in project gitlab-lsp
Definition: export const buildWebviewRequestHandler = ( webviewIds: WebviewId[], getWebviewResourcePath: (webviewId: WebviewId) => string, ): RouteHandlerMethod => { return withTrailingSlashRedirect( withKnownWebview(webviewIds, async (request: FastifyRequest, reply: FastifyReply) => { const { webviewId } = request.params as { webviewId: WebviewId }; const webviewPath = getWebviewResourcePath(webviewId); try { await reply.sendFile('index.html', webviewPath); } catch (error) { request.log.error(error, 'Error loading webview content'); await reply.status(500).send('Failed to load the webview content.'); } }), ); }; export const withKnownWebview = ( webviewIds: WebviewId[], handler: RouteHandlerMethod, ): RouteHandlerMethod => { return function (this: FastifyInstance, request: FastifyRequest, reply: FastifyReply) { const { webviewId } = request.params as { webviewId: WebviewId }; if (!webviewIds.includes(webviewId)) { return reply.status(404).send(`Unknown webview: ${webviewId}`); } return handler.call(this, request, reply); }; }; References: - src/node/webview/routes/webview_routes.ts:21 - src/node/webview/handlers/webview_handler.test.ts:11
You are a code assistant
Definition of 'getPaths' in file src/tests/int/hasbin.ts in project gitlab-lsp
Definition: 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/hasbin.ts:8 - src/tests/int/hasbin.ts:12
You are a code assistant
Definition of 'debug' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: debug(message: string, e?: Error | undefined): void; debug(): void { // NOOP } info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:
You are a code assistant
Definition of 'CreateMessageDefinitions' in file packages/lib_message_bus/src/types/utils.ts in project gitlab-lsp
Definition: export type CreateMessageDefinitions<T extends PartialDeep<MessageDefinitions> | undefined> = { notifications: T extends { notifications: infer M } ? MergeDeep<{}, M> : {}; requests: T extends { requests: infer M } ? MergeDeep<{}, M> : {}; }; /** * Utility type to create a message map. */ export type CreateMessageMap<T extends PartialDeep<MessageMap>> = MessageMap< CreateMessageDefinitions<T['inbound']>, CreateMessageDefinitions<T['outbound']> >; References:
You are a code assistant
Definition of 'IntentTestCase' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp
Definition: 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 'constructor' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp
Definition: constructor( webviewId: WebviewId, runtimeMessageBus: WebviewRuntimeMessageBus, messageBusFactory: WebviewMessageBusFactory, logger: Logger, ) { this.#logger = withPrefix(logger, `[WebviewController:${webviewId}]`); this.webviewId = webviewId; this.#messageBusFactory = messageBusFactory; this.#subscribeToEvents(runtimeMessageBus); } broadcast<TMethod extends keyof T['outbound']['notifications'] & string>( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) { for (const info of this.#instanceInfos.values()) { info.messageBus.sendNotification(type.toString(), payload); } } onInstanceConnected(handler: WebviewMessageBusManagerHandler<T>) { this.#handlers.add(handler); for (const [instanceId, info] of this.#instanceInfos) { const disposable = handler(instanceId, info.messageBus); if (isDisposable(disposable)) { info.pluginCallbackDisposables.add(disposable); } } } dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References:
You are a code assistant
Definition of 'createStringOfByteLength' in file src/common/advanced_context/lru_cache.test.ts in project gitlab-lsp
Definition: function createStringOfByteLength(char: string, byteLength: number): string { let result = ''; while (getByteSize(result) < byteLength) { result += char; } return result.slice(0, -1); // Remove last char as it might have pushed over the limit } const SMALL_SIZE = 200; const LARGE_SIZE = 400; const EXTRA_SMALL_SIZE = 50; const smallString = createStringOfByteLength('A', SMALL_SIZE); const largeString = createStringOfByteLength('C', LARGE_SIZE); const extraSmallString = createStringOfByteLength('D', EXTRA_SMALL_SIZE); export function createFakeContext(overrides: Partial<IDocContext> = {}): IDocContext { return { prefix: '', suffix: '', fileRelativePath: 'file:///test.ts', position: { line: 0, character: 0 }, uri: 'file:///test.ts', languageId: 'typescript', workspaceFolder: { uri: 'file:///workspace', name: 'test-workspace', }, ...overrides, }; } describe('LruCache', () => { let lruCache: LruCache; beforeEach(() => { lruCache = LruCache.getInstance(TEST_BYTE_LIMIT); }); afterEach(() => { LruCache.destroyInstance(); }); describe('getInstance', () => { it('should return a singleton instance of LruCache', () => { const cache1 = LruCache.getInstance(TEST_BYTE_LIMIT); const cache2 = LruCache.getInstance(TEST_BYTE_LIMIT); expect(cache1).toBe(cache2); expect(cache1).toBeInstanceOf(LruCache); }); }); describe('updateFile', () => { it('should add a new file to the cache', () => { const context = createFakeContext(); lruCache.updateFile(context); expect(lruCache.openFiles.size).toBe(1); expect(lruCache.openFiles.get(context.uri)).toEqual(context); }); it('should update an existing file in the cache', () => { const context1 = createFakeContext(); const context2 = { ...context1, text: 'Updated text' }; lruCache.updateFile(context1); lruCache.updateFile(context2); expect(lruCache.openFiles.size).toBe(1); expect(lruCache.openFiles.get(context1.uri)).toEqual(context2); }); }); describe('deleteFile', () => { it('should remove a file from the cache', () => { const context = createFakeContext(); lruCache.updateFile(context); const isDeleted = lruCache.deleteFile(context.uri); expect(lruCache.openFiles.size).toBe(0); expect(isDeleted).toBe(true); }); it(`should not remove a file that doesn't exist`, () => { const context = createFakeContext(); lruCache.updateFile(context); const isDeleted = lruCache.deleteFile('fake/uri/that/does/not.exist'); expect(lruCache.openFiles.size).toBe(1); expect(isDeleted).toBe(false); }); it('should return correct order of files after deletion', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.deleteFile(context2.uri); expect(lruCache.mostRecentFiles({ context: context1 })).toEqual([context3, context1]); }); }); describe('mostRecentFiles', () => { it('should return ordered files', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2 }); expect(result).toEqual([context2, context3, context1]); }); it('should return the most recently accessed files in the same workspace', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const otherWorkspaceFolder = { uri: 'file:///other', name: 'other-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); const context4 = createFakeContext({ uri: 'file:///other/file4.ts', workspaceFolder: otherWorkspaceFolder, }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.updateFile(context4); const result = lruCache.mostRecentFiles({ context: context2 }); expect(result.find((file) => file.uri === context4.uri)).toBeUndefined(); }); it('should include the current file if includeCurrentFile is true', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2, includeCurrentFile: true }); expect(result).toEqual([context2, context1]); }); it('should not include the current file if includeCurrentFile is false', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2, includeCurrentFile: false }); expect(result).toEqual([context1]); }); it('should return an empty array if no files match the criteria', () => { const context = createFakeContext(); const result = lruCache.mostRecentFiles({ context }); expect(result).toEqual([]); }); }); describe('updateFile with size limit', () => { it('should evict least recently used items when limit is reached', () => { const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', prefix: smallString, // 200 bytes suffix: smallString, // 200 bytes }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', prefix: smallString, // 200 bytes suffix: smallString, // 200 bytes }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', prefix: largeString, // 400 bytes suffix: '', }); const context4 = createFakeContext({ uri: 'file:///workspace/file4.ts', prefix: extraSmallString, // 50 bytes suffix: extraSmallString, // 50 bytes }); expect(lruCache.updateFile(context1)).toBeTruthy(); expect(lruCache.updateFile(context2)).toBeTruthy(); expect(lruCache.updateFile(context3)).toBeTruthy(); expect(lruCache.updateFile(context4)).toBeTruthy(); // The least recently used item (context1) should have been evicted expect(lruCache.openFiles.size).toBe(3); expect(lruCache.openFiles.has(context1.uri)).toBe(false); expect(lruCache.openFiles.has(context2.uri)).toBe(true); expect(lruCache.openFiles.has(context3.uri)).toBe(true); expect(lruCache.openFiles.has(context4.uri)).toBe(true); }); }); }); References: - src/common/advanced_context/lru_cache.test.ts:20 - src/common/advanced_context/lru_cache.test.ts:19 - src/common/advanced_context/lru_cache.test.ts:21
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp
Definition: greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References: - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21 - src/tests/fixtures/intent/empty_function/ruby.rb:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29
You are a code assistant
Definition of 'getMessageBus' in file packages/lib_webview_client/src/bus/provider/types.ts in project gitlab-lsp
Definition: getMessageBus<TMessages extends MessageMap>(webviewId: string): MessageBus<TMessages> | null; } References:
You are a code assistant
Definition of 'findFilesForDirectory' in file src/common/services/fs/dir.ts in project gitlab-lsp
Definition: 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 'TELEMETRY_ENABLED_MSG' in file src/common/tracking/constants.ts in project gitlab-lsp
Definition: export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.'; References:
You are a code assistant
Definition of 'onNotification' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'createMockLogger' in file packages/lib_webview/src/test_utils/mocks.ts in project gitlab-lsp
Definition: export const createMockLogger = (): jest.Mocked<Logger> => ({ debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), }); export const createMockTransport = (): jest.Mocked<Transport> => ({ publish: jest.fn(), on: jest.fn(), }); References: - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:27 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:338 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:21
You are a code assistant
Definition of 'constructor' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp
Definition: constructor(configService: ConfigService, fetch: LsFetch, api: GitLabApiClient) { this.#fetch = fetch; this.#api = api; configService.onConfigChange((config) => this.#reconfigure(config)); } #reconfigure(config: IConfig) { this.#dockerSocket = config.client.duoWorkflowSettings?.dockerSocket; this.#folders = config.client.workspaceFolders || []; this.#projectPath = config.client.projectPath; } async runWorkflow(goal: string, image: string): Promise<string> { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise<string> { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise<void> { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise<void> { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise<string> { const response = await this.#api?.fetchFromApi<CreateWorkflowResponse>({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise<GenerateTokenResponse> { const token = await this.#api?.fetchFromApi<GenerateTokenResponse>({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References:
You are a code assistant
Definition of 'transform' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: transform(context: IDocContext): IDocContext { return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context); } } export function getDocContext( document: TextDocument, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext { let prefix: string; if (completionContext?.selectedCompletionInfo) { const { selectedCompletionInfo } = completionContext; const range = sanitizeRange(selectedCompletionInfo.range); prefix = `${document.getText({ start: document.positionAt(0), end: range.start, })}${selectedCompletionInfo.text}`; } else { prefix = document.getText({ start: document.positionAt(0), end: position }); } const suffix = document.getText({ start: position, end: document.positionAt(document.getText().length), }); const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders); const fileRelativePath = getRelativePath(document.uri, workspaceFolder); return { prefix, suffix, fileRelativePath, position, uri: document.uri, languageId: document.languageId, workspaceFolder, }; } References:
You are a code assistant
Definition of 'goIntoCompletionMode' in file src/common/suggestion/suggestion_service.test.ts in project gitlab-lsp
Definition: function goIntoCompletionMode() { mockParseFile.mockReset(); jest.mocked(featureFlagService.isClientFlagEnabled).mockReturnValueOnce(false); mockParseFile.mockResolvedValue('completion'); } it('starts breaking after 4 errors', async () => { jest.mocked(DefaultStreamingHandler).mockClear(); jest.mocked(DefaultStreamingHandler).mockReturnValue( createFakePartial<DefaultStreamingHandler>({ startStream: jest.fn().mockResolvedValue([]), }), ); goIntoStreamingMode(); const successResult = await getCompletions(); expect(successResult.items.length).toEqual(1); jest.runOnlyPendingTimers(); expect(DefaultStreamingHandler).toHaveBeenCalled(); jest.mocked(DefaultStreamingHandler).mockClear(); goIntoCompletionMode(); mockGetCodeSuggestions.mockRejectedValue('test problem'); await turnOnCircuitBreaker(); goIntoStreamingMode(); const result = await getCompletions(); expect(result?.items).toEqual([]); expect(DefaultStreamingHandler).not.toHaveBeenCalled(); }); it(`starts the stream after circuit breaker's break time elapses`, async () => { jest.useFakeTimers().setSystemTime(new Date(Date.now())); goIntoCompletionMode(); mockGetCodeSuggestions.mockRejectedValue(new Error('test problem')); await turnOnCircuitBreaker(); jest.advanceTimersByTime(CIRCUIT_BREAK_INTERVAL_MS + 1); goIntoStreamingMode(); const result = await getCompletions(); expect(result?.items).toHaveLength(1); jest.runOnlyPendingTimers(); expect(DefaultStreamingHandler).toHaveBeenCalled(); }); }); }); describe('selection completion info', () => { beforeEach(() => { mockGetCodeSuggestions.mockReset(); mockGetCodeSuggestions.mockResolvedValue({ choices: [{ text: 'log("Hello world")' }], model: { lang: 'js', }, }); }); describe('when undefined', () => { it('does not update choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial<InlineCompletionContext>({ selectedCompletionInfo: undefined, }), }, token, ); expect(items[0].insertText).toBe('log("Hello world")'); }); }); describe('with range and text', () => { it('prepends text to suggestion choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial<InlineCompletionContext>({ selectedCompletionInfo: { text: 'console.', range: { start: { line: 1, character: 0 }, end: { line: 1, character: 2 } }, }, }), }, token, ); expect(items[0].insertText).toBe('nsole.log("Hello world")'); }); }); describe('with range (Array) and text', () => { it('prepends text to suggestion choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial<InlineCompletionContext>({ selectedCompletionInfo: { text: 'console.', // NOTE: This forcefully simulates the behavior we see where range is an Array at runtime. range: [ { line: 1, character: 0 }, { line: 1, character: 2 }, ] as unknown as Range, }, }), }, token, ); expect(items[0].insertText).toBe('nsole.log("Hello world")'); }); }); }); describe('Additional Context', () => { beforeEach(async () => { jest.mocked(shouldUseAdvancedContext).mockReturnValueOnce(true); getAdvancedContextSpy.mockResolvedValue(sampleAdvancedContext); contextBodySpy.mockReturnValue(sampleAdditionalContexts); await requestInlineCompletionNoDebounce(inlineCompletionParams, token); }); it('getCodeSuggestions should have additional context passed if feature is enabled', async () => { expect(getAdvancedContextSpy).toHaveBeenCalled(); expect(contextBodySpy).toHaveBeenCalledWith(sampleAdvancedContext); expect(api.getCodeSuggestions).toHaveBeenCalledWith( expect.objectContaining({ context: sampleAdditionalContexts }), ); }); it('should be tracked with telemetry', () => { expect(tracker.setCodeSuggestionsContext).toHaveBeenCalledWith( TRACKING_ID, expect.objectContaining({ additionalContexts: sampleAdditionalContexts }), ); }); }); }); }); }); References: - src/common/suggestion/suggestion_service.test.ts:1008 - src/common/suggestion/suggestion_service.test.ts:993
You are a code assistant
Definition of 'buildWebviewAddressFilter' in file packages/lib_webview/src/setup/plugin/utils/filters.ts in project gitlab-lsp
Definition: export const buildWebviewAddressFilter = (address: WebviewAddress) => <T extends WebviewAddress>(event: T): boolean => { return ( event.webviewId === address.webviewId && event.webviewInstanceId === address.webviewInstanceId ); }; References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:46
You are a code assistant
Definition of 'EmptyFileResolver' in file src/common/services/fs/file.ts in project gitlab-lsp
Definition: export class EmptyFileResolver { // eslint-disable-next-line @typescript-eslint/no-unused-vars readFile(_args: ReadFile): Promise<string> { return Promise.resolve(''); } } References:
You are a code assistant
Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp
Definition: processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return Promise.resolve(input); } processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise<SuggestionOption[]> { return Promise.resolve(input); } } /** * Pipeline for running post-processors on completion and streaming (generation) responses. * Post-processors are used to modify completion responses before they are sent to the client. * They can be used to filter, sort, or modify completion suggestions. */ export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run<T extends ProcessorType>({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise<ProcessorInputMap[T]> { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise<ProcessorInputMap[T]>; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise<ProcessorInputMap[T]>; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise<ProcessorInputMap[T]>, ); } } References:
You are a code assistant
Definition of 'initialize' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp
Definition: async initialize(workspaceFolders: WorkspaceFolder[]): Promise<void> { await Promise.all( workspaceFolders.map(async (workspaceFolder) => { const files = await this.#directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, }); this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFilesUpdate, { files, workspaceFolder, }); this.#directoryWalker.setupFileWatcher(workspaceFolder, this.#handleFileChange); }), ); } #emitFileSystemEvent<T extends VirtualFileSystemEvents>( eventType: T, data: FileSystemEventMap[T], ) { this.#emitter.emit(FILE_SYSTEM_EVENT_NAME, eventType, data); } onFileSystemEvent(listener: FileSystemEventListener) { this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener), }; } } References: - src/tests/fixtures/intent/empty_function/ruby.rb:17 - src/tests/fixtures/intent/empty_function/ruby.rb:25