instruction
stringclasses
1 value
input
stringlengths
67
168
output
stringlengths
46
67k
You are a code assistant
Definition of 'FetchError' in file src/common/fetch_error.ts in project gitlab-lsp
Definition: export class FetchError extends Error implements ResponseError, DetailedError { response: Response; #body?: string; constructor(response: Response, resourceName: string, body?: string) { let message = `Fetching ${resourceName} from ${response.url} failed`; if (isInvalidTokenError(response, body)) { message = `Request for ${resourceName} failed because the token is expired or revoked.`; } if (isInvalidRefresh(response, body)) { message = `Request to refresh token failed, because it's revoked or already refreshed.`; } super(message); this.response = response; this.#body = body; } get status() { return this.response.status; } isInvalidToken(): boolean { return ( isInvalidTokenError(this.response, this.#body) || isInvalidRefresh(this.response, this.#body) ); } get details() { const { message, stack } = this; return { message, stack: stackToArray(stack), response: { status: this.response.status, headers: this.response.headers, body: this.#body, }, }; } } export class TimeoutError extends Error { constructor(url: URL | RequestInfo) { const timeoutInSeconds = Math.round(REQUEST_TIMEOUT_MILLISECONDS / 1000); super( `Request to ${extractURL(url)} timed out after ${timeoutInSeconds} second${timeoutInSeconds === 1 ? '' : 's'}`, ); } } export class InvalidInstanceVersionError extends Error {} References: - src/common/suggestion/streaming_handler.test.ts:326 - src/common/fetch_error.test.ts:20 - src/common/suggestion/suggestion_service.test.ts:302 - src/common/handle_fetch_error.ts:6 - src/common/fetch_error.test.ts:36 - src/common/suggestion/suggestion_service.test.ts:896 - src/common/fetch_error.test.ts:6
You are a code assistant
Definition of 'GetRequestBase' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp
Definition: interface GetRequestBase<_TReturnType> { method: 'GET'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; searchParams?: Record<string, string>; headers?: Record<string, string>; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase<Uint8Array> { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record<string, unknown>; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; // The interface of the VSCode mediator command COMMAND_FETCH_FROM_API // Will throw ResponseError if HTTP response status isn't 200 export type fetchFromApi = <_TReturnType>( request: ApiRequest<_TReturnType>, ) => Promise<_TReturnType>; // The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API // Will throw ResponseError if HTTP response status isn't 200 export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>; /* API exposed by the Web IDE extension * See https://code.visualstudio.com/api/references/vscode-api#extensions */ export interface WebIDEExtension { isTelemetryEnabled: () => boolean; projectPath: string; gitlabUrl: string; } export interface ResponseError extends Error { status: number; body?: unknown; } References:
You are a code assistant
Definition of 'ConfigService' in file src/common/config_service.ts in project gitlab-lsp
Definition: export interface ConfigService { get: TypedGetter<IConfig>; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter<IConfig>; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial<IConfig>): void; } export const ConfigService = createInterfaceId<ConfigService>('ConfigService'); @Injectable(ConfigService, []) export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/feature_state/project_duo_acces_check.ts:42 - src/common/core/handlers/initialize_handler.test.ts:15 - src/common/connection.ts:25 - src/common/suggestion/supported_languages_service.ts:34 - src/common/security_diagnostics_publisher.test.ts:18 - src/common/suggestion/suggestions_cache.ts:52 - src/common/advanced_context/advanced_context_service.ts:26 - src/common/core/handlers/initialize_handler.ts:19 - src/common/suggestion_client/direct_connection_client.test.ts:26 - src/common/message_handler.ts:71 - src/common/suggestion_client/direct_connection_client.ts:32 - src/common/core/handlers/did_change_workspace_folders_handler.ts:14 - src/common/feature_flags.ts:49 - src/common/tracking/snowplow_tracker.ts:160 - src/common/advanced_context/advanced_context_service.ts:33 - src/browser/tree_sitter/index.ts:11 - src/common/api.ts:131 - src/common/core/handlers/initialize_handler.ts:21 - src/common/suggestion_client/direct_connection_client.ts:54 - src/common/suggestion/supported_languages_service.ts:38 - src/common/feature_state/project_duo_acces_check.ts:34 - src/node/duo_workflow/desktop_workflow_runner.test.ts:15 - src/common/api.ts:135 - src/common/core/handlers/did_change_workspace_folders_handler.test.ts:13 - src/common/tracking/snowplow_tracker.ts:131 - src/common/secret_redaction/index.ts:17 - src/common/tracking/instance_tracker.ts:51 - src/common/suggestion/suggestions_cache.ts:50 - src/browser/tree_sitter/index.ts:13 - src/browser/tree_sitter/index.test.ts:12 - src/common/secret_redaction/index.ts:19 - src/node/duo_workflow/desktop_workflow_runner.ts:53 - src/common/core/handlers/did_change_workspace_folders_handler.ts:16 - src/common/suggestion/suggestion_service.test.ts:177 - src/common/secret_redaction/redactor.test.ts:21 - src/common/log.ts:65 - src/common/suggestion/suggestion_service.ts:117 - src/common/feature_flags.test.ts:14 - src/common/security_diagnostics_publisher.ts:41 - src/common/suggestion/supported_languages_service.test.ts:8 - src/common/api.test.ts:38 - src/common/suggestion/suggestion_service.ts:78 - src/common/message_handler.ts:35 - src/common/feature_flags.ts:45 - src/common/message_handler.test.ts:202 - src/common/advanced_context/helpers.ts:22 - src/common/tracking/instance_tracker.ts:37 - src/common/suggestion/suggestion_service.test.ts:439 - src/common/message_handler.test.ts:85
You are a code assistant
Definition of 'ChatRecordState' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp
Definition: type ChatRecordState = 'pending' | 'ready'; type ChatRecordType = | 'general' | 'explainCode' | 'generateTests' | 'refactorCode' | 'newConversation'; type GitLabChatRecordAttributes = { chunkId?: number | null; type?: ChatRecordType; role: ChatRecordRole; content?: string; contentHtml?: string; requestId?: string; state?: ChatRecordState; errors?: string[]; timestamp?: string; extras?: { sources: object[]; }; }; export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial<GitLabChatRecordAttributes>) { const convertedAttributes = attributes as Partial<GitLabChatRecord>; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:21 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:42
You are a code assistant
Definition of 'constructor' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'HostApplicationMessageBusProvider' in file packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.ts in project gitlab-lsp
Definition: export class HostApplicationMessageBusProvider implements MessageBusProvider { readonly name = 'HostApplicationMessageBusProvider'; getMessageBus<TMessages extends MessageMap>(): MessageBus<TMessages> | null { return 'gitlab' in window && isHostConfig<TMessages>(window.gitlab) ? window.gitlab.host : null; } } References: - packages/lib_webview_client/src/bus/provider/get_default_providers.ts:5 - packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.test.ts:20 - packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.test.ts:7
You are a code assistant
Definition of 'TELEMETRY_DISABLED_WARNING_MSG' in file src/common/tracking/constants.ts in project gitlab-lsp
Definition: export const TELEMETRY_DISABLED_WARNING_MSG = 'GitLab Duo Code Suggestions telemetry is disabled. Please consider enabling telemetry to help improve our service.'; export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.'; References:
You are a code assistant
Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: 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 'ChatPlatformForProject' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp
Definition: export class ChatPlatformForProject extends ChatPlatform implements GitLabPlatformForProject { readonly type = 'project' as const; project: GitLabProject = { gqlId: 'gid://gitlab/Project/123456', restId: 0, name: '', description: '', namespaceWithPath: '', webUrl: '', }; } References:
You are a code assistant
Definition of 'sendNotification' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp
Definition: sendNotification(type: Method, payload?: unknown): void { this.#logger.debug(`Sending notification: ${type}`); this.#runtimeMessageBus.publish('plugin:notification', { ...this.#address, type, payload, }); } onNotification(type: Method, handler: Handler): Disposable { return this.#notificationEvents.register(type, handler); } async sendRequest(type: Method, payload?: unknown): Promise<never> { const requestId = generateRequestId(); this.#logger.debug(`Sending request: ${type}, ID: ${requestId}`); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestHandle = this.#pendingResponseEvents.register( requestId, (message: ResponseMessage) => { if (message.success) { resolve(message.payload as PromiseLike<never>); } else { reject(new Error(message.reason)); } clearTimeout(timeout); pendingRequestHandle.dispose(); }, ); this.#runtimeMessageBus.publish('plugin:request', { ...this.#address, requestId, type, payload, }); timeout = setTimeout(() => { pendingRequestHandle.dispose(); this.#logger.debug(`Request with ID: ${requestId} timed out`); reject(new Error('Request timed out')); }, 10000); }); } onRequest(type: Method, handler: Handler): Disposable { return this.#requestEvents.register(type, (requestId: RequestId, payload: unknown) => { try { const result = handler(payload); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: true, payload: result, }); } catch (error) { this.#logger.error(`Error handling request of type ${type}:`, error as Error); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: false, reason: (error as Error).message, }); } }); } dispose(): void { this.#eventSubscriptions.dispose(); this.#notificationEvents.dispose(); this.#requestEvents.dispose(); this.#pendingResponseEvents.dispose(); } } References:
You are a code assistant
Definition of 'FeatureState' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: 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 'buildContext' in file src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts in project gitlab-lsp
Definition: async *buildContext({ documentContext, includeCurrentFile = false, }: { documentContext?: IDocContext; includeCurrentFile?: boolean; }): AsyncGenerator<ContextResolution> { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); const openFiles = lruCache.mostRecentFiles({ context: documentContext, includeCurrentFile, }); for (const file of openFiles) { yield { uri: file.uri, type: 'file' as const, content: `${file.prefix}${file.suffix}`, fileRelativePath: file.fileRelativePath, strategy: 'open_tabs' as const, workspaceFolder: file.workspaceFolder ?? { name: '', uri: '' }, }; } } } References:
You are a code assistant
Definition of 'Handler' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp
Definition: export type Handler = (...args: any) => any; export interface HandlerRegistry<TKey, THandler extends Handler = Handler> { size: number; has(key: TKey): boolean; register(key: TKey, handler: THandler): Disposable; handle(key: TKey, ...args: Parameters<THandler>): Promise<ReturnType<THandler>>; dispose(): void; } References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:139 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:99
You are a code assistant
Definition of 'size' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp
Definition: get size() { return this.#handlers.size; } register(key: string, handler: THandler): Disposable { this.#handlers.set(key, handler); return { dispose: () => { this.#handlers.delete(key); }, }; } has(key: string) { return this.#handlers.has(key); } async handle(key: string, ...args: Parameters<THandler>): Promise<ReturnType<THandler>> { const handler = this.#handlers.get(key); if (!handler) { throw new HandlerNotFoundError(key); } try { const handlerResult = await handler(...args); return handlerResult as ReturnType<THandler>; } catch (error) { throw new UnhandledHandlerError(key, resolveError(error)); } } 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 'EVENT_VALIDATION_ERROR_MSG' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp
Definition: export const EVENT_VALIDATION_ERROR_MSG = `Telemetry event context is not valid - event won't be tracked.`; export class SnowplowTracker implements TelemetryTracker { #snowplow: Snowplow; #ajv = new Ajv({ strict: false }); #configService: ConfigService; #api: GitLabApiClient; #options: ITelemetryOptions = { enabled: true, baseUrl: SAAS_INSTANCE_URL, trackingUrl: DEFAULT_TRACKING_ENDPOINT, // the list of events that the client can track themselves actions: [], }; #clientContext: ISnowplowClientContext = { schema: 'iglu:com.gitlab/ide_extension_version/jsonschema/1-1-0', data: {}, }; #codeSuggestionStates = new Map<string, TRACKING_EVENTS>(); #lsFetch: LsFetch; #featureFlagService: FeatureFlagService; #gitlabRealm: GitlabRealm = GitlabRealm.saas; #codeSuggestionsContextMap = new Map<string, ISnowplowCodeSuggestionContext>(); constructor( lsFetch: LsFetch, configService: ConfigService, featureFlagService: FeatureFlagService, api: GitLabApiClient, ) { this.#configService = configService; this.#configService.onConfigChange((config) => this.#reconfigure(config)); this.#api = api; const trackingUrl = DEFAULT_TRACKING_ENDPOINT; this.#lsFetch = lsFetch; this.#configService = configService; this.#featureFlagService = featureFlagService; this.#snowplow = Snowplow.getInstance(this.#lsFetch, { ...DEFAULT_SNOWPLOW_OPTIONS, endpoint: trackingUrl, enabled: this.isEnabled.bind(this), }); this.#options.trackingUrl = trackingUrl; this.#ajv.addMetaSchema(SnowplowMetaSchema); } isEnabled(): boolean { return Boolean(this.#options.enabled); } async #reconfigure(config: IConfig) { const { baseUrl } = config.client; const trackingUrl = config.client.telemetry?.trackingUrl; const enabled = config.client.telemetry?.enabled; const actions = config.client.telemetry?.actions; if (typeof enabled !== 'undefined') { this.#options.enabled = enabled; if (enabled === false) { log.warn(`Snowplow Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`); } else if (enabled === true) { log.info(`Snowplow Telemetry: ${TELEMETRY_ENABLED_MSG}`); } } if (baseUrl) { this.#options.baseUrl = baseUrl; this.#gitlabRealm = baseUrl.endsWith(SAAS_INSTANCE_URL) ? GitlabRealm.saas : GitlabRealm.selfManaged; } if (trackingUrl && this.#options.trackingUrl !== trackingUrl) { await this.#snowplow.stop(); this.#snowplow.destroy(); this.#snowplow = Snowplow.getInstance(this.#lsFetch, { ...DEFAULT_SNOWPLOW_OPTIONS, endpoint: trackingUrl, enabled: this.isEnabled.bind(this), }); } if (actions) { this.#options.actions = actions; } this.#setClientContext({ extension: config.client.telemetry?.extension, ide: config.client.telemetry?.ide, }); } #setClientContext(context: IClientContext) { this.#clientContext.data = { ide_name: context?.ide?.name ?? null, ide_vendor: context?.ide?.vendor ?? null, ide_version: context?.ide?.version ?? null, extension_name: context?.extension?.name ?? null, extension_version: context?.extension?.version ?? null, language_server_version: lsVersion ?? null, }; } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ) { const { documentContext, source = SuggestionSource.network, language, isStreaming, triggerKind, optionsCount, additionalContexts, isDirectConnection, } = context; const { gitlab_instance_id, gitlab_global_user_id, gitlab_host_name, gitlab_saas_duo_pro_namespace_ids, } = this.#configService.get('client.snowplowTrackerOptions') ?? {}; if (source === SuggestionSource.cache) { log.debug(`Snowplow Telemetry: Retrieved suggestion from cache`); } else { log.debug(`Snowplow Telemetry: Received request to create a new suggestion`); } // Only auto-reject if client is set up to track accepted and not rejected events. if ( canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) && !canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED) ) { this.rejectOpenedSuggestions(); } setTimeout(() => { if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) { this.#codeSuggestionsContextMap.delete(uniqueTrackingId); this.#codeSuggestionStates.delete(uniqueTrackingId); } }, GC_TIME); const advancedContextData = this.#getAdvancedContextData({ additionalContexts, documentContext, }); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { schema: 'iglu:com.gitlab/code_suggestions_context/jsonschema/3-5-0', data: { suffix_length: documentContext?.suffix.length ?? 0, prefix_length: documentContext?.prefix.length ?? 0, gitlab_realm: this.#gitlabRealm, model_engine: null, model_name: null, language: language ?? null, api_status_code: null, debounce_interval: source === SuggestionSource.cache ? 0 : SUGGESTIONS_DEBOUNCE_INTERVAL_MS, suggestion_source: source, gitlab_global_user_id: gitlab_global_user_id ?? null, gitlab_host_name: gitlab_host_name ?? null, gitlab_instance_id: gitlab_instance_id ?? null, gitlab_saas_duo_pro_namespace_ids: gitlab_saas_duo_pro_namespace_ids ?? null, gitlab_instance_version: this.#api.instanceVersion ?? null, is_streaming: isStreaming ?? false, is_invoked: SnowplowTracker.#isCompletionInvoked(triggerKind), options_count: optionsCount ?? null, has_advanced_context: advancedContextData.hasAdvancedContext, is_direct_connection: isDirectConnection ?? null, total_context_size_bytes: advancedContextData.totalContextSizeBytes, content_above_cursor_size_bytes: advancedContextData.contentAboveCursorSizeBytes, content_below_cursor_size_bytes: advancedContextData.contentBelowCursorSizeBytes, context_items: advancedContextData.contextItems, }, }); this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Snowplow Telemetry: Could not track telemetry', e), ); log.debug(`Snowplow Telemetry: New suggestion ${uniqueTrackingId} has been requested`); } // FIXME: the set and update context methods have similar logic and they should have to grow linearly with each new attribute // the solution might be some generic update method used by both public updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ) { const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate; if (context) { if (model) { context.data.language = model.lang ?? null; context.data.model_engine = model.engine ?? null; context.data.model_name = model.name ?? null; context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null; context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null; context.data.context_tokens_sent = model.tokens_consumption_metadata?.context_tokens_sent ?? null; context.data.context_tokens_used = model.tokens_consumption_metadata?.context_tokens_used ?? null; } if (status) { context.data.api_status_code = status; } if (optionsCount) { context.data.options_count = optionsCount; } if (isDirectConnection !== undefined) { context.data.is_direct_connection = isDirectConnection; } if (acceptedOption) { context.data.accepted_option = acceptedOption; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { if (!this.isEnabled()) { return; } const event: StructuredEvent = { category: CODE_SUGGESTIONS_CATEGORY, action: eventType, label: uniqueTrackingId, }; try { const contexts: SelfDescribingJson[] = [this.#clientContext]; const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId); if (codeSuggestionContext) { contexts.push(codeSuggestionContext); } const suggestionContextValid = this.#ajv.validate( CodeSuggestionContextSchema, codeSuggestionContext?.data, ); if (!suggestionContextValid) { log.warn(EVENT_VALIDATION_ERROR_MSG); log.debug(JSON.stringify(this.#ajv.errors, null, 2)); return; } const ideExtensionContextValid = this.#ajv.validate( IdeExtensionContextSchema, this.#clientContext?.data, ); if (!ideExtensionContextValid) { log.warn(EVENT_VALIDATION_ERROR_MSG); log.debug(JSON.stringify(this.#ajv.errors, null, 2)); return; } await this.#snowplow.trackStructEvent(event, contexts); } catch (error) { log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error); } } public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const isStreaming = Boolean( this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming, ); const allowedTransitions = isStreaming ? streamingSuggestionStateGraph.get(state) : nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `Snowplow Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`, ); // Allow state to update to ACCEPTED despite 'allowed transitions' constraint. if (newState !== TRACKING_EVENTS.ACCEPTED) { return; } log.debug( `Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Snowplow Telemetry: Could not track telemetry', e), ); log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } rejectOpenedSuggestions() { log.debug(`Snowplow Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } #hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null { const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextFeatureFlagsEnabled) { return Boolean(advancedContexts?.length); } return null; } #getAdvancedContextData({ additionalContexts, documentContext, }: { additionalContexts?: AdditionalContext[]; documentContext?: IDocContext; }) { const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts); const contentAboveCursorSizeBytes = documentContext?.prefix ? getByteSize(documentContext.prefix) : 0; const contentBelowCursorSizeBytes = documentContext?.suffix ? getByteSize(documentContext.suffix) : 0; const contextItems: ContextItem[] | null = additionalContexts?.map((item) => ({ file_extension: item.name.split('.').pop() || '', type: item.type, resolution_strategy: item.resolution_strategy, byte_size: item?.content ? getByteSize(item.content) : 0, })) ?? null; const totalContextSizeBytes = contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0; return { totalContextSizeBytes, contentAboveCursorSizeBytes, contentBelowCursorSizeBytes, contextItems, hasAdvancedContext, }; } static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null { let isInvoked = null; if (triggerKind === InlineCompletionTriggerKind.Invoked) { isInvoked = true; } else if (triggerKind === InlineCompletionTriggerKind.Automatic) { isInvoked = false; } return isInvoked; } } References:
You are a code assistant
Definition of 'InvalidInstanceVersionError' in file src/common/fetch_error.ts in project gitlab-lsp
Definition: export class InvalidInstanceVersionError extends Error {} References: - src/common/api.ts:319 - src/common/tracking/instance_tracker.test.ts:345
You are a code assistant
Definition of 'UnwrapInterfaceIds' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: type UnwrapInterfaceIds<T extends InterfaceId<unknown>[]> = { [K in keyof T]: T[K] extends InterfaceId<infer U> ? U : never; }; interface Metadata { id: string; dependencies: string[]; } /** * Here we store the id and dependencies for all classes decorated with @Injectable */ const injectableMetadata = new WeakMap<object, Metadata>(); /** * Decorate your class with @Injectable(id, dependencies) * param id = InterfaceId of the interface implemented by your class (use createInterfaceId to create one) * param dependencies = List of InterfaceIds that will be injected into class' constructor */ export function Injectable<I, TDependencies extends InterfaceId<unknown>[]>( id: InterfaceId<I>, dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments ) { // this is the trickiest part of the whole DI framework // we say, this decorator takes // - id (the interface that the injectable implements) // - dependencies (list of interface ids that will be injected to constructor) // // With then we return function that ensures that the decorated class implements the id interface // and its constructor has arguments of same type and order as the dependencies argument to the decorator return function <T extends { new (...args: UnwrapInterfaceIds<TDependencies>): I }>( constructor: T, { kind }: ClassDecoratorContext, ) { if (kind === 'class') { injectableMetadata.set(constructor, { id, dependencies: dependencies || [] }); return constructor; } throw new Error('Injectable decorator can only be used on a class.'); }; } // new (...args: any[]): any is actually how TS defines type of a class // eslint-disable-next-line @typescript-eslint/no-explicit-any type WithConstructor = { new (...args: any[]): any; name: string }; 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 'constructor' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp
Definition: constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References:
You are a code assistant
Definition of 'engaged' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp
Definition: get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise<void> { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise<WorkspaceFolder | undefined> { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References:
You are a code assistant
Definition of 'greetGenerator' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp
Definition: function* greetGenerator() { yield 'Hello'; } References:
You are a code assistant
Definition of 'MessagesToClient' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: 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 'getForActiveProject' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp
Definition: 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 'redactSecrets' in file src/common/secret_redaction/index.ts in project gitlab-lsp
Definition: redactSecrets(raw: string): string; } 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:
You are a code assistant
Definition of 'Matchers' in file src/tests/int/test_utils.ts in project gitlab-lsp
Definition: interface Matchers<LspClient> { toEventuallyContainChildProcessConsoleOutput( expectedMessage: string, timeoutMs?: number, intervalMs?: number, ): Promise<LspClient>; } } } expect.extend({ /** * Custom matcher to check the language client child process console output for an expected string. * This is useful when an operation does not directly run some logic, (e.g. internally emits events * which something later does the thing you're testing), so you cannot just await and check the output. * * await expect(lsClient).toEventuallyContainChildProcessConsoleOutput('foo'); * * @param lsClient LspClient instance to check * @param expectedMessage Message to check for * @param timeoutMs How long to keep checking before test is considered failed * @param intervalMs How frequently to check the log */ async toEventuallyContainChildProcessConsoleOutput( lsClient: LspClient, expectedMessage: string, timeoutMs = 1000, intervalMs = 25, ) { const expectedResult = `Expected language service child process console output to contain "${expectedMessage}"`; const checkOutput = () => lsClient.childProcessConsole.some((line) => line.includes(expectedMessage)); const sleep = () => new Promise((resolve) => { setTimeout(resolve, intervalMs); }); let remainingRetries = Math.ceil(timeoutMs / intervalMs); while (remainingRetries > 0) { if (checkOutput()) { return { message: () => expectedResult, pass: true, }; } // eslint-disable-next-line no-await-in-loop await sleep(); remainingRetries--; } return { message: () => `"${expectedResult}", but it was not found within ${timeoutMs}ms`, pass: false, }; }, }); References:
You are a code assistant
Definition of 'TransportMessageHandler' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: 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 'GITLAB_STAGING_URL' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp
Definition: export const GITLAB_STAGING_URL: string = 'https://staging.gitlab.com'; export const GITLAB_ORG_URL: string = 'https://dev.gitlab.org'; export const GITLAB_DEVELOPMENT_URL: string = 'http://localhost'; export enum GitLabEnvironment { GITLAB_COM = 'production', GITLAB_STAGING = 'staging', GITLAB_ORG = 'org', GITLAB_DEVELOPMENT = 'development', GITLAB_SELF_MANAGED = 'self-managed', } export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise<string | undefined> { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise<GitLabPlatformForAccount | undefined> { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise<GitLabEnvironment> { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:
You are a code assistant
Definition of 'FeatureStateManager' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp
Definition: export interface FeatureStateManager extends Notifier<FeatureStateNotificationParams>, Disposable {} export const FeatureStateManager = createInterfaceId<FeatureStateManager>('FeatureStateManager'); @Injectable(FeatureStateManager, [CodeSuggestionsSupportedLanguageCheck, ProjectDuoAccessCheck]) export class DefaultFeatureStateManager implements FeatureStateManager { #checks: StateCheck[] = []; #subscriptions: Disposable[] = []; #notify?: NotifyFn<FeatureStateNotificationParams>; constructor( supportedLanguagePolicy: CodeSuggestionsSupportedLanguageCheck, projectDuoAccessCheck: ProjectDuoAccessCheck, ) { this.#checks.push(supportedLanguagePolicy, projectDuoAccessCheck); this.#subscriptions.push( ...this.#checks.map((check) => check.onChanged(() => this.#notifyClient())), ); } init(notify: NotifyFn<FeatureStateNotificationParams>): void { this.#notify = notify; } async #notifyClient() { if (!this.#notify) { throw new Error( "The state manager hasn't been initialized. It can't send notifications. Call the init method first.", ); } await this.#notify(this.#state); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References: - src/common/connection_service.ts:68
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/ruby_comments.rb in project gitlab-lsp
Definition: def greet(name) # function to greet the user end 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 'runWorkflow' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp
Definition: 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 'ProjectDuoAccessCheck' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp
Definition: export const ProjectDuoAccessCheck = createInterfaceId<ProjectDuoAccessCheck>('ProjectDuoAccessCheck'); @Injectable(ProjectDuoAccessCheck, [ DocumentService, ConfigService, DuoProjectAccessChecker, DuoProjectAccessCache, ]) export class DefaultProjectDuoAccessCheck implements StateCheck { #subscriptions: Disposable[] = []; #stateEmitter = new EventEmitter(); #hasDuoAccess?: boolean; #duoProjectAccessChecker: DuoProjectAccessChecker; #configService: ConfigService; #currentDocument?: TextDocument; #isEnabledInSettings = true; constructor( documentService: DocumentService, configService: ConfigService, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, ) { this.#configService = configService; this.#duoProjectAccessChecker = duoProjectAccessChecker; this.#subscriptions.push( documentService.onDocumentChange(async (event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#currentDocument = event.document; await this.#checkIfProjectHasDuoAccess(); } }), configService.onConfigChange(async (config) => { this.#isEnabledInSettings = config.client.duo?.enabledWithoutGitlabProject ?? true; await this.#checkIfProjectHasDuoAccess(); }), duoProjectAccessCache.onDuoProjectCacheUpdate(() => this.#checkIfProjectHasDuoAccess()), ); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise<void> { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise<WorkspaceFolder | undefined> { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References: - src/common/feature_state/project_duo_acces_check.test.ts:15 - src/common/feature_state/feature_state_manager.ts:29
You are a code assistant
Definition of 'SuggestionCache' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp
Definition: export type SuggestionCache = { options: SuggestionOption[]; additionalContexts?: AdditionalContext[]; }; function isNonEmptyLine(s: string) { return s.trim().length > 0; } type Required<T> = { [P in keyof T]-?: T[P]; }; const DEFAULT_CONFIG: Required<ISuggestionsCacheOptions> = { enabled: true, maxSize: 1024 * 1024, ttl: 60 * 1000, prefixLines: 1, suffixLines: 1, }; export class SuggestionsCache { #cache: LRUCache<string, SuggestionCacheEntry>; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache<string, SuggestionCacheEntry>({ ttlAutopurge: true, sizeCalculation: (value, key) => value.suggestions.reduce((acc, suggestion) => acc + suggestion.text.length, 0) + key.length, ...DEFAULT_CONFIG, ...currentConfig, ttl: Number(currentConfig.ttl), }); } #getCurrentConfig(): Required<ISuggestionsCacheOptions> { return { ...DEFAULT_CONFIG, ...(this.#configService.get('client.suggestionsCache') ?? {}), }; } #getSuggestionKey(ctx: SuggestionCacheContext) { const prefixLines = ctx.context.prefix.split('\n'); const currentLine = prefixLines.pop() ?? ''; const indentation = (currentLine.match(/^\s*/)?.[0] ?? '').length; const config = this.#getCurrentConfig(); const cachedPrefixLines = prefixLines .filter(isNonEmptyLine) .slice(-config.prefixLines) .join('\n'); const cachedSuffixLines = ctx.context.suffix .split('\n') .filter(isNonEmptyLine) .slice(0, config.suffixLines) .join('\n'); return [ ctx.document.uri, ctx.position.line, cachedPrefixLines, cachedSuffixLines, indentation, ].join(':'); } #increaseCacheEntryRetrievedCount(suggestionKey: string, character: number) { const item = this.#cache.get(suggestionKey); if (item && item.timesRetrievedByPosition) { item.timesRetrievedByPosition[character] = (item.timesRetrievedByPosition[character] ?? 0) + 1; } } addToSuggestionCache(config: { request: SuggestionCacheContext; suggestions: SuggestionOption[]; }) { if (!this.#getCurrentConfig().enabled) { return; } const currentLine = config.request.context.prefix.split('\n').at(-1) ?? ''; this.#cache.set(this.#getSuggestionKey(config.request), { character: config.request.position.character, suggestions: config.suggestions, currentLine, timesRetrievedByPosition: {}, additionalContexts: config.request.additionalContexts, }); } 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 'setup' in file scripts/esbuild/helpers.ts in project gitlab-lsp
Definition: setup(build) { build.onLoad({ filter: /[/\\]get_language_server_version\.ts$/ }, ({ path: filePath }) => { if (!filePath.match(nodeModulesRegex)) { let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( '{{GITLAB_LANGUAGE_SERVER_VERSION}}', packageJson['version'], ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } return null; }); }, } satisfies Plugin; export { fixVendorGrammarsPlugin, fixWebviewPathPlugin, setLanguageServerVersionPlugin, wasmEntryPoints, }; References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197
You are a code assistant
Definition of 'IHttpAgentOptions' in file src/common/config_service.ts in project gitlab-lsp
Definition: export interface IHttpAgentOptions { ca?: string; cert?: string; certKey?: string; } export interface ISnowplowTrackerOptions { gitlab_instance_id?: string; gitlab_global_user_id?: string; gitlab_host_name?: string; gitlab_saas_duo_pro_namespace_ids?: number[]; } export interface ISecurityScannerOptions { enabled?: boolean; serviceUrl?: string; } export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record<string, boolean>; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter<IConfig>; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter<IConfig>; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial<IConfig>): void; } export const ConfigService = createInterfaceId<ConfigService>('ConfigService'); @Injectable(ConfigService, []) export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:70
You are a code assistant
Definition of 'Processor1' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestProcessor()); const invalidInput = { invalid: 'input' }; await expect( pipeline.run({ documentContext: mockContext, input: invalidInput as unknown as StreamingCompletionResponse, type: 'invalid' as 'stream', }), ).rejects.toThrow('Unexpected type in pipeline processing'); }); }); References: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:162 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:116
You are a code assistant
Definition of 'lintMr' in file scripts/commit-lint/lint.js in project gitlab-lsp
Definition: async function lintMr() { const commits = await getCommitsInMr(); // When MR is set to squash, but it's not yet being merged, we check the MR Title if ( CI_MERGE_REQUEST_SQUASH_ON_MERGE === 'true' && CI_MERGE_REQUEST_EVENT_TYPE !== 'merge_train' ) { console.log( 'INFO: The MR is set to squash. We will lint the MR Title (used as the commit message by default).', ); return isConventional(CI_MERGE_REQUEST_TITLE).then(Array.of); } console.log('INFO: Checking all commits that will be added by this MR.'); return Promise.all(commits.map(isConventional)); } async function run() { if (!CI) { console.error('This script can only run in GitLab CI.'); process.exit(1); } if (!LAST_MR_COMMIT) { console.error( 'LAST_MR_COMMIT environment variable is not present. Make sure this script is run from `lint.sh`', ); process.exit(1); } const results = await lintMr(); console.error(format({ results }, { helpUrl: urlSemanticRelease })); const numOfErrors = results.reduce((acc, result) => acc + result.errors.length, 0); if (numOfErrors !== 0) { process.exit(1); } } run().catch((err) => { console.error(err); process.exit(1); }); References: - scripts/commit-lint/lint.js:83
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp
Definition: def greet(self): class Greet3: 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 'getChatSupport' in file packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts in project gitlab-lsp
Definition: 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.test.ts:31 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:40 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:59 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:33 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:52
You are a code assistant
Definition of 'AiContextPolicy' in file src/common/ai_context_management_2/policies/ai_context_policy.ts in project gitlab-lsp
Definition: export interface AiContextPolicy { isAllowed(aiProviderItem: AiContextProviderItem): Promise<{ allowed: boolean; reason?: string; }>; } References:
You are a code assistant
Definition of 'GenerateTokenResponse' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp
Definition: interface GenerateTokenResponse { gitlab_rails: { base_url: string; token: string; }; duo_workflow_service: { base_url: string; token: string; headers: { 'X-Gitlab-Host-Name': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Realm': string; 'X-Gitlab-Version': string; 'X-Gitlab-Global-User-Id': string; }; }; } interface CreateWorkflowResponse { id: string; } const DuoWorkflowAPIService = createInterfaceId<WorkflowAPI>('WorkflowAPI'); @Injectable(DuoWorkflowAPIService, [ConfigService, LsFetch, GitLabApiClient]) export class DesktopWorkflowRunner implements WorkflowAPI { #dockerSocket?: string; #folders?: WorkspaceFolder[]; #fetch: LsFetch; #api: GitLabApiClient; #projectPath: string | undefined; constructor(configService: ConfigService, fetch: LsFetch, api: GitLabApiClient) { this.#fetch = fetch; this.#api = api; configService.onConfigChange((config) => this.#reconfigure(config)); } #reconfigure(config: IConfig) { this.#dockerSocket = config.client.duoWorkflowSettings?.dockerSocket; this.#folders = config.client.workspaceFolders || []; this.#projectPath = config.client.projectPath; } async runWorkflow(goal: string, image: string): Promise<string> { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise<string> { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise<void> { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise<void> { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise<string> { const response = await this.#api?.fetchFromApi<CreateWorkflowResponse>({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise<GenerateTokenResponse> { const token = await this.#api?.fetchFromApi<GenerateTokenResponse>({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References:
You are a code assistant
Definition of 'ApiRequest' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp
Definition: export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>; connectToCable(): Promise<Cable>; } References:
You are a code assistant
Definition of 'FastifyInstance' in file src/node/http/plugin/fastify_socket_io_plugin.ts in project gitlab-lsp
Definition: interface FastifyInstance { io: Server; } } References: - src/node/webview/handlers/webview_handler.ts:27 - src/node/http/utils/register_static_plugin_safely.ts:5 - src/node/http/create_fastify_http_server.ts:72 - src/node/webview/routes/webview_routes.ts:15 - src/node/http/create_fastify_http_server.ts:56 - src/node/http/fastify_utilities.ts:4 - src/node/http/create_fastify_http_server.ts:14
You are a code assistant
Definition of 'DuoChatPluginFactoryParams' in file packages/webview_duo_chat/src/plugin/index.ts in project gitlab-lsp
Definition: type DuoChatPluginFactoryParams = { gitlabApiClient: GitLabApiClient; }; 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: - packages/webview_duo_chat/src/plugin/index.ts:14
You are a code assistant
Definition of 'OAuthToken' in file src/common/api.ts in project gitlab-lsp
Definition: 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 'checkProjectStatus' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp
Definition: checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus; } export const DuoProjectAccessChecker = createInterfaceId<DuoProjectAccessChecker>('DuoProjectAccessChecker'); @Injectable(DuoProjectAccessChecker, [DuoProjectAccessCache]) export class DefaultDuoProjectAccessChecker { #projectAccessCache: DuoProjectAccessCache; constructor(projectAccessCache: DuoProjectAccessCache) { this.#projectAccessCache = projectAccessCache; } /** * Check if Duo features are enabled for a given DocumentUri. * * We match the DocumentUri to the project with the longest path. * The enabled projects come from the `DuoProjectAccessCache`. * * @reference `DocumentUri` is the URI of the document to check. Comes from * the `TextDocument` object. */ checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus { const projects = this.#projectAccessCache.getProjectsForWorkspaceFolder(workspaceFolder); if (projects.length === 0) { return DuoProjectStatus.NonGitlabProject; } const project = this.#findDeepestProjectByPath(uri, projects); if (!project) { return DuoProjectStatus.NonGitlabProject; } return project.enabled ? DuoProjectStatus.DuoEnabled : DuoProjectStatus.DuoDisabled; } #findDeepestProjectByPath(uri: string, projects: DuoProject[]): DuoProject | undefined { let deepestProject: DuoProject | undefined; for (const project of projects) { if (uri.startsWith(project.uri.replace('.git/config', ''))) { if (!deepestProject || project.uri.length > deepestProject.uri.length) { deepestProject = project; } } } return deepestProject; } } References:
You are a code assistant
Definition of 'DuoWorkflowEvents' in file src/common/graphql/workflow/types.ts in project gitlab-lsp
Definition: export type DuoWorkflowEvents = { nodes: LangGraphCheckpoint[]; }; export type DuoWorkflowEventConnectionType = { duoWorkflowEvents: DuoWorkflowEvents; }; References: - packages/webview_duo_workflow/src/types.ts:10 - src/common/graphql/workflow/types.ts:10
You are a code assistant
Definition of 'WebviewConnection' in file packages/lib_webview_plugin/src/types.ts in project gitlab-lsp
Definition: export interface WebviewConnection<T extends MessageMap> { broadcast: <TMethod extends keyof T['outbound']['notifications'] & string>( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) => void; onInstanceConnected: (handler: WebviewMessageBusManagerHandler<T>) => void; } References:
You are a code assistant
Definition of 'destroyInstance' in file src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts in project gitlab-lsp
Definition: public static destroyInstance(): void { OpenTabsResolver.#instance = undefined; } async *buildContext({ documentContext, includeCurrentFile = false, }: { documentContext?: IDocContext; includeCurrentFile?: boolean; }): AsyncGenerator<ContextResolution> { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); const openFiles = lruCache.mostRecentFiles({ context: documentContext, includeCurrentFile, }); for (const file of openFiles) { yield { uri: file.uri, type: 'file' as const, content: `${file.prefix}${file.suffix}`, fileRelativePath: file.fileRelativePath, strategy: 'open_tabs' as const, workspaceFolder: file.workspaceFolder ?? { name: '', uri: '' }, }; } } } References:
You are a code assistant
Definition of 'getProviderItems' in file src/common/ai_context_management_2/providers/ai_file_context_provider.ts in project gitlab-lsp
Definition: async getProviderItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise<AiContextProviderItem[]> { const items = query.trim() === '' ? await this.#getOpenTabsItems() : await this.#getSearchedItems(query, workspaceFolders); log.info(`Found ${items.length} results for ${query}`); return items; } async #getOpenTabsItems(): Promise<AiContextProviderItem[]> { const resolutions: ContextResolution[] = []; for await (const resolution of OpenTabsResolver.getInstance().buildContext({ includeCurrentFile: true, })) { resolutions.push(resolution); } return resolutions.map((resolution) => this.#providerItemForOpenTab(resolution)); } async #getSearchedItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise<AiContextProviderItem[]> { const allFiles: RepositoryFile[] = []; for (const folder of workspaceFolders) { const files = this.#repositoryService.getFilesForWorkspace(folder.uri, { excludeGitFolder: true, excludeIgnored: true, }); allFiles.push(...files); } const fileNames = allFiles.map((file) => file.uri.fsPath); const allFilesMap = new Map(allFiles.map((file) => [file.uri.fsPath, file])); const results = filter(fileNames, query, { maxResults: 100 }); const resultFiles: RepositoryFile[] = []; for (const result of results) { if (allFilesMap.has(result)) { resultFiles.push(allFilesMap.get(result) as RepositoryFile); } } return resultFiles.map((file) => this.#providerItemForSearchResult(file)); } #openTabResolutionToRepositoryFile(resolution: ContextResolution): [URI, RepositoryFile | null] { const fileUri = parseURIString(resolution.uri); const repo = this.#repositoryService.findMatchingRepositoryUri( fileUri, resolution.workspaceFolder, ); if (!repo) { log.warn(`Could not find repository for ${resolution.uri}`); return [fileUri, null]; } const repositoryFile = this.#repositoryService.getRepositoryFileForUri( fileUri, repo, resolution.workspaceFolder, ); if (!repositoryFile) { log.warn(`Could not find repository file for ${resolution.uri}`); return [fileUri, null]; } return [fileUri, repositoryFile]; } #providerItemForOpenTab(resolution: ContextResolution): AiContextProviderItem { const [fileUri, repositoryFile] = this.#openTabResolutionToRepositoryFile(resolution); return { fileUri, workspaceFolder: resolution.workspaceFolder, providerType: 'file', subType: 'open_tab', repositoryFile, }; } #providerItemForSearchResult(repositoryFile: RepositoryFile): AiContextProviderItem { return { fileUri: repositoryFile.uri, workspaceFolder: repositoryFile.workspaceFolder, providerType: 'file', subType: 'local_file_search', repositoryFile, }; } } References:
You are a code assistant
Definition of 'isFileIgnored' in file src/common/git/repository.ts in project gitlab-lsp
Definition: isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map<string, RepositoryFile> { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:
You are a code assistant
Definition of 'setup' in file scripts/esbuild/helpers.ts in project gitlab-lsp
Definition: setup(build) { console.log('[fixWebviewPath] plugin initialized'); build.onLoad({ filter: /.*[/\\]webview[/\\]constants\.ts/ }, ({ path: filePath }) => { console.log('[fixWebviewPath] File load attempt:', filePath); if (!filePath.match(/.*[/\\]?node_modules[/\\].*?/)) { console.log('[fixWebviewPath] Modifying file:', filePath); let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( "WEBVIEW_BASE_PATH = path.join(__dirname, '../../../out/webviews/');", "WEBVIEW_BASE_PATH = path.join(__dirname, '../webviews/');", ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } else { console.log('[fixWebviewPath] Skipping file:', filePath); } return null; }); }, } satisfies Plugin; const setLanguageServerVersionPlugin = { name: 'setLanguageServerVersion', setup(build) { build.onLoad({ filter: /[/\\]get_language_server_version\.ts$/ }, ({ path: filePath }) => { if (!filePath.match(nodeModulesRegex)) { let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( '{{GITLAB_LANGUAGE_SERVER_VERSION}}', packageJson['version'], ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } return null; }); }, } satisfies Plugin; export { fixVendorGrammarsPlugin, fixWebviewPathPlugin, setLanguageServerVersionPlugin, wasmEntryPoints, }; References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197
You are a code assistant
Definition of 'openFiles' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp
Definition: get openFiles() { return this.#cache; } #getDocumentSize(context: IDocContext): number { const size = getByteSize(`${context.prefix}${context.suffix}`); return Math.max(1, size); } /** * Update the file in the cache. * Uses lru-cache under the hood. */ updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:
You are a code assistant
Definition of 'EmptyFunctionResolver' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp
Definition: export class EmptyFunctionResolver { 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 = emptyFunctionQueries[language]; if (!queryString) { log.warn(`No empty function query found for: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ isCursorInEmptyFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return false; } const emptyBodyPositions = query.captures(tree.rootNode).map((capture) => { return EmptyFunctionResolver.#findEmptyBodyPosition(capture.node); }); const cursorInsideInOneOfTheCaptures = emptyBodyPositions.some( (emptyBody) => EmptyFunctionResolver.#isValidBodyPosition(emptyBody) && EmptyFunctionResolver.#isCursorInsideNode( cursorPosition, emptyBody.startPosition, emptyBody.endPosition, ), ); return ( cursorInsideInOneOfTheCaptures || EmptyFunctionResolver.isCursorAfterEmptyPythonFunction({ languageName, tree, treeSitterLanguage, cursorPosition, }) ); } static #isCursorInsideNode( cursorPosition: Point, startPosition: Point, endPosition: Point, ): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorAfterNodeStart = cursorRow > startPosition.row || (cursorRow === startPosition.row && cursorColumn >= startPosition.column); const isCursorBeforeNodeEnd = cursorRow < endPosition.row || (cursorRow === endPosition.row && cursorColumn <= endPosition.column); return isCursorAfterNodeStart && isCursorBeforeNodeEnd; } static #isCursorRightAfterNode(cursorPosition: Point, endPosition: Point): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorRightAfterNode = cursorRow - endPosition.row === 1 || (cursorRow === endPosition.row && cursorColumn > endPosition.column); return isCursorRightAfterNode; } static #findEmptyBodyPosition(node: SyntaxNode): { startPosition?: Point; endPosition?: Point } { const startPosition = node.lastChild?.previousSibling?.endPosition; const endPosition = node.lastChild?.startPosition; return { startPosition, endPosition }; } static #isValidBodyPosition(arg: { startPosition?: Point; endPosition?: Point; }): arg is { startPosition: Point; endPosition: Point } { return !isUndefined(arg.startPosition) && !isUndefined(arg.endPosition); } static isCursorAfterEmptyPythonFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { if (languageName !== 'python') return false; const pythonQuery = treeSitterLanguage.query(`[ (function_definition) (class_definition) ] @function`); const captures = pythonQuery.captures(tree.rootNode); if (captures.length === 0) return false; // Check if any function or class body is empty and cursor is after it return captures.some((capture) => { const bodyNode = capture.node.childForFieldName('body'); return ( bodyNode?.childCount === 0 && EmptyFunctionResolver.#isCursorRightAfterNode(cursorPosition, capture.node.endPosition) ); }); } } let emptyFunctionResolver: EmptyFunctionResolver; export function getEmptyFunctionResolver(): EmptyFunctionResolver { if (!emptyFunctionResolver) { emptyFunctionResolver = new EmptyFunctionResolver(); } return emptyFunctionResolver; } References: - src/common/tree_sitter/empty_function/empty_function_resolver.ts:153 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:9 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:16 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:155 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:152
You are a code assistant
Definition of 'SuggestionResponse' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'ResponseError' in file src/common/fetch_error.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'IDocContext' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: export interface IDocContext { /** * The text before the cursor. */ prefix: string; /** * The text after the cursor. */ suffix: string; /** * This is most likely path to a file relative to the workspace * but if the file doesn't belong to a workspace, this field is identical to document URI * * Example: If the workspace root is `/home/user/workspace` * and the file is `/home/user/workspace/src/file.txt`, * then the filename is `src/file.txt`. */ fileRelativePath: string; position: Position; /** * The URI of the document. */ uri: DocumentUri; /** * languageId of the document * @readonly */ languageId: TextDocument['languageId']; /** * The workspace folder that the document belongs to. */ workspaceFolder?: WorkspaceFolder; } export interface IDocTransformer { transform(context: IDocContext): IDocContext; } const getMatchingWorkspaceFolder = ( fileUri: DocumentUri, workspaceFolders: WorkspaceFolder[], ): WorkspaceFolder | undefined => workspaceFolders.find((wf) => fileUri.startsWith(wf.uri)); const getRelativePath = (fileUri: DocumentUri, workspaceFolder?: WorkspaceFolder): string => { if (!workspaceFolder) { // splitting a string will produce at least one item and so the pop can't return undefined // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return fileUri.split(/[\\/]/).pop()!; } return fileUri.slice(workspaceFolder.uri.length).replace(/^\//, ''); }; export interface DocumentTransformerService { get(uri: string): TextDocument | undefined; getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId<DocumentTransformerService>( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; constructor(documents: LsTextDocuments, secretRedactor: SecretRedactor) { this.#documents = documents; this.#transformers.push(secretRedactor); } get(uri: string) { return this.#documents.get(uri); } getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined { const doc = this.get(uri); if (doc === undefined) { return undefined; } return this.transform(getDocContext(doc, position, workspaceFolders, completionContext)); } transform(context: IDocContext): IDocContext { return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context); } } export function getDocContext( document: TextDocument, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext { let prefix: string; if (completionContext?.selectedCompletionInfo) { const { selectedCompletionInfo } = completionContext; const range = sanitizeRange(selectedCompletionInfo.range); prefix = `${document.getText({ start: document.positionAt(0), end: range.start, })}${selectedCompletionInfo.text}`; } else { prefix = document.getText({ start: document.positionAt(0), end: position }); } const suffix = document.getText({ start: position, end: document.positionAt(document.getText().length), }); const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders); const fileRelativePath = getRelativePath(document.uri, workspaceFolder); return { prefix, suffix, fileRelativePath, position, uri: document.uri, languageId: document.languageId, workspaceFolder, }; } References: - src/common/test_utils/mocks.ts:62 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:178 - src/common/suggestion/suggestion_service.ts:287 - src/common/advanced_context/context_resolvers/advanced_context_resolver.ts:47 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:10 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:86 - src/common/tracking/instance_tracker.test.ts:15 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:148 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:8 - src/common/tracking/snowplow_tracker.ts:484 - src/common/tracking/snowplow_tracker.test.ts:56 - src/common/advanced_context/lru_cache.test.ts:23 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:93 - src/common/document_transformer_service.ts:103 - src/common/advanced_context/lru_cache.ts:42 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:185 - src/common/test_utils/mocks.ts:7 - src/common/suggestion/suggestion_service.ts:541 - src/common/document_transformer_service.ts:69 - src/common/tracking/tracking_types.ts:8 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:57 - src/common/suggestion/suggestion_service.ts:352 - src/common/suggestion/suggestion_service.ts:510 - src/common/advanced_context/advanced_context_filters.ts:11 - src/common/tree_sitter/parser.test.ts:103 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:28 - src/common/advanced_context/lru_cache.ts:51 - src/common/suggestion/suggestion_service.ts:391 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:50 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:64 - src/common/advanced_context/lru_cache.ts:71 - src/common/tree_sitter/parser.test.ts:74 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:155 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:28 - src/common/advanced_context/advanced_context_factory.ts:23 - src/common/suggestion/suggestion_service.ts:325 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:132 - src/common/suggestion/suggestions_cache.ts:22 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:22 - src/common/document_transformer_service.ts:113 - src/common/document_transformer_service.ts:44 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:109 - src/common/tree_sitter/parser.ts:37 - src/common/suggestion_client/suggestion_client.ts:20 - src/common/test_utils/mocks.ts:38 - src/common/test_utils/mocks.ts:50 - src/common/secret_redaction/index.ts:28 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:102 - src/common/suggestion/streaming_handler.ts:39 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts:26 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:35 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:139 - src/common/advanced_context/advanced_context_filters.test.ts:17 - src/common/suggestion/streaming_handler.test.ts:33
You are a code assistant
Definition of 'init' in file src/common/diagnostics_publisher.ts in project gitlab-lsp
Definition: init(publish: DiagnosticsPublisherFn): void; } References:
You are a code assistant
Definition of 'StateCheckChangedEventData' in file src/common/feature_state/state_check.ts in project gitlab-lsp
Definition: export interface StateCheckChangedEventData { checkId: StateCheckId; engaged: boolean; details?: string; } export interface StateCheck { id: StateCheckId; engaged: boolean; /** registers a listener that's called when the policy changes */ onChanged: (listener: (data: StateCheckChangedEventData) => void) => Disposable; details?: string; } References: - src/common/feature_state/project_duo_acces_check.ts:68 - src/common/feature_state/state_check.ts:14 - src/common/feature_state/supported_language_check.ts:45
You are a code assistant
Definition of 'CodeSuggestionsSupportedLanguageCheck' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp
Definition: export const CodeSuggestionsSupportedLanguageCheck = createInterfaceId<CodeSuggestionsSupportedLanguageCheck>('CodeSuggestionsSupportedLanguageCheck'); @Injectable(CodeSuggestionsSupportedLanguageCheck, [DocumentService, SupportedLanguagesService]) export class DefaultCodeSuggestionsSupportedLanguageCheck implements StateCheck { #documentService: DocumentService; #isLanguageEnabled = false; #isLanguageSupported = false; #supportedLanguagesService: SupportedLanguagesService; #currentDocument?: TextDocument; #stateEmitter = new EventEmitter(); constructor( documentService: DocumentService, supportedLanguagesService: SupportedLanguagesService, ) { this.#documentService = documentService; this.#supportedLanguagesService = supportedLanguagesService; this.#documentService.onDocumentChange((event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#updateWithDocument(event.document); } }); this.#supportedLanguagesService.onLanguageChange(() => this.#update()); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } #updateWithDocument(document: TextDocument) { this.#currentDocument = document; this.#update(); } get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References: - src/common/feature_state/feature_state_manager.ts:28 - src/common/feature_state/supported_language_check.test.ts:22
You are a code assistant
Definition of 'GitLabChatRecordContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.ts in project gitlab-lsp
Definition: export type GitLabChatRecordContext = { currentFile: GitLabChatFileContext; }; export const buildCurrentContext = (): GitLabChatRecordContext | undefined => { const currentFile = getActiveFileContext(); if (!currentFile) { return undefined; } return { currentFile }; }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:54
You are a code assistant
Definition of 'startTinyProxy' in file src/tests/int/fetch.test.ts in project gitlab-lsp
Definition: async function startTinyProxy(): Promise<ChildProcessWithoutNullStreams> { const tinyProxy = spawn(TINYPROXY, ['-d', '-c', TINYPROXY_CONF]); if (tinyProxy == null) { throw new Error('Error, failed to start tinyproxy. tinyProxy == null.'); } if (!tinyProxy?.pid) { throw new Error('Error, failed to start tinyproxy. pid undefined.'); } try { // Wait for tinyproxy to startup await tcpPortUsed.waitUntilUsedOnHost(PROXY_PORT, '127.0.0.1'); } catch (err) { console.error('Timed out checking for proxy port in use.'); if (tinyProxy.exitCode) { console.error(`Tinyproxy exited with code ${tinyProxy.exitCode}. Logs:`); } else { console.warn('Tinyproxy still running. Logs:'); } const data = await readFile(TINYPROXY_LOG, 'utf8'); console.warn(data); throw err; } return tinyProxy; } const cleanupTinyProxy = async (tinyProxy: ChildProcessWithoutNullStreams): Promise<void> => { // Wait a little bit to make sure sockets are // cleaned up in node before we kill our proxy // instance. Otherwise we might get connection // reset exceptions from node. const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await delay(500); // Try and stop tinyproxy nicely (SIGTERM) tinyProxy.kill(); for (let cnt = 0; cnt < 5 && tinyProxy.exitCode == null; cnt++) { await delay(100); } if (tinyProxy.exitCode == null) { // Kill the process if it didn't exit nicely tinyProxy.kill('SIGKILL'); for (let cnt = 0; cnt < 5 && tinyProxy.exitCode == null; cnt++) { await delay(100); } if (tinyProxy.exitCode == null) { throw new Error('Tinyproxy failed to exit properly.'); } } if (fs.existsSync(TINYPROXY_LOG)) { fs.unlinkSync(TINYPROXY_LOG); } }; describe('LsFetch', () => { it('can make a get request', async () => { const lsFetch = new Fetch(); await lsFetch.initialize(); const resp = await lsFetch.get('https://gitlab.com/'); expect(resp.status).toBe(200); }); describe('proxy Support', () => { it('tinyproxy is installed', () => { expect(hasbinSync(TINYPROXY)).toBeTruthy(); }); describe('when proxy is configured', () => { beforeEach(() => { if (fs.existsSync(TINYPROXY_LOG)) { fs.unlinkSync(TINYPROXY_LOG); } if (process.env.https_proxy) { delete process.env.https_proxy; } if (process.env.http_proxy) { delete process.env.http_proxy; } }); afterEach(() => { if (fs.existsSync(TINYPROXY_LOG)) { fs.unlinkSync(TINYPROXY_LOG); } if (process.env.https_proxy) { delete process.env.https_proxy; } if (process.env.http_proxy) { delete process.env.http_proxy; } }); describe('when proxy not running', () => { it('get should return connection error', async () => { process.env.https_proxy = PROXY; process.env.http_proxy = PROXY; const lsFetch = new Fetch(); await lsFetch.initialize(); try { await expect(() => lsFetch.get('https://gitlab.com/')).rejects.toHaveProperty( 'message', 'request to https://gitlab.com/ failed, reason: connect ECONNREFUSED 127.0.0.1:8888', ); } finally { await lsFetch.destroy(); } }); }); describe('when proxy is running', () => { let tinyProxy: ChildProcessWithoutNullStreams; jest.setTimeout(10 * 1000); beforeEach(async () => { tinyProxy = await startTinyProxy(); }); afterEach(async () => { await cleanupTinyProxy(tinyProxy); }); it('request should happen through proxy', async () => { process.env.https_proxy = PROXY; process.env.http_proxy = PROXY; const lsFetch = new Fetch(); await lsFetch.initialize(); try { const resp = await lsFetch.get('https://gitlab.com/'); await resp.text(); expect(resp.status).toBe(200); expect(await checkLogForRequest('gitlab.com:443')).toBe(true); } finally { await lsFetch.destroy(); } }); }); }); }); }); References: - src/tests/int/fetch.test.ts:143
You are a code assistant
Definition of 'error' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References: - scripts/commit-lint/lint.js:72 - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94
You are a code assistant
Definition of 'gitlabPlatformForAccount' in file packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts in project gitlab-lsp
Definition: export const gitlabPlatformForAccount: GitLabPlatformForAccount = { type: 'account', account, project: undefined, fetchFromApi: createFakeFetchFromApi(), connectToCable: async () => createFakeCable(), getUserAgentHeader: () => ({}), }; References:
You are a code assistant
Definition of 'retrieve' in file src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts in project gitlab-lsp
Definition: async retrieve(aiContextItem: AiContextItem): Promise<string | null> { if (aiContextItem.type !== 'file') { return null; } try { log.info(`retrieving file ${aiContextItem.id}`); const fileContent = await this.fileResolver.readFile({ fileUri: aiContextItem.id, }); log.info(`redacting secrets for file ${aiContextItem.id}`); const redactedContent = this.secretRedactor.redactSecrets(fileContent); return redactedContent; } catch (e) { log.warn(`Failed to retrieve file ${aiContextItem.id}`, e); return null; } } } References:
You are a code assistant
Definition of 'TimesRetrievedByPosition' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp
Definition: type TimesRetrievedByPosition = { [key: string]: number; }; export type SuggestionCacheEntry = { character: number; suggestions: SuggestionOption[]; additionalContexts?: AdditionalContext[]; currentLine: string; timesRetrievedByPosition: TimesRetrievedByPosition; }; export type SuggestionCacheContext = { document: TextDocumentIdentifier; context: IDocContext; position: Position; additionalContexts?: AdditionalContext[]; }; export type SuggestionCache = { options: SuggestionOption[]; additionalContexts?: AdditionalContext[]; }; function isNonEmptyLine(s: string) { return s.trim().length > 0; } type Required<T> = { [P in keyof T]-?: T[P]; }; const DEFAULT_CONFIG: Required<ISuggestionsCacheOptions> = { enabled: true, maxSize: 1024 * 1024, ttl: 60 * 1000, prefixLines: 1, suffixLines: 1, }; export class SuggestionsCache { #cache: LRUCache<string, SuggestionCacheEntry>; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache<string, SuggestionCacheEntry>({ ttlAutopurge: true, sizeCalculation: (value, key) => value.suggestions.reduce((acc, suggestion) => acc + suggestion.text.length, 0) + key.length, ...DEFAULT_CONFIG, ...currentConfig, ttl: Number(currentConfig.ttl), }); } #getCurrentConfig(): Required<ISuggestionsCacheOptions> { return { ...DEFAULT_CONFIG, ...(this.#configService.get('client.suggestionsCache') ?? {}), }; } #getSuggestionKey(ctx: SuggestionCacheContext) { const prefixLines = ctx.context.prefix.split('\n'); const currentLine = prefixLines.pop() ?? ''; const indentation = (currentLine.match(/^\s*/)?.[0] ?? '').length; const config = this.#getCurrentConfig(); const cachedPrefixLines = prefixLines .filter(isNonEmptyLine) .slice(-config.prefixLines) .join('\n'); const cachedSuffixLines = ctx.context.suffix .split('\n') .filter(isNonEmptyLine) .slice(0, config.suffixLines) .join('\n'); return [ ctx.document.uri, ctx.position.line, cachedPrefixLines, cachedSuffixLines, indentation, ].join(':'); } #increaseCacheEntryRetrievedCount(suggestionKey: string, character: number) { const item = this.#cache.get(suggestionKey); if (item && item.timesRetrievedByPosition) { item.timesRetrievedByPosition[character] = (item.timesRetrievedByPosition[character] ?? 0) + 1; } } addToSuggestionCache(config: { request: SuggestionCacheContext; suggestions: SuggestionOption[]; }) { if (!this.#getCurrentConfig().enabled) { return; } const currentLine = config.request.context.prefix.split('\n').at(-1) ?? ''; this.#cache.set(this.#getSuggestionKey(config.request), { character: config.request.position.character, suggestions: config.suggestions, currentLine, timesRetrievedByPosition: {}, additionalContexts: config.request.additionalContexts, }); } 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: - src/common/suggestion/suggestions_cache.ts:17
You are a code assistant
Definition of 'withTrailingSlashRedirect' in file src/node/http/fastify_utilities.ts in project gitlab-lsp
Definition: export const withTrailingSlashRedirect = (handler: RouteHandlerMethod): RouteHandlerMethod => { return function (this: FastifyInstance, request: FastifyRequest, reply: FastifyReply) { if (!request.url.endsWith('/')) { return reply.redirect(`${request.url}/`); } return handler.call(this, request, reply); }; }; References: - src/node/webview/handlers/webview_handler.ts:9
You are a code assistant
Definition of 'runScript' in file scripts/watcher/run_script.ts in project gitlab-lsp
Definition: export async function runScript(script: string, dir?: string): Promise<void> { const [file, ...args] = script.split(' '); const { exitCode } = await execa(file, args, { env: { ...process.env, FORCE_COLOR: 'true' }, stdio: 'inherit', // Inherit stdio to preserve color and formatting cwd: dir, extendEnv: true, shell: true, }); if (exitCode !== 0) { throw new Error(`Script ${script} exited with code ${exitCode}`); } } References: - scripts/watcher/watch.ts:32 - scripts/watcher/watch.ts:14 - scripts/watcher/watch.ts:30
You are a code assistant
Definition of 'onOpen' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: onOpen(listener: () => void): Disposable { this.#eventEmitter.on('open', listener); return { dispose: () => this.#eventEmitter.removeListener('open', listener) }; } onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:
You are a code assistant
Definition of 'WorkflowGraphQLService' in file src/common/graphql/workflow/service.ts in project gitlab-lsp
Definition: export class WorkflowGraphQLService implements WorkflowServiceInterface { #apiClient: GitLabApiClient; #logger: Logger; constructor(apiClient: GitLabApiClient, logger: Logger) { this.#apiClient = apiClient; this.#logger = withPrefix(logger, '[WorkflowGraphQLService]'); } generateWorkflowID(id: string): string { return `gid://gitlab/Ai::DuoWorkflows::Workflow/${id}`; } sortCheckpoints(checkpoints: LangGraphCheckpoint[]) { return [...checkpoints].sort((a: LangGraphCheckpoint, b: LangGraphCheckpoint) => { const parsedCheckpointA = JSON.parse(a.checkpoint); const parsedCheckpointB = JSON.parse(b.checkpoint); return new Date(parsedCheckpointA.ts).getTime() - new Date(parsedCheckpointB.ts).getTime(); }); } getStatus(checkpoints: LangGraphCheckpoint[]): string { const startingCheckpoint: LangGraphCheckpoint = { checkpoint: '{ "channel_values": { "status": "Starting" }}', }; const lastCheckpoint = checkpoints.at(-1) || startingCheckpoint; const checkpoint = JSON.parse(lastCheckpoint.checkpoint); return checkpoint?.channel_values?.status; } async pollWorkflowEvents(id: string, messageBus: MessageBus): Promise<void> { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise<void> => { try { const checkpoints: LangGraphCheckpoint[] = await this.getWorkflowEvents(workflowId); messageBus.sendNotification('workflowCheckpoints', checkpoints); const status = this.getStatus(checkpoints); messageBus.sendNotification('workflowStatus', status); // If the status is Completed, we dont call the next setTimeout and polling stops if (status !== 'Completed') { timeout = setTimeout(poll, 3000); } else { clearTimeout(timeout); } } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } }; await poll(); } async getWorkflowEvents(id: string): Promise<LangGraphCheckpoint[]> { try { const data: DuoWorkflowEventConnectionType = await this.#apiClient.fetchFromApi({ type: 'graphql', query: GET_WORKFLOW_EVENTS_QUERY, variables: { workflowId: id }, }); return this.sortCheckpoints(data?.duoWorkflowEvents?.nodes || []); } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } } } References: - src/common/graphql/workflow/service.test.ts:14 - src/common/graphql/workflow/service.test.ts:44 - packages/webview_duo_workflow/src/plugin/index.ts:14 - src/node/main.ts:174
You are a code assistant
Definition of 'connectToCable' in file src/common/api.ts in project gitlab-lsp
Definition: connectToCable(): Promise<ActionCableCable>; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId<GitLabApiClient>('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/action_cable.test.ts:21 - src/common/action_cable.test.ts:40 - src/common/api.ts:348 - src/common/action_cable.test.ts:54 - src/common/action_cable.test.ts:32
You are a code assistant
Definition of 'DEFAULT_MAX_BACKOFF_MS' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: export const DEFAULT_MAX_BACKOFF_MS = 60000; export const DEFAULT_BACKOFF_MULTIPLIER = 2; export interface ExponentialBackoffCircuitBreakerOptions { maxErrorsBeforeBreaking?: number; initialBackoffMs?: number; maxBackoffMs?: number; backoffMultiplier?: number; } export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } success() { this.#errorCount = 0; this.#close(); } onOpen(listener: () => void): Disposable { this.#eventEmitter.on('open', listener); return { dispose: () => this.#eventEmitter.removeListener('open', listener) }; } onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:
You are a code assistant
Definition of 'dispose' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp
Definition: public dispose(): void { this.clear(); } } References:
You are a code assistant
Definition of 'DISABLED_LANGUAGE' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: 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 'Handlers' in file src/common/webview/extension/types.ts in project gitlab-lsp
Definition: export type Handlers = { notification: ExtensionMessageHandlerRegistry; request: ExtensionMessageHandlerRegistry; }; References: - src/common/webview/extension/extension_connection_message_bus.ts:23 - src/common/webview/extension/extension_connection_message_bus_provider.ts:30 - src/common/webview/extension/extension_connection_message_bus.ts:11
You are a code assistant
Definition of 'getContext' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId<DocumentTransformerService>( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; constructor(documents: LsTextDocuments, secretRedactor: SecretRedactor) { this.#documents = documents; this.#transformers.push(secretRedactor); } get(uri: string) { return this.#documents.get(uri); } getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined { const doc = this.get(uri); if (doc === undefined) { return undefined; } return this.transform(getDocContext(doc, position, workspaceFolders, completionContext)); } transform(context: IDocContext): IDocContext { return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context); } } export function getDocContext( document: TextDocument, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext { let prefix: string; if (completionContext?.selectedCompletionInfo) { const { selectedCompletionInfo } = completionContext; const range = sanitizeRange(selectedCompletionInfo.range); prefix = `${document.getText({ start: document.positionAt(0), end: range.start, })}${selectedCompletionInfo.text}`; } else { prefix = document.getText({ start: document.positionAt(0), end: position }); } const suffix = document.getText({ start: position, end: document.positionAt(document.getText().length), }); const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders); const fileRelativePath = getRelativePath(document.uri, workspaceFolder); return { prefix, suffix, fileRelativePath, position, uri: document.uri, languageId: document.languageId, workspaceFolder, }; } References:
You are a code assistant
Definition of 'buildWebviewCollectionMetadataRequestHandler' in file src/node/webview/handlers/build_webview_metadata_request_handler.ts in project gitlab-lsp
Definition: export const buildWebviewCollectionMetadataRequestHandler = ( webviewIds: WebviewId[], ): ((req: FastifyRequest, reply: FastifyReply) => Promise<void>) => { return async (_, reply) => { const urls = webviewIds.reduce( (acc, webviewId) => { acc[webviewId] = `/webview/${webviewId}/`; return acc; }, {} as Record<WebviewId, string>, ); await reply.send(urls); }; }; References: - src/node/webview/handlers/build_webview_metadata_request_handler.test.ts:10 - src/node/webview/routes/webview_routes.ts:20
You are a code assistant
Definition of 'MockFastifyReply' in file src/node/webview/test-utils/mock_fastify_reply.ts in project gitlab-lsp
Definition: export type MockFastifyReply = { [P in keyof FastifyReply]: jest.Mock<FastifyReply[P]>; }; export const createMockFastifyReply = (): MockFastifyReply & FastifyReply => { const reply: Partial<MockFastifyReply> = {}; reply.send = jest.fn().mockReturnThis(); reply.status = jest.fn().mockReturnThis(); reply.redirect = jest.fn().mockReturnThis(); reply.sendFile = jest.fn().mockReturnThis(); reply.code = jest.fn().mockReturnThis(); reply.header = jest.fn().mockReturnThis(); reply.type = jest.fn().mockReturnThis(); return reply as MockFastifyReply & FastifyReply; }; References:
You are a code assistant
Definition of 'INSTANCE_FEATURE_FLAG_QUERY' in file src/common/feature_flags.ts in project gitlab-lsp
Definition: export const INSTANCE_FEATURE_FLAG_QUERY = gql` query featureFlagsEnabled($name: String!) { featureFlagEnabled(name: $name) } `; export const FeatureFlagService = createInterfaceId<FeatureFlagService>('FeatureFlagService'); 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:
You are a code assistant
Definition of 'processCompletion' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestProcessor()); const invalidInput = { invalid: 'input' }; await expect( pipeline.run({ documentContext: mockContext, input: invalidInput as unknown as StreamingCompletionResponse, type: 'invalid' as 'stream', }), ).rejects.toThrow('Unexpected type in pipeline processing'); }); }); References:
You are a code assistant
Definition of 'getSuggestions' in file src/common/suggestion_client/default_suggestion_client.ts in project gitlab-lsp
Definition: async getSuggestions( suggestionContext: SuggestionContext, ): Promise<SuggestionResponse | undefined> { const response = await this.#api.getCodeSuggestions(createV2Request(suggestionContext)); return response && { ...response, isDirectConnection: false }; } } References:
You are a code assistant
Definition of 'getProjectsForWorkspaceFolder' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise<DuoProject[]> { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise<GitlabRemoteAndFileUri[]> { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise<GitlabRemoteAndFileUri[]> { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce<string[]>((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:
You are a code assistant
Definition of 'DuoProjectPolicy' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp
Definition: export interface DuoProjectPolicy extends DefaultDuoProjectPolicy {} export const DuoProjectPolicy = createInterfaceId<DuoProjectPolicy>('AiFileContextProvider'); @Injectable(DuoProjectPolicy, [DuoProjectAccessChecker]) 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: - src/common/ai_context_management_2/ai_policy_management.ts:24
You are a code assistant
Definition of 'warn' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: 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 'onChanged' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp
Definition: onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise<void> { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise<WorkspaceFolder | undefined> { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References:
You are a code assistant
Definition of 'GenerationType' in file src/common/api.ts in project gitlab-lsp
Definition: 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:46 - src/common/api.ts:55 - src/common/tree_sitter/intent_resolver.ts:14 - src/common/suggestion/streaming_handler.test.ts:181 - src/common/suggestion/suggestion_service.ts:289
You are a code assistant
Definition of 'SuccessfulResponse' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp
Definition: export type SuccessfulResponse = WebviewAddress & { requestId: string; success: true; type: string; payload?: unknown; }; export type FailedResponse = WebviewAddress & { requestId: string; success: false; reason: string; type: string; }; export type ResponseMessage = SuccessfulResponse | FailedResponse; export type Messages = { 'webview:connect': WebviewAddress; 'webview:disconnect': WebviewAddress; 'webview:notification': NotificationMessage; 'webview:request': RequestMessage; 'webview:response': ResponseMessage; 'plugin:notification': NotificationMessage; 'plugin:request': RequestMessage; 'plugin:response': ResponseMessage; }; export class WebviewRuntimeMessageBus extends MessageBus<Messages> {} References:
You are a code assistant
Definition of 'getInstance' in file src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts in project gitlab-lsp
Definition: public static getInstance(): OpenTabsResolver { if (!OpenTabsResolver.#instance) { log.debug('OpenTabsResolver: initializing'); OpenTabsResolver.#instance = new OpenTabsResolver(); } return OpenTabsResolver.#instance; } public static destroyInstance(): void { OpenTabsResolver.#instance = undefined; } async *buildContext({ documentContext, includeCurrentFile = false, }: { documentContext?: IDocContext; includeCurrentFile?: boolean; }): AsyncGenerator<ContextResolution> { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); const openFiles = lruCache.mostRecentFiles({ context: documentContext, includeCurrentFile, }); for (const file of openFiles) { yield { uri: file.uri, type: 'file' as const, content: `${file.prefix}${file.suffix}`, fileRelativePath: file.fileRelativePath, strategy: 'open_tabs' as const, workspaceFolder: file.workspaceFolder ?? { name: '', uri: '' }, }; } } } References:
You are a code assistant
Definition of 'waitForMs' in file packages/webview_duo_chat/src/plugin/port/utils/wait_for_ms.ts in project gitlab-lsp
Definition: export const waitForMs = (ms: number) => new Promise<void>((resolve) => { setTimeout(resolve, ms); }); References: - packages/webview_duo_chat/src/plugin/port/utils/wait_for_ms.test.ts:7 - packages/webview_duo_chat/src/plugin/port/chat/api/pulling.ts:23
You are a code assistant
Definition of 'Emitter' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp
Definition: export class Emitter { #trackingQueue: PayloadBuilder[] = []; #callback: SendEventCallback; #timeInterval: number; #maxItems: number; #currentState: EmitterState; #timeout: NodeJS.Timeout | undefined; constructor(timeInterval: number, maxItems: number, callback: SendEventCallback) { this.#maxItems = maxItems; this.#timeInterval = timeInterval; this.#callback = callback; this.#currentState = EmitterState.STOPPED; } add(data: PayloadBuilder) { this.#trackingQueue.push(data); if (this.#trackingQueue.length >= this.#maxItems) { this.#drainQueue().catch(() => {}); } } async #drainQueue(): Promise<void> { if (this.#trackingQueue.length > 0) { const copyOfTrackingQueue = this.#trackingQueue.map((e) => e); this.#trackingQueue = []; await this.#callback(copyOfTrackingQueue); } } start() { this.#timeout = setTimeout(async () => { await this.#drainQueue(); if (this.#currentState !== EmitterState.STOPPING) { this.start(); } }, this.#timeInterval); this.#currentState = EmitterState.STARTED; } async stop() { this.#currentState = EmitterState.STOPPING; if (this.#timeout) { clearTimeout(this.#timeout); } this.#timeout = undefined; await this.#drainQueue(); } } References: - src/common/tracking/snowplow/emitter.test.ts:14 - src/common/tracking/snowplow/emitter.test.ts:73 - src/common/tracking/snowplow/emitter.test.ts:9 - src/common/tracking/snowplow/emitter.test.ts:19 - src/common/tracking/snowplow/snowplow.ts:46 - src/common/tracking/snowplow/emitter.test.ts:61 - src/common/tracking/snowplow/emitter.test.ts:28 - src/common/tracking/snowplow/emitter.test.ts:37 - src/common/tracking/snowplow/snowplow.ts:60 - src/common/tracking/snowplow/emitter.test.ts:49
You are a code assistant
Definition of 'ICodeCompletionConfig' in file src/common/config_service.ts in project gitlab-lsp
Definition: export interface ICodeCompletionConfig { enableSecretRedaction?: boolean; additionalLanguages?: string[]; disabledSupportedLanguages?: string[]; } export interface ISuggestionsCacheOptions { enabled?: boolean; maxSize?: number; ttl?: number; prefixLines?: number; suffixLines?: number; } export interface IHttpAgentOptions { ca?: string; cert?: string; certKey?: string; } export interface ISnowplowTrackerOptions { gitlab_instance_id?: string; gitlab_global_user_id?: string; gitlab_host_name?: string; gitlab_saas_duo_pro_namespace_ids?: number[]; } export interface ISecurityScannerOptions { enabled?: boolean; serviceUrl?: string; } export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record<string, boolean>; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter<IConfig>; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter<IConfig>; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial<IConfig>): void; } export const ConfigService = createInterfaceId<ConfigService>('ConfigService'); @Injectable(ConfigService, []) export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:60
You are a code assistant
Definition of 'ChatInputTemplate' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: 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:148
You are a code assistant
Definition of 'getInstance' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp
Definition: public static getInstance(maxSize: number): LruCache { if (!LruCache.#instance) { log.debug('LruCache: initializing'); LruCache.#instance = new LruCache(maxSize); } return LruCache.#instance; } public static destroyInstance(): void { LruCache.#instance = undefined; } get openFiles() { return this.#cache; } #getDocumentSize(context: IDocContext): number { const size = getByteSize(`${context.prefix}${context.suffix}`); return Math.max(1, size); } /** * Update the file in the cache. * Uses lru-cache under the hood. */ updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:
You are a code assistant
Definition of 'updateCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise<void>; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId<DuoProjectAccessCache>('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map<WorkspaceFolderUri, DuoProject[]>; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map<WorkspaceFolderUri, DuoProject[]>(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise<DuoProject[]> { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise<GitlabRemoteAndFileUri[]> { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise<GitlabRemoteAndFileUri[]> { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce<string[]>((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:
You are a code assistant
Definition of 'WebviewMetadata' in file src/common/webview/webview_metadata_provider.ts in project gitlab-lsp
Definition: export type WebviewMetadata = { id: WebviewId; title: string; uris: string[]; }; export class WebviewMetadataProvider { #plugins: Set<WebviewPlugin>; #accessInfoProviders: WebviewLocationService; constructor(accessInfoProviders: WebviewLocationService, plugins: Set<WebviewPlugin>) { this.#accessInfoProviders = accessInfoProviders; this.#plugins = plugins; } 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 'onNotification' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: 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 'constructor' in file src/common/api.ts in project gitlab-lsp
Definition: 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 'RequestListener' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: 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 'Greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp
Definition: class Greet3: pass def greet3(name): ... class Greet4: def __init__(self, name): ... def greet(self): ... class Greet3: ... def greet3(name): class Greet4: def __init__(self, name): def greet(self): class Greet3: References: - src/tests/fixtures/intent/empty_function/ruby.rb:34
You are a code assistant
Definition of 'serializeAccountSafe' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp
Definition: export const serializeAccountSafe = (account: Account) => JSON.stringify(account, ['instanceUrl', 'id', 'username', 'scopes']); export const makeAccountId = (instanceUrl: string, userId: string | number) => `${instanceUrl}|${userId}`; export const extractUserId = (accountId: string) => accountId.split('|').pop(); References: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.test.ts:14
You are a code assistant
Definition of 'WebviewSocketConnectionId' in file packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts in project gitlab-lsp
Definition: export type WebviewSocketConnectionId = string & { __type: 'WebviewSocketConnectionId' }; export function buildConnectionId( webviewInstanceInfo: WebviewInstanceInfo, ): WebviewSocketConnectionId { return `${webviewInstanceInfo.webviewId}:${webviewInstanceInfo.webviewInstanceId}` as WebviewSocketConnectionId; } References: - packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts:7
You are a code assistant
Definition of 'setup' in file src/common/log.ts in project gitlab-lsp
Definition: setup(configService: ConfigService) { this.#configService = configService; } /** * @param messageOrError can be error (if we don't want to provide any additional info), or a string message * @param trailingError is an optional error (if messageOrError was a message) * but we also mention `unknown` type because JS doesn't guarantee that in `catch(e)`, * the `e` is an `Error`, it can be anything. * */ #log( incomingLogLevel: LogLevel, messageOrError: Error | string, trailingError?: Error | unknown, ) { const configuredLevel = this.#configService?.get('client.logLevel'); const shouldShowLog = getNumericMapping(configuredLevel) >= LOG_LEVEL_MAPPING[incomingLogLevel]; if (shouldShowLog) { logWithLevel(incomingLogLevel, messageOrError, ensureError(trailingError)); } } debug(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.DEBUG, messageOrError, trailingError); } info(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.INFO, messageOrError, trailingError); } warn(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError); } error(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError); } } // TODO: rename the export and replace usages of `log` with `Log`. export const log = new Log(); References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197