instruction
stringclasses
1 value
input
stringlengths
67
168
output
stringlengths
46
67k
You are a code assistant
Definition of 'onClose' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp
Definition: onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } } References:
You are a code assistant
Definition of 'init' in file src/node/tree_sitter/parser.ts in project gitlab-lsp
Definition: async init(): Promise<void> { try { await Parser.init(); log.debug('DesktopTreeSitterParser: Initialized tree-sitter parser.'); this.loadState = TreeSitterParserLoadState.READY; } catch (err) { log.warn('DesktopTreeSitterParser: Error initializing tree-sitter parsers.', err); this.loadState = TreeSitterParserLoadState.ERRORED; } } } References:
You are a code assistant
Definition of 'INITIALIZE_PARAMS' in file src/common/test_utils/mocks.ts in project gitlab-lsp
Definition: export const INITIALIZE_PARAMS: CustomInitializeParams = { clientInfo: { name: 'Visual Studio Code', version: '1.82.0', }, capabilities: { textDocument: { completion: {}, inlineCompletion: {} } }, rootUri: '/', initializationOptions: {}, processId: 1, }; export const EMPTY_COMPLETION_CONTEXT: IDocContext = { prefix: '', suffix: '', fileRelativePath: 'test.js', position: { line: 0, character: 0, }, uri: 'file:///example.ts', languageId: 'javascript', }; export const SHORT_COMPLETION_CONTEXT: IDocContext = { prefix: 'abc', suffix: 'def', fileRelativePath: 'test.js', position: { line: 0, character: 3, }, uri: 'file:///example.ts', languageId: 'typescript', }; export const LONG_COMPLETION_CONTEXT: IDocContext = { prefix: 'abc 123', suffix: 'def 456', fileRelativePath: 'test.js', position: { line: 0, character: 7, }, uri: 'file:///example.ts', languageId: 'typescript', }; const textDocument: TextDocumentIdentifier = { uri: '/' }; const position: Position = { line: 0, character: 0 }; export const COMPLETION_PARAMS: TextDocumentPositionParams = { textDocument, position }; References:
You are a code assistant
Definition of 'WebviewTransportEventEmitter' in file packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp
Definition: export type WebviewTransportEventEmitter = TypedEmitter<WebviewTransportEventEmitterMessages>; export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:43 - packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts:11 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:35 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:27 - packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts:11
You are a code assistant
Definition of 'TestType' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp
Definition: type TestType = | 'empty_function_declaration' | 'non_empty_function_declaration' | 'empty_function_expression' | 'non_empty_function_expression' | 'empty_arrow_function' | 'non_empty_arrow_function' | 'empty_method_definition' | 'non_empty_method_definition' | 'empty_class_constructor' | 'non_empty_class_constructor' | 'empty_class_declaration' | 'non_empty_class_declaration' | 'empty_anonymous_function' | 'non_empty_anonymous_function' | 'empty_implementation' | 'non_empty_implementation' | 'empty_closure_expression' | 'non_empty_closure_expression' | 'empty_generator' | 'non_empty_generator' | 'empty_macro' | 'non_empty_macro'; type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:
You are a code assistant
Definition of 'AiContextFileRetriever' in file src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts in project gitlab-lsp
Definition: export interface AiContextFileRetriever extends DefaultAiContextFileRetriever {} export const AiContextFileRetriever = createInterfaceId<AiContextFileRetriever>('AiContextFileRetriever'); @Injectable(AiContextFileRetriever, [FileResolver, SecretRedactor]) export class DefaultAiContextFileRetriever implements AiContextRetriever { constructor( private fileResolver: FileResolver, private secretRedactor: SecretRedactor, ) {} 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: - src/common/ai_context_management_2/ai_context_manager.ts:13 - src/common/ai_context_management_2/ai_context_manager.ts:15
You are a code assistant
Definition of 'EMPTY_COMPLETION_CONTEXT' in file src/common/test_utils/mocks.ts in project gitlab-lsp
Definition: export const EMPTY_COMPLETION_CONTEXT: IDocContext = { prefix: '', suffix: '', fileRelativePath: 'test.js', position: { line: 0, character: 0, }, uri: 'file:///example.ts', languageId: 'javascript', }; export const SHORT_COMPLETION_CONTEXT: IDocContext = { prefix: 'abc', suffix: 'def', fileRelativePath: 'test.js', position: { line: 0, character: 3, }, uri: 'file:///example.ts', languageId: 'typescript', }; export const LONG_COMPLETION_CONTEXT: IDocContext = { prefix: 'abc 123', suffix: 'def 456', fileRelativePath: 'test.js', position: { line: 0, character: 7, }, uri: 'file:///example.ts', languageId: 'typescript', }; const textDocument: TextDocumentIdentifier = { uri: '/' }; const position: Position = { line: 0, character: 0 }; export const COMPLETION_PARAMS: TextDocumentPositionParams = { textDocument, position }; References:
You are a code assistant
Definition of 'updateCodeSuggestionsContext' in file src/common/tracking/tracking_types.ts in project gitlab-lsp
Definition: updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker'); References:
You are a code assistant
Definition of 'destroy' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp
Definition: public destroy() { Snowplow.#instance = undefined; } } References:
You are a code assistant
Definition of 'BrandedInstance' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: 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 'getLanguageInfoForFile' in file src/common/tree_sitter/parser.ts in project gitlab-lsp
Definition: getLanguageInfoForFile(filename: string): TreeSitterLanguageInfo | undefined { const ext = filename.split('.').pop(); return this.languages.get(`.${ext}`); } buildTreeSitterInfoByExtMap( languages: TreeSitterLanguageInfo[], ): Map<string, TreeSitterLanguageInfo> { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map<string, TreeSitterLanguageInfo>()); } } References:
You are a code assistant
Definition of 'completionOptionMapper' in file src/common/utils/suggestion_mappers.ts in project gitlab-lsp
Definition: export const completionOptionMapper = (options: SuggestionOption[]): CompletionItem[] => options.map((option, index) => ({ label: `GitLab Suggestion ${index + 1}: ${option.text}`, kind: CompletionItemKind.Text, insertText: option.text, detail: option.text, command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId], }, data: { index, trackingId: option.uniqueTrackingId, }, })); /* this value will be used for telemetry so to make it human-readable we use the 1-based indexing instead of 0 */ const getOptionTrackingIndex = (option: SuggestionOption) => { return typeof option.index === 'number' ? option.index + 1 : undefined; }; export const inlineCompletionOptionMapper = ( params: InlineCompletionParams, options: SuggestionOptionOrStream[], ): InlineCompletionList => ({ items: options.map((option) => { if (isStream(option)) { // the streaming item is empty and only indicates to the client that streaming started return { insertText: '', command: { title: 'Start streaming', command: START_STREAMING_COMMAND, arguments: [option.streamId, option.uniqueTrackingId], }, }; } const completionInfo = params.context.selectedCompletionInfo; let rangeDiff = 0; if (completionInfo) { const range = sanitizeRange(completionInfo.range); rangeDiff = range.end.character - range.start.character; } return { insertText: completionInfo ? `${completionInfo.text.substring(rangeDiff)}${option.text}` : option.text, range: Range.create(params.position, params.position), command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId, getOptionTrackingIndex(option)], }, }; }), }); References: - src/common/utils/suggestion_mapper.test.ts:17 - src/common/suggestion/suggestion_service.ts:189
You are a code assistant
Definition of 'WorkflowAPI' in file packages/lib_workflow_api/src/index.ts in project gitlab-lsp
Definition: export interface WorkflowAPI { runWorkflow(goal: string, image: string): Promise<string>; } References: - packages/webview_duo_workflow/src/plugin/index.ts:15
You are a code assistant
Definition of 'getGitLabPlatform' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp
Definition: 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 'ExtensionConnectionMessageBusProvider' in file src/common/webview/extension/extension_connection_message_bus_provider.ts in project gitlab-lsp
Definition: export class ExtensionConnectionMessageBusProvider implements ExtensionMessageBusProvider, Disposable { #connection: Connection; #rpcMethods: RpcMethods; #handlers: Handlers; #logger: Logger; #notificationHandlers = new ExtensionMessageHandlerRegistry(); #requestHandlers = new ExtensionMessageHandlerRegistry(); #disposables = new CompositeDisposable(); constructor({ connection, logger, notificationRpcMethod = DEFAULT_NOTIFICATION_RPC_METHOD, requestRpcMethod = DEFAULT_REQUEST_RPC_METHOD, }: ExtensionConnectionMessageBusProviderProps) { this.#connection = connection; this.#logger = withPrefix(logger, '[ExtensionConnectionMessageBusProvider]'); this.#rpcMethods = { notification: notificationRpcMethod, request: requestRpcMethod, }; this.#handlers = { notification: new ExtensionMessageHandlerRegistry(), request: new ExtensionMessageHandlerRegistry(), }; this.#setupConnectionSubscriptions(); } getMessageBus<T extends MessageMap>(webviewId: WebviewId): MessageBus<T> { return new ExtensionConnectionMessageBus({ webviewId, connection: this.#connection, rpcMethods: this.#rpcMethods, handlers: this.#handlers, }); } dispose(): void { this.#disposables.dispose(); } #setupConnectionSubscriptions() { this.#disposables.add( this.#connection.onNotification( this.#rpcMethods.notification, handleNotificationMessage(this.#notificationHandlers, this.#logger), ), ); this.#disposables.add( this.#connection.onRequest( this.#rpcMethods.request, handleRequestMessage(this.#requestHandlers, this.#logger), ), ); } } References: - src/common/webview/extension/extension_connection_message_bus_provider.test.ts:24 - src/node/main.ts:192 - src/common/webview/extension/extension_connection_message_bus_provider.test.ts:11
You are a code assistant
Definition of 'removeItem' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp
Definition: removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise<AiContextItemWithContent[]> { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:
You are a code assistant
Definition of 'MANUAL_REQUEST_OPTIONS_COUNT' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp
Definition: export const MANUAL_REQUEST_OPTIONS_COUNT = 4; export type OptionsCount = 1 | typeof MANUAL_REQUEST_OPTIONS_COUNT; export const GENERATION = 'generation'; export const COMPLETION = 'completion'; export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined>; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType<SuggestionClientFn>; References:
You are a code assistant
Definition of 'NotificationPublisher' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: export interface NotificationPublisher<TNotifications extends NotificationMap> { sendNotification<T extends KeysWithOptionalValues<TNotifications>>(type: T): void; sendNotification<T extends keyof TNotifications>(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener<TNotifications extends NotificationMap> { onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'error' in file src/common/log.ts in project gitlab-lsp
Definition: 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: - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94 - scripts/commit-lint/lint.js:72
You are a code assistant
Definition of 'isIgnored' in file src/common/git/ignore_trie.ts in project gitlab-lsp
Definition: isIgnored(pathParts: string[]): boolean { if (pathParts.length === 0) { return false; } const [current, ...rest] = pathParts; if (this.#ignoreInstance && this.#ignoreInstance.ignores(path.join(...pathParts))) { return true; } const child = this.#children.get(current); if (child) { return child.isIgnored(rest); } return false; } dispose(): void { this.#clear(); } #clear(): void { this.#children.forEach((child) => child.#clear()); this.#children.clear(); this.#ignoreInstance = null; } #removeChild(key: string): void { const child = this.#children.get(key); if (child) { child.#clear(); this.#children.delete(key); } } #prune(): void { this.#children.forEach((child, key) => { if (child.#isEmpty()) { this.#removeChild(key); } else { child.#prune(); } }); } #isEmpty(): boolean { return this.#children.size === 0 && !this.#ignoreInstance; } } References:
You are a code assistant
Definition of 'addToSuggestionCache' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp
Definition: 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 'HandlerRegistry' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'SupportedSinceInstanceVersion' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp
Definition: interface SupportedSinceInstanceVersion { version: string; resourceName: string; } interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; headers?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record<string, unknown>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'POST'; body?: unknown; } /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'GET'; searchParams?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>; connectToCable(): Promise<Cable>; } References: - src/common/api_types.ts:47 - src/common/api_types.ts:31 - packages/webview_duo_chat/src/plugin/types.ts:41 - packages/webview_duo_chat/src/plugin/types.ts:49 - src/common/api_types.ts:23 - packages/webview_duo_chat/src/plugin/types.ts:65
You are a code assistant
Definition of 'info' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:
You are a code assistant
Definition of 'isLanguageSupported' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp
Definition: isLanguageSupported(languageId: string) { return this.#supportedLanguages.has(languageId); } isLanguageEnabled(languageId: string) { return this.#enabledLanguages.has(languageId); } onLanguageChange(listener: () => void): Disposable { this.#eventEmitter.on('languageChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('languageChange'); } #normalizeLanguageIdentifier(language: string) { return language.trim().toLowerCase().replace(/^\./, ''); } } References:
You are a code assistant
Definition of 'resolveUris' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp
Definition: resolveUris(webviewId: WebviewId): Uri[] { const uris: Uri[] = []; for (const provider of this.#uriProviders) { uris.push(provider.getUri(webviewId)); } return uris; } } References:
You are a code assistant
Definition of 'onChanged' in file src/common/feature_state/supported_language_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), }; } #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:
You are a code assistant
Definition of 'NotificationMap' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: export type NotificationMap = Record<Method, MessagePayload>; /** * Interface for publishing notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationPublisher<TNotifications extends NotificationMap> { sendNotification<T extends KeysWithOptionalValues<TNotifications>>(type: T): void; sendNotification<T extends keyof TNotifications>(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener<TNotifications extends NotificationMap> { onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'buildCurrentContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.ts in project gitlab-lsp
Definition: 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_context.test.ts:29 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:83 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.test.ts:20
You are a code assistant
Definition of 'fetchFromApi' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp
Definition: fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { return this.#client.fetchFromApi(request); } connectToCable(): Promise<Cable> { return this.#client.connectToCable(); } getUserAgentHeader(): Record<string, string> { return {}; } } export class ChatPlatformForAccount extends ChatPlatform implements GitLabPlatformForAccount { readonly type = 'account' as const; project: undefined; } export class ChatPlatformForProject extends ChatPlatform implements GitLabPlatformForProject { readonly type = 'project' as const; project: GitLabProject = { gqlId: 'gid://gitlab/Project/123456', restId: 0, name: '', description: '', namespaceWithPath: '', webUrl: '', }; } References: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11 - packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10
You are a code assistant
Definition of 'LsFetchMocked' in file src/common/tracking/snowplow/snowplow.test.ts in project gitlab-lsp
Definition: class LsFetchMocked extends FetchBase implements LsFetch {} const structEvent = { category: 'test', action: 'test', label: 'test', value: 1, }; const enabledMock = jest.fn(); const lsFetch = new LsFetchMocked(); const sp = Snowplow.getInstance(lsFetch, { appId: 'test', timeInterval: 1000, maxItems: 1, endpoint: 'http://localhost', enabled: enabledMock, }); describe('Snowplow', () => { describe('Snowplow interface', () => { it('should initialize', async () => { const newSP = Snowplow.getInstance(lsFetch); expect(newSP).toBe(sp); }); it('should let you track events', async () => { (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValue({ status: 200, statusText: 'OK', } as Response); enabledMock.mockReturnValue(true); await sp.trackStructEvent(structEvent); await sp.stop(); }); it('should let you stop when the program ends', async () => { enabledMock.mockReturnValue(true); await sp.stop(); }); it('should destroy the instance', async () => { const sameInstance = Snowplow.getInstance(lsFetch, { appId: 'test', timeInterval: 1000, maxItems: 1, endpoint: 'http://localhost', enabled: enabledMock, }); expect(sp).toBe(sameInstance); await sp.stop(); sp.destroy(); const newInstance = Snowplow.getInstance(lsFetch, { appId: 'test', timeInterval: 1000, maxItems: 1, endpoint: 'http://localhost', enabled: enabledMock, }); expect(sp).not.toBe(newInstance); await newInstance.stop(); }); }); describe('should track and send events to snowplow', () => { beforeEach(() => { enabledMock.mockReturnValue(true); }); afterEach(async () => { await sp.stop(); }); it('should send the events to snowplow', async () => { (fetch as jest.MockedFunction<typeof fetch>).mockClear(); (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValue({ status: 200, statusText: 'OK', } as Response); const structEvent1 = { ...structEvent }; structEvent1.action = 'action'; await sp.trackStructEvent(structEvent); await sp.trackStructEvent(structEvent1); expect(fetch).toBeCalledTimes(2); await sp.stop(); }); }); describe('enabled function', () => { it('should not send events to snowplow when disabled', async () => { (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValue({ status: 200, statusText: 'OK', } as Response); enabledMock.mockReturnValue(false); const structEvent1 = { ...structEvent }; structEvent1.action = 'action'; await sp.trackStructEvent(structEvent); expect(fetch).not.toBeCalled(); await sp.stop(); }); it('should send events to snowplow when enabled', async () => { (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValue({ status: 200, statusText: 'OK', } as Response); enabledMock.mockReturnValue(true); const structEvent1 = { ...structEvent }; structEvent1.action = 'action'; await sp.trackStructEvent(structEvent); expect(fetch).toBeCalled(); await sp.stop(); }); }); describe('when hostname cannot be resolved', () => { it('should disable sending events', async () => { const logSpy = jest.spyOn(global.console, 'log'); // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-shadow const sp = Snowplow.getInstance(lsFetch, { appId: 'test', timeInterval: 1000, maxItems: 2, endpoint: 'http://askdalksdjalksjd.com', enabled: enabledMock, }); (fetch as jest.MockedFunction<typeof fetch>).mockRejectedValue({ message: '', errno: 'ENOTFOUND', }); expect(sp.disabled).toBe(false); await sp.trackStructEvent(structEvent); await sp.stop(); expect(sp.disabled).toBe(true); expect(logSpy).toHaveBeenCalledWith( expect.stringContaining('Disabling telemetry, unable to resolve endpoint address.'), ); logSpy.mockClear(); await sp.trackStructEvent(structEvent); await sp.stop(); expect(sp.disabled).toBe(true); expect(logSpy).not.toHaveBeenCalledWith(); }); }); }); References: - src/common/tracking/snowplow/snowplow.test.ts:18
You are a code assistant
Definition of 'IStartWorkflowParams' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp
Definition: export interface IStartWorkflowParams { goal: string; image: string; } export const waitMs = (msToWait: number) => new Promise((resolve) => { setTimeout(resolve, msToWait); }); /* CompletionRequest represents LS client's request for either completion or inlineCompletion */ export interface CompletionRequest { textDocument: TextDocumentIdentifier; position: Position; token: CancellationToken; inlineCompletionContext?: InlineCompletionContext; } export class DefaultSuggestionService { readonly #suggestionClientPipeline: SuggestionClientPipeline; #configService: ConfigService; #api: GitLabApiClient; #tracker: TelemetryTracker; #connection: Connection; #documentTransformerService: DocumentTransformerService; #circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests'); #subscriptions: Disposable[] = []; #suggestionsCache: SuggestionsCache; #treeSitterParser: TreeSitterParser; #duoProjectAccessChecker: DuoProjectAccessChecker; #featureFlagService: FeatureFlagService; #postProcessorPipeline = new PostProcessorPipeline(); constructor({ telemetryTracker, configService, api, connection, documentTransformerService, featureFlagService, treeSitterParser, duoProjectAccessChecker, }: SuggestionServiceOptions) { this.#configService = configService; this.#api = api; this.#tracker = telemetryTracker; this.#connection = connection; this.#documentTransformerService = documentTransformerService; this.#suggestionsCache = new SuggestionsCache(this.#configService); this.#treeSitterParser = treeSitterParser; this.#featureFlagService = featureFlagService; const suggestionClient = new FallbackClient( new DirectConnectionClient(this.#api, this.#configService), new DefaultSuggestionClient(this.#api), ); this.#suggestionClientPipeline = new SuggestionClientPipeline([ clientToMiddleware(suggestionClient), createTreeSitterMiddleware({ treeSitterParser, getIntentFn: getIntent, }), ]); this.#subscribeToCircuitBreakerEvents(); this.#duoProjectAccessChecker = duoProjectAccessChecker; } completionHandler = async ( { textDocument, position }: CompletionParams, token: CancellationToken, ): Promise<CompletionItem[]> => { log.debug('Completion requested'); const suggestionOptions = await this.#getSuggestionOptions({ textDocument, position, token }); if (suggestionOptions.find(isStream)) { log.warn( `Completion response unexpectedly contained streaming response. Streaming for completion is not supported. Please report this issue.`, ); } return completionOptionMapper(suggestionOptions.filter(isTextSuggestion)); }; #getSuggestionOptions = async ( request: CompletionRequest, ): Promise<SuggestionOptionOrStream[]> => { const { textDocument, position, token, inlineCompletionContext: context } = request; const suggestionContext = this.#documentTransformerService.getContext( textDocument.uri, position, this.#configService.get('client.workspaceFolders') ?? [], context, ); if (!suggestionContext) { return []; } const cachedSuggestions = this.#useAndTrackCachedSuggestions( textDocument, position, suggestionContext, context?.triggerKind, ); if (context?.triggerKind === InlineCompletionTriggerKind.Invoked) { const options = await this.#handleNonStreamingCompletion(request, suggestionContext); options.unshift(...(cachedSuggestions ?? [])); (cachedSuggestions ?? []).forEach((cs) => this.#tracker.updateCodeSuggestionsContext(cs.uniqueTrackingId, { optionsCount: options.length, }), ); return options; } if (cachedSuggestions) { return cachedSuggestions; } // debounce await waitMs(SUGGESTIONS_DEBOUNCE_INTERVAL_MS); if (token.isCancellationRequested) { log.debug('Debounce triggered for completion'); return []; } if ( context && shouldRejectCompletionWithSelectedCompletionTextMismatch( context, this.#documentTransformerService.get(textDocument.uri), ) ) { return []; } const additionalContexts = await this.#getAdditionalContexts(suggestionContext); // right now we only support streaming for inlineCompletion // if the context is present, we know we are handling inline completion if ( context && this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.StreamCodeGenerations) ) { const intentResolution = await this.#getIntent(suggestionContext); if (intentResolution?.intent === 'generation') { return this.#handleStreamingInlineCompletion( suggestionContext, intentResolution.commentForCursor?.content, intentResolution.generationType, additionalContexts, ); } } return this.#handleNonStreamingCompletion(request, suggestionContext, additionalContexts); }; inlineCompletionHandler = async ( params: InlineCompletionParams, token: CancellationToken, ): Promise<InlineCompletionList> => { log.debug('Inline completion requested'); const options = await this.#getSuggestionOptions({ textDocument: params.textDocument, position: params.position, token, inlineCompletionContext: params.context, }); return inlineCompletionOptionMapper(params, options); }; async #handleStreamingInlineCompletion( context: IDocContext, userInstruction?: string, generationType?: GenerationType, additionalContexts?: AdditionalContext[], ): Promise<StartStreamOption[]> { if (this.#circuitBreaker.isOpen()) { log.warn('Stream was not started as the circuit breaker is open.'); return []; } const streamId = uniqueId('code-suggestion-stream-'); const uniqueTrackingId = generateUniqueTrackingId(); setTimeout(() => { log.debug(`Starting to stream (id: ${streamId})`); const streamingHandler = new DefaultStreamingHandler({ api: this.#api, circuitBreaker: this.#circuitBreaker, connection: this.#connection, documentContext: context, parser: this.#treeSitterParser, postProcessorPipeline: this.#postProcessorPipeline, streamId, tracker: this.#tracker, uniqueTrackingId, userInstruction, generationType, additionalContexts, }); streamingHandler.startStream().catch((e: Error) => log.error('Failed to start streaming', e)); }, 0); return [{ streamId, uniqueTrackingId }]; } async #handleNonStreamingCompletion( request: CompletionRequest, documentContext: IDocContext, additionalContexts?: AdditionalContext[], ): Promise<SuggestionOption[]> { const uniqueTrackingId: string = generateUniqueTrackingId(); try { return await this.#getSuggestions({ request, uniqueTrackingId, documentContext, additionalContexts, }); } catch (e) { if (isFetchError(e)) { this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: e.status }); } this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); this.#circuitBreaker.error(); log.error('Failed to get code suggestions!', e); return []; } } /** * FIXME: unify how we get code completion and generation * so we don't have duplicate intent detection (see `tree_sitter_middleware.ts`) * */ async #getIntent(context: IDocContext): Promise<IntentResolution | undefined> { try { const treeAndLanguage = await this.#treeSitterParser.parseFile(context); if (!treeAndLanguage) { return undefined; } return await getIntent({ treeAndLanguage, position: context.position, prefix: context.prefix, suffix: context.suffix, }); } catch (error) { log.error('Failed to parse with tree sitter', error); return undefined; } } #trackShowIfNeeded(uniqueTrackingId: string) { if ( !canClientTrackEvent( this.#configService.get('client.telemetry.actions'), TRACKING_EVENTS.SHOWN, ) ) { /* If the Client can detect when the suggestion is shown in the IDE, it will notify the Server. Otherwise the server will assume that returned suggestions are shown and tracks the event */ this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); } } async #getSuggestions({ request, uniqueTrackingId, documentContext, additionalContexts, }: { request: CompletionRequest; uniqueTrackingId: string; documentContext: IDocContext; additionalContexts?: AdditionalContext[]; }): Promise<SuggestionOption[]> { const { textDocument, position, token } = request; const triggerKind = request.inlineCompletionContext?.triggerKind; log.info('Suggestion requested.'); if (this.#circuitBreaker.isOpen()) { log.warn('Code suggestions were not requested as the circuit breaker is open.'); return []; } if (!this.#configService.get('client.token')) { return []; } // Do not send a suggestion if content is less than 10 characters const contentLength = (documentContext?.prefix?.length || 0) + (documentContext?.suffix?.length || 0); if (contentLength < 10) { return []; } if (!isAtOrNearEndOfLine(documentContext.suffix)) { return []; } // Creates the suggestion and tracks suggestion_requested this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, triggerKind, additionalContexts, }); /** how many suggestion options should we request from the API */ const optionsCount: OptionsCount = triggerKind === InlineCompletionTriggerKind.Invoked ? MANUAL_REQUEST_OPTIONS_COUNT : 1; const suggestionsResponse = await this.#suggestionClientPipeline.getSuggestions({ document: documentContext, projectPath: this.#configService.get('client.projectPath'), optionsCount, additionalContexts, }); this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { model: suggestionsResponse?.model, status: suggestionsResponse?.status, optionsCount: suggestionsResponse?.choices?.length, isDirectConnection: suggestionsResponse?.isDirectConnection, }); if (suggestionsResponse?.error) { throw new Error(suggestionsResponse.error); } this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED); this.#circuitBreaker.success(); const areSuggestionsNotProvided = !suggestionsResponse?.choices?.length || suggestionsResponse?.choices.every(({ text }) => !text?.length); const suggestionOptions = (suggestionsResponse?.choices || []).map((choice, index) => ({ ...choice, index, uniqueTrackingId, lang: suggestionsResponse?.model?.lang, })); const processedChoices = await this.#postProcessorPipeline.run({ documentContext, input: suggestionOptions, type: 'completion', }); this.#suggestionsCache.addToSuggestionCache({ request: { document: textDocument, position, context: documentContext, additionalContexts, }, suggestions: processedChoices, }); if (token.isCancellationRequested) { this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); return []; } if (areSuggestionsNotProvided) { this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); return []; } this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { suggestionOptions }); this.#trackShowIfNeeded(uniqueTrackingId); return processedChoices; } dispose() { this.#subscriptions.forEach((subscription) => subscription?.dispose()); } #subscribeToCircuitBreakerEvents() { this.#subscriptions.push( this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)), ); this.#subscriptions.push( this.#circuitBreaker.onClose(() => this.#connection.sendNotification(API_RECOVERY_NOTIFICATION), ), ); } #useAndTrackCachedSuggestions( textDocument: TextDocumentIdentifier, position: Position, documentContext: IDocContext, triggerKind?: InlineCompletionTriggerKind, ): SuggestionOption[] | undefined { const suggestionsCache = this.#suggestionsCache.getCachedSuggestions({ document: textDocument, position, context: documentContext, }); if (suggestionsCache?.options?.length) { const { uniqueTrackingId, lang } = suggestionsCache.options[0]; const { additionalContexts } = suggestionsCache; this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, source: SuggestionSource.cache, triggerKind, suggestionOptions: suggestionsCache?.options, language: lang, additionalContexts, }); this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED); this.#trackShowIfNeeded(uniqueTrackingId); return suggestionsCache.options.map((option, index) => ({ ...option, index })); } return undefined; } async #getAdditionalContexts(documentContext: IDocContext): Promise<AdditionalContext[]> { let additionalContexts: AdditionalContext[] = []; const advancedContextEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextEnabled) { const advancedContext = await getAdvancedContext({ documentContext, dependencies: { duoProjectAccessChecker: this.#duoProjectAccessChecker }, }); additionalContexts = advancedContextToRequestBody(advancedContext); } return additionalContexts; } } References: - src/common/message_handler.ts:187
You are a code assistant
Definition of 'createMockTransport' in file packages/lib_webview/src/test_utils/mocks.ts in project gitlab-lsp
Definition: export const createMockTransport = (): jest.Mocked<Transport> => ({ publish: jest.fn(), on: jest.fn(), }); References:
You are a code assistant
Definition of 'CImpl' in file packages/lib_di/src/index.test.ts in project gitlab-lsp
Definition: class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId<object>('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance<object>)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) class AImpl2 implements A { a = () => 'hello'; } expect(() => container.instantiate(AImpl, AImpl2)).toThrow( /The following interface IDs were used multiple times 'A' \(classes: AImpl,AImpl2\)/, ); }); it('detects duplicate id with pre-existing instance', () => { const aInstance = new AImpl(); const a = brandInstance(A, aInstance); container.addInstances(a); expect(() => container.instantiate(AImpl)).toThrow(/classes are clashing/); }); it('detects missing dependencies', () => { expect(() => container.instantiate(BImpl)).toThrow( /Class BImpl \(interface B\) depends on interfaces \[A]/, ); }); it('it uses existing instances as dependencies', () => { const aInstance = new AImpl(); const a = brandInstance(A, aInstance); container.addInstances(a); container.instantiate(BImpl); expect(container.get(B).b()).toBe('B(a)'); }); it("detects classes what aren't decorated with @Injectable", () => { class AImpl2 implements A { a = () => 'hello'; } expect(() => container.instantiate(AImpl2)).toThrow( /Classes \[AImpl2] are not decorated with @Injectable/, ); }); it('detects circular dependencies', () => { @Injectable(A, [C]) class ACircular implements A { a = () => 'hello'; constructor(c: C) { // eslint-disable-next-line no-unused-expressions c; } } expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow( /Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./, ); }); // this test ensures that we don't store any references to the classes and we instantiate them only once it('does not instantiate classes from previous instantiate call', () => { let globCount = 0; @Injectable(A, []) class Counter implements A { counter = globCount; constructor() { globCount++; } a = () => this.counter.toString(); } container.instantiate(Counter); container.instantiate(BImpl); expect(container.get(A).a()).toBe('0'); }); }); describe('get', () => { it('returns an instance of the interfaceId', () => { container.instantiate(AImpl); expect(container.get(A)).toBeInstanceOf(AImpl); }); it('throws an error for missing dependency', () => { container.instantiate(); expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/); }); }); }); References:
You are a code assistant
Definition of 'SUGGESTIONS_DEBOUNCE_INTERVAL_MS' in file src/common/constants.ts in project gitlab-lsp
Definition: export const SUGGESTIONS_DEBOUNCE_INTERVAL_MS = 250; export const WORKFLOW_EXECUTOR_DOWNLOAD_PATH = `https://gitlab.com/api/v4/projects/58711783/packages/generic/duo_workflow_executor/${WORKFLOW_EXECUTOR_VERSION}/duo_workflow_executor.tar.gz`; References:
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/typescript_comments.ts in project gitlab-lsp
Definition: function greet(name: string): string { return `Hello, ${name}!`; } // This file has more than 5 non-comment lines const a = 1; const b = 2; const c = 3; const d = 4; const e = 5; const f = 6; function hello(user) { // function to greet the user } 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 'AiFileContextProvider' in file src/common/ai_context_management_2/providers/ai_file_context_provider.ts in project gitlab-lsp
Definition: export const AiFileContextProvider = createInterfaceId<AiFileContextProvider>('AiFileContextProvider'); @Injectable(AiFileContextProvider, [RepositoryService, DuoProjectAccessChecker]) export class DefaultAiFileContextProvider implements AiContextProvider { #repositoryService: DefaultRepositoryService; constructor(repositoryService: DefaultRepositoryService) { this.#repositoryService = repositoryService; } 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: - src/common/ai_context_management_2/ai_context_aggregator.ts:29 - src/common/ai_context_management_2/ai_context_aggregator.ts:24
You are a code assistant
Definition of 'GENERATION' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp
Definition: export const GENERATION = 'generation'; export const COMPLETION = 'completion'; export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined>; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType<SuggestionClientFn>; References:
You are a code assistant
Definition of 'IClientInfo' in file src/common/tracking/tracking_types.ts in project gitlab-lsp
Definition: export type IClientInfo = InitializeParams['clientInfo']; export enum GitlabRealm { saas = 'saas', selfManaged = 'self-managed', } export enum SuggestionSource { cache = 'cache', network = 'network', } export interface IIDEInfo { name: string; version: string; vendor: string; } export interface IClientContext { ide?: IIDEInfo; extension?: IClientInfo; } export interface ITelemetryOptions { enabled?: boolean; baseUrl?: string; trackingUrl?: string; actions?: Array<{ action: TRACKING_EVENTS }>; ide?: IIDEInfo; extension?: IClientInfo; } export interface ICodeSuggestionModel { lang: string; engine: string; name: string; tokens_consumption_metadata?: { input_tokens?: number; output_tokens?: number; context_tokens_sent?: number; context_tokens_used?: number; }; } export interface TelemetryTracker { isEnabled(): boolean; setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker'); References: - src/common/tracking/tracking_types.ts:47 - src/common/config_service.ts:58 - src/common/api.ts:125 - src/common/tracking/tracking_types.ts:56
You are a code assistant
Definition of 'WebviewRuntimeMessageBus' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp
Definition: export class WebviewRuntimeMessageBus extends MessageBus<Messages> {} References: - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:22 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:9 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:19 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.ts:7 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:8 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:13 - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:28 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:17 - packages/lib_webview/src/setup/plugin/webview_controller.ts:75 - packages/lib_webview/src/setup/transport/setup_transport.ts:37 - packages/lib_webview/src/setup/plugin/webview_controller.ts:39 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:20 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:14 - packages/lib_webview/src/setup/transport/setup_transport.ts:10 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:13 - packages/lib_webview/src/setup/setup_webview_runtime.ts:22 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:9 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:34
You are a code assistant
Definition of 'GitLabChatController' in file packages/webview_duo_chat/src/plugin/chat_controller.ts in project gitlab-lsp
Definition: export class GitLabChatController implements Disposable { readonly chatHistory: GitLabChatRecord[]; readonly #api: GitLabChatApi; readonly #extensionMessageBus: DuoChatExtensionMessageBus; readonly #webviewMessageBus: DuoChatWebviewMessageBus; readonly #subscriptions = new CompositeDisposable(); constructor( manager: GitLabPlatformManagerForChat, webviewMessageBus: DuoChatWebviewMessageBus, extensionMessageBus: DuoChatExtensionMessageBus, ) { this.#api = new GitLabChatApi(manager); this.chatHistory = []; this.#webviewMessageBus = webviewMessageBus; this.#extensionMessageBus = extensionMessageBus; this.#setupMessageHandlers.bind(this)(); } dispose(): void { this.#subscriptions.dispose(); } #setupMessageHandlers() { this.#subscriptions.add( this.#webviewMessageBus.onNotification('newPrompt', async (message) => { const record = GitLabChatRecord.buildWithContext({ role: 'user', content: message.record.content, }); await this.#processNewUserRecord(record); }), ); } async #processNewUserRecord(record: GitLabChatRecord) { if (!record.content) return; await this.#sendNewPrompt(record); if (record.errors.length > 0) { this.#extensionMessageBus.sendNotification('showErrorMessage', { message: record.errors[0], }); return; } await this.#addToChat(record); if (record.type === 'newConversation') return; const responseRecord = new GitLabChatRecord({ role: 'assistant', state: 'pending', requestId: record.requestId, }); await this.#addToChat(responseRecord); try { await this.#api.subscribeToUpdates(this.#subscriptionUpdateHandler.bind(this), record.id); } catch (err) { // TODO: log error } // Fallback if websocket fails or disabled. await Promise.all([this.#refreshRecord(record), this.#refreshRecord(responseRecord)]); } async #subscriptionUpdateHandler(data: AiCompletionResponseMessageType) { const record = this.#findRecord(data); if (!record) return; record.update({ chunkId: data.chunkId, content: data.content, contentHtml: data.contentHtml, extras: data.extras, timestamp: data.timestamp, errors: data.errors, }); record.state = 'ready'; this.#webviewMessageBus.sendNotification('updateRecord', record); } // async #restoreHistory() { // this.chatHistory.forEach((record) => { // this.#webviewMessageBus.sendNotification('newRecord', record); // }, this); // } async #addToChat(record: GitLabChatRecord) { this.chatHistory.push(record); this.#webviewMessageBus.sendNotification('newRecord', record); } async #sendNewPrompt(record: GitLabChatRecord) { if (!record.content) throw new Error('Trying to send prompt without content.'); try { const actionResponse = await this.#api.processNewUserPrompt( record.content, record.id, record.context?.currentFile, ); record.update(actionResponse.aiAction); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-explicit-any record.update({ errors: [`API error: ${(err as any).response.errors[0].message}`] }); } } async #refreshRecord(record: GitLabChatRecord) { if (!record.requestId) { throw Error('requestId must be present!'); } const apiResponse = await this.#api.pullAiMessage(record.requestId, record.role); if (apiResponse.type !== 'error') { record.update({ content: apiResponse.content, contentHtml: apiResponse.contentHtml, extras: apiResponse.extras, timestamp: apiResponse.timestamp, }); } record.update({ errors: apiResponse.errors, state: 'ready' }); this.#webviewMessageBus.sendNotification('updateRecord', record); } #findRecord(data: { requestId: string; role: string }) { return this.chatHistory.find( (r) => r.requestId === data.requestId && r.role.toLowerCase() === data.role.toLowerCase(), ); } } References: - packages/webview_duo_chat/src/plugin/index.ts:22
You are a code assistant
Definition of 'clientToMiddleware' in file src/common/suggestion_client/client_to_middleware.ts in project gitlab-lsp
Definition: export const clientToMiddleware = (client: SuggestionClient): SuggestionClientMiddleware => (context) => client.getSuggestions(context); References: - src/common/suggestion/suggestion_service.ts:166
You are a code assistant
Definition of 'hello' in file src/tests/fixtures/intent/javascript_comments.js in project gitlab-lsp
Definition: function hello(user) { // function to greet the user } References:
You are a code assistant
Definition of 'createLoggerTransport' in file src/node/http/utils/create_logger_transport.ts in project gitlab-lsp
Definition: export const createLoggerTransport = (logger: ILog, level: keyof ILog = 'debug') => new Writable({ objectMode: true, write(chunk, _encoding, callback) { logger[level](chunk.toString()); callback(); }, }); References: - src/node/http/create_fastify_http_server.ts:90 - src/node/http/utils/create_logger_transport.test.ts:31 - src/node/http/utils/create_logger_transport.test.ts:18
You are a code assistant
Definition of 'pullHandler' in file packages/webview_duo_chat/src/plugin/port/chat/api/pulling.ts in project gitlab-lsp
Definition: export const pullHandler = async <T>( handler: () => Promise<T | undefined>, retry = API_PULLING.maxRetries, ): Promise<T | undefined> => { if (retry <= 0) { log.debug('Pull handler: no retries left, exiting without return value.'); return undefined; } log.debug(`Pull handler: pulling, ${retry - 1} retries left.`); const response = await handler(); if (response) return response; await waitForMs(API_PULLING.interval); return pullHandler(handler, retry - 1); }; References: - packages/webview_duo_chat/src/plugin/port/chat/api/pulling.ts:24 - packages/webview_duo_chat/src/plugin/port/chat/api/pulling.test.ts:27 - packages/webview_duo_chat/src/plugin/port/chat/api/pulling.test.ts:20 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:169
You are a code assistant
Definition of 'sendRequest' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'LsAgentOptions' in file src/node/fetch.ts in project gitlab-lsp
Definition: interface LsAgentOptions { rejectUnauthorized: boolean; ca?: Buffer; cert?: Buffer; key?: Buffer; } /** * Wrap fetch to support proxy configurations */ @Injectable(LsFetch, []) export class Fetch extends FetchBase implements LsFetch { #proxy?: ProxyAgent; #userProxy?: string; #initialized: boolean = false; #httpsAgent: https.Agent; #agentOptions: Readonly<LsAgentOptions>; constructor(userProxy?: string) { super(); this.#agentOptions = { rejectUnauthorized: true, }; this.#userProxy = userProxy; this.#httpsAgent = this.#createHttpsAgent(); } async initialize(): Promise<void> { // Set http_proxy and https_proxy environment variables // which will then get picked up by the ProxyAgent and // used. try { const proxy = await getProxySettings(); if (proxy?.http) { process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`; log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`); } if (proxy?.https) { process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`; log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`); } if (!proxy?.http && !proxy?.https) { log.debug(`fetch: Detected no proxy settings`); } } catch (err) { log.warn('Unable to load proxy settings', err); } if (this.#userProxy) { log.debug(`fetch: Detected user proxy ${this.#userProxy}`); process.env.http_proxy = this.#userProxy; process.env.https_proxy = this.#userProxy; } if (process.env.http_proxy || process.env.https_proxy) { log.info( `fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`, ); this.#proxy = this.#createProxyAgent(); } this.#initialized = true; } async destroy(): Promise<void> { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { if (!this.#initialized) { throw new Error('LsFetch not initialized. Make sure LsFetch.initialize() was called.'); } try { return await this.#fetchLogged(input, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MILLISECONDS), ...init, agent: this.#getAgent(input), }); } catch (e) { if (hasName(e) && e.name === 'AbortError') { throw new TimeoutError(input); } throw e; } } updateAgentOptions({ ignoreCertificateErrors, ca, cert, certKey }: FetchAgentOptions): void { let fileOptions = {}; try { fileOptions = { ...(ca ? { ca: fs.readFileSync(ca) } : {}), ...(cert ? { cert: fs.readFileSync(cert) } : {}), ...(certKey ? { key: fs.readFileSync(certKey) } : {}), }; } catch (err) { log.error('Error reading https agent options from file', err); } const newOptions: LsAgentOptions = { rejectUnauthorized: !ignoreCertificateErrors, ...fileOptions, }; if (isEqual(newOptions, this.#agentOptions)) { // new and old options are the same, nothing to do return; } this.#agentOptions = newOptions; this.#httpsAgent = this.#createHttpsAgent(); if (this.#proxy) { this.#proxy = this.#createProxyAgent(); } } async *streamFetch( url: string, body: string, headers: FetchHeaders, ): AsyncGenerator<string, void, void> { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream<Uint8Array>, ): AsyncGenerator<string, void, void> { for await (const chunk of stream) { buffer += decoder.decode(chunk); yield buffer; } } const response: Response = await this.fetch(url, { method: 'POST', headers, body, }); await handleFetchError(response, 'Code Suggestions Streaming'); if (response.body) { // Note: Using (node:stream).ReadableStream as it supports async iterators yield* readStream(response.body as ReadableStream); } } #createHttpsAgent(): https.Agent { const agentOptions = { ...this.#agentOptions, keepAlive: true, }; log.debug( `fetch: https agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(agentOptions), )}.`, ); return new https.Agent(agentOptions); } #createProxyAgent(): ProxyAgent { log.debug( `fetch: proxy agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(this.#agentOptions), )}.`, ); return new ProxyAgent(this.#agentOptions); } async #fetchLogged(input: RequestInfo | URL, init: LsRequestInit): Promise<Response> { const start = Date.now(); const url = this.#extractURL(input); if (init.agent === httpAgent) { log.debug(`fetch: request for ${url} made with http agent.`); } else { const type = init.agent === this.#proxy ? 'proxy' : 'https'; log.debug(`fetch: request for ${url} made with ${type} agent.`); } try { const resp = await fetch(input, init); const duration = Date.now() - start; log.debug(`fetch: request to ${url} returned HTTP ${resp.status} after ${duration} ms`); return resp; } catch (e) { const duration = Date.now() - start; log.debug(`fetch: request to ${url} threw an exception after ${duration} ms`); log.error(`fetch: request to ${url} failed with:`, e); throw e; } } #getAgent(input: RequestInfo | URL): ProxyAgent | https.Agent | http.Agent { if (this.#proxy) { return this.#proxy; } if (input.toString().startsWith('https://')) { return this.#httpsAgent; } return httpAgent; } #extractURL(input: RequestInfo | URL): string { if (input instanceof URL) { return input.toString(); } if (typeof input === 'string') { return input; } return input.url; } #sanitizeAgentOptions(agentOptions: LsAgentOptions) { const { ca, cert, key, ...options } = agentOptions; return { ...options, ...(ca ? { ca: '<hidden>' } : {}), ...(cert ? { cert: '<hidden>' } : {}), ...(key ? { key: '<hidden>' } : {}), }; } } References: - src/node/fetch.ts:251 - src/node/fetch.ts:132
You are a code assistant
Definition of 'WebviewTransportEventEmitterMessages' in file packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp
Definition: export type WebviewTransportEventEmitterMessages = { [K in keyof MessagesToServer]: (payload: MessagesToServer[K]) => void; }; export type WebviewTransportEventEmitter = TypedEmitter<WebviewTransportEventEmitterMessages>; export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References:
You are a code assistant
Definition of 'WebviewTransportEventEmitter' in file packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp
Definition: export type WebviewTransportEventEmitter = TypedEmitter<WebviewTransportEventEmitterMessages>; export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References: - packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts:11 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:35 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:27 - packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts:11 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:43
You are a code assistant
Definition of 'ACircular' in file packages/lib_di/src/index.test.ts in project gitlab-lsp
Definition: class ACircular implements A { a = () => 'hello'; constructor(c: C) { // eslint-disable-next-line no-unused-expressions c; } } expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow( /Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./, ); }); // this test ensures that we don't store any references to the classes and we instantiate them only once it('does not instantiate classes from previous instantiate call', () => { let globCount = 0; @Injectable(A, []) class Counter implements A { counter = globCount; constructor() { globCount++; } a = () => this.counter.toString(); } container.instantiate(Counter); container.instantiate(BImpl); expect(container.get(A).a()).toBe('0'); }); }); describe('get', () => { it('returns an instance of the interfaceId', () => { container.instantiate(AImpl); expect(container.get(A)).toBeInstanceOf(AImpl); }); it('throws an error for missing dependency', () => { container.instantiate(); expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/); }); }); }); References:
You are a code assistant
Definition of 'GitLabPlatformBase' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp
Definition: export interface GitLabPlatformBase { fetchFromApi: fetchFromApi; connectToCable: () => Promise<ActionCableCable>; account: Account; /** * What user agent should be used for API calls that are not made to GitLab API * (e.g. when calling Model Gateway for code suggestions) */ getUserAgentHeader(): Record<string, string>; } export interface GitLabPlatformForAccount extends GitLabPlatformBase { type: 'account'; project: undefined; } export interface GitLabPlatformForProject extends GitLabPlatformBase { type: 'project'; project: GitLabProject; } export type GitLabPlatform = GitLabPlatformForProject | GitLabPlatformForAccount; export interface GitLabPlatformManager { /** * Returns GitLabPlatform for the active project * * This is how we decide what is "active project": * - if there is only one Git repository opened, we always return GitLab project associated with that repository * - if there are multiple Git repositories opened, we return the one associated with the active editor * - if there isn't active editor, we will return undefined if `userInitiated` is false, or we ask user to select one if user initiated is `true` * * @param userInitiated - Indicates whether the user initiated the action. * @returns A Promise that resolves with the fetched GitLabProject or undefined if an active project does not exist. */ getForActiveProject(userInitiated: boolean): Promise<GitLabPlatformForProject | undefined>; /** * Returns a GitLabPlatform for the active account * * This is how we decide what is "active account": * - If the user has signed in to a single GitLab account, it will return that account. * - If the user has signed in to multiple GitLab accounts, a UI picker will request the user to choose the desired account. */ getForActiveAccount(): Promise<GitLabPlatformForAccount | undefined>; /** * onAccountChange indicates that any of the GitLab accounts in the extension has changed. * This can mean account was removed, added or the account token has been changed. */ // onAccountChange: vscode.Event<void>; getForAllAccounts(): Promise<GitLabPlatformForAccount[]>; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined>; } References:
You are a code assistant
Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } 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 'REQUEST_TIMEOUT_MS' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: export const REQUEST_TIMEOUT_MS = 10000; export const SOCKET_NOTIFICATION_CHANNEL = 'notification'; export const SOCKET_REQUEST_CHANNEL = 'request'; export const SOCKET_RESPONSE_CHANNEL = 'response'; export type SocketEvents = | typeof SOCKET_NOTIFICATION_CHANNEL | typeof SOCKET_REQUEST_CHANNEL | typeof SOCKET_RESPONSE_CHANNEL; export class SocketIoMessageBus<TMessages extends MessageMap> implements MessageBus<TMessages> { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification<T extends keyof TMessages['outbound']['notifications']>( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise<void> { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest<T extends keyof TMessages['outbound']['requests'] & string>( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise<ExtractRequestResult<TMessages['outbound']['requests'][T]>> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult<TMessages['outbound']['requests'][T]>) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification<T extends keyof TMessages['inbound']['notifications'] & string>( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest<T extends keyof TMessages['inbound']['requests'] & string>( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise<ExtractRequestResult<TMessages['inbound']['requests'][T]>>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:
You are a code assistant
Definition of 'FailedResponse' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler<T> { (payload: T): void; } export interface TransportListener { on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable; } export interface TransportPublisher { publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void>; } export interface Transport extends TransportListener, TransportPublisher {} References:
You are a code assistant
Definition of 'IDocTransformer' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'constructor' in file packages/lib-pkg-2/src/fast_fibonacci_solver.ts in project gitlab-lsp
Definition: constructor() { this.#memo.set(0, 0); this.#memo.set(1, 1); } solve(index: number): number { if (index < 0) { throw NegativeIndexError; } if (this.#memo.has(index)) { return this.#memo.get(index) as number; } let a = this.#memo.get(this.#lastComputedIndex - 1) as number; let b = this.#memo.get(this.#lastComputedIndex) as number; for (let i = this.#lastComputedIndex + 1; i <= index; i++) { const nextValue = a + b; a = b; b = nextValue; this.#memo.set(i, nextValue); } this.#lastComputedIndex = index; return this.#memo.get(index) as number; } } References:
You are a code assistant
Definition of 'AiCompletionResponseMessageType' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp
Definition: export type AiCompletionResponseMessageType = { requestId: string; role: string; content: string; contentHtml?: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; chunkId?: number; type?: string; }; type AiCompletionResponseResponseType = { result: { data: { aiCompletionResponse: AiCompletionResponseMessageType; }; }; more: boolean; }; interface AiCompletionResponseChannelEvents extends ChannelEvents<AiCompletionResponseResponseType> { systemMessage: (msg: AiCompletionResponseMessageType) => void; newChunk: (msg: AiCompletionResponseMessageType) => void; fullMessage: (msg: AiCompletionResponseMessageType) => void; } export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; 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: - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:72 - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:71 - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:73 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:200 - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:63 - packages/webview_duo_chat/src/plugin/chat_controller.ts:82
You are a code assistant
Definition of 'connectToCable' in file src/common/action_cable.ts in project gitlab-lsp
Definition: export const connectToCable = async (instanceUrl: string, websocketOptions?: object) => { const cableUrl = new URL('/-/cable', instanceUrl); cableUrl.protocol = cableUrl.protocol === 'http:' ? 'ws:' : 'wss:'; const cable = createCable(cableUrl.href, { websocketImplementation: WebSocket, websocketOptions, }); await cable.connect(); return cable; }; References: - 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 - src/common/action_cable.test.ts:21
You are a code assistant
Definition of 'extractUserId' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp
Definition: export const extractUserId = (accountId: string) => accountId.split('|').pop(); References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:207
You are a code assistant
Definition of 'getSuggestions' in file src/common/suggestion_client/fallback_client.ts in project gitlab-lsp
Definition: async getSuggestions(context: SuggestionContext) { for (const client of this.#clients) { // eslint-disable-next-line no-await-in-loop const result = await client.getSuggestions(context); if (result) { // TODO create a follow up issue to consider scenario when the result is defined, but it contains an error field return result; } } return undefined; } } References:
You are a code assistant
Definition of 'setupFileWatcher' in file src/node/services/fs/dir.ts in project gitlab-lsp
Definition: setupFileWatcher(workspaceFolder: WorkspaceFolder, fileChangeHandler: FileChangeHandler): void { const fsPath = fsPathFromUri(workspaceFolder.uri); const watcher = chokidar.watch(fsPath, { persistent: true, alwaysStat: false, ignoreInitial: true, }); watcher .on('add', (path) => fileChangeHandler('add', workspaceFolder, path)) .on('change', (path) => fileChangeHandler('change', workspaceFolder, path)) .on('unlink', (path) => fileChangeHandler('unlink', workspaceFolder, path)); this.#watchers.set(workspaceFolder.uri, watcher); } async dispose(): Promise<void> { const promises = Array.from(this.#watchers.values()).map((watcher) => watcher.close()); await Promise.all(promises); this.#watchers.clear(); } } References:
You are a code assistant
Definition of 'DUO_WORKFLOW_WEBVIEW_ID' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp
Definition: export const DUO_WORKFLOW_WEBVIEW_ID = 'duo-workflow'; export const DUO_CHAT_WEBVIEW_ID = 'chat'; References:
You are a code assistant
Definition of 'AiContextItemInfo' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp
Definition: export type AiContextItemInfo = { project?: string; disabledReasons?: string[]; iid?: number; relFilePath?: string; }; export type AiContextItemType = 'issue' | 'merge_request' | 'file'; export type AiContextItemSubType = 'open_tab' | 'local_file_search'; export type AiContextItem = { id: string; name: string; isEnabled: boolean; info: AiContextItemInfo; type: AiContextItemType; } & ( | { type: 'issue' | 'merge_request'; subType?: never } | { type: 'file'; subType: AiContextItemSubType } ); export type AiContextItemWithContent = AiContextItem & { content: string; }; References: - src/common/ai_context_management_2/ai_context_item.ts:16
You are a code assistant
Definition of 'dispose' in file src/common/git/repository.ts in project gitlab-lsp
Definition: dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:
You are a code assistant
Definition of 'LsTextDocuments' in file src/common/external_interfaces.ts in project gitlab-lsp
Definition: export type LsTextDocuments = TextDocuments<TextDocument>; export const LsTextDocuments = createInterfaceId<LsTextDocuments>('LsTextDocuments'); References: - src/common/document_transformer_service.ts:79 - src/common/document_transformer_service.ts:81
You are a code assistant
Definition of 'getMessageBus' in file packages/lib_webview/src/types.ts in project gitlab-lsp
Definition: getMessageBus<T extends MessageMap>(webviewId: WebviewId): MessageBus<T>; } References:
You are a code assistant
Definition of 'isOpen' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp
Definition: isOpen() { return this.#state === CircuitBreakerState.OPEN; } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } 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) }; } } References:
You are a code assistant
Definition of 'greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp
Definition: 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:8
You are a code assistant
Definition of 'AiContextManager' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp
Definition: export interface AiContextManager extends DefaultAiContextManager {} export const AiContextManager = createInterfaceId<AiContextManager>('AiContextManager'); @Injectable(AiContextManager, [AiContextFileRetriever]) export class DefaultAiContextManager { #fileRetriever: AiContextFileRetriever; constructor(fileRetriever: AiContextFileRetriever) { this.#fileRetriever = fileRetriever; } #items: Map<string, AiContextItem> = new Map(); addItem(item: AiContextItem): boolean { if (this.#items.has(item.id)) { return false; } this.#items.set(item.id, item); return true; } removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise<AiContextItemWithContent[]> { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References: - src/common/connection_service.ts:57 - src/common/connection_service.ts:67
You are a code assistant
Definition of 'IDirectConnectionModelDetails' in file src/common/api.ts in project gitlab-lsp
Definition: 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_client/create_v2_request.ts:6 - src/common/api.ts:114
You are a code assistant
Definition of 'DefaultRepositoryService' in file src/common/git/repository_service.ts in project gitlab-lsp
Definition: export class DefaultRepositoryService { #virtualFileSystemService: DefaultVirtualFileSystemService; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map<WorkspaceFolderUri, RepositoryMap> = new Map(); #workspaceRepositoryTries: Map<WorkspaceFolderUri, RepositoryTrie> = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References: - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:23 - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:21
You are a code assistant
Definition of 'start' in file src/common/test_utils/create_fake_response.ts in project gitlab-lsp
Definition: start(controller) { // Add text (as Uint8Array) to the stream controller.enqueue(new TextEncoder().encode(text)); }, }), }); }; References:
You are a code assistant
Definition of 'isStream' in file src/common/utils/suggestion_mappers.ts in project gitlab-lsp
Definition: export const isStream = (o: SuggestionOptionOrStream): o is StartStreamOption => Boolean((o as StartStreamOption).streamId); export const isTextSuggestion = (o: SuggestionOptionOrStream): o is SuggestionOption => Boolean((o as SuggestionOption).text); export const completionOptionMapper = (options: SuggestionOption[]): CompletionItem[] => options.map((option, index) => ({ label: `GitLab Suggestion ${index + 1}: ${option.text}`, kind: CompletionItemKind.Text, insertText: option.text, detail: option.text, command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId], }, data: { index, trackingId: option.uniqueTrackingId, }, })); /* this value will be used for telemetry so to make it human-readable we use the 1-based indexing instead of 0 */ const getOptionTrackingIndex = (option: SuggestionOption) => { return typeof option.index === 'number' ? option.index + 1 : undefined; }; export const inlineCompletionOptionMapper = ( params: InlineCompletionParams, options: SuggestionOptionOrStream[], ): InlineCompletionList => ({ items: options.map((option) => { if (isStream(option)) { // the streaming item is empty and only indicates to the client that streaming started return { insertText: '', command: { title: 'Start streaming', command: START_STREAMING_COMMAND, arguments: [option.streamId, option.uniqueTrackingId], }, }; } const completionInfo = params.context.selectedCompletionInfo; let rangeDiff = 0; if (completionInfo) { const range = sanitizeRange(completionInfo.range); rangeDiff = range.end.character - range.start.character; } return { insertText: completionInfo ? `${completionInfo.text.substring(rangeDiff)}${option.text}` : option.text, range: Range.create(params.position, params.position), command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId, getOptionTrackingIndex(option)], }, }; }), }); References: - src/common/utils/suggestion_mappers.ts:46
You are a code assistant
Definition of 'ContextItem' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp
Definition: interface ContextItem { file_extension: string; type: AdditionalContext['type']; resolution_strategy: ContextResolution['strategy']; byte_size: number; } export interface ISnowplowCodeSuggestionContext { schema: string; data: { prefix_length?: number; suffix_length?: number; language?: string | null; gitlab_realm?: GitlabRealm; model_engine?: string | null; model_name?: string | null; api_status_code?: number | null; debounce_interval?: number | null; suggestion_source?: SuggestionSource; gitlab_global_user_id?: string | null; gitlab_instance_id?: string | null; gitlab_host_name?: string | null; gitlab_saas_duo_pro_namespace_ids: number[] | null; gitlab_instance_version: string | null; is_streaming?: boolean; is_invoked?: boolean | null; options_count?: number | null; accepted_option?: number | null; /** * boolean indicating whether the feature is enabled * and we sent context in the request */ has_advanced_context?: boolean | null; /** * boolean indicating whether request is direct to cloud connector */ is_direct_connection?: boolean | null; total_context_size_bytes?: number; content_above_cursor_size_bytes?: number; content_below_cursor_size_bytes?: number; /** * set of final context items sent to AI Gateway */ context_items?: ContextItem[] | null; /** * total tokens used in request to model provider */ input_tokens?: number | null; /** * total output tokens recieved from model provider */ output_tokens?: number | null; /** * total tokens sent as context to AI Gateway */ context_tokens_sent?: number | null; /** * total context tokens used in request to model provider */ context_tokens_used?: number | null; }; } interface ISnowplowClientContext { schema: string; data: { ide_name?: string | null; ide_vendor?: string | null; ide_version?: string | null; extension_name?: string | null; extension_version?: string | null; language_server_version?: string | null; }; } const DEFAULT_SNOWPLOW_OPTIONS = { appId: 'gitlab_ide_extension', timeInterval: 5000, maxItems: 10, }; export const EVENT_VALIDATION_ERROR_MSG = `Telemetry event context is not valid - event won't be tracked.`; export class SnowplowTracker implements TelemetryTracker { #snowplow: Snowplow; #ajv = new Ajv({ strict: false }); #configService: ConfigService; #api: GitLabApiClient; #options: ITelemetryOptions = { enabled: true, baseUrl: SAAS_INSTANCE_URL, trackingUrl: DEFAULT_TRACKING_ENDPOINT, // the list of events that the client can track themselves actions: [], }; #clientContext: ISnowplowClientContext = { schema: 'iglu:com.gitlab/ide_extension_version/jsonschema/1-1-0', data: {}, }; #codeSuggestionStates = new Map<string, TRACKING_EVENTS>(); #lsFetch: LsFetch; #featureFlagService: FeatureFlagService; #gitlabRealm: GitlabRealm = GitlabRealm.saas; #codeSuggestionsContextMap = new Map<string, ISnowplowCodeSuggestionContext>(); constructor( lsFetch: LsFetch, configService: ConfigService, featureFlagService: FeatureFlagService, api: GitLabApiClient, ) { this.#configService = configService; this.#configService.onConfigChange((config) => this.#reconfigure(config)); this.#api = api; const trackingUrl = DEFAULT_TRACKING_ENDPOINT; this.#lsFetch = lsFetch; this.#configService = configService; this.#featureFlagService = featureFlagService; this.#snowplow = Snowplow.getInstance(this.#lsFetch, { ...DEFAULT_SNOWPLOW_OPTIONS, endpoint: trackingUrl, enabled: this.isEnabled.bind(this), }); this.#options.trackingUrl = trackingUrl; this.#ajv.addMetaSchema(SnowplowMetaSchema); } isEnabled(): boolean { return Boolean(this.#options.enabled); } async #reconfigure(config: IConfig) { const { baseUrl } = config.client; const trackingUrl = config.client.telemetry?.trackingUrl; const enabled = config.client.telemetry?.enabled; const actions = config.client.telemetry?.actions; if (typeof enabled !== 'undefined') { this.#options.enabled = enabled; if (enabled === false) { log.warn(`Snowplow Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`); } else if (enabled === true) { log.info(`Snowplow Telemetry: ${TELEMETRY_ENABLED_MSG}`); } } if (baseUrl) { this.#options.baseUrl = baseUrl; this.#gitlabRealm = baseUrl.endsWith(SAAS_INSTANCE_URL) ? GitlabRealm.saas : GitlabRealm.selfManaged; } if (trackingUrl && this.#options.trackingUrl !== trackingUrl) { await this.#snowplow.stop(); this.#snowplow.destroy(); this.#snowplow = Snowplow.getInstance(this.#lsFetch, { ...DEFAULT_SNOWPLOW_OPTIONS, endpoint: trackingUrl, enabled: this.isEnabled.bind(this), }); } if (actions) { this.#options.actions = actions; } this.#setClientContext({ extension: config.client.telemetry?.extension, ide: config.client.telemetry?.ide, }); } #setClientContext(context: IClientContext) { this.#clientContext.data = { ide_name: context?.ide?.name ?? null, ide_vendor: context?.ide?.vendor ?? null, ide_version: context?.ide?.version ?? null, extension_name: context?.extension?.name ?? null, extension_version: context?.extension?.version ?? null, language_server_version: lsVersion ?? null, }; } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ) { const { documentContext, source = SuggestionSource.network, language, isStreaming, triggerKind, optionsCount, additionalContexts, isDirectConnection, } = context; const { gitlab_instance_id, gitlab_global_user_id, gitlab_host_name, gitlab_saas_duo_pro_namespace_ids, } = this.#configService.get('client.snowplowTrackerOptions') ?? {}; if (source === SuggestionSource.cache) { log.debug(`Snowplow Telemetry: Retrieved suggestion from cache`); } else { log.debug(`Snowplow Telemetry: Received request to create a new suggestion`); } // Only auto-reject if client is set up to track accepted and not rejected events. if ( canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) && !canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED) ) { this.rejectOpenedSuggestions(); } setTimeout(() => { if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) { this.#codeSuggestionsContextMap.delete(uniqueTrackingId); this.#codeSuggestionStates.delete(uniqueTrackingId); } }, GC_TIME); const advancedContextData = this.#getAdvancedContextData({ additionalContexts, documentContext, }); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { schema: 'iglu:com.gitlab/code_suggestions_context/jsonschema/3-5-0', data: { suffix_length: documentContext?.suffix.length ?? 0, prefix_length: documentContext?.prefix.length ?? 0, gitlab_realm: this.#gitlabRealm, model_engine: null, model_name: null, language: language ?? null, api_status_code: null, debounce_interval: source === SuggestionSource.cache ? 0 : SUGGESTIONS_DEBOUNCE_INTERVAL_MS, suggestion_source: source, gitlab_global_user_id: gitlab_global_user_id ?? null, gitlab_host_name: gitlab_host_name ?? null, gitlab_instance_id: gitlab_instance_id ?? null, gitlab_saas_duo_pro_namespace_ids: gitlab_saas_duo_pro_namespace_ids ?? null, gitlab_instance_version: this.#api.instanceVersion ?? null, is_streaming: isStreaming ?? false, is_invoked: SnowplowTracker.#isCompletionInvoked(triggerKind), options_count: optionsCount ?? null, has_advanced_context: advancedContextData.hasAdvancedContext, is_direct_connection: isDirectConnection ?? null, total_context_size_bytes: advancedContextData.totalContextSizeBytes, content_above_cursor_size_bytes: advancedContextData.contentAboveCursorSizeBytes, content_below_cursor_size_bytes: advancedContextData.contentBelowCursorSizeBytes, context_items: advancedContextData.contextItems, }, }); this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Snowplow Telemetry: Could not track telemetry', e), ); log.debug(`Snowplow Telemetry: New suggestion ${uniqueTrackingId} has been requested`); } // FIXME: the set and update context methods have similar logic and they should have to grow linearly with each new attribute // the solution might be some generic update method used by both public updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ) { const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate; if (context) { if (model) { context.data.language = model.lang ?? null; context.data.model_engine = model.engine ?? null; context.data.model_name = model.name ?? null; context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null; context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null; context.data.context_tokens_sent = model.tokens_consumption_metadata?.context_tokens_sent ?? null; context.data.context_tokens_used = model.tokens_consumption_metadata?.context_tokens_used ?? null; } if (status) { context.data.api_status_code = status; } if (optionsCount) { context.data.options_count = optionsCount; } if (isDirectConnection !== undefined) { context.data.is_direct_connection = isDirectConnection; } if (acceptedOption) { context.data.accepted_option = acceptedOption; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { if (!this.isEnabled()) { return; } const event: StructuredEvent = { category: CODE_SUGGESTIONS_CATEGORY, action: eventType, label: uniqueTrackingId, }; try { const contexts: SelfDescribingJson[] = [this.#clientContext]; const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId); if (codeSuggestionContext) { contexts.push(codeSuggestionContext); } const suggestionContextValid = this.#ajv.validate( CodeSuggestionContextSchema, codeSuggestionContext?.data, ); if (!suggestionContextValid) { log.warn(EVENT_VALIDATION_ERROR_MSG); log.debug(JSON.stringify(this.#ajv.errors, null, 2)); return; } const ideExtensionContextValid = this.#ajv.validate( IdeExtensionContextSchema, this.#clientContext?.data, ); if (!ideExtensionContextValid) { log.warn(EVENT_VALIDATION_ERROR_MSG); log.debug(JSON.stringify(this.#ajv.errors, null, 2)); return; } await this.#snowplow.trackStructEvent(event, contexts); } catch (error) { log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error); } } public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const isStreaming = Boolean( this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming, ); const allowedTransitions = isStreaming ? streamingSuggestionStateGraph.get(state) : nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `Snowplow Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`, ); // Allow state to update to ACCEPTED despite 'allowed transitions' constraint. if (newState !== TRACKING_EVENTS.ACCEPTED) { return; } log.debug( `Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Snowplow Telemetry: Could not track telemetry', e), ); log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } rejectOpenedSuggestions() { log.debug(`Snowplow Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } #hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null { const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextFeatureFlagsEnabled) { return Boolean(advancedContexts?.length); } return null; } #getAdvancedContextData({ additionalContexts, documentContext, }: { additionalContexts?: AdditionalContext[]; documentContext?: IDocContext; }) { const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts); const contentAboveCursorSizeBytes = documentContext?.prefix ? getByteSize(documentContext.prefix) : 0; const contentBelowCursorSizeBytes = documentContext?.suffix ? getByteSize(documentContext.suffix) : 0; const contextItems: ContextItem[] | null = additionalContexts?.map((item) => ({ file_extension: item.name.split('.').pop() || '', type: item.type, resolution_strategy: item.resolution_strategy, byte_size: item?.content ? getByteSize(item.content) : 0, })) ?? null; const totalContextSizeBytes = contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0; return { totalContextSizeBytes, contentAboveCursorSizeBytes, contentBelowCursorSizeBytes, contextItems, hasAdvancedContext, }; } static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null { let isInvoked = null; if (triggerKind === InlineCompletionTriggerKind.Invoked) { isInvoked = true; } else if (triggerKind === InlineCompletionTriggerKind.Automatic) { isInvoked = false; } return isInvoked; } } References:
You are a code assistant
Definition of 'engaged' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'hasbin' in file src/tests/int/hasbin.ts in project gitlab-lsp
Definition: export function hasbin(bin: string, done: (result: boolean) => void) { async.some(getPaths(bin), fileExists, done); } export function hasbinSync(bin: string) { return getPaths(bin).some(fileExistsSync); } export function hasbinAll(bins: string[], done: (result: boolean) => void) { async.every(bins, hasbin.async, done); } export function hasbinAllSync(bins: string[]) { return bins.every(hasbin.sync); } export function hasbinSome(bins: string[], done: (result: boolean) => void) { async.some(bins, hasbin.async, done); } export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/["]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } export function fileExists(filePath: string, done: (result: boolean) => void) { stat(filePath, function (error, stat) { if (error) { return done(false); } done(stat.isFile()); }); } export function fileExistsSync(filePath: string) { try { return statSync(filePath).isFile(); } catch (error) { return false; } } References:
You are a code assistant
Definition of 'VirtualFileSystemEvents' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp
Definition: export enum VirtualFileSystemEvents { WorkspaceFileUpdate = 'workspaceFileUpdate', WorkspaceFilesUpdate = 'workspaceFilesUpdate', } const FILE_SYSTEM_EVENT_NAME = 'fileSystemEvent'; export interface FileSystemEventMap { [VirtualFileSystemEvents.WorkspaceFileUpdate]: WorkspaceFileUpdate; [VirtualFileSystemEvents.WorkspaceFilesUpdate]: WorkspaceFilesUpdate; } export interface FileSystemEventListener { <T extends VirtualFileSystemEvents>(eventType: T, data: FileSystemEventMap[T]): void; } export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype; export const VirtualFileSystemService = createInterfaceId<VirtualFileSystemService>( 'VirtualFileSystemService', ); @Injectable(VirtualFileSystemService, [DirectoryWalker]) export class DefaultVirtualFileSystemService { #directoryWalker: DirectoryWalker; #emitter = new EventEmitter(); constructor(directoryWalker: DirectoryWalker) { this.#directoryWalker = directoryWalker; } #handleFileChange: FileChangeHandler = (event, workspaceFolder, filePath) => { const fileUri = fsPathToUri(filePath); this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFileUpdate, { event, fileUri, workspaceFolder, }); }; async initialize(workspaceFolders: WorkspaceFolder[]): Promise<void> { await Promise.all( workspaceFolders.map(async (workspaceFolder) => { const files = await this.#directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, }); this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFilesUpdate, { files, workspaceFolder, }); this.#directoryWalker.setupFileWatcher(workspaceFolder, this.#handleFileChange); }), ); } #emitFileSystemEvent<T extends VirtualFileSystemEvents>( eventType: T, data: FileSystemEventMap[T], ) { this.#emitter.emit(FILE_SYSTEM_EVENT_NAME, eventType, data); } onFileSystemEvent(listener: FileSystemEventListener) { this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener), }; } } References:
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: ... 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 'CommentResolution' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp
Definition: export type CommentResolution = | { commentAtCursor: Comment; commentAboveCursor?: never } | { commentAtCursor?: never; commentAboveCursor: Comment }; export class CommentResolver { protected queryByLanguage: Map<string, Query>; constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = commentQueries[language]; if (!queryString) { log.warn(`No comment query found for language: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is on or directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ getCommentForCursor({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): CommentResolution | undefined { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return undefined; } const comments = query.captures(tree.rootNode).map((capture) => { return { start: capture.node.startPosition, end: capture.node.endPosition, content: capture.node.text, capture, }; }); const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition); if (commentAtCursor) { // No need to further check for isPositionInNode etc. as cursor is directly on the comment return { commentAtCursor }; } const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition); if (!commentAboveCursor) { return undefined; } const commentParentNode = commentAboveCursor.capture.node.parent; if (!commentParentNode) { return undefined; } if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) { return undefined; } const directChildren = commentParentNode.children; for (const child of directChildren) { const hasNodeBetweenCursorAndComment = child.startPosition.row > commentAboveCursor.capture.node.endPosition.row && child.startPosition.row <= cursorPosition.row; if (hasNodeBetweenCursorAndComment) { return undefined; } } return { commentAboveCursor }; } static #isPositionInNode(position: Point, node: SyntaxNode): boolean { return position.row >= node.startPosition.row && position.row <= node.endPosition.row; } static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter((comment) => comment.end.row < cursorPosition.row), ); } static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter( (comment) => comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row, ), ); } static #getLastComment(comments: Comment[]): Comment | undefined { return comments.sort((a, b) => b.end.row - a.end.row)[0]; } /** * Returns the total number of lines that are comments in a parsed syntax tree. * Uses a Set because we only want to count each line once. * @param {Object} params - Parameters for counting comment lines. * @param {TreeSitterLanguageName} params.languageName - The name of the programming language. * @param {Tree} params.tree - The syntax tree to analyze. * @param {Language} params.treeSitterLanguage - The Tree-sitter language instance. * @returns {number} - The total number of unique lines containing comments. */ getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set<number>(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:
You are a code assistant
Definition of 'hasbinSome' in file src/tests/int/hasbin.ts in project gitlab-lsp
Definition: export function hasbinSome(bins: string[], done: (result: boolean) => void) { async.some(bins, hasbin.async, done); } export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/["]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } export function fileExists(filePath: string, done: (result: boolean) => void) { stat(filePath, function (error, stat) { if (error) { return done(false); } done(stat.isFile()); }); } export function fileExistsSync(filePath: string) { try { return statSync(filePath).isFile(); } catch (error) { return false; } } References:
You are a code assistant
Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } 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 'GET_WEBVIEW_METADATA_REQUEST' in file src/common/connection.ts in project gitlab-lsp
Definition: export const GET_WEBVIEW_METADATA_REQUEST = '$/gitlab/webview-metadata'; export function setup( telemetryTracker: TelemetryTracker, connection: Connection, documentTransformerService: DocumentTransformerService, apiClient: GitLabApiClient, featureFlagService: FeatureFlagService, configService: ConfigService, { treeSitterParser, }: { treeSitterParser: TreeSitterParser; }, webviewMetadataProvider: WebviewMetadataProvider | undefined = undefined, workflowAPI: WorkflowAPI | undefined = undefined, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, virtualFileSystemService: VirtualFileSystemService, ) { const suggestionService = new DefaultSuggestionService({ telemetryTracker, connection, configService, api: apiClient, featureFlagService, treeSitterParser, documentTransformerService, duoProjectAccessChecker, }); const messageHandler = new MessageHandler({ telemetryTracker, connection, configService, featureFlagService, duoProjectAccessCache, virtualFileSystemService, workflowAPI, }); connection.onCompletion(suggestionService.completionHandler); // TODO: does Visual Studio or Neovim need this? VS Code doesn't connection.onCompletionResolve((item: CompletionItem) => item); connection.onRequest(InlineCompletionRequest.type, suggestionService.inlineCompletionHandler); connection.onDidChangeConfiguration(messageHandler.didChangeConfigurationHandler); connection.onNotification(TELEMETRY_NOTIFICATION, messageHandler.telemetryNotificationHandler); connection.onNotification( START_WORKFLOW_NOTIFICATION, messageHandler.startWorkflowNotificationHandler, ); connection.onRequest(GET_WEBVIEW_METADATA_REQUEST, () => { return webviewMetadataProvider?.getMetadata() ?? []; }); connection.onShutdown(messageHandler.onShutdownHandler); } References:
You are a code assistant
Definition of 'GC_TIME' in file src/common/tracking/constants.ts in project gitlab-lsp
Definition: export const GC_TIME = 60000; export const INSTANCE_TRACKING_EVENTS_MAP = { [TRACKING_EVENTS.REQUESTED]: null, [TRACKING_EVENTS.LOADED]: null, [TRACKING_EVENTS.NOT_PROVIDED]: null, [TRACKING_EVENTS.SHOWN]: 'code_suggestion_shown_in_ide', [TRACKING_EVENTS.ERRORED]: null, [TRACKING_EVENTS.ACCEPTED]: 'code_suggestion_accepted_in_ide', [TRACKING_EVENTS.REJECTED]: 'code_suggestion_rejected_in_ide', [TRACKING_EVENTS.CANCELLED]: null, [TRACKING_EVENTS.STREAM_STARTED]: null, [TRACKING_EVENTS.STREAM_COMPLETED]: null, }; // FIXME: once we remove the default from ConfigService, we can move this back to the SnowplowTracker export const DEFAULT_TRACKING_ENDPOINT = 'https://snowplow.trx.gitlab.net'; 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 'Method' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: export type Method = string; /** * Represents the state of a message payload and can either be empty (no data) or contain a single data item. * Payloads are wrapped in a tuple to maintain consistent structure and type-checking capabilities across message handlers. * * @example * type NoPayload = []; * type WithStringPayload = [string]; */ export type MessagePayload = unknown | undefined; export type KeysWithOptionalValues<T> = { [K in keyof T]: undefined extends T[K] ? K : never; }[keyof T]; /** * Maps notification message types to their corresponding payloads. * @typedef {Record<Method, MessagePayload>} NotificationMap */ export type NotificationMap = Record<Method, MessagePayload>; /** * Interface for publishing notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationPublisher<TNotifications extends NotificationMap> { sendNotification<T extends KeysWithOptionalValues<TNotifications>>(type: T): void; sendNotification<T extends keyof TNotifications>(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener<TNotifications extends NotificationMap> { onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:90 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:139 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:99 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:103
You are a code assistant
Definition of 'error' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References: - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94 - scripts/commit-lint/lint.js:72
You are a code assistant
Definition of 'WORKFLOW_EXECUTOR_DOWNLOAD_PATH' in file src/common/constants.ts in project gitlab-lsp
Definition: export const WORKFLOW_EXECUTOR_DOWNLOAD_PATH = `https://gitlab.com/api/v4/projects/58711783/packages/generic/duo_workflow_executor/${WORKFLOW_EXECUTOR_VERSION}/duo_workflow_executor.tar.gz`; References:

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
2
Add dataset card