instruction
stringclasses 1
value | input
stringlengths 67
168
| output
stringlengths 46
67k
|
---|---|---|
You are a code assistant | Definition of 'get' in file packages/lib_di/src/index.ts in project gitlab-lsp | Definition:
get<T>(id: InterfaceId<T>): T {
const instance = this.#instances.get(id);
if (!instance) {
throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`);
}
return instance as T;
}
}
References:
- src/common/utils/headers_to_snowplow_options.ts:22
- src/common/utils/headers_to_snowplow_options.ts:21
- src/common/config_service.ts:134
- src/common/utils/headers_to_snowplow_options.ts:12
- src/common/utils/headers_to_snowplow_options.ts:20 |
You are a code assistant | Definition of 'InstanceTracker' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp | Definition:
export class InstanceTracker implements TelemetryTracker {
#api: GitLabApiClient;
#codeSuggestionsContextMap = new Map<string, СodeSuggestionContext>();
#circuitBreaker = new FixedTimeCircuitBreaker('Instance telemetry');
#configService: ConfigService;
#options: ITelemetryOptions = {
enabled: true,
actions: [],
};
#codeSuggestionStates = new Map<string, TRACKING_EVENTS>();
// API used for tracking events is available since GitLab v17.2.0.
// Given the track request is done for each CS request
// we need to make sure we do not log the unsupported instance message many times
#invalidInstanceMsgLogged = false;
constructor(api: GitLabApiClient, configService: ConfigService) {
this.#configService = configService;
this.#configService.onConfigChange((config) => this.#reconfigure(config));
this.#api = api;
}
#reconfigure(config: IConfig) {
const { baseUrl } = config.client;
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(`Instance Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`);
} else if (enabled === true) {
log.info(`Instance Telemetry: ${TELEMETRY_ENABLED_MSG}`);
}
}
if (baseUrl) {
this.#options.baseUrl = baseUrl;
}
if (actions) {
this.#options.actions = actions;
}
}
isEnabled(): boolean {
return Boolean(this.#options.enabled);
}
public setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
if (this.#circuitBreaker.isOpen()) {
return;
}
const { language, isStreaming } = context;
// Only auto-reject if client is set up to track accepted and not rejected events.
if (
canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) &&
!canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED)
) {
this.rejectOpenedSuggestions();
}
setTimeout(() => {
if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) {
this.#codeSuggestionsContextMap.delete(uniqueTrackingId);
this.#codeSuggestionStates.delete(uniqueTrackingId);
}
}, GC_TIME);
this.#codeSuggestionsContextMap.set(uniqueTrackingId, {
is_streaming: isStreaming,
language,
timestamp: new Date().toISOString(),
});
if (this.#isStreamingSuggestion(uniqueTrackingId)) return;
this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED);
this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) =>
log.warn('Instance telemetry: Could not track telemetry', e),
);
log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`);
}
async updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
if (this.#circuitBreaker.isOpen()) {
return;
}
if (this.#isStreamingSuggestion(uniqueTrackingId)) return;
const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
const { model, suggestionOptions, isStreaming } = contextUpdate;
if (context) {
if (model) {
context.language = model.lang ?? null;
}
if (suggestionOptions?.length) {
context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions);
}
if (typeof isStreaming === 'boolean') {
context.is_streaming = isStreaming;
}
this.#codeSuggestionsContextMap.set(uniqueTrackingId, context);
}
}
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void {
if (this.#circuitBreaker.isOpen()) {
return;
}
if (!this.isEnabled()) return;
if (this.#isStreamingSuggestion(uniqueTrackingId)) return;
const state = this.#codeSuggestionStates.get(uniqueTrackingId);
if (!state) {
log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`);
return;
}
const allowedTransitions = nonStreamingSuggestionStateGraph.get(state);
if (!allowedTransitions) {
log.debug(
`Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`,
);
return;
}
if (!allowedTransitions.includes(newState)) {
log.debug(
`Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`,
);
// Allow state to update to ACCEPTED despite 'allowed transitions' constraint.
if (newState !== TRACKING_EVENTS.ACCEPTED) {
return;
}
log.debug(
`Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`,
);
}
this.#codeSuggestionStates.set(uniqueTrackingId, newState);
this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) =>
log.warn('Instance telemetry: Could not track telemetry', e),
);
log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`);
}
async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) {
const event = INSTANCE_TRACKING_EVENTS_MAP[eventType];
if (!event) {
return;
}
try {
const { language, suggestion_size } =
this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {};
await this.#api.fetchFromApi({
type: 'rest',
method: 'POST',
path: '/usage_data/track_event',
body: {
event,
additional_properties: {
unique_tracking_id: uniqueTrackingId,
timestamp: new Date().toISOString(),
language,
suggestion_size,
},
},
supportedSinceInstanceVersion: {
resourceName: 'track instance telemetry',
version: '17.2.0',
},
});
this.#circuitBreaker.success();
} catch (error) {
if (error instanceof InvalidInstanceVersionError) {
if (this.#invalidInstanceMsgLogged) return;
this.#invalidInstanceMsgLogged = true;
}
log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error);
this.#circuitBreaker.error();
}
}
rejectOpenedSuggestions() {
log.debug(`Instance Telemetry: Reject all opened suggestions`);
this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => {
if (endStates.includes(state)) {
return;
}
this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
});
}
static #suggestionSize(options: SuggestionOption[]): number {
const countLines = (text: string) => (text ? text.split('\n').length : 0);
return Math.max(...options.map(({ text }) => countLines(text)));
}
#isStreamingSuggestion(uniqueTrackingId: string): boolean {
return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming);
}
}
References:
- src/common/tracking/instance_tracker.test.ts:70
- src/browser/main.ts:106
- src/node/main.ts:159
- src/common/tracking/instance_tracker.test.ts:31 |
You are a code assistant | Definition of 'greet2' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
function greet2(name) {
console.log(name);
}
const greet3 = function (name) {};
const greet4 = function (name) {
console.log(name);
};
const greet5 = (name) => {};
const greet6 = (name) => {
console.log(name);
};
class Greet {
constructor(name) {}
greet() {}
}
class Greet2 {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:4 |
You are a code assistant | Definition of 'generateRequestId' in file packages/lib_webview/src/setup/plugin/utils/generate_request_id.ts in project gitlab-lsp | Definition:
export const generateRequestId = () => {
return Math.random().toString(36).substring(2);
};
References:
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:104
- packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:43 |
You are a code assistant | Definition of 'installLanguages' in file scripts/wasm/build_tree_sitter_wasm.ts in project gitlab-lsp | Definition:
async function installLanguages() {
const installPromises = TREE_SITTER_LANGUAGES.map(installLanguage);
await Promise.all(installPromises);
}
installLanguages()
.then(() => {
console.log('Language parsers installed successfully.');
})
.catch((error) => {
console.error('Error installing language parsers:', error);
});
References:
- scripts/wasm/build_tree_sitter_wasm.ts:34 |
You are a code assistant | Definition of 'FeatureStateManager' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp | Definition:
export const FeatureStateManager = createInterfaceId<FeatureStateManager>('FeatureStateManager');
@Injectable(FeatureStateManager, [CodeSuggestionsSupportedLanguageCheck, ProjectDuoAccessCheck])
export class DefaultFeatureStateManager implements FeatureStateManager {
#checks: StateCheck[] = [];
#subscriptions: Disposable[] = [];
#notify?: NotifyFn<FeatureStateNotificationParams>;
constructor(
supportedLanguagePolicy: CodeSuggestionsSupportedLanguageCheck,
projectDuoAccessCheck: ProjectDuoAccessCheck,
) {
this.#checks.push(supportedLanguagePolicy, projectDuoAccessCheck);
this.#subscriptions.push(
...this.#checks.map((check) => check.onChanged(() => this.#notifyClient())),
);
}
init(notify: NotifyFn<FeatureStateNotificationParams>): void {
this.#notify = notify;
}
async #notifyClient() {
if (!this.#notify) {
throw new Error(
"The state manager hasn't been initialized. It can't send notifications. Call the init method first.",
);
}
await this.#notify(this.#state);
}
dispose() {
this.#subscriptions.forEach((s) => s.dispose());
}
get #state(): FeatureState[] {
const engagedChecks = this.#checks.filter((check) => check.engaged);
return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => {
const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks
.filter(({ id }) => stateChecks.includes(id))
.map((stateCheck) => ({
checkId: stateCheck.id,
details: stateCheck.details,
}));
return {
featureId,
engagedChecks: engagedFeatureChecks,
};
});
}
}
References:
- src/common/connection_service.ts:68 |
You are a code assistant | Definition of 'getActiveFileName' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp | Definition:
export const getActiveFileName = (): string | null => {
return null;
// const editor = vscode.window.activeTextEditor;
// if (!editor) return null;
// return vscode.workspace.asRelativePath(editor.document.uri);
};
export const getTextBeforeSelected = (): string | null => {
return null;
// const editor = vscode.window.activeTextEditor;
// if (!editor || !editor.selection || editor.selection.isEmpty) return null;
// const { selection, document } = editor;
// const { line: lineNum, character: charNum } = selection.start;
// const isFirstCharOnLineSelected = charNum === 0;
// const isFirstLine = lineNum === 0;
// const getEndLine = () => {
// if (isFirstCharOnLineSelected) {
// if (isFirstLine) {
// return lineNum;
// }
// return lineNum - 1;
// }
// return lineNum;
// };
// const getEndChar = () => {
// if (isFirstCharOnLineSelected) {
// if (isFirstLine) {
// return 0;
// }
// return document.lineAt(lineNum - 1).range.end.character;
// }
// return charNum - 1;
// };
// const selectionRange = new vscode.Range(0, 0, getEndLine(), getEndChar());
// return editor.document.getText(selectionRange);
};
export const getTextAfterSelected = (): string | null => {
return null;
// const editor = vscode.window.activeTextEditor;
// if (!editor || !editor.selection || editor.selection.isEmpty) return null;
// const { selection, document } = editor;
// const { line: lineNum, character: charNum } = selection.end;
// const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character;
// const isLastLine = lineNum === document.lineCount;
// const getStartLine = () => {
// if (isLastCharOnLineSelected) {
// if (isLastLine) {
// return lineNum;
// }
// return lineNum + 1;
// }
// return lineNum;
// };
// const getStartChar = () => {
// if (isLastCharOnLineSelected) {
// if (isLastLine) {
// return charNum;
// }
// return 0;
// }
// return charNum + 1;
// };
// const selectionRange = new vscode.Range(
// getStartLine(),
// getStartChar(),
// document.lineCount,
// document.lineAt(document.lineCount - 1).range.end.character,
// );
// return editor.document.getText(selectionRange);
};
References:
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts:17 |
You are a code assistant | Definition of 'getFilesForWorkspace' in file src/common/git/repository_service.ts in project gitlab-lsp | Definition:
getFilesForWorkspace(
workspaceFolderUri: WorkspaceFolderUri,
options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {},
): RepositoryFile[] {
const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri);
const allFiles: RepositoryFile[] = [];
repositories.forEach((repository) => {
repository.getFiles().forEach((file) => {
// apply the filters
if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) {
return;
}
if (options.excludeIgnored && file.isIgnored) {
return;
}
allFiles.push(file);
});
});
return allFiles;
}
// Helper method to check if a file is in the .git folder
#isInGitFolder(fileUri: URI, repositoryUri: URI): boolean {
const relativePath = fileUri.path.slice(repositoryUri.path.length);
return relativePath.split('/').some((part) => part === '.git');
}
}
References: |
You are a code assistant | Definition of 'SuggestionContext' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp | Definition:
export interface SuggestionContext {
document: IDocContext;
intent?: Intent;
projectPath?: string;
optionsCount?: OptionsCount;
additionalContexts?: AdditionalContext[];
}
export interface SuggestionResponse {
choices?: SuggestionResponseChoice[];
model?: SuggestionModel;
status: number;
error?: string;
isDirectConnection?: boolean;
}
export interface SuggestionResponseChoice {
text: string;
}
export interface SuggestionClient {
getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined>;
}
export type SuggestionClientFn = SuggestionClient['getSuggestions'];
export type SuggestionClientMiddleware = (
context: SuggestionContext,
next: SuggestionClientFn,
) => ReturnType<SuggestionClientFn>;
References:
- src/common/suggestion_client/tree_sitter_middleware.test.ts:46
- src/common/suggestion_client/default_suggestion_client.test.ts:10
- src/common/suggestion_client/create_v2_request.ts:5
- src/common/suggestion_client/suggestion_client_pipeline.ts:38
- src/common/suggestion_client/suggestion_client.ts:46
- src/common/suggestion_client/default_suggestion_client.ts:13
- src/common/suggestion_client/suggestion_client_pipeline.test.ts:14
- src/common/suggestion_client/direct_connection_client.ts:124
- src/common/suggestion_client/direct_connection_client.test.ts:24
- src/common/suggestion_client/suggestion_client_pipeline.test.ts:40
- src/common/suggestion_client/tree_sitter_middleware.test.ts:71
- src/common/suggestion_client/suggestion_client.ts:40
- src/common/suggestion_client/suggestion_client_pipeline.ts:27
- src/common/suggestion_client/fallback_client.ts:10 |
You are a code assistant | Definition of 'LangGraphCheckpoint' in file src/common/graphql/workflow/types.ts in project gitlab-lsp | Definition:
export type LangGraphCheckpoint = {
checkpoint: string;
};
export type DuoWorkflowEvents = {
nodes: LangGraphCheckpoint[];
};
export type DuoWorkflowEventConnectionType = {
duoWorkflowEvents: DuoWorkflowEvents;
};
References:
- src/common/graphql/workflow/service.ts:37
- src/common/graphql/workflow/service.ts:28 |
You are a code assistant | Definition of 'parseURIString' in file src/common/services/fs/utils.ts in project gitlab-lsp | Definition:
export const parseURIString = (uri: string): URI => {
return URI.parse(uri);
};
References:
- src/common/ai_context_management_2/providers/ai_file_context_provider.ts:78
- src/common/ai_context_management_2/ai_context_aggregator.ts:67 |
You are a code assistant | Definition of 'handleWebviewDestroyed' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp | Definition:
export const handleWebviewDestroyed = (
messageEmitter: WebviewTransportEventEmitter,
logger?: Logger,
) =>
withJsonRpcMessageValidation(isWebviewInstanceDestroyedEventData, logger, (message) => {
messageEmitter.emit('webview_instance_destroyed', message);
});
export const handleWebviewMessage = (
messageEmitter: WebviewTransportEventEmitter,
logger?: Logger,
) =>
withJsonRpcMessageValidation(isWebviewInstanceMessageEventData, logger, (message) => {
messageEmitter.emit('webview_instance_notification_received', message);
});
export type JsonRpcConnectionTransportProps = {
connection: Connection;
logger: Logger;
notificationRpcMethod?: string;
webviewCreatedRpcMethod?: string;
webviewDestroyedRpcMethod?: string;
};
export class JsonRpcConnectionTransport implements Transport {
#messageEmitter = createWebviewTransportEventEmitter();
#connection: Connection;
#notificationChannel: string;
#webviewCreatedChannel: string;
#webviewDestroyedChannel: string;
#logger?: Logger;
#disposables: Disposable[] = [];
constructor({
connection,
logger,
notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD,
webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD,
webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD,
}: JsonRpcConnectionTransportProps) {
this.#connection = connection;
this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined;
this.#notificationChannel = notificationChannel;
this.#webviewCreatedChannel = webviewCreatedChannel;
this.#webviewDestroyedChannel = webviewDestroyedChannel;
this.#subscribeToConnection();
}
#subscribeToConnection() {
const channelToNotificationHandlerMap = {
[this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger),
[this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger),
[this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger),
};
Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => {
const disposable = this.#connection.onNotification(channel, handler);
this.#disposables.push(disposable);
});
}
on<K extends keyof MessagesToServer>(
type: K,
callback: TransportMessageHandler<MessagesToServer[K]>,
): Disposable {
this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]);
return {
dispose: () =>
this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]),
};
}
publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void> {
if (type === 'webview_instance_notification') {
return this.#connection.sendNotification(this.#notificationChannel, payload);
}
throw new Error(`Unknown message type: ${type}`);
}
dispose(): void {
this.#messageEmitter.removeAllListeners();
this.#disposables.forEach((disposable) => disposable.dispose());
this.#logger?.debug('JsonRpcConnectionTransport disposed');
}
}
References:
- packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:92 |
You are a code assistant | Definition of 'post' in file src/common/fetch.ts in project gitlab-lsp | Definition:
post(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
updateAgentOptions(options: FetchAgentOptions): void;
streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>;
}
export const LsFetch = createInterfaceId<LsFetch>('LsFetch');
export class FetchBase implements LsFetch {
updateRequestInit(method: string, init?: RequestInit): RequestInit {
if (typeof init === 'undefined') {
// eslint-disable-next-line no-param-reassign
init = { method };
} else {
// eslint-disable-next-line no-param-reassign
init.method = method;
}
return init;
}
async initialize(): Promise<void> {}
async destroy(): Promise<void> {}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
async *streamFetch(
/* eslint-disable @typescript-eslint/no-unused-vars */
_url: string,
_body: string,
_headers: FetchHeaders,
/* eslint-enable @typescript-eslint/no-unused-vars */
): AsyncGenerator<string, void, void> {
// Stub. Should delegate to the node or browser fetch implementations
throw new Error('Not implemented');
yield '';
}
async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('DELETE', init));
}
async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('GET', init));
}
async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('POST', init));
}
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References: |
You are a code assistant | Definition of 'DesktopTreeSitterParser' in file src/node/tree_sitter/parser.ts in project gitlab-lsp | Definition:
export class DesktopTreeSitterParser extends TreeSitterParser {
constructor() {
super({
languages: TREE_SITTER_LANGUAGES,
});
}
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:
- src/tests/unit/tree_sitter/test_utils.ts:37
- src/node/main.ts:168 |
You are a code assistant | Definition of 'DUO_CHAT_WEBVIEW_ID' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp | Definition:
export const DUO_CHAT_WEBVIEW_ID = 'chat';
References: |
You are a code assistant | Definition of 'log' in file src/common/log.ts in project gitlab-lsp | Definition:
export const log = new Log();
References:
- src/tests/fixtures/intent/empty_function/javascript.js:16
- src/tests/fixtures/intent/empty_function/javascript.js:10
- scripts/set_ls_version.js:17
- scripts/commit-lint/lint.js:66
- src/tests/fixtures/intent/empty_function/javascript.js:4
- src/tests/fixtures/intent/empty_function/javascript.js:31
- scripts/commit-lint/lint.js:61 |
You are a code assistant | Definition of 'debug' in file src/common/log.ts in project gitlab-lsp | Definition:
debug(messageOrError: Error | string, trailingError?: Error | unknown) {
this.#log(LOG_LEVEL.DEBUG, messageOrError, trailingError);
}
info(messageOrError: Error | string, trailingError?: Error | unknown) {
this.#log(LOG_LEVEL.INFO, messageOrError, trailingError);
}
warn(messageOrError: Error | string, trailingError?: Error | unknown) {
this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError);
}
error(messageOrError: Error | string, trailingError?: Error | unknown) {
this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError);
}
}
// TODO: rename the export and replace usages of `log` with `Log`.
export const log = new Log();
References: |
You are a code assistant | Definition of 'Fetch' in file src/browser/fetch.ts in project gitlab-lsp | Definition:
export class Fetch extends FetchBase implements LsFetch {
/**
* Browser-specific fetch implementation.
* See https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/171 for details
*/
async *streamFetch(
url: string,
body: string,
headers: FetchHeaders,
): AsyncGenerator<string, void, void> {
const response = await this.fetch(url, {
method: 'POST',
headers,
body,
});
await handleFetchError(response, 'Streaming Code Suggestions');
const reader = response?.body?.getReader();
if (!reader) {
return undefined;
}
let buffer = '';
let readResult = await reader.read();
while (!readResult.done) {
// TODO: We should consider streaming the raw bytes instead of the decoded string
const rawContent = new TextDecoder().decode(readResult.value);
buffer += rawContent;
// TODO if we cancel the stream, and nothing will consume it, we probably leave the HTTP connection open :-O
yield buffer;
// eslint-disable-next-line no-await-in-loop
readResult = await reader.read();
}
return undefined;
}
}
References:
- src/node/fetch.test.ts:57
- src/node/fetch.test.ts:90
- src/browser/fetch.test.ts:33
- src/node/fetch.test.ts:74
- src/tests/int/snowplow.test.ts:16
- src/browser/main.ts:67
- src/node/main.ts:113
- src/tests/int/fetch.test.ts:124
- src/node/fetch.test.ts:191
- src/node/fetch.test.ts:194
- src/tests/int/fetch.test.ts:82
- src/tests/int/fetch.test.ts:154
- src/node/fetch.test.ts:38 |
You are a code assistant | Definition of 'createFakePartial' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_partial.ts in project gitlab-lsp | Definition:
export const createFakePartial = <T>(x: DeepPartial<T>): T => x as T;
References:
- src/common/suggestion/suggestion_service.test.ts:436
- src/common/suggestion_client/create_v2_request.test.ts:10
- src/common/feature_state/project_duo_acces_check.test.ts:32
- src/common/suggestion/suggestion_filter.test.ts:80
- src/common/tree_sitter/comments/comment_resolver.test.ts:164
- src/common/message_handler.test.ts:53
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:74
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:198
- src/common/services/duo_access/project_access_checker.test.ts:48
- src/common/services/duo_access/project_access_checker.test.ts:15
- src/common/advanced_context/advanced_context_service.test.ts:34
- src/common/message_handler.test.ts:57
- src/common/connection.test.ts:48
- src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:14
- src/common/advanced_context/helpers.test.ts:10
- src/common/connection.test.ts:58
- src/tests/int/lsp_client.ts:38
- src/common/tree_sitter/intent_resolver.test.ts:40
- src/common/connection.test.ts:47
- src/common/graphql/workflow/service.test.ts:35
- src/common/suggestion/suggestion_service.test.ts:983
- src/common/suggestion/suggestion_service.test.ts:105
- src/common/graphql/workflow/service.test.ts:41
- packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:16
- src/common/services/duo_access/project_access_checker.test.ts:70
- src/common/connection.test.ts:31
- src/common/feature_state/project_duo_acces_check.test.ts:23
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:17
- src/common/core/handlers/initialize_handler.test.ts:17
- src/common/feature_state/project_duo_acces_check.test.ts:40
- src/common/tracking/snowplow_tracker.test.ts:82
- src/common/api.test.ts:349
- src/common/tree_sitter/comments/comment_resolver.test.ts:129
- src/common/feature_state/supported_language_check.test.ts:38
- src/common/tracking/snowplow_tracker.test.ts:78
- src/common/suggestion_client/direct_connection_client.test.ts:50
- src/common/tree_sitter/intent_resolver.test.ts:160
- src/common/suggestion/streaming_handler.test.ts:65
- src/tests/int/lsp_client.ts:164
- src/common/suggestion_client/fallback_client.test.ts:8
- src/common/log.test.ts:10
- src/common/services/duo_access/project_access_cache.test.ts:12
- src/common/suggestion_client/fallback_client.test.ts:15
- src/common/test_utils/create_fake_response.ts:18
- src/common/tree_sitter/parser.test.ts:86
- src/common/suggestion_client/fallback_client.test.ts:7
- src/common/suggestion_client/tree_sitter_middleware.test.ts:33
- src/common/feature_flags.test.ts:17
- src/common/services/duo_access/project_access_checker.test.ts:148
- src/common/suggestion/suggestion_service.test.ts:193
- src/common/suggestion/suggestion_service.test.ts:1054
- src/common/connection.test.ts:53
- src/common/suggestion/streaming_handler.test.ts:75
- src/common/suggestion/suggestion_service.test.ts:464
- src/common/advanced_context/advanced_context_service.test.ts:53
- src/common/feature_state/feature_state_manager.test.ts:21
- src/common/message_handler.test.ts:48
- src/common/document_service.test.ts:8
- src/common/services/duo_access/project_access_checker.test.ts:92
- src/common/tree_sitter/comments/comment_resolver.test.ts:199
- src/common/suggestion_client/tree_sitter_middleware.test.ts:86
- src/common/suggestion/suggestion_service.test.ts:190
- src/common/suggestion/suggestion_filter.test.ts:79
- src/common/feature_flags.test.ts:93
- src/common/advanced_context/advanced_context_service.test.ts:50
- src/common/message_handler.test.ts:64
- src/common/suggestion/suggestion_filter.test.ts:35
- src/common/suggestion/suggestion_service.test.ts:770
- src/common/api.test.ts:406
- src/common/tracking/instance_tracker.test.ts:179
- src/common/suggestion_client/default_suggestion_client.test.ts:24
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:31
- src/common/suggestion_client/tree_sitter_middleware.test.ts:62
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:199
- src/common/suggestion_client/fallback_client.test.ts:27
- src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:24
- src/common/suggestion_client/default_suggestion_client.test.ts:7
- src/common/suggestion/suggestion_service.test.ts:86
- src/common/tree_sitter/parser.test.ts:127
- src/common/services/duo_access/project_access_checker.test.ts:145
- src/common/tree_sitter/comments/comment_resolver.test.ts:30
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:44
- src/common/suggestion_client/direct_connection_client.test.ts:32
- src/common/suggestion/streaming_handler.test.ts:50
- src/common/feature_state/project_duo_acces_check.test.ts:27
- src/common/document_transformer_service.test.ts:68
- src/node/duo_workflow/desktop_workflow_runner.test.ts:22
- src/common/suggestion/suggestion_service.test.ts:164
- src/common/suggestion/suggestion_service.test.ts:89
- src/common/suggestion/suggestion_service.test.ts:76
- src/common/suggestion_client/direct_connection_client.test.ts:152
- src/common/feature_state/project_duo_acces_check.test.ts:41
- src/common/suggestion_client/fallback_client.test.ts:9
- src/common/advanced_context/advanced_context_factory.test.ts:72
- src/common/fetch_error.test.ts:37
- src/common/suggestion_client/direct_connection_client.test.ts:52
- src/common/suggestion_client/direct_connection_client.test.ts:35
- src/common/feature_state/feature_state_manager.test.ts:34
- src/common/services/duo_access/project_access_checker.test.ts:40
- src/common/api.test.ts:438
- src/common/tree_sitter/comments/comment_resolver.test.ts:31
- src/common/suggestion/suggestion_filter.test.ts:56
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:32
- src/common/services/duo_access/project_access_cache.test.ts:20
- src/common/suggestion_client/fallback_client.test.ts:30
- src/common/feature_state/feature_state_manager.test.ts:55
- src/common/services/duo_access/project_access_checker.test.ts:44
- src/common/suggestion/suggestion_filter.test.ts:77
- src/common/tree_sitter/comments/comment_resolver.test.ts:208
- src/common/tree_sitter/comments/comment_resolver.test.ts:212
- src/common/message_handler.test.ts:215
- src/common/suggestion/suggestion_service.test.ts:84
- src/common/services/duo_access/project_access_checker.test.ts:126
- src/common/connection.test.ts:44
- src/common/advanced_context/advanced_context_service.test.ts:39
- src/common/tracking/instance_tracker.test.ts:32
- src/common/services/duo_access/project_access_checker.test.ts:153
- src/common/services/duo_access/project_access_checker.test.ts:74
- src/common/tree_sitter/parser.test.ts:83
- src/common/suggestion/streaming_handler.test.ts:70
- src/common/tree_sitter/intent_resolver.test.ts:47
- src/common/services/duo_access/project_access_checker.test.ts:157
- src/common/fetch_error.test.ts:7
- src/common/core/handlers/initialize_handler.test.ts:8
- src/common/message_handler.test.ts:204
- src/common/suggestion/suggestion_service.test.ts:108
- src/common/advanced_context/advanced_context_service.test.ts:47
- src/common/suggestion_client/direct_connection_client.test.ts:58
- src/common/suggestion/suggestion_service.test.ts:100
- src/common/tree_sitter/comments/comment_resolver.test.ts:162
- src/common/tree_sitter/comments/comment_resolver.test.ts:27
- src/common/tree_sitter/comments/comment_resolver.test.ts:206
- src/common/feature_flags.test.ts:21
- src/common/message_handler.test.ts:136
- src/common/advanced_context/helpers.test.ts:7
- src/common/message_handler.test.ts:42
- src/common/suggestion/suggestion_service.test.ts:1038
- src/common/suggestion/suggestion_service.test.ts:469
- src/common/tree_sitter/comments/comment_resolver.test.ts:127
- src/common/suggestion/suggestion_service.test.ts:582
- src/common/services/duo_access/project_access_checker.test.ts:66
- src/common/graphql/workflow/service.test.ts:38
- src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:57
- src/common/tree_sitter/comments/comment_resolver.test.ts:16
- src/common/services/duo_access/project_access_checker.test.ts:100
- src/common/tracking/multi_tracker.test.ts:8
- src/common/suggestion/suggestion_service.test.ts:492
- src/common/advanced_context/advanced_context_service.test.ts:28
- src/common/suggestion_client/suggestion_client_pipeline.test.ts:10
- src/common/connection.test.ts:57
- src/common/suggestion/suggestion_service.test.ts:1073
- src/common/suggestion/streaming_handler.test.ts:46
- src/common/tree_sitter/comments/comment_resolver.test.ts:193
- src/common/suggestion/suggestion_filter.test.ts:57
- src/common/suggestion/suggestion_service.test.ts:756
- src/common/tree_sitter/comments/comment_resolver.test.ts:195
- src/common/advanced_context/advanced_context_factory.test.ts:73
- src/common/tree_sitter/comments/comment_resolver.test.ts:133
- src/common/connection.test.ts:59
- src/node/duo_workflow/desktop_workflow_runner.test.ts:24
- src/common/services/duo_access/project_access_checker.test.ts:122
- src/common/security_diagnostics_publisher.test.ts:51
- src/common/fetch_error.test.ts:21
- src/common/core/handlers/token_check_notifier.test.ts:11
- src/common/message_handler.test.ts:61
- src/common/suggestion/suggestion_service.test.ts:476
- src/common/suggestion_client/create_v2_request.test.ts:8
- src/common/suggestion/suggestion_service.test.ts:199
- src/common/services/duo_access/project_access_cache.test.ts:16
- src/common/advanced_context/advanced_context_service.test.ts:42
- src/common/services/duo_access/project_access_checker.test.ts:24
- src/common/api.test.ts:422
- src/common/security_diagnostics_publisher.test.ts:48
- src/common/suggestion/streaming_handler.test.ts:56
- src/common/tracking/instance_tracker.test.ts:176
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:28
- src/common/suggestion_client/fallback_client.test.ts:12
- src/common/feature_state/project_duo_acces_check.test.ts:35
- src/common/services/duo_access/project_access_checker.test.ts:118
- src/common/suggestion_client/direct_connection_client.test.ts:150
- src/common/feature_state/supported_language_check.test.ts:39
- src/common/services/duo_access/project_access_checker.test.ts:96
- src/common/suggestion_client/direct_connection_client.test.ts:33
- src/node/fetch.test.ts:16
- src/common/suggestion/streaming_handler.test.ts:62
- src/common/suggestion_client/tree_sitter_middleware.test.ts:24
- src/common/api.test.ts:298
- src/common/suggestion/suggestion_service.test.ts:205
- src/common/feature_state/feature_state_manager.test.ts:78
- src/common/suggestion/suggestion_service.test.ts:94
- src/common/suggestion_client/direct_connection_client.test.ts:106
- src/common/suggestion/suggestion_service.test.ts:461
- src/common/suggestion_client/default_suggestion_client.test.ts:11
- src/common/suggestion_client/direct_connection_client.test.ts:103
- src/common/api.test.ts:318
- src/common/services/duo_access/project_access_checker.test.ts:163
- src/common/feature_state/supported_language_check.test.ts:27 |
You are a code assistant | Definition of 'CHAT_INPUT_TEMPLATE_17_3_AND_LATER' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp | Definition:
export const CHAT_INPUT_TEMPLATE_17_3_AND_LATER = {
query: gql`
mutation chat(
$question: String!
$resourceId: AiModelID
$currentFileContext: AiCurrentFileInput
$clientSubscriptionId: String
$platformOrigin: String!
) {
aiAction(
input: {
chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext }
clientSubscriptionId: $clientSubscriptionId
platformOrigin: $platformOrigin
}
) {
requestId
errors
}
}
`,
defaultVariables: {
platformOrigin: PLATFORM_ORIGIN,
},
};
export type AiActionResponseType = {
aiAction: { requestId: string; errors: string[] };
};
export const AI_MESSAGES_QUERY = gql`
query getAiMessages($requestIds: [ID!], $roles: [AiMessageRole!]) {
aiMessages(requestIds: $requestIds, roles: $roles) {
nodes {
requestId
role
content
contentHtml
timestamp
errors
extras {
sources
}
}
}
}
`;
type AiMessageResponseType = {
requestId: string;
role: string;
content: string;
contentHtml: string;
timestamp: string;
errors: string[];
extras?: {
sources: object[];
};
};
type AiMessagesResponseType = {
aiMessages: {
nodes: AiMessageResponseType[];
};
};
interface ErrorMessage {
type: 'error';
requestId: string;
role: 'system';
errors: string[];
}
const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({
requestId,
errors,
role: 'system',
type: 'error',
});
interface SuccessMessage {
type: 'message';
requestId: string;
role: string;
content: string;
contentHtml: string;
timestamp: string;
errors: string[];
extras?: {
sources: object[];
};
}
const successResponse = (response: AiMessageResponseType): SuccessMessage => ({
type: 'message',
...response,
});
type AiMessage = SuccessMessage | ErrorMessage;
type ChatInputTemplate = {
query: string;
defaultVariables: {
platformOrigin?: string;
};
};
export class GitLabChatApi {
#cachedActionQuery?: ChatInputTemplate = undefined;
#manager: GitLabPlatformManagerForChat;
constructor(manager: GitLabPlatformManagerForChat) {
this.#manager = manager;
}
async processNewUserPrompt(
question: string,
subscriptionId?: string,
currentFileContext?: GitLabChatFileContext,
): Promise<AiActionResponseType> {
return this.#sendAiAction({
question,
currentFileContext,
clientSubscriptionId: subscriptionId,
});
}
async pullAiMessage(requestId: string, role: string): Promise<AiMessage> {
const response = await pullHandler(() => this.#getAiMessage(requestId, role));
if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']);
return successResponse(response);
}
async cleanChat(): Promise<AiActionResponseType> {
return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN });
}
async #currentPlatform() {
const platform = await this.#manager.getGitLabPlatform();
if (!platform) throw new Error('Platform is missing!');
return platform;
}
async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> {
const request: GraphQLRequest<AiMessagesResponseType> = {
type: 'graphql',
query: AI_MESSAGES_QUERY,
variables: { requestIds: [requestId], roles: [role.toUpperCase()] },
};
const platform = await this.#currentPlatform();
const history = await platform.fetchFromApi(request);
return history.aiMessages.nodes[0];
}
async subscribeToUpdates(
messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>,
subscriptionId?: string,
) {
const platform = await this.#currentPlatform();
const channel = new AiCompletionResponseChannel({
htmlResponse: true,
userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`,
aiAction: 'CHAT',
clientSubscriptionId: subscriptionId,
});
const cable = await platform.connectToCable();
// we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397
// sometimes a chunk comes after the full message and it broke the chat
let fullMessageReceived = false;
channel.on('newChunk', async (msg) => {
if (fullMessageReceived) {
log.info(`CHAT-DEBUG: full message received, ignoring chunk`);
return;
}
await messageCallback(msg);
});
channel.on('fullMessage', async (message) => {
fullMessageReceived = true;
await messageCallback(message);
if (subscriptionId) {
cable.disconnect();
}
});
cable.subscribe(channel);
}
async #sendAiAction(variables: object): Promise<AiActionResponseType> {
const platform = await this.#currentPlatform();
const { query, defaultVariables } = await this.#actionQuery();
const projectGqlId = await this.#manager.getProjectGqlId();
const request: GraphQLRequest<AiActionResponseType> = {
type: 'graphql',
query,
variables: {
...variables,
...defaultVariables,
resourceId: projectGqlId ?? null,
},
};
return platform.fetchFromApi(request);
}
async #actionQuery(): Promise<ChatInputTemplate> {
if (!this.#cachedActionQuery) {
const platform = await this.#currentPlatform();
try {
const { version } = await platform.fetchFromApi(versionRequest);
this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>(
version,
MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION,
() => CHAT_INPUT_TEMPLATE_17_3_AND_LATER,
() => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER,
);
} catch (e) {
log.debug(`GitLab version check for sending chat failed:`, e as Error);
this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER;
}
}
return this.#cachedActionQuery;
}
}
References: |
You are a code assistant | Definition of 'ISuggestionsCacheOptions' in file src/common/config_service.ts in project gitlab-lsp | Definition:
export interface ISuggestionsCacheOptions {
enabled?: boolean;
maxSize?: number;
ttl?: number;
prefixLines?: number;
suffixLines?: number;
}
export interface IHttpAgentOptions {
ca?: string;
cert?: string;
certKey?: string;
}
export interface ISnowplowTrackerOptions {
gitlab_instance_id?: string;
gitlab_global_user_id?: string;
gitlab_host_name?: string;
gitlab_saas_duo_pro_namespace_ids?: number[];
}
export interface ISecurityScannerOptions {
enabled?: boolean;
serviceUrl?: string;
}
export interface IWorkflowSettings {
dockerSocket?: string;
}
export interface IDuoConfig {
enabledWithoutGitlabProject?: boolean;
}
export interface IClientConfig {
/** GitLab API URL used for getting code suggestions */
baseUrl?: string;
/** Full project path. */
projectPath?: string;
/** PAT or OAuth token used to authenticate to GitLab API */
token?: string;
/** The base URL for language server assets in the client-side extension */
baseAssetsUrl?: string;
clientInfo?: IClientInfo;
// FIXME: this key should be codeSuggestions (we have code completion and code generation)
codeCompletion?: ICodeCompletionConfig;
openTabsContext?: boolean;
telemetry?: ITelemetryOptions;
/** Config used for caching code suggestions */
suggestionsCache?: ISuggestionsCacheOptions;
workspaceFolders?: WorkspaceFolder[] | null;
/** Collection of Feature Flag values which are sent from the client */
featureFlags?: Record<string, boolean>;
logLevel?: LogLevel;
ignoreCertificateErrors?: boolean;
httpAgentOptions?: IHttpAgentOptions;
snowplowTrackerOptions?: ISnowplowTrackerOptions;
// TODO: move to `duo`
duoWorkflowSettings?: IWorkflowSettings;
securityScannerOptions?: ISecurityScannerOptions;
duo?: IDuoConfig;
}
export interface IConfig {
// TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig
client: IClientConfig;
}
/**
* ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled)
* TODO: Maybe in the future we would like to separate these two
*/
export interface ConfigService {
get: TypedGetter<IConfig>;
/**
* set sets the property of the config
* the new value completely overrides the old one
*/
set: TypedSetter<IConfig>;
onConfigChange(listener: (config: IConfig) => void): Disposable;
/**
* merge adds `newConfig` properties into existing config, if the
* property is present in both old and new config, `newConfig`
* properties take precedence unless not defined
*
* This method performs deep merge
*
* **Arrays are not merged; they are replaced with the new value.**
*
*/
merge(newConfig: Partial<IConfig>): void;
}
export const ConfigService = createInterfaceId<ConfigService>('ConfigService');
@Injectable(ConfigService, [])
export class DefaultConfigService implements ConfigService {
#config: IConfig;
#eventEmitter = new EventEmitter();
constructor() {
this.#config = {
client: {
baseUrl: GITLAB_API_BASE_URL,
codeCompletion: {
enableSecretRedaction: true,
},
telemetry: {
enabled: true,
},
logLevel: LOG_LEVEL.INFO,
ignoreCertificateErrors: false,
httpAgentOptions: {},
},
};
}
get: TypedGetter<IConfig> = (key?: string) => {
return key ? get(this.#config, key) : this.#config;
};
set: TypedSetter<IConfig> = (key: string, value: unknown) => {
set(this.#config, key, value);
this.#triggerChange();
};
onConfigChange(listener: (config: IConfig) => void): Disposable {
this.#eventEmitter.on('configChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('configChange', this.#config);
}
merge(newConfig: Partial<IConfig>) {
mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined));
this.#triggerChange();
}
}
References:
- src/common/config_service.ts:64 |
You are a code assistant | Definition of 'getSuggestions' in file src/common/suggestion_client/direct_connection_client.ts in project gitlab-lsp | Definition:
async getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined> {
// TODO we would like to send direct request only for intent === COMPLETION
// however, currently we are not certain that the intent is completion
// when we finish the following two issues, we can be certain that the intent is COMPLETION
//
// https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/173
// https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/247
if (context.intent === GENERATION) {
return undefined;
}
if (!this.#isValidApi) {
return undefined;
}
if (this.#directConnectionCircuitBreaker.isOpen()) {
return undefined;
}
if (!this.#connectionDetails || areExpired(this.#connectionDetails)) {
this.#fetchDirectConnectionDetails().catch(
(e) => log.error(`#fetchDirectConnectionDetails error: ${e}`), // this makes eslint happy, the method should never throw
);
return undefined;
}
try {
const response = await this.#fetchUsingDirectConnection<SuggestionResponse>(
createV2Request(context, this.#connectionDetails.model_details),
);
return response && { ...response, isDirectConnection: true };
} catch (e) {
this.#directConnectionCircuitBreaker.error();
log.warn(
'Direct connection for code suggestions failed. Code suggestion requests will be sent to your GitLab instance.',
e,
);
}
return undefined;
}
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp | Definition:
private constructor(lsFetch: LsFetch, options: SnowplowOptions) {
this.#lsFetch = lsFetch;
this.#options = options;
this.#emitter = new Emitter(
this.#options.timeInterval,
this.#options.maxItems,
this.#sendEvent.bind(this),
);
this.#emitter.start();
this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) });
}
public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow {
if (!this.#instance) {
if (!options) {
throw new Error('Snowplow should be instantiated');
}
const sp = new Snowplow(lsFetch, options);
Snowplow.#instance = sp;
}
// FIXME: this eslint violation was introduced before we set up linting
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return Snowplow.#instance!;
}
async #sendEvent(events: PayloadBuilder[]): Promise<void> {
if (!this.#options.enabled() || this.disabled) {
return;
}
try {
const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`;
const data = {
schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4',
data: events.map((event) => {
const eventId = uuidv4();
// All values prefilled below are part of snowplow tracker protocol
// https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters
// Values are set according to either common GitLab standard:
// tna - representing tracker namespace and being set across GitLab to "gl"
// tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with "js-*""
// aid - represents app Id is configured via options to gitlab_ide_extension
// eid - represents uuid for each emitted event
event.add('eid', eventId);
event.add('p', 'app');
event.add('tv', 'js-gitlab');
event.add('tna', 'gl');
event.add('aid', this.#options.appId);
return preparePayload(event.build());
}),
};
const config = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
};
const response = await this.#lsFetch.post(url, config);
if (response.status !== 200) {
log.warn(
`Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`,
);
}
} catch (error) {
let errorHandled = false;
if (typeof error === 'object' && 'errno' in (error as object)) {
const errObject = error as object;
// ENOTFOUND occurs when the snowplow hostname cannot be resolved.
if ('errno' in errObject && errObject.errno === 'ENOTFOUND') {
this.disabled = true;
errorHandled = true;
log.info('Disabling telemetry, unable to resolve endpoint address.');
} else {
log.warn(JSON.stringify(errObject));
}
}
if (!errorHandled) {
log.warn('Failed to send telemetry event, this warning can be safely ignored');
log.warn(JSON.stringify(error));
}
}
}
public async trackStructEvent(
event: StructuredEvent,
context?: SelfDescribingJson[] | null,
): Promise<void> {
this.#tracker.track(buildStructEvent(event), context);
}
async stop() {
await this.#emitter.stop();
}
public destroy() {
Snowplow.#instance = undefined;
}
}
References: |
You are a code assistant | Definition of 'GitLabVersionResponse' in file packages/webview_duo_chat/src/plugin/port/gilab/check_version.ts in project gitlab-lsp | Definition:
export type GitLabVersionResponse = {
version: string;
enterprise?: boolean;
};
export const versionRequest: ApiRequest<GitLabVersionResponse> = {
type: 'rest',
method: 'GET',
path: '/version',
};
References: |
You are a code assistant | Definition of 'getItem' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp | Definition:
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 'API_ERROR_NOTIFICATION' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp | Definition:
export const API_ERROR_NOTIFICATION = '$/gitlab/api/error';
export const API_RECOVERY_NOTIFICATION = '$/gitlab/api/recovered';
export enum CircuitBreakerState {
OPEN = 'Open',
CLOSED = 'Closed',
}
export interface CircuitBreaker {
error(): void;
success(): void;
isOpen(): boolean;
onOpen(listener: () => void): Disposable;
onClose(listener: () => void): Disposable;
}
References: |
You are a code assistant | Definition of 'sendTextDocumentDidOpen' in file src/tests/int/lsp_client.ts in project gitlab-lsp | Definition:
public async sendTextDocumentDidOpen(
uri: string,
languageId: string,
version: number,
text: string,
): Promise<void> {
const params = {
textDocument: {
uri,
languageId,
version,
text,
},
};
const request = new NotificationType<DidOpenTextDocumentParams>('textDocument/didOpen');
await this.#connection.sendNotification(request, params);
}
public async sendTextDocumentDidClose(uri: string): Promise<void> {
const params = {
textDocument: {
uri,
},
};
const request = new NotificationType<DidCloseTextDocumentParams>('textDocument/didClose');
await this.#connection.sendNotification(request, params);
}
/**
* Send LSP 'textDocument/didChange' using Full sync method notification
*
* @param uri File URL. Should include the workspace path in the url
* @param version Change version (incrementing from 0)
* @param text Full contents of the file
*/
public async sendTextDocumentDidChangeFull(
uri: string,
version: number,
text: string,
): Promise<void> {
const params = {
textDocument: {
uri,
version,
},
contentChanges: [{ text }],
};
const request = new NotificationType<DidChangeTextDocumentParams>('textDocument/didChange');
await this.#connection.sendNotification(request, params);
}
public async sendTextDocumentCompletion(
uri: string,
line: number,
character: number,
): Promise<CompletionItem[] | CompletionList | null> {
const params: CompletionParams = {
textDocument: {
uri,
},
position: {
line,
character,
},
context: {
triggerKind: 1, // invoked
},
};
const request = new RequestType1<
CompletionParams,
CompletionItem[] | CompletionList | null,
void
>('textDocument/completion');
const result = await this.#connection.sendRequest(request, params);
return result;
}
public async sendDidChangeDocumentInActiveEditor(uri: string): Promise<void> {
await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri);
}
public async getWebviewMetadata(): Promise<WebviewMetadata[]> {
const result = await this.#connection.sendRequest<WebviewMetadata[]>(
'$/gitlab/webview-metadata',
);
return result;
}
}
References: |
You are a code assistant | Definition of 'getEmptyFunctionResolver' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp | Definition:
export function getEmptyFunctionResolver(): EmptyFunctionResolver {
if (!emptyFunctionResolver) {
emptyFunctionResolver = new EmptyFunctionResolver();
}
return emptyFunctionResolver;
}
References:
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:142
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:141
- src/common/tree_sitter/intent_resolver.ts:37 |
You are a code assistant | Definition of 'constructor' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp | Definition:
constructor(
webviewAddress: WebviewAddress,
runtimeMessageBus: WebviewRuntimeMessageBus,
logger: Logger,
) {
this.#address = webviewAddress;
this.#runtimeMessageBus = runtimeMessageBus;
this.#logger = withPrefix(
logger,
`[WebviewInstanceMessageBus:${webviewAddress.webviewId}:${webviewAddress.webviewInstanceId}]`,
);
this.#logger.debug('initializing');
const eventFilter = buildWebviewAddressFilter(webviewAddress);
this.#eventSubscriptions.add(
this.#runtimeMessageBus.subscribe(
'webview:notification',
async (message) => {
try {
await this.#notificationEvents.handle(message.type, message.payload);
} catch (error) {
this.#logger.debug(
`Failed to handle webview instance notification: ${message.type}`,
error instanceof Error ? error : undefined,
);
}
},
eventFilter,
),
this.#runtimeMessageBus.subscribe(
'webview:request',
async (message) => {
try {
await this.#requestEvents.handle(message.type, message.requestId, message.payload);
} catch (error) {
this.#logger.error(error as Error);
}
},
eventFilter,
),
this.#runtimeMessageBus.subscribe(
'webview:response',
async (message) => {
try {
await this.#pendingResponseEvents.handle(message.requestId, message);
} catch (error) {
this.#logger.error(error as Error);
}
},
eventFilter,
),
);
this.#logger.debug('initialized');
}
sendNotification(type: Method, payload?: unknown): void {
this.#logger.debug(`Sending notification: ${type}`);
this.#runtimeMessageBus.publish('plugin:notification', {
...this.#address,
type,
payload,
});
}
onNotification(type: Method, handler: Handler): Disposable {
return this.#notificationEvents.register(type, handler);
}
async sendRequest(type: Method, payload?: unknown): Promise<never> {
const requestId = generateRequestId();
this.#logger.debug(`Sending request: ${type}, ID: ${requestId}`);
let timeout: NodeJS.Timeout | undefined;
return new Promise((resolve, reject) => {
const pendingRequestHandle = this.#pendingResponseEvents.register(
requestId,
(message: ResponseMessage) => {
if (message.success) {
resolve(message.payload as PromiseLike<never>);
} else {
reject(new Error(message.reason));
}
clearTimeout(timeout);
pendingRequestHandle.dispose();
},
);
this.#runtimeMessageBus.publish('plugin:request', {
...this.#address,
requestId,
type,
payload,
});
timeout = setTimeout(() => {
pendingRequestHandle.dispose();
this.#logger.debug(`Request with ID: ${requestId} timed out`);
reject(new Error('Request timed out'));
}, 10000);
});
}
onRequest(type: Method, handler: Handler): Disposable {
return this.#requestEvents.register(type, (requestId: RequestId, payload: unknown) => {
try {
const result = handler(payload);
this.#runtimeMessageBus.publish('plugin:response', {
...this.#address,
requestId,
type,
success: true,
payload: result,
});
} catch (error) {
this.#logger.error(`Error handling request of type ${type}:`, error as Error);
this.#runtimeMessageBus.publish('plugin:response', {
...this.#address,
requestId,
type,
success: false,
reason: (error as Error).message,
});
}
});
}
dispose(): void {
this.#eventSubscriptions.dispose();
this.#notificationEvents.dispose();
this.#requestEvents.dispose();
this.#pendingResponseEvents.dispose();
}
}
References: |
You are a code assistant | Definition of 'VSCodeBuffer' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export interface VSCodeBuffer {
readonly buffer: Uint8Array;
}
// region: Shared configuration ----------------------------------------
export interface InteropConfig {
projectPath: string;
gitlabUrl: string;
}
// region: API types ---------------------------------------------------
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
export interface PostRequest<_TReturnType> {
type: 'rest';
method: 'POST';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
interface GetRequestBase<_TReturnType> {
method: 'GET';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
searchParams?: Record<string, string>;
headers?: Record<string, string>;
}
export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> {
type: 'rest';
}
export interface GetBufferRequest extends GetRequestBase<Uint8Array> {
type: 'rest-buffer';
}
export interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchFromApi = <_TReturnType>(
request: ApiRequest<_TReturnType>,
) => Promise<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>;
/* API exposed by the Web IDE extension
* See https://code.visualstudio.com/api/references/vscode-api#extensions
*/
export interface WebIDEExtension {
isTelemetryEnabled: () => boolean;
projectPath: string;
gitlabUrl: string;
}
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'redactSecrets' in file src/common/secret_redaction/index.ts in project gitlab-lsp | Definition:
redactSecrets(raw: string): string {
return this.#rules.reduce((redacted: string, rule: IGitleaksRule) => {
return this.#redactRuleSecret(redacted, rule);
}, raw);
}
#redactRuleSecret(str: string, rule: IGitleaksRule): string {
if (!rule.compiledRegex) return str;
if (!this.#keywordHit(rule, str)) {
return str;
}
const matches = [...str.matchAll(rule.compiledRegex)];
return matches.reduce((redacted: string, match: RegExpMatchArray) => {
const secret = match[rule.secretGroup ?? 0];
return redacted.replace(secret, '*'.repeat(secret.length));
}, str);
}
#keywordHit(rule: IGitleaksRule, raw: string) {
if (!rule.keywords?.length) {
return true;
}
for (const keyword of rule.keywords) {
if (raw.toLowerCase().includes(keyword)) {
return true;
}
}
return false;
}
}
References: |
You are a code assistant | Definition of 'setupWebviewRuntime' in file packages/lib_webview/src/setup/setup_webview_runtime.ts in project gitlab-lsp | Definition:
export function setupWebviewRuntime(props: SetupWebviewRuntimeProps): Disposable {
const logger = withPrefix(props.logger, '[Webview]');
logger.debug('Setting up webview runtime');
try {
const runtimeMessageBus = new WebviewRuntimeMessageBus();
const transportDisposable = setupTransports(props.transports, runtimeMessageBus, logger);
const webviewPluginDisposable = setupWebviewPlugins({
runtimeMessageBus,
logger,
plugins: props.plugins,
extensionMessageBusProvider: props.extensionMessageBusProvider,
});
logger.info('Webview runtime setup completed successfully');
return {
dispose: () => {
logger.debug('Disposing webview runtime');
transportDisposable.dispose();
webviewPluginDisposable.dispose();
logger.info('Webview runtime disposed');
},
};
} catch (error) {
props.logger.error(
'Failed to setup webview runtime',
error instanceof Error ? error : undefined,
);
return {
dispose: () => {
logger.debug('Disposing empty webview runtime due to setup failure');
},
};
}
}
References:
- src/node/main.ts:228 |
You are a code assistant | Definition of 'WebviewAddress' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp | Definition:
export type WebviewAddress = {
webviewId: WebviewId;
webviewInstanceId: WebviewInstanceId;
};
export type WebviewRequestInfo = {
requestId: string;
};
export type WebviewEventInfo = {
type: string;
payload?: unknown;
};
export type WebviewInstanceCreatedEventData = WebviewAddress;
export type WebviewInstanceDestroyedEventData = WebviewAddress;
export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo;
export type WebviewInstanceRequestEventData = WebviewAddress &
WebviewEventInfo &
WebviewRequestInfo;
export type SuccessfulResponse = {
success: true;
};
export type FailedResponse = {
success: false;
reason: string;
};
export type WebviewInstanceResponseEventData = WebviewAddress &
WebviewRequestInfo &
WebviewEventInfo &
(SuccessfulResponse | FailedResponse);
export type MessagesToServer = {
webview_instance_created: WebviewInstanceCreatedEventData;
webview_instance_destroyed: WebviewInstanceDestroyedEventData;
webview_instance_notification_received: WebviewInstanceNotificationEventData;
webview_instance_request_received: WebviewInstanceRequestEventData;
webview_instance_response_received: WebviewInstanceResponseEventData;
};
export type MessagesToClient = {
webview_instance_notification: WebviewInstanceNotificationEventData;
webview_instance_request: WebviewInstanceRequestEventData;
webview_instance_response: WebviewInstanceResponseEventData;
};
export interface TransportMessageHandler<T> {
(payload: T): void;
}
export interface TransportListener {
on<K extends keyof MessagesToServer>(
type: K,
callback: TransportMessageHandler<MessagesToServer[K]>,
): Disposable;
}
export interface TransportPublisher {
publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void>;
}
export interface Transport extends TransportListener, TransportPublisher {}
References:
- packages/lib_webview/src/setup/plugin/utils/filters.ts:10
- packages/lib_webview/src/setup/plugin/webview_controller.test.ts:15
- packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:16
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:18
- packages/lib_webview/src/events/webview_runtime_message_bus.ts:31
- packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:12
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:8
- packages/lib_webview/src/setup/plugin/webview_controller.test.ts:175
- packages/lib_webview/src/events/webview_runtime_message_bus.ts:30
- packages/lib_webview/src/setup/plugin/webview_controller.test.ts:219
- packages/lib_webview/src/setup/plugin/webview_controller.ts:112
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:331
- packages/lib_webview/src/setup/plugin/webview_controller.ts:21
- packages/lib_webview/src/setup/plugin/webview_controller.ts:88
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:15
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:33
- packages/lib_webview/src/setup/plugin/setup_plugins.ts:30 |
You are a code assistant | Definition of 'fetchBufferFromApi' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>;
/* API exposed by the Web IDE extension
* See https://code.visualstudio.com/api/references/vscode-api#extensions
*/
export interface WebIDEExtension {
isTelemetryEnabled: () => boolean;
projectPath: string;
gitlabUrl: string;
}
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'waitMs' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp | Definition:
export const waitMs = (msToWait: number) =>
new Promise((resolve) => {
setTimeout(resolve, msToWait);
});
/* CompletionRequest represents LS client's request for either completion or inlineCompletion */
export interface CompletionRequest {
textDocument: TextDocumentIdentifier;
position: Position;
token: CancellationToken;
inlineCompletionContext?: InlineCompletionContext;
}
export class DefaultSuggestionService {
readonly #suggestionClientPipeline: SuggestionClientPipeline;
#configService: ConfigService;
#api: GitLabApiClient;
#tracker: TelemetryTracker;
#connection: Connection;
#documentTransformerService: DocumentTransformerService;
#circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests');
#subscriptions: Disposable[] = [];
#suggestionsCache: SuggestionsCache;
#treeSitterParser: TreeSitterParser;
#duoProjectAccessChecker: DuoProjectAccessChecker;
#featureFlagService: FeatureFlagService;
#postProcessorPipeline = new PostProcessorPipeline();
constructor({
telemetryTracker,
configService,
api,
connection,
documentTransformerService,
featureFlagService,
treeSitterParser,
duoProjectAccessChecker,
}: SuggestionServiceOptions) {
this.#configService = configService;
this.#api = api;
this.#tracker = telemetryTracker;
this.#connection = connection;
this.#documentTransformerService = documentTransformerService;
this.#suggestionsCache = new SuggestionsCache(this.#configService);
this.#treeSitterParser = treeSitterParser;
this.#featureFlagService = featureFlagService;
const suggestionClient = new FallbackClient(
new DirectConnectionClient(this.#api, this.#configService),
new DefaultSuggestionClient(this.#api),
);
this.#suggestionClientPipeline = new SuggestionClientPipeline([
clientToMiddleware(suggestionClient),
createTreeSitterMiddleware({
treeSitterParser,
getIntentFn: getIntent,
}),
]);
this.#subscribeToCircuitBreakerEvents();
this.#duoProjectAccessChecker = duoProjectAccessChecker;
}
completionHandler = async (
{ textDocument, position }: CompletionParams,
token: CancellationToken,
): Promise<CompletionItem[]> => {
log.debug('Completion requested');
const suggestionOptions = await this.#getSuggestionOptions({ textDocument, position, token });
if (suggestionOptions.find(isStream)) {
log.warn(
`Completion response unexpectedly contained streaming response. Streaming for completion is not supported. Please report this issue.`,
);
}
return completionOptionMapper(suggestionOptions.filter(isTextSuggestion));
};
#getSuggestionOptions = async (
request: CompletionRequest,
): Promise<SuggestionOptionOrStream[]> => {
const { textDocument, position, token, inlineCompletionContext: context } = request;
const suggestionContext = this.#documentTransformerService.getContext(
textDocument.uri,
position,
this.#configService.get('client.workspaceFolders') ?? [],
context,
);
if (!suggestionContext) {
return [];
}
const cachedSuggestions = this.#useAndTrackCachedSuggestions(
textDocument,
position,
suggestionContext,
context?.triggerKind,
);
if (context?.triggerKind === InlineCompletionTriggerKind.Invoked) {
const options = await this.#handleNonStreamingCompletion(request, suggestionContext);
options.unshift(...(cachedSuggestions ?? []));
(cachedSuggestions ?? []).forEach((cs) =>
this.#tracker.updateCodeSuggestionsContext(cs.uniqueTrackingId, {
optionsCount: options.length,
}),
);
return options;
}
if (cachedSuggestions) {
return cachedSuggestions;
}
// debounce
await waitMs(SUGGESTIONS_DEBOUNCE_INTERVAL_MS);
if (token.isCancellationRequested) {
log.debug('Debounce triggered for completion');
return [];
}
if (
context &&
shouldRejectCompletionWithSelectedCompletionTextMismatch(
context,
this.#documentTransformerService.get(textDocument.uri),
)
) {
return [];
}
const additionalContexts = await this.#getAdditionalContexts(suggestionContext);
// right now we only support streaming for inlineCompletion
// if the context is present, we know we are handling inline completion
if (
context &&
this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.StreamCodeGenerations)
) {
const intentResolution = await this.#getIntent(suggestionContext);
if (intentResolution?.intent === 'generation') {
return this.#handleStreamingInlineCompletion(
suggestionContext,
intentResolution.commentForCursor?.content,
intentResolution.generationType,
additionalContexts,
);
}
}
return this.#handleNonStreamingCompletion(request, suggestionContext, additionalContexts);
};
inlineCompletionHandler = async (
params: InlineCompletionParams,
token: CancellationToken,
): Promise<InlineCompletionList> => {
log.debug('Inline completion requested');
const options = await this.#getSuggestionOptions({
textDocument: params.textDocument,
position: params.position,
token,
inlineCompletionContext: params.context,
});
return inlineCompletionOptionMapper(params, options);
};
async #handleStreamingInlineCompletion(
context: IDocContext,
userInstruction?: string,
generationType?: GenerationType,
additionalContexts?: AdditionalContext[],
): Promise<StartStreamOption[]> {
if (this.#circuitBreaker.isOpen()) {
log.warn('Stream was not started as the circuit breaker is open.');
return [];
}
const streamId = uniqueId('code-suggestion-stream-');
const uniqueTrackingId = generateUniqueTrackingId();
setTimeout(() => {
log.debug(`Starting to stream (id: ${streamId})`);
const streamingHandler = new DefaultStreamingHandler({
api: this.#api,
circuitBreaker: this.#circuitBreaker,
connection: this.#connection,
documentContext: context,
parser: this.#treeSitterParser,
postProcessorPipeline: this.#postProcessorPipeline,
streamId,
tracker: this.#tracker,
uniqueTrackingId,
userInstruction,
generationType,
additionalContexts,
});
streamingHandler.startStream().catch((e: Error) => log.error('Failed to start streaming', e));
}, 0);
return [{ streamId, uniqueTrackingId }];
}
async #handleNonStreamingCompletion(
request: CompletionRequest,
documentContext: IDocContext,
additionalContexts?: AdditionalContext[],
): Promise<SuggestionOption[]> {
const uniqueTrackingId: string = generateUniqueTrackingId();
try {
return await this.#getSuggestions({
request,
uniqueTrackingId,
documentContext,
additionalContexts,
});
} catch (e) {
if (isFetchError(e)) {
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: e.status });
}
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED);
this.#circuitBreaker.error();
log.error('Failed to get code suggestions!', e);
return [];
}
}
/**
* FIXME: unify how we get code completion and generation
* so we don't have duplicate intent detection (see `tree_sitter_middleware.ts`)
* */
async #getIntent(context: IDocContext): Promise<IntentResolution | undefined> {
try {
const treeAndLanguage = await this.#treeSitterParser.parseFile(context);
if (!treeAndLanguage) {
return undefined;
}
return await getIntent({
treeAndLanguage,
position: context.position,
prefix: context.prefix,
suffix: context.suffix,
});
} catch (error) {
log.error('Failed to parse with tree sitter', error);
return undefined;
}
}
#trackShowIfNeeded(uniqueTrackingId: string) {
if (
!canClientTrackEvent(
this.#configService.get('client.telemetry.actions'),
TRACKING_EVENTS.SHOWN,
)
) {
/* If the Client can detect when the suggestion is shown in the IDE, it will notify the Server.
Otherwise the server will assume that returned suggestions are shown and tracks the event */
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN);
}
}
async #getSuggestions({
request,
uniqueTrackingId,
documentContext,
additionalContexts,
}: {
request: CompletionRequest;
uniqueTrackingId: string;
documentContext: IDocContext;
additionalContexts?: AdditionalContext[];
}): Promise<SuggestionOption[]> {
const { textDocument, position, token } = request;
const triggerKind = request.inlineCompletionContext?.triggerKind;
log.info('Suggestion requested.');
if (this.#circuitBreaker.isOpen()) {
log.warn('Code suggestions were not requested as the circuit breaker is open.');
return [];
}
if (!this.#configService.get('client.token')) {
return [];
}
// Do not send a suggestion if content is less than 10 characters
const contentLength =
(documentContext?.prefix?.length || 0) + (documentContext?.suffix?.length || 0);
if (contentLength < 10) {
return [];
}
if (!isAtOrNearEndOfLine(documentContext.suffix)) {
return [];
}
// Creates the suggestion and tracks suggestion_requested
this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
triggerKind,
additionalContexts,
});
/** how many suggestion options should we request from the API */
const optionsCount: OptionsCount =
triggerKind === InlineCompletionTriggerKind.Invoked ? MANUAL_REQUEST_OPTIONS_COUNT : 1;
const suggestionsResponse = await this.#suggestionClientPipeline.getSuggestions({
document: documentContext,
projectPath: this.#configService.get('client.projectPath'),
optionsCount,
additionalContexts,
});
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, {
model: suggestionsResponse?.model,
status: suggestionsResponse?.status,
optionsCount: suggestionsResponse?.choices?.length,
isDirectConnection: suggestionsResponse?.isDirectConnection,
});
if (suggestionsResponse?.error) {
throw new Error(suggestionsResponse.error);
}
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED);
this.#circuitBreaker.success();
const areSuggestionsNotProvided =
!suggestionsResponse?.choices?.length ||
suggestionsResponse?.choices.every(({ text }) => !text?.length);
const suggestionOptions = (suggestionsResponse?.choices || []).map((choice, index) => ({
...choice,
index,
uniqueTrackingId,
lang: suggestionsResponse?.model?.lang,
}));
const processedChoices = await this.#postProcessorPipeline.run({
documentContext,
input: suggestionOptions,
type: 'completion',
});
this.#suggestionsCache.addToSuggestionCache({
request: {
document: textDocument,
position,
context: documentContext,
additionalContexts,
},
suggestions: processedChoices,
});
if (token.isCancellationRequested) {
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED);
return [];
}
if (areSuggestionsNotProvided) {
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED);
return [];
}
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { suggestionOptions });
this.#trackShowIfNeeded(uniqueTrackingId);
return processedChoices;
}
dispose() {
this.#subscriptions.forEach((subscription) => subscription?.dispose());
}
#subscribeToCircuitBreakerEvents() {
this.#subscriptions.push(
this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)),
);
this.#subscriptions.push(
this.#circuitBreaker.onClose(() =>
this.#connection.sendNotification(API_RECOVERY_NOTIFICATION),
),
);
}
#useAndTrackCachedSuggestions(
textDocument: TextDocumentIdentifier,
position: Position,
documentContext: IDocContext,
triggerKind?: InlineCompletionTriggerKind,
): SuggestionOption[] | undefined {
const suggestionsCache = this.#suggestionsCache.getCachedSuggestions({
document: textDocument,
position,
context: documentContext,
});
if (suggestionsCache?.options?.length) {
const { uniqueTrackingId, lang } = suggestionsCache.options[0];
const { additionalContexts } = suggestionsCache;
this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
source: SuggestionSource.cache,
triggerKind,
suggestionOptions: suggestionsCache?.options,
language: lang,
additionalContexts,
});
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED);
this.#trackShowIfNeeded(uniqueTrackingId);
return suggestionsCache.options.map((option, index) => ({ ...option, index }));
}
return undefined;
}
async #getAdditionalContexts(documentContext: IDocContext): Promise<AdditionalContext[]> {
let additionalContexts: AdditionalContext[] = [];
const advancedContextEnabled = shouldUseAdvancedContext(
this.#featureFlagService,
this.#configService,
);
if (advancedContextEnabled) {
const advancedContext = await getAdvancedContext({
documentContext,
dependencies: { duoProjectAccessChecker: this.#duoProjectAccessChecker },
});
additionalContexts = advancedContextToRequestBody(advancedContext);
}
return additionalContexts;
}
}
References:
- src/common/suggestion/suggestion_service.ts:232 |
You are a code assistant | Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp | Definition:
def greet(self):
print(f"Hello {self.name}")
class Greet3:
pass
def greet3(name):
...
class Greet4:
def __init__(self, name):
...
def greet(self):
...
class Greet3:
...
def greet3(name):
class Greet4:
def __init__(self, name):
def greet(self):
class Greet3:
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:1
- src/tests/fixtures/intent/ruby_comments.rb:21
- src/tests/fixtures/intent/empty_function/ruby.rb:20
- src/tests/fixtures/intent/empty_function/ruby.rb:29 |
You are a code assistant | Definition of 'SuggestionCacheContext' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp | Definition:
export type SuggestionCacheContext = {
document: TextDocumentIdentifier;
context: IDocContext;
position: Position;
additionalContexts?: AdditionalContext[];
};
export type SuggestionCache = {
options: SuggestionOption[];
additionalContexts?: AdditionalContext[];
};
function isNonEmptyLine(s: string) {
return s.trim().length > 0;
}
type Required<T> = {
[P in keyof T]-?: T[P];
};
const DEFAULT_CONFIG: Required<ISuggestionsCacheOptions> = {
enabled: true,
maxSize: 1024 * 1024,
ttl: 60 * 1000,
prefixLines: 1,
suffixLines: 1,
};
export class SuggestionsCache {
#cache: LRUCache<string, SuggestionCacheEntry>;
#configService: ConfigService;
constructor(configService: ConfigService) {
this.#configService = configService;
const currentConfig = this.#getCurrentConfig();
this.#cache = new LRUCache<string, SuggestionCacheEntry>({
ttlAutopurge: true,
sizeCalculation: (value, key) =>
value.suggestions.reduce((acc, suggestion) => acc + suggestion.text.length, 0) + key.length,
...DEFAULT_CONFIG,
...currentConfig,
ttl: Number(currentConfig.ttl),
});
}
#getCurrentConfig(): Required<ISuggestionsCacheOptions> {
return {
...DEFAULT_CONFIG,
...(this.#configService.get('client.suggestionsCache') ?? {}),
};
}
#getSuggestionKey(ctx: SuggestionCacheContext) {
const prefixLines = ctx.context.prefix.split('\n');
const currentLine = prefixLines.pop() ?? '';
const indentation = (currentLine.match(/^\s*/)?.[0] ?? '').length;
const config = this.#getCurrentConfig();
const cachedPrefixLines = prefixLines
.filter(isNonEmptyLine)
.slice(-config.prefixLines)
.join('\n');
const cachedSuffixLines = ctx.context.suffix
.split('\n')
.filter(isNonEmptyLine)
.slice(0, config.suffixLines)
.join('\n');
return [
ctx.document.uri,
ctx.position.line,
cachedPrefixLines,
cachedSuffixLines,
indentation,
].join(':');
}
#increaseCacheEntryRetrievedCount(suggestionKey: string, character: number) {
const item = this.#cache.get(suggestionKey);
if (item && item.timesRetrievedByPosition) {
item.timesRetrievedByPosition[character] =
(item.timesRetrievedByPosition[character] ?? 0) + 1;
}
}
addToSuggestionCache(config: {
request: SuggestionCacheContext;
suggestions: SuggestionOption[];
}) {
if (!this.#getCurrentConfig().enabled) {
return;
}
const currentLine = config.request.context.prefix.split('\n').at(-1) ?? '';
this.#cache.set(this.#getSuggestionKey(config.request), {
character: config.request.position.character,
suggestions: config.suggestions,
currentLine,
timesRetrievedByPosition: {},
additionalContexts: config.request.additionalContexts,
});
}
getCachedSuggestions(request: SuggestionCacheContext): SuggestionCache | undefined {
if (!this.#getCurrentConfig().enabled) {
return undefined;
}
const currentLine = request.context.prefix.split('\n').at(-1) ?? '';
const key = this.#getSuggestionKey(request);
const candidate = this.#cache.get(key);
if (!candidate) {
return undefined;
}
const { character } = request.position;
if (candidate.timesRetrievedByPosition[character] > 0) {
// If cache has already returned this suggestion from the same position before, discard it.
this.#cache.delete(key);
return undefined;
}
this.#increaseCacheEntryRetrievedCount(key, character);
const options = candidate.suggestions
.map((s) => {
const currentLength = currentLine.length;
const previousLength = candidate.currentLine.length;
const diff = currentLength - previousLength;
if (diff < 0) {
return null;
}
if (
currentLine.slice(0, previousLength) !== candidate.currentLine ||
s.text.slice(0, diff) !== currentLine.slice(previousLength)
) {
return null;
}
return {
...s,
text: s.text.slice(diff),
uniqueTrackingId: generateUniqueTrackingId(),
};
})
.filter((x): x is SuggestionOption => Boolean(x));
return {
options,
additionalContexts: candidate.additionalContexts,
};
}
}
References:
- src/common/suggestion/suggestions_cache.ts:126
- src/common/suggestion/suggestions_cache.test.ts:16
- src/common/suggestion/suggestions_cache.ts:73
- src/common/suggestion/suggestions_cache.ts:109 |
You are a code assistant | Definition of '_DeepPartial' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_partial.ts in project gitlab-lsp | Definition:
type _DeepPartial<T> = T extends Function
? T
: T extends Array<infer U>
? _DeepPartialArray<U>
: T extends object
? // eslint-disable-next-line no-use-before-define
DeepPartial<T>
: T | undefined;
type DeepPartial<T> = { [P in keyof T]?: _DeepPartial<T[P]> };
export const createFakePartial = <T>(x: DeepPartial<T>): T => x as T;
References: |
You are a code assistant | Definition of 'GITLAB_DEVELOPMENT_URL' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp | Definition:
export const GITLAB_DEVELOPMENT_URL: string = 'http://localhost';
export enum GitLabEnvironment {
GITLAB_COM = 'production',
GITLAB_STAGING = 'staging',
GITLAB_ORG = 'org',
GITLAB_DEVELOPMENT = 'development',
GITLAB_SELF_MANAGED = 'self-managed',
}
export class GitLabPlatformManagerForChat {
readonly #platformManager: GitLabPlatformManager;
constructor(platformManager: GitLabPlatformManager) {
this.#platformManager = platformManager;
}
async getProjectGqlId(): Promise<string | undefined> {
const projectManager = await this.#platformManager.getForActiveProject(false);
return projectManager?.project.gqlId;
}
/**
* Obtains a GitLab Platform to send API requests to the GitLab API
* for the Duo Chat feature.
*
* - It returns a GitLabPlatformForAccount for the first linked account.
* - It returns undefined if there are no accounts linked
*/
async getGitLabPlatform(): Promise<GitLabPlatformForAccount | undefined> {
const platforms = await this.#platformManager.getForAllAccounts();
if (!platforms.length) {
return undefined;
}
let platform: GitLabPlatformForAccount | undefined;
// Using a for await loop in this context because we want to stop
// evaluating accounts as soon as we find one with code suggestions enabled
for await (const result of platforms.map(getChatSupport)) {
if (result.hasSupportForChat) {
platform = result.platform;
break;
}
}
return platform;
}
async getGitLabEnvironment(): Promise<GitLabEnvironment> {
const platform = await this.getGitLabPlatform();
const instanceUrl = platform?.account.instanceUrl;
switch (instanceUrl) {
case GITLAB_COM_URL:
return GitLabEnvironment.GITLAB_COM;
case GITLAB_DEVELOPMENT_URL:
return GitLabEnvironment.GITLAB_DEVELOPMENT;
case GITLAB_STAGING_URL:
return GitLabEnvironment.GITLAB_STAGING;
case GITLAB_ORG_URL:
return GitLabEnvironment.GITLAB_ORG;
default:
return GitLabEnvironment.GITLAB_SELF_MANAGED;
}
}
}
References: |
You are a code assistant | Definition of 'connectToCable' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp | Definition:
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:
- src/common/action_cable.test.ts:32
- src/common/action_cable.test.ts:21
- src/common/action_cable.test.ts:40
- src/common/api.ts:348
- src/common/action_cable.test.ts:54 |
You are a code assistant | Definition of 'error' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp | Definition:
error() {
this.#errorCount += 1;
if (this.#errorCount >= this.#maxErrorsBeforeBreaking) {
this.#open();
}
}
#open() {
this.#state = CircuitBreakerState.OPEN;
log.warn(
`Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#breakTimeMs / 1000} second(s).`,
);
this.#timeoutId = setTimeout(() => this.#close(), this.#breakTimeMs);
this.#eventEmitter.emit('open');
}
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:
- 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 'messageBus' in file packages/webview_duo_chat/src/app/message_bus.ts in project gitlab-lsp | Definition:
export const messageBus = resolveMessageBus<{
inbound: Messages['pluginToWebview'];
outbound: Messages['webviewToPlugin'];
}>({
webviewId: WEBVIEW_ID,
});
References: |
You are a code assistant | Definition of 'DefaultDocumentService' in file src/common/document_service.ts in project gitlab-lsp | Definition:
export class DefaultDocumentService
implements DocumentService, HandlesNotification<DidChangeDocumentInActiveEditorParams>
{
#subscriptions: Disposable[] = [];
#emitter = new EventEmitter();
#documents: TextDocuments<TextDocument>;
constructor(documents: TextDocuments<TextDocument>) {
this.#documents = documents;
this.#subscriptions.push(
documents.onDidOpen(this.#createMediatorListener(TextDocumentChangeListenerType.onDidOpen)),
);
documents.onDidChangeContent(
this.#createMediatorListener(TextDocumentChangeListenerType.onDidChangeContent),
);
documents.onDidClose(this.#createMediatorListener(TextDocumentChangeListenerType.onDidClose));
documents.onDidSave(this.#createMediatorListener(TextDocumentChangeListenerType.onDidSave));
}
notificationHandler = (param: DidChangeDocumentInActiveEditorParams) => {
const document = isTextDocument(param) ? param : this.#documents.get(param);
if (!document) {
log.error(`Active editor document cannot be retrieved by URL: ${param}`);
return;
}
const event: TextDocumentChangeEvent<TextDocument> = { document };
this.#emitter.emit(
DOCUMENT_CHANGE_EVENT_NAME,
event,
TextDocumentChangeListenerType.onDidSetActive,
);
};
#createMediatorListener =
(type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent<TextDocument>) => {
this.#emitter.emit(DOCUMENT_CHANGE_EVENT_NAME, event, type);
};
onDocumentChange(listener: TextDocumentChangeListener) {
this.#emitter.on(DOCUMENT_CHANGE_EVENT_NAME, listener);
return {
dispose: () => this.#emitter.removeListener(DOCUMENT_CHANGE_EVENT_NAME, listener),
};
}
}
References:
- src/common/document_service.test.ts:54
- src/common/document_service.test.ts:18
- src/common/document_service.test.ts:34
- src/browser/main.ts:76
- src/common/document_service.test.ts:50
- src/node/main.ts:117 |
You are a code assistant | Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp | Definition:
def greet(name):
pass
def greet2(name):
print(name)
class Greet:
def __init__(self, name):
pass
def greet(self):
pass
class Greet2:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello {self.name}")
class Greet3:
pass
def greet3(name):
...
class Greet4:
def __init__(self, name):
...
def greet(self):
...
class Greet3:
...
def greet3(name):
class Greet4:
def __init__(self, name):
def greet(self):
class Greet3:
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:29
- src/tests/fixtures/intent/empty_function/ruby.rb:1
- src/tests/fixtures/intent/ruby_comments.rb:21
- src/tests/fixtures/intent/empty_function/ruby.rb:20 |
You are a code assistant | Definition of 'PersonalAccessToken' in file src/common/api.ts in project gitlab-lsp | Definition:
export interface PersonalAccessToken {
name: string;
scopes: string[];
active: boolean;
}
export interface OAuthToken {
scope: string[];
}
export interface TokenCheckResponse {
valid: boolean;
reason?: 'unknown' | 'not_active' | 'invalid_scopes';
message?: string;
}
export interface IDirectConnectionDetailsHeaders {
'X-Gitlab-Global-User-Id': string;
'X-Gitlab-Instance-Id': string;
'X-Gitlab-Host-Name': string;
'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string;
}
export interface IDirectConnectionModelDetails {
model_provider: string;
model_name: string;
}
export interface IDirectConnectionDetails {
base_url: string;
token: string;
expires_at: number;
headers: IDirectConnectionDetailsHeaders;
model_details: IDirectConnectionModelDetails;
}
const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured';
@Injectable(GitLabApiClient, [LsFetch, ConfigService])
export class GitLabAPI implements GitLabApiClient {
#token: string | undefined;
#baseURL: string;
#clientInfo?: IClientInfo;
#lsFetch: LsFetch;
#eventEmitter = new EventEmitter();
#configService: ConfigService;
#instanceVersion?: string;
constructor(lsFetch: LsFetch, configService: ConfigService) {
this.#baseURL = GITLAB_API_BASE_URL;
this.#lsFetch = lsFetch;
this.#configService = configService;
this.#configService.onConfigChange(async (config) => {
this.#clientInfo = configService.get('client.clientInfo');
this.#lsFetch.updateAgentOptions({
ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false,
...(this.#configService.get('client.httpAgentOptions') ?? {}),
});
await this.configureApi(config.client);
});
}
onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable {
this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener);
return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) };
}
#fireApiReconfigured(isInValidState: boolean, validationMessage?: string) {
const data: ApiReconfiguredData = { isInValidState, validationMessage };
this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data);
}
async configureApi({
token,
baseUrl = GITLAB_API_BASE_URL,
}: {
token?: string;
baseUrl?: string;
}) {
if (this.#token === token && this.#baseURL === baseUrl) return;
this.#token = token;
this.#baseURL = baseUrl;
const { valid, reason, message } = await this.checkToken(this.#token);
let validationMessage;
if (!valid) {
this.#configService.set('client.token', undefined);
validationMessage = `Token is invalid. ${message}. Reason: ${reason}`;
log.warn(validationMessage);
} else {
log.info('Token is valid');
}
this.#instanceVersion = await this.#getGitLabInstanceVersion();
this.#fireApiReconfigured(valid, validationMessage);
}
#looksLikePatToken(token: string): boolean {
// OAuth tokens will be longer than 42 characters and PATs will be shorter.
return token.length < 42;
}
async #checkPatToken(token: string): Promise<TokenCheckResponse> {
const headers = this.#getDefaultHeaders(token);
const response = await this.#lsFetch.get(
`${this.#baseURL}/api/v4/personal_access_tokens/self`,
{ headers },
);
await handleFetchError(response, 'Information about personal access token');
const { active, scopes } = (await response.json()) as PersonalAccessToken;
if (!active) {
return {
valid: false,
reason: 'not_active',
message: 'Token is not active.',
};
}
if (!this.#hasValidScopes(scopes)) {
const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', ');
return {
valid: false,
reason: 'invalid_scopes',
message: `Token has scope(s) ${joinedScopes} (needs 'api').`,
};
}
return { valid: true };
}
async #checkOAuthToken(token: string): Promise<TokenCheckResponse> {
const headers = this.#getDefaultHeaders(token);
const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, {
headers,
});
await handleFetchError(response, 'Information about OAuth token');
const { scope: scopes } = (await response.json()) as OAuthToken;
if (!this.#hasValidScopes(scopes)) {
const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', ');
return {
valid: false,
reason: 'invalid_scopes',
message: `Token has scope(s) ${joinedScopes} (needs 'api').`,
};
}
return { valid: true };
}
async checkToken(token: string = ''): Promise<TokenCheckResponse> {
try {
if (this.#looksLikePatToken(token)) {
log.info('Checking token for PAT validity');
return await this.#checkPatToken(token);
}
log.info('Checking token for OAuth validity');
return await this.#checkOAuthToken(token);
} catch (err) {
log.error('Error performing token check', err);
return {
valid: false,
reason: 'unknown',
message: `Failed to check token: ${err}`,
};
}
}
#hasValidScopes(scopes: string[]): boolean {
return scopes.includes('api');
}
async getCodeSuggestions(
request: CodeSuggestionRequest,
): Promise<CodeSuggestionResponse | undefined> {
if (!this.#token) {
throw new Error('Token needs to be provided to request Code Suggestions');
}
const headers = {
...this.#getDefaultHeaders(this.#token),
'Content-Type': 'application/json',
};
const response = await this.#lsFetch.post(
`${this.#baseURL}/api/v4/code_suggestions/completions`,
{ headers, body: JSON.stringify(request) },
);
await handleFetchError(response, 'Code Suggestions');
const data = await response.json();
return { ...data, status: response.status };
}
async *getStreamingCodeSuggestions(
request: CodeSuggestionRequest,
): AsyncGenerator<string, void, void> {
if (!this.#token) {
throw new Error('Token needs to be provided to stream code suggestions');
}
const headers = {
...this.#getDefaultHeaders(this.#token),
'Content-Type': 'application/json',
};
yield* this.#lsFetch.streamFetch(
`${this.#baseURL}/api/v4/code_suggestions/completions`,
JSON.stringify(request),
headers,
);
}
async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> {
if (!this.#token) {
return Promise.reject(new Error('Token needs to be provided to authorise API request.'));
}
if (
request.supportedSinceInstanceVersion &&
!this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version)
) {
return Promise.reject(
new InvalidInstanceVersionError(
`Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`,
),
);
}
if (request.type === 'graphql') {
return this.#graphqlRequest(request.query, request.variables);
}
switch (request.method) {
case 'GET':
return this.#fetch(request.path, request.searchParams, 'resource', request.headers);
case 'POST':
return this.#postFetch(request.path, 'resource', request.body, request.headers);
default:
// the type assertion is necessary because TS doesn't expect any other types
throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`);
}
}
async connectToCable(): Promise<ActionCableCable> {
const headers = this.#getDefaultHeaders(this.#token);
const websocketOptions = {
headers: {
...headers,
Origin: this.#baseURL,
},
};
return connectToCable(this.#baseURL, websocketOptions);
}
async #graphqlRequest<T = unknown, V extends Variables = Variables>(
document: RequestDocument,
variables?: V,
): Promise<T> {
const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/');
const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab"
const graphqlFetch = async (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> => {
const url = input instanceof URL ? input.toString() : input;
return this.#lsFetch.post(url, {
...init,
headers: { ...headers, ...init?.headers },
});
};
const headers = this.#getDefaultHeaders(this.#token);
const client = new GraphQLClient(endpoint, {
headers,
fetch: graphqlFetch,
});
return client.request(document, variables);
}
async #fetch<T>(
apiResourcePath: string,
query: Record<string, QueryValue> = {},
resourceName = 'resource',
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`;
const result = await this.#lsFetch.get(url, {
headers: { ...this.#getDefaultHeaders(this.#token), ...headers },
});
await handleFetchError(result, resourceName);
return result.json() as Promise<T>;
}
async #postFetch<T>(
apiResourcePath: string,
resourceName = 'resource',
body?: unknown,
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}`;
const response = await this.#lsFetch.post(url, {
headers: {
'Content-Type': 'application/json',
...this.#getDefaultHeaders(this.#token),
...headers,
},
body: JSON.stringify(body),
});
await handleFetchError(response, resourceName);
return response.json() as Promise<T>;
}
#getDefaultHeaders(token?: string) {
return {
Authorization: `Bearer ${token}`,
'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`,
'X-Gitlab-Language-Server-Version': getLanguageServerVersion(),
};
}
#instanceVersionHigherOrEqualThen(version: string): boolean {
if (!this.#instanceVersion) return false;
return semverCompare(this.#instanceVersion, version) >= 0;
}
async #getGitLabInstanceVersion(): Promise<string> {
if (!this.#token) {
return '';
}
const headers = this.#getDefaultHeaders(this.#token);
const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, {
headers,
});
const { version } = await response.json();
return version;
}
get instanceVersion() {
return this.#instanceVersion;
}
}
References: |
You are a code assistant | Definition of 'processNewUserPrompt' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp | Definition:
async processNewUserPrompt(
question: string,
subscriptionId?: string,
currentFileContext?: GitLabChatFileContext,
): Promise<AiActionResponseType> {
return this.#sendAiAction({
question,
currentFileContext,
clientSubscriptionId: subscriptionId,
});
}
async pullAiMessage(requestId: string, role: string): Promise<AiMessage> {
const response = await pullHandler(() => this.#getAiMessage(requestId, role));
if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']);
return successResponse(response);
}
async cleanChat(): Promise<AiActionResponseType> {
return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN });
}
async #currentPlatform() {
const platform = await this.#manager.getGitLabPlatform();
if (!platform) throw new Error('Platform is missing!');
return platform;
}
async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> {
const request: GraphQLRequest<AiMessagesResponseType> = {
type: 'graphql',
query: AI_MESSAGES_QUERY,
variables: { requestIds: [requestId], roles: [role.toUpperCase()] },
};
const platform = await this.#currentPlatform();
const history = await platform.fetchFromApi(request);
return history.aiMessages.nodes[0];
}
async subscribeToUpdates(
messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>,
subscriptionId?: string,
) {
const platform = await this.#currentPlatform();
const channel = new AiCompletionResponseChannel({
htmlResponse: true,
userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`,
aiAction: 'CHAT',
clientSubscriptionId: subscriptionId,
});
const cable = await platform.connectToCable();
// we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397
// sometimes a chunk comes after the full message and it broke the chat
let fullMessageReceived = false;
channel.on('newChunk', async (msg) => {
if (fullMessageReceived) {
log.info(`CHAT-DEBUG: full message received, ignoring chunk`);
return;
}
await messageCallback(msg);
});
channel.on('fullMessage', async (message) => {
fullMessageReceived = true;
await messageCallback(message);
if (subscriptionId) {
cable.disconnect();
}
});
cable.subscribe(channel);
}
async #sendAiAction(variables: object): Promise<AiActionResponseType> {
const platform = await this.#currentPlatform();
const { query, defaultVariables } = await this.#actionQuery();
const projectGqlId = await this.#manager.getProjectGqlId();
const request: GraphQLRequest<AiActionResponseType> = {
type: 'graphql',
query,
variables: {
...variables,
...defaultVariables,
resourceId: projectGqlId ?? null,
},
};
return platform.fetchFromApi(request);
}
async #actionQuery(): Promise<ChatInputTemplate> {
if (!this.#cachedActionQuery) {
const platform = await this.#currentPlatform();
try {
const { version } = await platform.fetchFromApi(versionRequest);
this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>(
version,
MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION,
() => CHAT_INPUT_TEMPLATE_17_3_AND_LATER,
() => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER,
);
} catch (e) {
log.debug(`GitLab version check for sending chat failed:`, e as Error);
this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER;
}
}
return this.#cachedActionQuery;
}
}
References: |
You are a code assistant | Definition of 'details' in file src/common/fetch_error.ts in project gitlab-lsp | Definition:
get details() {
const { message, stack } = this;
return {
message,
stack: stackToArray(stack),
response: {
status: this.response.status,
headers: this.response.headers,
body: this.#body,
},
};
}
}
export class TimeoutError extends Error {
constructor(url: URL | RequestInfo) {
const timeoutInSeconds = Math.round(REQUEST_TIMEOUT_MILLISECONDS / 1000);
super(
`Request to ${extractURL(url)} timed out after ${timeoutInSeconds} second${timeoutInSeconds === 1 ? '' : 's'}`,
);
}
}
export class InvalidInstanceVersionError extends Error {}
References: |
You are a code assistant | Definition of 'DuoProjectStatus' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp | Definition:
export enum DuoProjectStatus {
DuoEnabled = 'duo-enabled',
DuoDisabled = 'duo-disabled',
NonGitlabProject = 'non-gitlab-project',
}
export interface DuoProjectAccessChecker {
checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus;
}
export const DuoProjectAccessChecker =
createInterfaceId<DuoProjectAccessChecker>('DuoProjectAccessChecker');
@Injectable(DuoProjectAccessChecker, [DuoProjectAccessCache])
export class DefaultDuoProjectAccessChecker {
#projectAccessCache: DuoProjectAccessCache;
constructor(projectAccessCache: DuoProjectAccessCache) {
this.#projectAccessCache = projectAccessCache;
}
/**
* Check if Duo features are enabled for a given DocumentUri.
*
* We match the DocumentUri to the project with the longest path.
* The enabled projects come from the `DuoProjectAccessCache`.
*
* @reference `DocumentUri` is the URI of the document to check. Comes from
* the `TextDocument` object.
*/
checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus {
const projects = this.#projectAccessCache.getProjectsForWorkspaceFolder(workspaceFolder);
if (projects.length === 0) {
return DuoProjectStatus.NonGitlabProject;
}
const project = this.#findDeepestProjectByPath(uri, projects);
if (!project) {
return DuoProjectStatus.NonGitlabProject;
}
return project.enabled ? DuoProjectStatus.DuoEnabled : DuoProjectStatus.DuoDisabled;
}
#findDeepestProjectByPath(uri: string, projects: DuoProject[]): DuoProject | undefined {
let deepestProject: DuoProject | undefined;
for (const project of projects) {
if (uri.startsWith(project.uri.replace('.git/config', ''))) {
if (!deepestProject || project.uri.length > deepestProject.uri.length) {
deepestProject = project;
}
}
}
return deepestProject;
}
}
References:
- src/common/services/duo_access/project_access_checker.ts:12
- src/common/services/duo_access/project_access_checker.ts:35 |
You are a code assistant | Definition of 'setupWebviewPluginsProps' in file packages/lib_webview/src/setup/plugin/setup_plugins.ts in project gitlab-lsp | Definition:
type setupWebviewPluginsProps = {
plugins: WebviewPlugin[];
extensionMessageBusProvider: ExtensionMessageBusProvider;
logger: Logger;
runtimeMessageBus: WebviewRuntimeMessageBus;
};
export function setupWebviewPlugins({
plugins,
extensionMessageBusProvider,
logger,
runtimeMessageBus,
}: setupWebviewPluginsProps) {
logger.debug(`Setting up (${plugins.length}) plugins`);
const compositeDisposable = new CompositeDisposable();
for (const plugin of plugins) {
logger.debug(`Setting up plugin: ${plugin.id}`);
const extensionMessageBus = extensionMessageBusProvider.getMessageBus(plugin.id);
const webviewInstanceMessageBusFactory = (address: WebviewAddress) => {
return new WebviewInstanceMessageBus(address, runtimeMessageBus, logger);
};
const webviewController = new WebviewController(
plugin.id,
runtimeMessageBus,
webviewInstanceMessageBusFactory,
logger,
);
const disposable = plugin.setup({
webview: webviewController,
extension: extensionMessageBus,
});
if (isDisposable(disposable)) {
compositeDisposable.add(disposable);
}
}
logger.debug('All plugins were set up successfully');
return compositeDisposable;
}
References:
- packages/lib_webview/src/setup/plugin/setup_plugins.ts:21 |
You are a code assistant | Definition of 'ILog' in file src/common/log_types.ts in project gitlab-lsp | Definition:
export interface ILog {
debug(e: Error): void;
debug(message: string, e?: Error): void;
info(e: Error): void;
info(message: string, e?: Error): void;
warn(e: Error): void;
warn(message: string, e?: Error): void;
error(e: Error): void;
error(message: string, e?: Error): void;
}
export const LOG_LEVEL = {
DEBUG: 'debug',
INFO: 'info',
WARNING: 'warning',
ERROR: 'error',
} as const;
export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL];
References:
- src/node/http/create_fastify_http_server.ts:72
- src/node/http/create_fastify_http_server.test.ts:12
- src/node/http/utils/logger_with_prefix.ts:5
- src/node/http/create_fastify_http_server.ts:58
- src/node/http/utils/logger_with_prefix.test.ts:5
- src/node/http/create_fastify_http_server.ts:89
- src/node/http/utils/create_logger_transport.ts:4
- src/node/http/create_fastify_http_server.ts:9
- src/node/http/utils/create_logger_transport.test.ts:5 |
You are a code assistant | Definition of 'SuggestionModel' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp | Definition:
export interface SuggestionModel {
lang: string;
engine: string;
name: string;
}
/** We request 4 options. That's maximum supported number of Google Vertex */
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:
- src/common/suggestion_client/suggestion_client.ts:29 |
You are a code assistant | Definition of 'VirtualFileSystemService' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp | Definition:
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:
- src/common/connection.ts:35
- src/common/message_handler.ts:87
- src/common/message_handler.ts:39 |
You are a code assistant | Definition of 'findNotificationHandler' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts in project gitlab-lsp | Definition:
function findNotificationHandler(
connection: jest.Mocked<Connection>,
method: string,
): ((message: unknown) => void) | undefined {
type NotificationCall = [string, (message: unknown) => void];
return (connection.onNotification.mock.calls as unknown as NotificationCall[]).find(
([notificationMethod]) => notificationMethod === method,
)?.[1];
}
References:
- packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:57 |
You are a code assistant | Definition of 'FallbackClient' in file src/common/suggestion_client/fallback_client.ts in project gitlab-lsp | Definition:
export class FallbackClient implements SuggestionClient {
#clients: SuggestionClient[];
constructor(...clients: SuggestionClient[]) {
this.#clients = clients;
}
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:
- src/common/suggestion_client/fallback_client.test.ts:33
- src/common/suggestion_client/fallback_client.test.ts:18
- src/common/suggestion/suggestion_service.ts:160 |
You are a code assistant | Definition of 'processCompletion' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp | Definition:
async processCompletion(
_context: IDocContext,
input: SuggestionOption[],
): Promise<SuggestionOption[]> {
return input;
}
}
pipeline.addProcessor(new Processor1());
pipeline.addProcessor(new Processor2());
const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false };
const result = await pipeline.run({
documentContext: mockContext,
input: streamInput,
type: 'stream',
});
expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false });
});
test('should chain multiple processors correctly for completion input', async () => {
class Processor1 extends PostProcessor {
async processStream(
_context: IDocContext,
input: StreamingCompletionResponse,
): Promise<StreamingCompletionResponse> {
return input;
}
async processCompletion(
_context: IDocContext,
input: SuggestionOption[],
): Promise<SuggestionOption[]> {
return input.map((option) => ({ ...option, text: `${option.text} [1]` }));
}
}
class Processor2 extends PostProcessor {
async processStream(
_context: IDocContext,
input: StreamingCompletionResponse,
): Promise<StreamingCompletionResponse> {
return input;
}
async processCompletion(
_context: IDocContext,
input: SuggestionOption[],
): Promise<SuggestionOption[]> {
return input.map((option) => ({ ...option, text: `${option.text} [2]` }));
}
}
pipeline.addProcessor(new Processor1());
pipeline.addProcessor(new Processor2());
const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }];
const result = await pipeline.run({
documentContext: mockContext,
input: completionInput,
type: 'completion',
});
expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]);
});
test('should throw an error for unexpected type', async () => {
class TestProcessor extends PostProcessor {
async processStream(
_context: IDocContext,
input: StreamingCompletionResponse,
): Promise<StreamingCompletionResponse> {
return input;
}
async processCompletion(
_context: IDocContext,
input: SuggestionOption[],
): Promise<SuggestionOption[]> {
return input;
}
}
pipeline.addProcessor(new TestProcessor());
const invalidInput = { invalid: 'input' };
await expect(
pipeline.run({
documentContext: mockContext,
input: invalidInput as unknown as StreamingCompletionResponse,
type: 'invalid' as 'stream',
}),
).rejects.toThrow('Unexpected type in pipeline processing');
});
});
References: |
You are a code assistant | Definition of 'constructor' in file src/common/tree_sitter/parser.ts in project gitlab-lsp | Definition:
constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) {
this.languages = this.buildTreeSitterInfoByExtMap(languages);
this.loadState = TreeSitterParserLoadState.INIT;
}
get loadStateValue(): TreeSitterParserLoadState {
return this.loadState;
}
async parseFile(context: IDocContext): Promise<TreeAndLanguage | undefined> {
const init = await this.#handleInit();
if (!init) {
return undefined;
}
const languageInfo = this.getLanguageInfoForFile(context.fileRelativePath);
if (!languageInfo) {
return undefined;
}
const parser = await this.getParser(languageInfo);
if (!parser) {
log.debug(
'TreeSitterParser: Skipping intent detection using tree-sitter due to missing parser.',
);
return undefined;
}
const tree = parser.parse(`${context.prefix}${context.suffix}`);
return {
tree,
language: parser.getLanguage(),
languageInfo,
};
}
async #handleInit(): Promise<boolean> {
try {
await this.init();
return true;
} catch (err) {
log.warn('TreeSitterParser: Error initializing an appropriate tree-sitter parser', err);
this.loadState = TreeSitterParserLoadState.ERRORED;
}
return false;
}
getLanguageNameForFile(filename: string): TreeSitterLanguageName | undefined {
return this.getLanguageInfoForFile(filename)?.name;
}
async getParser(languageInfo: TreeSitterLanguageInfo): Promise<Parser | undefined> {
if (this.parsers.has(languageInfo.name)) {
return this.parsers.get(languageInfo.name) as Parser;
}
try {
const parser = new Parser();
const language = await Parser.Language.load(languageInfo.wasmPath);
parser.setLanguage(language);
this.parsers.set(languageInfo.name, parser);
log.debug(
`TreeSitterParser: Loaded tree-sitter parser (tree-sitter-${languageInfo.name}.wasm present).`,
);
return parser;
} catch (err) {
this.loadState = TreeSitterParserLoadState.ERRORED;
// NOTE: We validate the below is not present in generation.test.ts integration test.
// Make sure to update the test appropriately if changing the error.
log.warn(
'TreeSitterParser: Unable to load tree-sitter parser due to an unexpected error.',
err,
);
return undefined;
}
}
getLanguageInfoForFile(filename: string): TreeSitterLanguageInfo | undefined {
const ext = filename.split('.').pop();
return this.languages.get(`.${ext}`);
}
buildTreeSitterInfoByExtMap(
languages: TreeSitterLanguageInfo[],
): Map<string, TreeSitterLanguageInfo> {
return languages.reduce((map, language) => {
for (const extension of language.extensions) {
map.set(extension, language);
}
return map;
}, new Map<string, TreeSitterLanguageInfo>());
}
}
References: |
You are a code assistant | Definition of 'register' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp | Definition:
register(provider: WebviewUriProvider): void;
}
export class WebviewLocationService implements WebviewUriProviderRegistry {
#uriProviders = new Set<WebviewUriProvider>();
register(provider: WebviewUriProvider) {
this.#uriProviders.add(provider);
}
resolveUris(webviewId: WebviewId): Uri[] {
const uris: Uri[] = [];
for (const provider of this.#uriProviders) {
uris.push(provider.getUri(webviewId));
}
return uris;
}
}
References: |
You are a code assistant | Definition of 'hasbinAll' in file src/tests/int/hasbin.ts in project gitlab-lsp | Definition:
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 'SOCKET_RESPONSE_CHANNEL' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp | Definition:
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 'dispose' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp | Definition:
dispose() {
this.#subscriptions.forEach((s) => s.dispose());
}
get #state(): FeatureState[] {
const engagedChecks = this.#checks.filter((check) => check.engaged);
return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => {
const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks
.filter(({ id }) => stateChecks.includes(id))
.map((stateCheck) => ({
checkId: stateCheck.id,
details: stateCheck.details,
}));
return {
featureId,
engagedChecks: engagedFeatureChecks,
};
});
}
}
References: |
You are a code assistant | Definition of 'update' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp | Definition:
update(attributes: Partial<GitLabChatRecordAttributes>) {
const convertedAttributes = attributes as Partial<GitLabChatRecord>;
if (attributes.timestamp) {
convertedAttributes.timestamp = Date.parse(attributes.timestamp);
}
Object.assign(this, convertedAttributes);
}
#detectType(): ChatRecordType {
if (this.content === SPECIAL_MESSAGES.RESET) {
return 'newConversation';
}
return 'general';
}
}
References: |
You are a code assistant | Definition of 'register' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp | Definition:
register(provider: WebviewUriProvider) {
this.#uriProviders.add(provider);
}
resolveUris(webviewId: WebviewId): Uri[] {
const uris: Uri[] = [];
for (const provider of this.#uriProviders) {
uris.push(provider.getUri(webviewId));
}
return uris;
}
}
References: |
You are a code assistant | Definition of 'TestMessageMap' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts in project gitlab-lsp | Definition:
interface TestMessageMap extends MessageMap {
inbound: {
notifications: {
testNotification: string;
};
requests: {
testRequest: {
params: number;
result: string;
};
};
};
outbound: {
notifications: {
testOutboundNotification: boolean;
};
requests: {
testOutboundRequest: {
params: string;
result: number;
};
};
};
}
const TEST_REQUEST_ID = 'mock-request-id';
describe('SocketIoMessageBus', () => {
let mockSocket: jest.Mocked<Socket>;
let messageBus: SocketIoMessageBus<TestMessageMap>;
beforeEach(() => {
jest.useFakeTimers();
jest.mocked(generateRequestId).mockReturnValue(TEST_REQUEST_ID);
mockSocket = {
emit: jest.fn(),
on: jest.fn(),
off: jest.fn(),
} as unknown as jest.Mocked<Socket>;
messageBus = new SocketIoMessageBus<TestMessageMap>(mockSocket);
});
afterEach(() => {
jest.useRealTimers();
});
describe('sendNotification', () => {
it('should emit a notification event', async () => {
// Arrange
const messageType = 'testOutboundNotification';
const payload = true;
// Act
await messageBus.sendNotification(messageType, payload);
// Assert
expect(mockSocket.emit).toHaveBeenCalledWith('notification', {
type: messageType,
payload,
});
});
});
describe('sendRequest', () => {
it('should emit a request event and resolve with the response', async () => {
// Arrange
const messageType = 'testOutboundRequest';
const payload = 'test';
const response = 42;
// Act
const promise = messageBus.sendRequest(messageType, payload);
// Simulate response
const handleResponse = getSocketEventHandler(mockSocket, SOCKET_RESPONSE_CHANNEL);
handleResponse({ requestId: TEST_REQUEST_ID, payload: response });
// Assert
await expect(promise).resolves.toBe(response);
expect(mockSocket.emit).toHaveBeenCalledWith('request', {
requestId: TEST_REQUEST_ID,
type: messageType,
payload,
});
});
it('should reject if the request times out', async () => {
// Arrange
const messageType = 'testOutboundRequest';
const payload = 'test';
// Act
const promise = messageBus.sendRequest(messageType, payload);
// Simulate timeout
jest.advanceTimersByTime(REQUEST_TIMEOUT_MS);
// Assert
await expect(promise).rejects.toThrow('Request timed out');
});
});
describe('onNotification', () => {
it('should register a notification handler', () => {
// Arrange
const messageType = 'testNotification';
const handler = jest.fn();
// Act
messageBus.onNotification(messageType, handler);
// Simulate incoming notification
const handleNotification = getSocketEventHandler(mockSocket, SOCKET_NOTIFICATION_CHANNEL);
handleNotification({ type: messageType, payload: 'test' });
// Assert
expect(handler).toHaveBeenCalledWith('test');
});
});
describe('onRequest', () => {
it('should register a request handler', async () => {
// Arrange
const messageType = 'testRequest';
const handler = jest.fn().mockResolvedValue('response');
// Act
messageBus.onRequest(messageType, handler);
// Simulate incoming request
const handleRequest = getSocketEventHandler(mockSocket, SOCKET_REQUEST_CHANNEL);
await handleRequest({
requestId: 'test-id',
event: messageType,
payload: 42,
});
// Assert
expect(handler).toHaveBeenCalledWith(42);
expect(mockSocket.emit).toHaveBeenCalledWith('response', {
requestId: 'test-id',
payload: 'response',
});
});
});
describe('dispose', () => {
it('should remove all event listeners', () => {
// Act
messageBus.dispose();
// Assert
expect(mockSocket.off).toHaveBeenCalledTimes(3);
expect(mockSocket.off).toHaveBeenCalledWith('notification', expect.any(Function));
expect(mockSocket.off).toHaveBeenCalledWith('request', expect.any(Function));
expect(mockSocket.off).toHaveBeenCalledWith('response', expect.any(Function));
});
});
});
// eslint-disable-next-line @typescript-eslint/ban-types
function getSocketEventHandler(socket: jest.Mocked<Socket>, eventName: SocketEvents): Function {
const [, handler] = socket.on.mock.calls.find((call) => call[0] === eventName)!;
return handler;
}
References: |
You are a code assistant | Definition of 'FastifyPluginRegistration' in file src/node/http/types.ts in project gitlab-lsp | Definition:
export type FastifyPluginRegistration<
TPluginOptions extends FastifyPluginOptions = FastifyPluginOptions,
> = {
plugin: FastifyPluginAsync<TPluginOptions>;
options?: TPluginOptions;
};
References:
- src/node/webview/webview_fastify_middleware.ts:12 |
You are a code assistant | Definition of 'createViteConfigForWebview' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp | Definition:
export function createViteConfigForWebview(name): UserConfig {
const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`);
return {
plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src/app', import.meta.url)),
},
},
root: './src/app',
base: '',
build: {
target: 'es2022',
emptyOutDir: true,
outDir,
rollupOptions: {
input: [path.join('src', 'app', 'index.html')],
},
},
};
}
References:
- packages/webview_duo_workflow/vite.config.ts:4
- packages/webview_duo_chat/vite.config.ts:4 |
You are a code assistant | Definition of 'build' in file scripts/esbuild/desktop.ts in project gitlab-lsp | Definition:
async function build() {
await esbuild.build(config);
}
void build();
References:
- scripts/esbuild/common.ts:31
- scripts/esbuild/browser.ts:26
- scripts/esbuild/desktop.ts:41 |
You are a code assistant | Definition of 'Greet4' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'getTextAfterSelected' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp | Definition:
export const getTextAfterSelected = (): string | null => {
return null;
// const editor = vscode.window.activeTextEditor;
// if (!editor || !editor.selection || editor.selection.isEmpty) return null;
// const { selection, document } = editor;
// const { line: lineNum, character: charNum } = selection.end;
// const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character;
// const isLastLine = lineNum === document.lineCount;
// const getStartLine = () => {
// if (isLastCharOnLineSelected) {
// if (isLastLine) {
// return lineNum;
// }
// return lineNum + 1;
// }
// return lineNum;
// };
// const getStartChar = () => {
// if (isLastCharOnLineSelected) {
// if (isLastLine) {
// return charNum;
// }
// return 0;
// }
// return charNum + 1;
// };
// const selectionRange = new vscode.Range(
// getStartLine(),
// getStartChar(),
// document.lineCount,
// document.lineAt(document.lineCount - 1).range.end.character,
// );
// return editor.document.getText(selectionRange);
};
References:
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts:27 |
You are a code assistant | Definition of 'a' in file packages/lib_di/src/index.test.ts in project gitlab-lsp | Definition:
a(): string;
}
interface B {
b(): string;
}
interface C {
c(): string;
}
const A = createInterfaceId<A>('A');
const B = createInterfaceId<B>('B');
const C = createInterfaceId<C>('C');
@Injectable(A, [])
class AImpl implements A {
a = () => 'a';
}
@Injectable(B, [A])
class BImpl implements B {
#a: A;
constructor(a: A) {
this.#a = a;
}
b = () => `B(${this.#a.a()})`;
}
@Injectable(C, [A, B])
class CImpl implements C {
#a: A;
#b: B;
constructor(a: A, b: B) {
this.#a = a;
this.#b = b;
}
c = () => `C(${this.#b.b()}, ${this.#a.a()})`;
}
let container: Container;
beforeEach(() => {
container = new Container();
});
describe('addInstances', () => {
const O = createInterfaceId<object>('object');
it('fails if the instance is not branded', () => {
expect(() => container.addInstances({ say: 'hello' } as BrandedInstance<object>)).toThrow(
/invoked without branded object/,
);
});
it('fails if the instance is already present', () => {
const a = brandInstance(O, { a: 'a' });
const b = brandInstance(O, { b: 'b' });
expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/);
});
it('adds instance', () => {
const instance = { a: 'a' };
const a = brandInstance(O, instance);
container.addInstances(a);
expect(container.get(O)).toBe(instance);
});
});
describe('instantiate', () => {
it('can instantiate three classes A,B,C', () => {
container.instantiate(AImpl, BImpl, CImpl);
const cInstance = container.get(C);
expect(cInstance.c()).toBe('C(B(a), a)');
});
it('instantiates dependencies in multiple instantiate calls', () => {
container.instantiate(AImpl);
// the order is important for this test
// we want to make sure that the stack in circular dependency discovery is being cleared
// to try why this order is necessary, remove the `inStack.delete()` from
// the `if (!cwd && instanceIds.includes(id))` condition in prod code
expect(() => container.instantiate(CImpl, BImpl)).not.toThrow();
});
it('detects duplicate ids', () => {
@Injectable(A, [])
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl, AImpl2)).toThrow(
/The following interface IDs were used multiple times 'A' \(classes: AImpl,AImpl2\)/,
);
});
it('detects duplicate id with pre-existing instance', () => {
const aInstance = new AImpl();
const a = brandInstance(A, aInstance);
container.addInstances(a);
expect(() => container.instantiate(AImpl)).toThrow(/classes are clashing/);
});
it('detects missing dependencies', () => {
expect(() => container.instantiate(BImpl)).toThrow(
/Class BImpl \(interface B\) depends on interfaces \[A]/,
);
});
it('it uses existing instances as dependencies', () => {
const aInstance = new AImpl();
const a = brandInstance(A, aInstance);
container.addInstances(a);
container.instantiate(BImpl);
expect(container.get(B).b()).toBe('B(a)');
});
it("detects classes what aren't decorated with @Injectable", () => {
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl2)).toThrow(
/Classes \[AImpl2] are not decorated with @Injectable/,
);
});
it('detects circular dependencies', () => {
@Injectable(A, [C])
class ACircular implements A {
a = () => 'hello';
constructor(c: C) {
// eslint-disable-next-line no-unused-expressions
c;
}
}
expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow(
/Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./,
);
});
// this test ensures that we don't store any references to the classes and we instantiate them only once
it('does not instantiate classes from previous instantiate call', () => {
let globCount = 0;
@Injectable(A, [])
class Counter implements A {
counter = globCount;
constructor() {
globCount++;
}
a = () => this.counter.toString();
}
container.instantiate(Counter);
container.instantiate(BImpl);
expect(container.get(A).a()).toBe('0');
});
});
describe('get', () => {
it('returns an instance of the interfaceId', () => {
container.instantiate(AImpl);
expect(container.get(A)).toBeInstanceOf(AImpl);
});
it('throws an error for missing dependency', () => {
container.instantiate();
expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/);
});
});
});
References:
- src/tests/fixtures/intent/ruby_comments.rb:14 |
You are a code assistant | Definition of 'CIRCUIT_BREAK_INTERVAL_MS' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp | Definition:
export const CIRCUIT_BREAK_INTERVAL_MS = 10000;
export const MAX_ERRORS_BEFORE_CIRCUIT_BREAK = 4;
export const API_ERROR_NOTIFICATION = '$/gitlab/api/error';
export const API_RECOVERY_NOTIFICATION = '$/gitlab/api/recovered';
export enum CircuitBreakerState {
OPEN = 'Open',
CLOSED = 'Closed',
}
export interface CircuitBreaker {
error(): void;
success(): void;
isOpen(): boolean;
onOpen(listener: () => void): Disposable;
onClose(listener: () => void): Disposable;
}
References: |
You are a code assistant | Definition of 'error' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp | Definition:
error(): void {
// NOOP
}
}
References:
- scripts/commit-lint/lint.js:72
- scripts/commit-lint/lint.js:77
- scripts/commit-lint/lint.js:85
- scripts/commit-lint/lint.js:94 |
You are a code assistant | Definition of 'constructor' in file src/common/suggestion_client/fallback_client.ts in project gitlab-lsp | Definition:
constructor(...clients: SuggestionClient[]) {
this.#clients = clients;
}
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 'getUserAgentHeader' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp | Definition:
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 'Greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp | Definition:
type Greet struct {
name string
}
// empty method declaration
func (g Greet) greet() { }
// non-empty method declaration
func (g Greet) greet() {
fmt.Printf("Hello %s\n", g.name)
}
References:
- src/tests/fixtures/intent/go_comments.go:24
- src/tests/fixtures/intent/empty_function/go.go:13
- src/tests/fixtures/intent/empty_function/go.go:23
- src/tests/fixtures/intent/empty_function/ruby.rb:16
- src/tests/fixtures/intent/empty_function/go.go:15
- src/tests/fixtures/intent/empty_function/go.go:20 |
You are a code assistant | Definition of 'getTextBeforeSelected' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp | Definition:
export const getTextBeforeSelected = (): string | null => {
return null;
// const editor = vscode.window.activeTextEditor;
// if (!editor || !editor.selection || editor.selection.isEmpty) return null;
// const { selection, document } = editor;
// const { line: lineNum, character: charNum } = selection.start;
// const isFirstCharOnLineSelected = charNum === 0;
// const isFirstLine = lineNum === 0;
// const getEndLine = () => {
// if (isFirstCharOnLineSelected) {
// if (isFirstLine) {
// return lineNum;
// }
// return lineNum - 1;
// }
// return lineNum;
// };
// const getEndChar = () => {
// if (isFirstCharOnLineSelected) {
// if (isFirstLine) {
// return 0;
// }
// return document.lineAt(lineNum - 1).range.end.character;
// }
// return charNum - 1;
// };
// const selectionRange = new vscode.Range(0, 0, getEndLine(), getEndChar());
// return editor.document.getText(selectionRange);
};
export const getTextAfterSelected = (): string | null => {
return null;
// const editor = vscode.window.activeTextEditor;
// if (!editor || !editor.selection || editor.selection.isEmpty) return null;
// const { selection, document } = editor;
// const { line: lineNum, character: charNum } = selection.end;
// const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character;
// const isLastLine = lineNum === document.lineCount;
// const getStartLine = () => {
// if (isLastCharOnLineSelected) {
// if (isLastLine) {
// return lineNum;
// }
// return lineNum + 1;
// }
// return lineNum;
// };
// const getStartChar = () => {
// if (isLastCharOnLineSelected) {
// if (isLastLine) {
// return charNum;
// }
// return 0;
// }
// return charNum + 1;
// };
// const selectionRange = new vscode.Range(
// getStartLine(),
// getStartChar(),
// document.lineCount,
// document.lineAt(document.lineCount - 1).range.end.character,
// );
// return editor.document.getText(selectionRange);
};
References:
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts:26 |
You are a code assistant | Definition of 'MessageBusProvider' in file packages/lib_webview_client/src/bus/provider/types.ts in project gitlab-lsp | Definition:
export interface MessageBusProvider {
name: string;
getMessageBus<TMessages extends MessageMap>(webviewId: string): MessageBus<TMessages> | null;
}
References:
- packages/lib_webview_client/src/bus/resolve_message_bus.ts:30 |
You are a code assistant | Definition of 'SuggestionsCache' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp | Definition:
export class SuggestionsCache {
#cache: LRUCache<string, SuggestionCacheEntry>;
#configService: ConfigService;
constructor(configService: ConfigService) {
this.#configService = configService;
const currentConfig = this.#getCurrentConfig();
this.#cache = new LRUCache<string, SuggestionCacheEntry>({
ttlAutopurge: true,
sizeCalculation: (value, key) =>
value.suggestions.reduce((acc, suggestion) => acc + suggestion.text.length, 0) + key.length,
...DEFAULT_CONFIG,
...currentConfig,
ttl: Number(currentConfig.ttl),
});
}
#getCurrentConfig(): Required<ISuggestionsCacheOptions> {
return {
...DEFAULT_CONFIG,
...(this.#configService.get('client.suggestionsCache') ?? {}),
};
}
#getSuggestionKey(ctx: SuggestionCacheContext) {
const prefixLines = ctx.context.prefix.split('\n');
const currentLine = prefixLines.pop() ?? '';
const indentation = (currentLine.match(/^\s*/)?.[0] ?? '').length;
const config = this.#getCurrentConfig();
const cachedPrefixLines = prefixLines
.filter(isNonEmptyLine)
.slice(-config.prefixLines)
.join('\n');
const cachedSuffixLines = ctx.context.suffix
.split('\n')
.filter(isNonEmptyLine)
.slice(0, config.suffixLines)
.join('\n');
return [
ctx.document.uri,
ctx.position.line,
cachedPrefixLines,
cachedSuffixLines,
indentation,
].join(':');
}
#increaseCacheEntryRetrievedCount(suggestionKey: string, character: number) {
const item = this.#cache.get(suggestionKey);
if (item && item.timesRetrievedByPosition) {
item.timesRetrievedByPosition[character] =
(item.timesRetrievedByPosition[character] ?? 0) + 1;
}
}
addToSuggestionCache(config: {
request: SuggestionCacheContext;
suggestions: SuggestionOption[];
}) {
if (!this.#getCurrentConfig().enabled) {
return;
}
const currentLine = config.request.context.prefix.split('\n').at(-1) ?? '';
this.#cache.set(this.#getSuggestionKey(config.request), {
character: config.request.position.character,
suggestions: config.suggestions,
currentLine,
timesRetrievedByPosition: {},
additionalContexts: config.request.additionalContexts,
});
}
getCachedSuggestions(request: SuggestionCacheContext): SuggestionCache | undefined {
if (!this.#getCurrentConfig().enabled) {
return undefined;
}
const currentLine = request.context.prefix.split('\n').at(-1) ?? '';
const key = this.#getSuggestionKey(request);
const candidate = this.#cache.get(key);
if (!candidate) {
return undefined;
}
const { character } = request.position;
if (candidate.timesRetrievedByPosition[character] > 0) {
// If cache has already returned this suggestion from the same position before, discard it.
this.#cache.delete(key);
return undefined;
}
this.#increaseCacheEntryRetrievedCount(key, character);
const options = candidate.suggestions
.map((s) => {
const currentLength = currentLine.length;
const previousLength = candidate.currentLine.length;
const diff = currentLength - previousLength;
if (diff < 0) {
return null;
}
if (
currentLine.slice(0, previousLength) !== candidate.currentLine ||
s.text.slice(0, diff) !== currentLine.slice(previousLength)
) {
return null;
}
return {
...s,
text: s.text.slice(diff),
uniqueTrackingId: generateUniqueTrackingId(),
};
})
.filter((x): x is SuggestionOption => Boolean(x));
return {
options,
additionalContexts: candidate.additionalContexts,
};
}
}
References:
- src/common/suggestion/suggestions_cache.test.ts:42
- src/common/suggestion/suggestion_service.ts:156
- src/common/suggestion/suggestion_service.ts:131
- src/common/suggestion/suggestions_cache.test.ts:50 |
You are a code assistant | Definition of 'InitializeHandler' in file src/common/core/handlers/initialize_handler.ts in project gitlab-lsp | Definition:
export interface InitializeHandler
extends HandlesRequest<CustomInitializeParams, InitializeResult, InitializeError> {}
export const InitializeHandler = createInterfaceId<InitializeHandler>('InitializeHandler');
@Injectable(InitializeHandler, [ConfigService])
export class DefaultInitializeHandler implements InitializeHandler {
#configService: ConfigService;
constructor(configService: ConfigService) {
this.#configService = configService;
}
requestHandler: RequestHandler<CustomInitializeParams, InitializeResult, InitializeError> = (
params: CustomInitializeParams,
): InitializeResult => {
const { clientInfo, initializationOptions, workspaceFolders } = params;
this.#configService.set('client.clientInfo', clientInfo);
this.#configService.set('client.workspaceFolders', workspaceFolders);
this.#configService.set('client.baseAssetsUrl', initializationOptions?.baseAssetsUrl);
this.#configService.set('client.telemetry.ide', initializationOptions?.ide ?? clientInfo);
this.#configService.set('client.telemetry.extension', initializationOptions?.extension);
return {
capabilities: {
completionProvider: {
resolveProvider: true,
},
inlineCompletionProvider: true,
textDocumentSync: TextDocumentSyncKind.Full,
},
};
};
}
References:
- src/common/core/handlers/initialize_handler.test.ts:16
- src/common/connection_service.ts:62 |
You are a code assistant | Definition of 'getIntent' in file src/common/tree_sitter/intent_resolver.ts in project gitlab-lsp | Definition:
export async function getIntent({
treeAndLanguage,
position,
prefix,
suffix,
}: {
treeAndLanguage: TreeAndLanguage;
position: Position;
prefix: string;
suffix: string;
}): Promise<IntentResolution> {
const commentResolver = getCommentResolver();
const emptyFunctionResolver = getEmptyFunctionResolver();
const cursorPosition = { row: position.line, column: position.character };
const { languageInfo, tree, language: treeSitterLanguage } = treeAndLanguage;
const commentResolution = commentResolver.getCommentForCursor({
languageName: languageInfo.name,
tree,
cursorPosition,
treeSitterLanguage,
});
if (commentResolution) {
const { commentAtCursor, commentAboveCursor } = commentResolution;
if (commentAtCursor) {
log.debug('IntentResolver: Cursor is directly on a comment, sending intent: completion');
return { intent: 'completion' };
}
const isCommentEmpty = CommentResolver.isCommentEmpty(commentAboveCursor);
if (isCommentEmpty) {
log.debug('IntentResolver: Cursor is after an empty comment, sending intent: completion');
return { intent: 'completion' };
}
log.debug('IntentResolver: Cursor is after a non-empty comment, sending intent: generation');
return {
intent: 'generation',
generationType: 'comment',
commentForCursor: commentAboveCursor,
};
}
const textContent = `${prefix}${suffix}`;
const totalCommentLines = commentResolver.getTotalCommentLines({
languageName: languageInfo.name,
treeSitterLanguage,
tree,
});
if (isSmallFile(textContent, totalCommentLines)) {
log.debug('IntentResolver: Small file detected, sending intent: generation');
return { intent: 'generation', generationType: 'small_file' };
}
const isCursorInEmptyFunction = emptyFunctionResolver.isCursorInEmptyFunction({
languageName: languageInfo.name,
tree,
cursorPosition,
treeSitterLanguage,
});
if (isCursorInEmptyFunction) {
log.debug('IntentResolver: Cursor is in an empty function, sending intent: generation');
return { intent: 'generation', generationType: 'empty_function' };
}
log.debug(
'IntentResolver: Cursor is neither at the end of non-empty comment, nor in a small file, nor in empty function - not sending intent.',
);
return { intent: undefined };
}
References:
- src/common/tree_sitter/intent_resolver.test.ts:181
- src/common/tree_sitter/intent_resolver.test.ts:144
- src/tests/unit/tree_sitter/intent_resolver.test.ts:671
- src/common/tree_sitter/intent_resolver.test.ts:167
- src/tests/unit/tree_sitter/intent_resolver.test.ts:33
- src/common/tree_sitter/intent_resolver.test.ts:72
- src/common/tree_sitter/intent_resolver.test.ts:97
- src/common/tree_sitter/intent_resolver.test.ts:119
- src/tests/unit/tree_sitter/intent_resolver.test.ts:20
- src/tests/unit/tree_sitter/intent_resolver.test.ts:400
- src/common/suggestion/suggestion_service.ts:358 |
You are a code assistant | Definition of 'AiMessagesResponseType' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp | Definition:
type AiMessagesResponseType = {
aiMessages: {
nodes: AiMessageResponseType[];
};
};
interface ErrorMessage {
type: 'error';
requestId: string;
role: 'system';
errors: string[];
}
const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({
requestId,
errors,
role: 'system',
type: 'error',
});
interface SuccessMessage {
type: 'message';
requestId: string;
role: string;
content: string;
contentHtml: string;
timestamp: string;
errors: string[];
extras?: {
sources: object[];
};
}
const successResponse = (response: AiMessageResponseType): SuccessMessage => ({
type: 'message',
...response,
});
type AiMessage = SuccessMessage | ErrorMessage;
type ChatInputTemplate = {
query: string;
defaultVariables: {
platformOrigin?: string;
};
};
export class GitLabChatApi {
#cachedActionQuery?: ChatInputTemplate = undefined;
#manager: GitLabPlatformManagerForChat;
constructor(manager: GitLabPlatformManagerForChat) {
this.#manager = manager;
}
async processNewUserPrompt(
question: string,
subscriptionId?: string,
currentFileContext?: GitLabChatFileContext,
): Promise<AiActionResponseType> {
return this.#sendAiAction({
question,
currentFileContext,
clientSubscriptionId: subscriptionId,
});
}
async pullAiMessage(requestId: string, role: string): Promise<AiMessage> {
const response = await pullHandler(() => this.#getAiMessage(requestId, role));
if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']);
return successResponse(response);
}
async cleanChat(): Promise<AiActionResponseType> {
return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN });
}
async #currentPlatform() {
const platform = await this.#manager.getGitLabPlatform();
if (!platform) throw new Error('Platform is missing!');
return platform;
}
async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> {
const request: GraphQLRequest<AiMessagesResponseType> = {
type: 'graphql',
query: AI_MESSAGES_QUERY,
variables: { requestIds: [requestId], roles: [role.toUpperCase()] },
};
const platform = await this.#currentPlatform();
const history = await platform.fetchFromApi(request);
return history.aiMessages.nodes[0];
}
async subscribeToUpdates(
messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>,
subscriptionId?: string,
) {
const platform = await this.#currentPlatform();
const channel = new AiCompletionResponseChannel({
htmlResponse: true,
userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`,
aiAction: 'CHAT',
clientSubscriptionId: subscriptionId,
});
const cable = await platform.connectToCable();
// we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397
// sometimes a chunk comes after the full message and it broke the chat
let fullMessageReceived = false;
channel.on('newChunk', async (msg) => {
if (fullMessageReceived) {
log.info(`CHAT-DEBUG: full message received, ignoring chunk`);
return;
}
await messageCallback(msg);
});
channel.on('fullMessage', async (message) => {
fullMessageReceived = true;
await messageCallback(message);
if (subscriptionId) {
cable.disconnect();
}
});
cable.subscribe(channel);
}
async #sendAiAction(variables: object): Promise<AiActionResponseType> {
const platform = await this.#currentPlatform();
const { query, defaultVariables } = await this.#actionQuery();
const projectGqlId = await this.#manager.getProjectGqlId();
const request: GraphQLRequest<AiActionResponseType> = {
type: 'graphql',
query,
variables: {
...variables,
...defaultVariables,
resourceId: projectGqlId ?? null,
},
};
return platform.fetchFromApi(request);
}
async #actionQuery(): Promise<ChatInputTemplate> {
if (!this.#cachedActionQuery) {
const platform = await this.#currentPlatform();
try {
const { version } = await platform.fetchFromApi(versionRequest);
this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>(
version,
MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION,
() => CHAT_INPUT_TEMPLATE_17_3_AND_LATER,
() => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER,
);
} catch (e) {
log.debug(`GitLab version check for sending chat failed:`, e as Error);
this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER;
}
}
return this.#cachedActionQuery;
}
}
References: |
You are a code assistant | Definition of 'constructor' in file src/node/tree_sitter/parser.ts in project gitlab-lsp | Definition:
constructor() {
super({
languages: TREE_SITTER_LANGUAGES,
});
}
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 'constructor' in file src/common/ai_context_management_2/ai_context_aggregator.ts in project gitlab-lsp | Definition:
constructor(
aiFileContextProvider: AiFileContextProvider,
aiContextPolicyManager: AiContextPolicyManager,
) {
this.#AiFileContextProvider = aiFileContextProvider;
this.#AiContextPolicyManager = aiContextPolicyManager;
}
async getContextForQuery(query: AiContextQuery): Promise<AiContextItem[]> {
switch (query.providerType) {
case 'file': {
const providerItems = await this.#AiFileContextProvider.getProviderItems(
query.query,
query.workspaceFolders,
);
const contextItems = await Promise.all(
providerItems.map((providerItem) => this.#providerItemToContextItem(providerItem)),
);
return contextItems;
}
default:
return [];
}
}
async #providerItemToContextItem(providerItem: AiContextProviderItem): Promise<AiContextItem> {
if (providerItem.providerType === 'file') {
const { fileUri, workspaceFolder, providerType, subType, repositoryFile } = providerItem;
const policyResult = await this.#AiContextPolicyManager.runPolicies(providerItem);
return {
id: fileUri.toString(),
isEnabled: policyResult.allowed,
info: {
project: repositoryFile?.repositoryUri.fsPath,
disabledReasons: policyResult.reasons,
relFilePath: repositoryFile
? this.#getBasePath(fileUri, parseURIString(workspaceFolder.uri))
: undefined,
},
name: Utils.basename(fileUri),
type: providerType,
subType,
};
}
throw new Error('Unknown provider type');
}
#getBasePath(targetUri: URI, baseUri: URI): string {
const targetPath = targetUri.fsPath;
const basePath = baseUri.fsPath;
return targetPath.replace(basePath, '').replace(/^[/\\]+/, '');
}
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp | Definition:
constructor(api: GitLabApiClient) {
api.onApiReconfigured(async ({ isInValidState, validationMessage }) => {
if (!isInValidState) {
if (!this.#notify) {
throw new Error(
'The DefaultTokenCheckNotifier has not been initialized. Call init first.',
);
}
await this.#notify({
message: validationMessage,
});
}
});
}
init(callback: NotifyFn<TokenCheckNotificationParams>) {
this.#notify = callback;
}
}
References: |
You are a code assistant | Definition of 'makeAccountId' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp | Definition:
export const makeAccountId = (instanceUrl: string, userId: string | number) =>
`${instanceUrl}|${userId}`;
export const extractUserId = (accountId: string) => accountId.split('|').pop();
References: |
You are a code assistant | Definition of 'getUserAgentHeader' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp | Definition:
getUserAgentHeader(): Record<string, string> {
return {};
}
}
export class ChatPlatformForAccount extends ChatPlatform implements GitLabPlatformForAccount {
readonly type = 'account' as const;
project: undefined;
}
export class ChatPlatformForProject extends ChatPlatform implements GitLabPlatformForProject {
readonly type = 'project' as const;
project: GitLabProject = {
gqlId: 'gid://gitlab/Project/123456',
restId: 0,
name: '',
description: '',
namespaceWithPath: '',
webUrl: '',
};
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/git/repository_trie.ts in project gitlab-lsp | Definition:
constructor() {
this.children = new Map();
this.repository = null;
}
dispose(): void {
this.children.forEach((child) => child.dispose());
this.children.clear();
this.repository = null;
}
}
References: |
You are a code assistant | Definition of 'merge' in file src/common/config_service.ts in project gitlab-lsp | Definition:
merge(newConfig: Partial<IConfig>) {
mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined));
this.#triggerChange();
}
}
References: |
You are a code assistant | Definition of 'StreamingCompletionResponse' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp | Definition:
export interface StreamingCompletionResponse {
/** stream ID taken from the request, all stream responses for one request will have the request's stream ID */
id: string;
/** most up-to-date generated suggestion, each time LS receives a chunk from LLM, it adds it to this string -> the client doesn't have to join the stream */
completion?: string;
done: boolean;
}
export const STREAMING_COMPLETION_RESPONSE_NOTIFICATION = 'streamingCompletionResponse';
export const CANCEL_STREAMING_COMPLETION_NOTIFICATION = 'cancelStreaming';
export const StreamingCompletionResponse = new NotificationType<StreamingCompletionResponse>(
STREAMING_COMPLETION_RESPONSE_NOTIFICATION,
);
export const CancelStreaming = new NotificationType<StreamWithId>(
CANCEL_STREAMING_COMPLETION_NOTIFICATION,
);
export interface StartStreamParams {
api: GitLabApiClient;
circuitBreaker: CircuitBreaker;
connection: Connection;
documentContext: IDocContext;
parser: TreeSitterParser;
postProcessorPipeline: PostProcessorPipeline;
streamId: string;
tracker: TelemetryTracker;
uniqueTrackingId: string;
userInstruction?: string;
generationType?: GenerationType;
additionalContexts?: AdditionalContext[];
}
export class DefaultStreamingHandler {
#params: StartStreamParams;
constructor(params: StartStreamParams) {
this.#params = params;
}
async startStream() {
return startStreaming(this.#params);
}
}
const startStreaming = async ({
additionalContexts,
api,
circuitBreaker,
connection,
documentContext,
parser,
postProcessorPipeline,
streamId,
tracker,
uniqueTrackingId,
userInstruction,
generationType,
}: StartStreamParams) => {
const language = parser.getLanguageNameForFile(documentContext.fileRelativePath);
tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
additionalContexts,
source: SuggestionSource.network,
language,
isStreaming: true,
});
let streamShown = false;
let suggestionProvided = false;
let streamCancelledOrErrored = false;
const cancellationTokenSource = new CancellationTokenSource();
const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => {
if (stream.id === streamId) {
streamCancelledOrErrored = true;
cancellationTokenSource.cancel();
if (streamShown) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
} else {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED);
}
}
});
const cancellationToken = cancellationTokenSource.token;
const endStream = async () => {
await connection.sendNotification(StreamingCompletionResponse, {
id: streamId,
done: true,
});
if (!streamCancelledOrErrored) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED);
if (!suggestionProvided) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED);
}
}
};
circuitBreaker.success();
const request: CodeSuggestionRequest = {
prompt_version: 1,
project_path: '',
project_id: -1,
current_file: {
content_above_cursor: documentContext.prefix,
content_below_cursor: documentContext.suffix,
file_name: documentContext.fileRelativePath,
},
intent: 'generation',
stream: true,
...(additionalContexts?.length && {
context: additionalContexts,
}),
...(userInstruction && {
user_instruction: userInstruction,
}),
generation_type: generationType,
};
const trackStreamStarted = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED);
});
const trackStreamShown = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN);
streamShown = true;
});
try {
for await (const response of api.getStreamingCodeSuggestions(request)) {
if (cancellationToken.isCancellationRequested) {
break;
}
if (circuitBreaker.isOpen()) {
break;
}
trackStreamStarted();
const processedCompletion = await postProcessorPipeline.run({
documentContext,
input: { id: streamId, completion: response, done: false },
type: 'stream',
});
await connection.sendNotification(StreamingCompletionResponse, processedCompletion);
if (response.replace(/\s/g, '').length) {
trackStreamShown();
suggestionProvided = true;
}
}
} catch (err) {
circuitBreaker.error();
if (isFetchError(err)) {
tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status });
}
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED);
streamCancelledOrErrored = true;
log.error('Error streaming code suggestions.', err);
} finally {
await endStream();
disposeStopStreaming.dispose();
cancellationTokenSource.dispose();
}
};
References:
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:179
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:29
- src/common/suggestion_client/post_processors/post_processor_pipeline.ts:9
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:119
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:16
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:58
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:44
- src/common/suggestion_client/post_processors/post_processor_pipeline.ts:23
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:133
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:149
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:103
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:87 |
You are a code assistant | Definition of 'id' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp | Definition:
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 'currentItems' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp | Definition:
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 'greet' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp | Definition:
def greet(name)
end
def greet2(name)
puts name
end
greet3 = Proc.new { |name| }
greet4 = Proc.new { |name| puts name }
greet5 = lambda { |name| }
greet6 = lambda { |name| puts name }
class Greet
def initialize(name)
end
def greet
end
end
class Greet2
def initialize(name)
@name = name
end
def greet
puts "Hello #{@name}"
end
end
class Greet3
end
def generate_greetings
end
def greet_generator
yield 'Hello'
end
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:29
- src/tests/fixtures/intent/empty_function/ruby.rb:1
- src/tests/fixtures/intent/ruby_comments.rb:21
- src/tests/fixtures/intent/empty_function/ruby.rb:20 |
You are a code assistant | Definition of 'IGitleaksRule' in file src/common/secret_redaction/gitleaks_rules.ts in project gitlab-lsp | Definition:
export interface IGitleaksRule {
id: string;
description: string;
secretGroup?: number;
entropy?: number;
allowlist?: object;
regex: string;
keywords: string[];
compiledRegex?: RegExp;
}
const rules: Array<IGitleaksRule> = [
{
description: 'Adafruit API Key',
id: 'adafruit-api-key',
regex:
'(?i)(?:adafruit)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9_-]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['adafruit'],
},
{
description: 'Adobe Client ID (OAuth Web)',
id: 'adobe-client-id',
regex:
'(?i)(?:adobe)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['adobe'],
},
{
description: 'Adobe Client Secret',
id: 'adobe-client-secret',
regex: '(?i)\\b((p8e-)(?i)[a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['p8e-'],
},
{
description: 'Age secret key',
id: 'age secret key',
regex: 'AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}',
keywords: ['age-secret-key-1'],
},
{
description: 'Airtable API Key',
id: 'airtable-api-key',
regex:
'(?i)(?:airtable)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{17})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['airtable'],
},
{
description: 'Algolia API Key',
id: 'algolia-api-key',
regex:
'(?i)(?:algolia)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['algolia'],
},
{
description: 'Alibaba AccessKey ID',
id: 'alibaba-access-key-id',
regex: '(?i)\\b((LTAI)(?i)[a-z0-9]{20})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['ltai'],
},
{
description: 'Alibaba Secret Key',
id: 'alibaba-secret-key',
regex:
'(?i)(?:alibaba)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{30})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['alibaba'],
},
{
description: 'Asana Client ID',
id: 'asana-client-id',
regex:
'(?i)(?:asana)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9]{16})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['asana'],
},
{
description: 'Asana Client Secret',
id: 'asana-client-secret',
regex:
'(?i)(?:asana)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['asana'],
},
{
description: 'Atlassian API token',
id: 'atlassian-api-token',
regex:
'(?i)(?:atlassian|confluence|jira)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{24})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['atlassian', 'confluence', 'jira'],
},
{
description: 'Authress Service Client Access Key',
id: 'authress-service-client-access-key',
regex:
'(?i)\\b((?:sc|ext|scauth|authress)_[a-z0-9]{5,30}\\.[a-z0-9]{4,6}\\.acc_[a-z0-9-]{10,32}\\.[a-z0-9+/_=-]{30,120})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['sc_', 'ext_', 'scauth_', 'authress_'],
},
{
description: 'AWS',
id: 'aws-access-token',
regex: '(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}',
keywords: ['akia', 'agpa', 'aida', 'aroa', 'aipa', 'anpa', 'anva', 'asia'],
},
{
description: 'Beamer API token',
id: 'beamer-api-token',
regex:
'(?i)(?:beamer)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(b_[a-z0-9=_\\-]{44})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['beamer'],
},
{
description: 'Bitbucket Client ID',
id: 'bitbucket-client-id',
regex:
'(?i)(?:bitbucket)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['bitbucket'],
},
{
description: 'Bitbucket Client Secret',
id: 'bitbucket-client-secret',
regex:
'(?i)(?:bitbucket)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['bitbucket'],
},
{
description: 'Bittrex Access Key',
id: 'bittrex-access-key',
regex:
'(?i)(?:bittrex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['bittrex'],
},
{
description: 'Bittrex Secret Key',
id: 'bittrex-secret-key',
regex:
'(?i)(?:bittrex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['bittrex'],
},
{
description: 'Clojars API token',
id: 'clojars-api-token',
regex: '(?i)(CLOJARS_)[a-z0-9]{60}',
keywords: ['clojars'],
},
{
description: 'Codecov Access Token',
id: 'codecov-access-token',
regex:
'(?i)(?:codecov)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['codecov'],
},
{
description: 'Coinbase Access Token',
id: 'coinbase-access-token',
regex:
'(?i)(?:coinbase)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9_-]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['coinbase'],
},
{
description: 'Confluent Access Token',
id: 'confluent-access-token',
regex:
'(?i)(?:confluent)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{16})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['confluent'],
},
{
description: 'Confluent Secret Key',
id: 'confluent-secret-key',
regex:
'(?i)(?:confluent)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['confluent'],
},
{
description: 'Contentful delivery API token',
id: 'contentful-delivery-api-token',
regex:
'(?i)(?:contentful)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{43})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['contentful'],
},
{
description: 'Databricks API token',
id: 'databricks-api-token',
regex: '(?i)\\b(dapi[a-h0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['dapi'],
},
{
description: 'Datadog Access Token',
id: 'datadog-access-token',
regex:
'(?i)(?:datadog)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['datadog'],
},
{
description: 'Defined Networking API token',
id: 'defined-networking-api-token',
regex:
'(?i)(?:dnkey)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(dnkey-[a-z0-9=_\\-]{26}-[a-z0-9=_\\-]{52})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['dnkey'],
},
{
description: 'DigitalOcean OAuth Access Token',
id: 'digitalocean-access-token',
regex: '(?i)\\b(doo_v1_[a-f0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['doo_v1_'],
},
{
description: 'DigitalOcean Personal Access Token',
id: 'digitalocean-pat',
regex: '(?i)\\b(dop_v1_[a-f0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['dop_v1_'],
},
{
description: 'DigitalOcean OAuth Refresh Token',
id: 'digitalocean-refresh-token',
regex: '(?i)\\b(dor_v1_[a-f0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['dor_v1_'],
},
{
description: 'Discord API key',
id: 'discord-api-token',
regex:
'(?i)(?:discord)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['discord'],
},
{
description: 'Discord client ID',
id: 'discord-client-id',
regex:
'(?i)(?:discord)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9]{18})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['discord'],
},
{
description: 'Discord client secret',
id: 'discord-client-secret',
regex:
'(?i)(?:discord)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['discord'],
},
{
description: 'Doppler API token',
id: 'doppler-api-token',
regex: '(dp\\.pt\\.)(?i)[a-z0-9]{43}',
keywords: ['doppler'],
},
{
description: 'Droneci Access Token',
id: 'droneci-access-token',
regex:
'(?i)(?:droneci)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['droneci'],
},
{
description: 'Dropbox API secret',
id: 'dropbox-api-token',
regex:
'(?i)(?:dropbox)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{15})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['dropbox'],
},
{
description: 'Dropbox long lived API token',
id: 'dropbox-long-lived-api-token',
regex:
'(?i)(?:dropbox)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{11}(AAAAAAAAAA)[a-z0-9\\-_=]{43})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['dropbox'],
},
{
description: 'Dropbox short lived API token',
id: 'dropbox-short-lived-api-token',
regex:
'(?i)(?:dropbox)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(sl\\.[a-z0-9\\-=_]{135})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['dropbox'],
},
{
description: 'Duffel API token',
id: 'duffel-api-token',
regex: 'duffel_(test|live)_(?i)[a-z0-9_\\-=]{43}',
keywords: ['duffel'],
},
{
description: 'Dynatrace API token',
id: 'dynatrace-api-token',
regex: 'dt0c01\\.(?i)[a-z0-9]{24}\\.[a-z0-9]{64}',
keywords: ['dynatrace'],
},
{
description: 'EasyPost API token',
id: 'easypost-api-token',
regex: '\\bEZAK(?i)[a-z0-9]{54}',
keywords: ['ezak'],
},
{
description: 'EasyPost test API token',
id: 'easypost-test-api-token',
regex: '\\bEZTK(?i)[a-z0-9]{54}',
keywords: ['eztk'],
},
{
description: 'Etsy Access Token',
id: 'etsy-access-token',
regex:
'(?i)(?:etsy)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{24})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['etsy'],
},
{
description: 'Facebook Access Token',
id: 'facebook',
regex:
'(?i)(?:facebook)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['facebook'],
},
{
description: 'Fastly API key',
id: 'fastly-api-token',
regex:
'(?i)(?:fastly)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['fastly'],
},
{
description: 'Finicity API token',
id: 'finicity-api-token',
regex:
'(?i)(?:finicity)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['finicity'],
},
{
description: 'Finicity Client Secret',
id: 'finicity-client-secret',
regex:
'(?i)(?:finicity)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{20})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['finicity'],
},
{
description: 'Finnhub Access Token',
id: 'finnhub-access-token',
regex:
'(?i)(?:finnhub)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{20})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['finnhub'],
},
{
description: 'Flickr Access Token',
id: 'flickr-access-token',
regex:
'(?i)(?:flickr)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['flickr'],
},
{
description: 'Flutterwave Encryption Key',
id: 'flutterwave-encryption-key',
regex: 'FLWSECK_TEST-(?i)[a-h0-9]{12}',
keywords: ['flwseck_test'],
},
{
description: 'Finicity Public Key',
id: 'flutterwave-public-key',
regex: 'FLWPUBK_TEST-(?i)[a-h0-9]{32}-X',
keywords: ['flwpubk_test'],
},
{
description: 'Flutterwave Secret Key',
id: 'flutterwave-secret-key',
regex: 'FLWSECK_TEST-(?i)[a-h0-9]{32}-X',
keywords: ['flwseck_test'],
},
{
description: 'Frame.io API token',
id: 'frameio-api-token',
regex: 'fio-u-(?i)[a-z0-9\\-_=]{64}',
keywords: ['fio-u-'],
},
{
description: 'Freshbooks Access Token',
id: 'freshbooks-access-token',
regex:
'(?i)(?:freshbooks)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['freshbooks'],
},
{
description: 'GCP API key',
id: 'gcp-api-key',
regex: '(?i)\\b(AIza[0-9A-Za-z\\\\-_]{35})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['aiza'],
},
{
description: 'Generic API Key',
id: 'generic-api-key',
regex:
'(?i)(?:key|api|token|secret|client|passwd|password|auth|access)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9a-z\\-_.=]{10,150})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
entropy: 3.5,
keywords: ['key', 'api', 'token', 'secret', 'client', 'passwd', 'password', 'auth', 'access'],
allowlist: {
stopwords: [
'client',
'endpoint',
'vpn',
'_ec2_',
'aws_',
'authorize',
'author',
'define',
'config',
'credential',
'setting',
'sample',
'xxxxxx',
'000000',
'buffer',
'delete',
'aaaaaa',
'fewfwef',
'getenv',
'env_',
'system',
'example',
'ecdsa',
'sha256',
'sha1',
'sha2',
'md5',
'alert',
'wizard',
'target',
'onboard',
'welcome',
'page',
'exploit',
'experiment',
'expire',
'rabbitmq',
'scraper',
'widget',
'music',
'dns_',
'dns-',
'yahoo',
'want',
'json',
'action',
'script',
'fix_',
'fix-',
'develop',
'compas',
'stripe',
'service',
'master',
'metric',
'tech',
'gitignore',
'rich',
'open',
'stack',
'irc_',
'irc-',
'sublime',
'kohana',
'has_',
'has-',
'fabric',
'wordpres',
'role',
'osx_',
'osx-',
'boost',
'addres',
'queue',
'working',
'sandbox',
'internet',
'print',
'vision',
'tracking',
'being',
'generator',
'traffic',
'world',
'pull',
'rust',
'watcher',
'small',
'auth',
'full',
'hash',
'more',
'install',
'auto',
'complete',
'learn',
'paper',
'installer',
'research',
'acces',
'last',
'binding',
'spine',
'into',
'chat',
'algorithm',
'resource',
'uploader',
'video',
'maker',
'next',
'proc',
'lock',
'robot',
'snake',
'patch',
'matrix',
'drill',
'terminal',
'term',
'stuff',
'genetic',
'generic',
'identity',
'audit',
'pattern',
'audio',
'web_',
'web-',
'crud',
'problem',
'statu',
'cms-',
'cms_',
'arch',
'coffee',
'workflow',
'changelog',
'another',
'uiview',
'content',
'kitchen',
'gnu_',
'gnu-',
'gnu.',
'conf',
'couchdb',
'client',
'opencv',
'rendering',
'update',
'concept',
'varnish',
'gui_',
'gui-',
'gui.',
'version',
'shared',
'extra',
'product',
'still',
'not_',
'not-',
'not.',
'drop',
'ring',
'png_',
'png-',
'png.',
'actively',
'import',
'output',
'backup',
'start',
'embedded',
'registry',
'pool',
'semantic',
'instagram',
'bash',
'system',
'ninja',
'drupal',
'jquery',
'polyfill',
'physic',
'league',
'guide',
'pack',
'synopsi',
'sketch',
'injection',
'svg_',
'svg-',
'svg.',
'friendly',
'wave',
'convert',
'manage',
'camera',
'link',
'slide',
'timer',
'wrapper',
'gallery',
'url_',
'url-',
'url.',
'todomvc',
'requirej',
'party',
'http',
'payment',
'async',
'library',
'home',
'coco',
'gaia',
'display',
'universal',
'func',
'metadata',
'hipchat',
'under',
'room',
'config',
'personal',
'realtime',
'resume',
'database',
'testing',
'tiny',
'basic',
'forum',
'meetup',
'yet_',
'yet-',
'yet.',
'cento',
'dead',
'fluentd',
'editor',
'utilitie',
'run_',
'run-',
'run.',
'box_',
'box-',
'box.',
'bot_',
'bot-',
'bot.',
'making',
'sample',
'group',
'monitor',
'ajax',
'parallel',
'cassandra',
'ultimate',
'site',
'get_',
'get-',
'get.',
'gen_',
'gen-',
'gen.',
'gem_',
'gem-',
'gem.',
'extended',
'image',
'knife',
'asset',
'nested',
'zero',
'plugin',
'bracket',
'mule',
'mozilla',
'number',
'act_',
'act-',
'act.',
'map_',
'map-',
'map.',
'micro',
'debug',
'openshift',
'chart',
'expres',
'backend',
'task',
'source',
'translate',
'jbos',
'composer',
'sqlite',
'profile',
'mustache',
'mqtt',
'yeoman',
'have',
'builder',
'smart',
'like',
'oauth',
'school',
'guideline',
'captcha',
'filter',
'bitcoin',
'bridge',
'color',
'toolbox',
'discovery',
'new_',
'new-',
'new.',
'dashboard',
'when',
'setting',
'level',
'post',
'standard',
'port',
'platform',
'yui_',
'yui-',
'yui.',
'grunt',
'animation',
'haskell',
'icon',
'latex',
'cheat',
'lua_',
'lua-',
'lua.',
'gulp',
'case',
'author',
'without',
'simulator',
'wifi',
'directory',
'lisp',
'list',
'flat',
'adventure',
'story',
'storm',
'gpu_',
'gpu-',
'gpu.',
'store',
'caching',
'attention',
'solr',
'logger',
'demo',
'shortener',
'hadoop',
'finder',
'phone',
'pipeline',
'range',
'textmate',
'showcase',
'app_',
'app-',
'app.',
'idiomatic',
'edit',
'our_',
'our-',
'our.',
'out_',
'out-',
'out.',
'sentiment',
'linked',
'why_',
'why-',
'why.',
'local',
'cube',
'gmail',
'job_',
'job-',
'job.',
'rpc_',
'rpc-',
'rpc.',
'contest',
'tcp_',
'tcp-',
'tcp.',
'usage',
'buildout',
'weather',
'transfer',
'automated',
'sphinx',
'issue',
'sas_',
'sas-',
'sas.',
'parallax',
'jasmine',
'addon',
'machine',
'solution',
'dsl_',
'dsl-',
'dsl.',
'episode',
'menu',
'theme',
'best',
'adapter',
'debugger',
'chrome',
'tutorial',
'life',
'step',
'people',
'joomla',
'paypal',
'developer',
'solver',
'team',
'current',
'love',
'visual',
'date',
'data',
'canva',
'container',
'future',
'xml_',
'xml-',
'xml.',
'twig',
'nagio',
'spatial',
'original',
'sync',
'archived',
'refinery',
'science',
'mapping',
'gitlab',
'play',
'ext_',
'ext-',
'ext.',
'session',
'impact',
'set_',
'set-',
'set.',
'see_',
'see-',
'see.',
'migration',
'commit',
'community',
'shopify',
"what'",
'cucumber',
'statamic',
'mysql',
'location',
'tower',
'line',
'code',
'amqp',
'hello',
'send',
'index',
'high',
'notebook',
'alloy',
'python',
'field',
'document',
'soap',
'edition',
'email',
'php_',
'php-',
'php.',
'command',
'transport',
'official',
'upload',
'study',
'secure',
'angularj',
'akka',
'scalable',
'package',
'request',
'con_',
'con-',
'con.',
'flexible',
'security',
'comment',
'module',
'flask',
'graph',
'flash',
'apache',
'change',
'window',
'space',
'lambda',
'sheet',
'bookmark',
'carousel',
'friend',
'objective',
'jekyll',
'bootstrap',
'first',
'article',
'gwt_',
'gwt-',
'gwt.',
'classic',
'media',
'websocket',
'touch',
'desktop',
'real',
'read',
'recorder',
'moved',
'storage',
'validator',
'add-on',
'pusher',
'scs_',
'scs-',
'scs.',
'inline',
'asp_',
'asp-',
'asp.',
'timeline',
'base',
'encoding',
'ffmpeg',
'kindle',
'tinymce',
'pretty',
'jpa_',
'jpa-',
'jpa.',
'used',
'user',
'required',
'webhook',
'download',
'resque',
'espresso',
'cloud',
'mongo',
'benchmark',
'pure',
'cakephp',
'modx',
'mode',
'reactive',
'fuel',
'written',
'flickr',
'mail',
'brunch',
'meteor',
'dynamic',
'neo_',
'neo-',
'neo.',
'new_',
'new-',
'new.',
'net_',
'net-',
'net.',
'typo',
'type',
'keyboard',
'erlang',
'adobe',
'logging',
'ckeditor',
'message',
'iso_',
'iso-',
'iso.',
'hook',
'ldap',
'folder',
'reference',
'railscast',
'www_',
'www-',
'www.',
'tracker',
'azure',
'fork',
'form',
'digital',
'exporter',
'skin',
'string',
'template',
'designer',
'gollum',
'fluent',
'entity',
'language',
'alfred',
'summary',
'wiki',
'kernel',
'calendar',
'plupload',
'symfony',
'foundry',
'remote',
'talk',
'search',
'dev_',
'dev-',
'dev.',
'del_',
'del-',
'del.',
'token',
'idea',
'sencha',
'selector',
'interface',
'create',
'fun_',
'fun-',
'fun.',
'groovy',
'query',
'grail',
'red_',
'red-',
'red.',
'laravel',
'monkey',
'slack',
'supported',
'instant',
'value',
'center',
'latest',
'work',
'but_',
'but-',
'but.',
'bug_',
'bug-',
'bug.',
'virtual',
'tweet',
'statsd',
'studio',
'path',
'real-time',
'frontend',
'notifier',
'coding',
'tool',
'firmware',
'flow',
'random',
'mediawiki',
'bosh',
'been',
'beer',
'lightbox',
'theory',
'origin',
'redmine',
'hub_',
'hub-',
'hub.',
'require',
'pro_',
'pro-',
'pro.',
'ant_',
'ant-',
'ant.',
'any_',
'any-',
'any.',
'recipe',
'closure',
'mapper',
'event',
'todo',
'model',
'redi',
'provider',
'rvm_',
'rvm-',
'rvm.',
'program',
'memcached',
'rail',
'silex',
'foreman',
'activity',
'license',
'strategy',
'batch',
'streaming',
'fast',
'use_',
'use-',
'use.',
'usb_',
'usb-',
'usb.',
'impres',
'academy',
'slider',
'please',
'layer',
'cros',
'now_',
'now-',
'now.',
'miner',
'extension',
'own_',
'own-',
'own.',
'app_',
'app-',
'app.',
'debian',
'symphony',
'example',
'feature',
'serie',
'tree',
'project',
'runner',
'entry',
'leetcode',
'layout',
'webrtc',
'logic',
'login',
'worker',
'toolkit',
'mocha',
'support',
'back',
'inside',
'device',
'jenkin',
'contact',
'fake',
'awesome',
'ocaml',
'bit_',
'bit-',
'bit.',
'drive',
'screen',
'prototype',
'gist',
'binary',
'nosql',
'rest',
'overview',
'dart',
'dark',
'emac',
'mongoid',
'solarized',
'homepage',
'emulator',
'commander',
'django',
'yandex',
'gradle',
'xcode',
'writer',
'crm_',
'crm-',
'crm.',
'jade',
'startup',
'error',
'using',
'format',
'name',
'spring',
'parser',
'scratch',
'magic',
'try_',
'try-',
'try.',
'rack',
'directive',
'challenge',
'slim',
'counter',
'element',
'chosen',
'doc_',
'doc-',
'doc.',
'meta',
'should',
'button',
'packet',
'stream',
'hardware',
'android',
'infinite',
'password',
'software',
'ghost',
'xamarin',
'spec',
'chef',
'interview',
'hubot',
'mvc_',
'mvc-',
'mvc.',
'exercise',
'leaflet',
'launcher',
'air_',
'air-',
'air.',
'photo',
'board',
'boxen',
'way_',
'way-',
'way.',
'computing',
'welcome',
'notepad',
'portfolio',
'cat_',
'cat-',
'cat.',
'can_',
'can-',
'can.',
'magento',
'yaml',
'domain',
'card',
'yii_',
'yii-',
'yii.',
'checker',
'browser',
'upgrade',
'only',
'progres',
'aura',
'ruby_',
'ruby-',
'ruby.',
'polymer',
'util',
'lite',
'hackathon',
'rule',
'log_',
'log-',
'log.',
'opengl',
'stanford',
'skeleton',
'history',
'inspector',
'help',
'soon',
'selenium',
'lab_',
'lab-',
'lab.',
'scheme',
'schema',
'look',
'ready',
'leveldb',
'docker',
'game',
'minimal',
'logstash',
'messaging',
'within',
'heroku',
'mongodb',
'kata',
'suite',
'picker',
'win_',
'win-',
'win.',
'wip_',
'wip-',
'wip.',
'panel',
'started',
'starter',
'front-end',
'detector',
'deploy',
'editing',
'based',
'admin',
'capture',
'spree',
'page',
'bundle',
'goal',
'rpg_',
'rpg-',
'rpg.',
'setup',
'side',
'mean',
'reader',
'cookbook',
'mini',
'modern',
'seed',
'dom_',
'dom-',
'dom.',
'doc_',
'doc-',
'doc.',
'dot_',
'dot-',
'dot.',
'syntax',
'sugar',
'loader',
'website',
'make',
'kit_',
'kit-',
'kit.',
'protocol',
'human',
'daemon',
'golang',
'manager',
'countdown',
'connector',
'swagger',
'map_',
'map-',
'map.',
'mac_',
'mac-',
'mac.',
'man_',
'man-',
'man.',
'orm_',
'orm-',
'orm.',
'org_',
'org-',
'org.',
'little',
'zsh_',
'zsh-',
'zsh.',
'shop',
'show',
'workshop',
'money',
'grid',
'server',
'octopres',
'svn_',
'svn-',
'svn.',
'ember',
'embed',
'general',
'file',
'important',
'dropbox',
'portable',
'public',
'docpad',
'fish',
'sbt_',
'sbt-',
'sbt.',
'done',
'para',
'network',
'common',
'readme',
'popup',
'simple',
'purpose',
'mirror',
'single',
'cordova',
'exchange',
'object',
'design',
'gateway',
'account',
'lamp',
'intellij',
'math',
'mit_',
'mit-',
'mit.',
'control',
'enhanced',
'emitter',
'multi',
'add_',
'add-',
'add.',
'about',
'socket',
'preview',
'vagrant',
'cli_',
'cli-',
'cli.',
'powerful',
'top_',
'top-',
'top.',
'radio',
'watch',
'fluid',
'amazon',
'report',
'couchbase',
'automatic',
'detection',
'sprite',
'pyramid',
'portal',
'advanced',
'plu_',
'plu-',
'plu.',
'runtime',
'git_',
'git-',
'git.',
'uri_',
'uri-',
'uri.',
'haml',
'node',
'sql_',
'sql-',
'sql.',
'cool',
'core',
'obsolete',
'handler',
'iphone',
'extractor',
'array',
'copy',
'nlp_',
'nlp-',
'nlp.',
'reveal',
'pop_',
'pop-',
'pop.',
'engine',
'parse',
'check',
'html',
'nest',
'all_',
'all-',
'all.',
'chinese',
'buildpack',
'what',
'tag_',
'tag-',
'tag.',
'proxy',
'style',
'cookie',
'feed',
'restful',
'compiler',
'creating',
'prelude',
'context',
'java',
'rspec',
'mock',
'backbone',
'light',
'spotify',
'flex',
'related',
'shell',
'which',
'clas',
'webapp',
'swift',
'ansible',
'unity',
'console',
'tumblr',
'export',
'campfire',
"conway'",
'made',
'riak',
'hero',
'here',
'unix',
'unit',
'glas',
'smtp',
'how_',
'how-',
'how.',
'hot_',
'hot-',
'hot.',
'debug',
'release',
'diff',
'player',
'easy',
'right',
'old_',
'old-',
'old.',
'animate',
'time',
'push',
'explorer',
'course',
'training',
'nette',
'router',
'draft',
'structure',
'note',
'salt',
'where',
'spark',
'trello',
'power',
'method',
'social',
'via_',
'via-',
'via.',
'vim_',
'vim-',
'vim.',
'select',
'webkit',
'github',
'ftp_',
'ftp-',
'ftp.',
'creator',
'mongoose',
'led_',
'led-',
'led.',
'movie',
'currently',
'pdf_',
'pdf-',
'pdf.',
'load',
'markdown',
'phalcon',
'input',
'custom',
'atom',
'oracle',
'phonegap',
'ubuntu',
'great',
'rdf_',
'rdf-',
'rdf.',
'popcorn',
'firefox',
'zip_',
'zip-',
'zip.',
'cuda',
'dotfile',
'static',
'openwrt',
'viewer',
'powered',
'graphic',
'les_',
'les-',
'les.',
'doe_',
'doe-',
'doe.',
'maven',
'word',
'eclipse',
'lab_',
'lab-',
'lab.',
'hacking',
'steam',
'analytic',
'option',
'abstract',
'archive',
'reality',
'switcher',
'club',
'write',
'kafka',
'arduino',
'angular',
'online',
'title',
"don't",
'contao',
'notice',
'analyzer',
'learning',
'zend',
'external',
'staging',
'busines',
'tdd_',
'tdd-',
'tdd.',
'scanner',
'building',
'snippet',
'modular',
'bower',
'stm_',
'stm-',
'stm.',
'lib_',
'lib-',
'lib.',
'alpha',
'mobile',
'clean',
'linux',
'nginx',
'manifest',
'some',
'raspberry',
'gnome',
'ide_',
'ide-',
'ide.',
'block',
'statistic',
'info',
'drag',
'youtube',
'koan',
'facebook',
'paperclip',
'art_',
'art-',
'art.',
'quality',
'tab_',
'tab-',
'tab.',
'need',
'dojo',
'shield',
'computer',
'stat',
'state',
'twitter',
'utility',
'converter',
'hosting',
'devise',
'liferay',
'updated',
'force',
'tip_',
'tip-',
'tip.',
'behavior',
'active',
'call',
'answer',
'deck',
'better',
'principle',
'ches',
'bar_',
'bar-',
'bar.',
'reddit',
'three',
'haxe',
'just',
'plug-in',
'agile',
'manual',
'tetri',
'super',
'beta',
'parsing',
'doctrine',
'minecraft',
'useful',
'perl',
'sharing',
'agent',
'switch',
'view',
'dash',
'channel',
'repo',
'pebble',
'profiler',
'warning',
'cluster',
'running',
'markup',
'evented',
'mod_',
'mod-',
'mod.',
'share',
'csv_',
'csv-',
'csv.',
'response',
'good',
'house',
'connect',
'built',
'build',
'find',
'ipython',
'webgl',
'big_',
'big-',
'big.',
'google',
'scala',
'sdl_',
'sdl-',
'sdl.',
'sdk_',
'sdk-',
'sdk.',
'native',
'day_',
'day-',
'day.',
'puppet',
'text',
'routing',
'helper',
'linkedin',
'crawler',
'host',
'guard',
'merchant',
'poker',
'over',
'writing',
'free',
'classe',
'component',
'craft',
'nodej',
'phoenix',
'longer',
'quick',
'lazy',
'memory',
'clone',
'hacker',
'middleman',
'factory',
'motion',
'multiple',
'tornado',
'hack',
'ssh_',
'ssh-',
'ssh.',
'review',
'vimrc',
'driver',
'driven',
'blog',
'particle',
'table',
'intro',
'importer',
'thrift',
'xmpp',
'framework',
'refresh',
'react',
'font',
'librarie',
'variou',
'formatter',
'analysi',
'karma',
'scroll',
'tut_',
'tut-',
'tut.',
'apple',
'tag_',
'tag-',
'tag.',
'tab_',
'tab-',
'tab.',
'category',
'ionic',
'cache',
'homebrew',
'reverse',
'english',
'getting',
'shipping',
'clojure',
'boot',
'book',
'branch',
'combination',
'combo',
],
},
},
{
description: 'GitHub App Token',
id: 'github-app-token',
regex: '(ghu|ghs)_[0-9a-zA-Z]{36}',
keywords: ['ghu_', 'ghs_'],
},
{
description: 'GitHub Fine-Grained Personal Access Token',
id: 'github-fine-grained-pat',
regex: 'github_pat_[0-9a-zA-Z_]{82}',
keywords: ['github_pat_'],
},
{
description: 'GitHub OAuth Access Token',
id: 'github-oauth',
regex: 'gho_[0-9a-zA-Z]{36}',
keywords: ['gho_'],
},
{
description: 'GitHub Personal Access Token',
id: 'github-pat',
regex: 'ghp_[0-9a-zA-Z]{36}',
keywords: ['ghp_'],
},
{
description: 'GitHub Refresh Token',
id: 'github-refresh-token',
regex: 'ghr_[0-9a-zA-Z]{36}',
keywords: ['ghr_'],
},
{
description: 'GitLab Personal Access Token',
id: 'gitlab-pat',
regex: 'glpat-[0-9a-zA-Z\\-\\_]{20}',
keywords: ['glpat-'],
},
{
description: 'GitLab Pipeline Trigger Token',
id: 'gitlab-ptt',
regex: 'glptt-[0-9a-f]{40}',
keywords: ['glptt-'],
},
{
description: 'GitLab Runner Registration Token',
id: 'gitlab-rrt',
regex: 'GR1348941[0-9a-zA-Z\\-\\_]{20}',
keywords: ['gr1348941'],
},
{
description: 'Gitter Access Token',
id: 'gitter-access-token',
regex:
'(?i)(?:gitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9_-]{40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['gitter'],
},
{
description: 'GoCardless API token',
id: 'gocardless-api-token',
regex:
'(?i)(?:gocardless)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(live_(?i)[a-z0-9\\-_=]{40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['live_', 'gocardless'],
},
{
description: 'Grafana api key (or Grafana cloud api key)',
id: 'grafana-api-key',
regex: '(?i)\\b(eyJrIjoi[A-Za-z0-9]{70,400}={0,2})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['eyjrijoi'],
},
{
description: 'Grafana cloud api token',
id: 'grafana-cloud-api-token',
regex: '(?i)\\b(glc_[A-Za-z0-9+/]{32,400}={0,2})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['glc_'],
},
{
description: 'Grafana service account token',
id: 'grafana-service-account-token',
regex: '(?i)\\b(glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['glsa_'],
},
{
description: 'HashiCorp Terraform user/org API token',
id: 'hashicorp-tf-api-token',
regex: '(?i)[a-z0-9]{14}\\.atlasv1\\.[a-z0-9\\-_=]{60,70}',
keywords: ['atlasv1'],
},
{
description: 'Heroku API Key',
id: 'heroku-api-key',
regex:
'(?i)(?:heroku)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['heroku'],
},
{
description: 'HubSpot API Token',
id: 'hubspot-api-key',
regex:
'(?i)(?:hubspot)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['hubspot'],
},
{
description: 'Intercom API Token',
id: 'intercom-api-key',
regex:
'(?i)(?:intercom)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{60})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['intercom'],
},
{
description: 'JSON Web Token',
id: 'jwt',
regex:
'(?i)\\b(ey[0-9a-z]{30,34}\\.ey[0-9a-z-\\/_]{30,500}\\.[0-9a-zA-Z-\\/_]{10,200}={0,2})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['ey'],
},
{
description: 'Kraken Access Token',
id: 'kraken-access-token',
regex:
'(?i)(?:kraken)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9\\/=_\\+\\-]{80,90})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['kraken'],
},
{
description: 'Kucoin Access Token',
id: 'kucoin-access-token',
regex:
'(?i)(?:kucoin)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{24})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['kucoin'],
},
{
description: 'Kucoin Secret Key',
id: 'kucoin-secret-key',
regex:
'(?i)(?:kucoin)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['kucoin'],
},
{
description: 'Launchdarkly Access Token',
id: 'launchdarkly-access-token',
regex:
'(?i)(?:launchdarkly)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['launchdarkly'],
},
{
description: 'Linear API Token',
id: 'linear-api-key',
regex: 'lin_api_(?i)[a-z0-9]{40}',
keywords: ['lin_api_'],
},
{
description: 'Linear Client Secret',
id: 'linear-client-secret',
regex:
'(?i)(?:linear)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['linear'],
},
{
description: 'LinkedIn Client ID',
id: 'linkedin-client-id',
regex:
'(?i)(?:linkedin|linked-in)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{14})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['linkedin', 'linked-in'],
},
{
description: 'LinkedIn Client secret',
id: 'linkedin-client-secret',
regex:
'(?i)(?:linkedin|linked-in)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{16})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['linkedin', 'linked-in'],
},
{
description: 'Lob API Key',
id: 'lob-api-key',
regex:
'(?i)(?:lob)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}((live|test)_[a-f0-9]{35})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['test_', 'live_'],
},
{
description: 'Lob Publishable API Key',
id: 'lob-pub-api-key',
regex:
'(?i)(?:lob)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}((test|live)_pub_[a-f0-9]{31})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['test_pub', 'live_pub', '_pub'],
},
{
description: 'Mailchimp API key',
id: 'mailchimp-api-key',
regex:
'(?i)(?:mailchimp)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{32}-us20)(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['mailchimp'],
},
{
description: 'Mailgun private API token',
id: 'mailgun-private-api-token',
regex:
'(?i)(?:mailgun)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(key-[a-f0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['mailgun'],
},
{
description: 'Mailgun public validation key',
id: 'mailgun-pub-key',
regex:
'(?i)(?:mailgun)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(pubkey-[a-f0-9]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['mailgun'],
},
{
description: 'Mailgun webhook signing key',
id: 'mailgun-signing-key',
regex:
'(?i)(?:mailgun)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['mailgun'],
},
{
description: 'MapBox API token',
id: 'mapbox-api-token',
regex:
'(?i)(?:mapbox)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(pk\\.[a-z0-9]{60}\\.[a-z0-9]{22})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['mapbox'],
},
{
description: 'Mattermost Access Token',
id: 'mattermost-access-token',
regex:
'(?i)(?:mattermost)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{26})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['mattermost'],
},
{
description: 'MessageBird API token',
id: 'messagebird-api-token',
regex:
'(?i)(?:messagebird|message-bird|message_bird)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{25})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['messagebird', 'message-bird', 'message_bird'],
},
{
description: 'MessageBird client ID',
id: 'messagebird-client-id',
regex:
'(?i)(?:messagebird|message-bird|message_bird)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['messagebird', 'message-bird', 'message_bird'],
},
{
description: 'Microsoft Teams Webhook',
id: 'microsoft-teams-webhook',
regex:
'https:\\/\\/[a-z0-9]+\\.webhook\\.office\\.com\\/webhookb2\\/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}@[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\\/IncomingWebhook\\/[a-z0-9]{32}\\/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}',
keywords: ['webhook.office.com', 'webhookb2', 'incomingwebhook'],
},
{
description: 'Netlify Access Token',
id: 'netlify-access-token',
regex:
'(?i)(?:netlify)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{40,46})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['netlify'],
},
{
description: 'New Relic ingest browser API token',
id: 'new-relic-browser-api-token',
regex:
'(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(NRJS-[a-f0-9]{19})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['nrjs-'],
},
{
description: 'New Relic user API ID',
id: 'new-relic-user-api-id',
regex:
'(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['new-relic', 'newrelic', 'new_relic'],
},
{
description: 'New Relic user API Key',
id: 'new-relic-user-api-key',
regex:
'(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(NRAK-[a-z0-9]{27})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['nrak'],
},
{
description: 'npm access token',
id: 'npm-access-token',
regex: '(?i)\\b(npm_[a-z0-9]{36})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['npm_'],
},
{
description: 'Nytimes Access Token',
id: 'nytimes-access-token',
regex:
'(?i)(?:nytimes|new-york-times,|newyorktimes)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{32})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['nytimes', 'new-york-times', 'newyorktimes'],
},
{
description: 'Okta Access Token',
id: 'okta-access-token',
regex:
'(?i)(?:okta)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{42})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['okta'],
},
{
description: 'Plaid API Token',
id: 'plaid-api-token',
regex:
'(?i)(?:plaid)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(access-(?:sandbox|development|production)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['plaid'],
},
{
description: 'Plaid Client ID',
id: 'plaid-client-id',
regex:
'(?i)(?:plaid)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{24})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['plaid'],
},
{
description: 'Plaid Secret key',
id: 'plaid-secret-key',
regex:
'(?i)(?:plaid)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{30})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['plaid'],
},
{
description: 'PlanetScale API token',
id: 'planetscale-api-token',
regex: '(?i)\\b(pscale_tkn_(?i)[a-z0-9=\\-_\\.]{32,64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['pscale_tkn_'],
},
{
description: 'PlanetScale OAuth token',
id: 'planetscale-oauth-token',
regex: '(?i)\\b(pscale_oauth_(?i)[a-z0-9=\\-_\\.]{32,64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['pscale_oauth_'],
},
{
description: 'PlanetScale password',
id: 'planetscale-password',
regex: '(?i)\\b(pscale_pw_(?i)[a-z0-9=\\-_\\.]{32,64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['pscale_pw_'],
},
{
description: 'Postman API token',
id: 'postman-api-token',
regex: '(?i)\\b(PMAK-(?i)[a-f0-9]{24}\\-[a-f0-9]{34})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['pmak-'],
},
{
description: 'Prefect API token',
id: 'prefect-api-token',
regex: '(?i)\\b(pnu_[a-z0-9]{36})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['pnu_'],
},
{
description: 'Private Key',
id: 'private-key',
regex: '(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY( BLOCK)?-----[\\s\\S-]*KEY( BLOCK)?----',
keywords: ['-----begin'],
},
{
description: 'Pulumi API token',
id: 'pulumi-api-token',
regex: '(?i)\\b(pul-[a-f0-9]{40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['pul-'],
},
{
description: 'PyPI upload token',
id: 'pypi-upload-token',
regex: 'pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\\-_]{50,1000}',
keywords: ['pypi-ageichlwas5vcmc'],
},
{
description: 'RapidAPI Access Token',
id: 'rapidapi-access-token',
regex:
'(?i)(?:rapidapi)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9_-]{50})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['rapidapi'],
},
{
description: 'Readme API token',
id: 'readme-api-token',
regex: '(?i)\\b(rdme_[a-z0-9]{70})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['rdme_'],
},
{
description: 'Rubygem API token',
id: 'rubygems-api-token',
regex: '(?i)\\b(rubygems_[a-f0-9]{48})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['rubygems_'],
},
{
description: 'Sendbird Access ID',
id: 'sendbird-access-id',
regex:
'(?i)(?:sendbird)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['sendbird'],
},
{
description: 'Sendbird Access Token',
id: 'sendbird-access-token',
regex:
'(?i)(?:sendbird)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['sendbird'],
},
{
description: 'SendGrid API token',
id: 'sendgrid-api-token',
regex: '(?i)\\b(SG\\.(?i)[a-z0-9=_\\-\\.]{66})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['sg.'],
},
{
description: 'Sendinblue API token',
id: 'sendinblue-api-token',
regex: '(?i)\\b(xkeysib-[a-f0-9]{64}\\-(?i)[a-z0-9]{16})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['xkeysib-'],
},
{
description: 'Sentry Access Token',
id: 'sentry-access-token',
regex:
'(?i)(?:sentry)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['sentry'],
},
{
description: 'Shippo API token',
id: 'shippo-api-token',
regex: '(?i)\\b(shippo_(live|test)_[a-f0-9]{40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['shippo_'],
},
{
description: 'Shopify access token',
id: 'shopify-access-token',
regex: 'shpat_[a-fA-F0-9]{32}',
keywords: ['shpat_'],
},
{
description: 'Shopify custom access token',
id: 'shopify-custom-access-token',
regex: 'shpca_[a-fA-F0-9]{32}',
keywords: ['shpca_'],
},
{
description: 'Shopify private app access token',
id: 'shopify-private-app-access-token',
regex: 'shppa_[a-fA-F0-9]{32}',
keywords: ['shppa_'],
},
{
description: 'Shopify shared secret',
id: 'shopify-shared-secret',
regex: 'shpss_[a-fA-F0-9]{32}',
keywords: ['shpss_'],
},
{
description: 'Sidekiq Secret',
id: 'sidekiq-secret',
regex:
'(?i)(?:BUNDLE_ENTERPRISE__CONTRIBSYS__COM|BUNDLE_GEMS__CONTRIBSYS__COM)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-f0-9]{8}:[a-f0-9]{8})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['bundle_enterprise__contribsys__com', 'bundle_gems__contribsys__com'],
},
{
description: 'Sidekiq Sensitive URL',
id: 'sidekiq-sensitive-url',
regex:
'(?i)\\b(http(?:s??):\\/\\/)([a-f0-9]{8}:[a-f0-9]{8})@(?:gems.contribsys.com|enterprise.contribsys.com)(?:[\\/|\\#|\\?|:]|$)',
secretGroup: 2,
keywords: ['gems.contribsys.com', 'enterprise.contribsys.com'],
},
{
description: 'Slack token',
id: 'slack-access-token',
regex: 'xox[baprs]-([0-9a-zA-Z]{10,48})',
keywords: ['xoxb', 'xoxa', 'xoxp', 'xoxr', 'xoxs'],
},
{
description: 'Slack Webhook',
id: 'slack-web-hook',
regex: 'https:\\/\\/hooks.slack.com\\/(services|workflows)\\/[A-Za-z0-9+\\/]{44,46}',
keywords: ['hooks.slack.com'],
},
{
description: 'Square Access Token',
id: 'square-access-token',
regex: '(?i)\\b(sq0atp-[0-9A-Za-z\\-_]{22})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['sq0atp-'],
},
{
description: 'Squarespace Access Token',
id: 'squarespace-access-token',
regex:
'(?i)(?:squarespace)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['squarespace'],
},
{
description: 'Stripe Access Token',
id: 'stripe-access-token',
regex: '(?i)(sk|pk)_(test|live)_[0-9a-z]{10,32}',
keywords: ['sk_test', 'pk_test', 'sk_live', 'pk_live'],
},
{
description: 'SumoLogic Access ID',
id: 'sumologic-access-id',
regex:
'(?i)(?:sumo)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{14})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['sumo'],
},
{
description: 'SumoLogic Access Token',
id: 'sumologic-access-token',
regex:
'(?i)(?:sumo)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{64})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['sumo'],
},
{
description: 'Telegram Bot API Token',
id: 'telegram-bot-api-token',
regex: '(?i)(?:^|[^0-9])([0-9]{5,16}:A[a-zA-Z0-9_\\-]{34})(?:$|[^a-zA-Z0-9_\\-])',
secretGroup: 1,
keywords: ['telegram', 'api', 'bot', 'token', 'url'],
},
{
description: 'Travis CI Access Token',
id: 'travisci-access-token',
regex:
'(?i)(?:travis)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{22})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['travis'],
},
{
description: 'Twilio API Key',
id: 'twilio-api-key',
regex: 'SK[0-9a-fA-F]{32}',
keywords: ['twilio'],
},
{
description: 'Twitch API token',
id: 'twitch-api-token',
regex:
'(?i)(?:twitch)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{30})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['twitch'],
},
{
description: 'Twitter Access Secret',
id: 'twitter-access-secret',
regex:
'(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{45})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['twitter'],
},
{
description: 'Twitter Access Token',
id: 'twitter-access-token',
regex:
'(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([0-9]{15,25}-[a-zA-Z0-9]{20,40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['twitter'],
},
{
description: 'Twitter API Key',
id: 'twitter-api-key',
regex:
'(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{25})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['twitter'],
},
{
description: 'Twitter API Secret',
id: 'twitter-api-secret',
regex:
'(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{50})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['twitter'],
},
{
description: 'Twitter Bearer Token',
id: 'twitter-bearer-token',
regex:
'(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(A{22}[a-zA-Z0-9%]{80,100})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['twitter'],
},
{
description: 'Typeform API token',
id: 'typeform-api-token',
regex:
'(?i)(?:typeform)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(tfp_[a-z0-9\\-_\\.=]{59})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['tfp_'],
},
{
description: 'Vault Batch Token',
id: 'vault-batch-token',
regex: '(?i)\\b(hvb\\.[a-z0-9_-]{138,212})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['hvb'],
},
{
description: 'Vault Service Token',
id: 'vault-service-token',
regex: '(?i)\\b(hvs\\.[a-z0-9_-]{90,100})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
keywords: ['hvs'],
},
{
description: 'Yandex Access Token',
id: 'yandex-access-token',
regex:
'(?i)(?:yandex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(t1\\.[A-Z0-9a-z_-]+[=]{0,2}\\.[A-Z0-9a-z_-]{86}[=]{0,2})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['yandex'],
},
{
description: 'Yandex API Key',
id: 'yandex-api-key',
regex:
'(?i)(?:yandex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(AQVN[A-Za-z0-9_\\-]{35,38})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['yandex'],
},
{
description: 'Yandex AWS Access Token',
id: 'yandex-aws-access-token',
regex:
'(?i)(?:yandex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}(YC[a-zA-Z0-9_\\-]{38})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['yandex'],
},
{
description: 'Zendesk Secret Key',
id: 'zendesk-secret-key',
regex:
'(?i)(?:zendesk)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|"]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\"|\\s|=|\\x60){0,5}([a-z0-9]{40})(?:[\'|\\"|\\n|\\r|\\s|\\x60|;]|$)',
secretGroup: 1,
keywords: ['zendesk'],
},
];
export default rules;
References:
- src/common/secret_redaction/index.ts:50
- src/common/secret_redaction/index.ts:65
- src/common/secret_redaction/index.ts:45 |
You are a code assistant | Definition of 'error' in file src/common/log_types.ts in project gitlab-lsp | Definition:
error(message: string, e?: Error): void;
}
export const LOG_LEVEL = {
DEBUG: 'debug',
INFO: 'info',
WARNING: 'warning',
ERROR: 'error',
} as const;
export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL];
References:
- 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 'MultiTracker' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp | Definition:
export class MultiTracker implements TelemetryTracker {
#trackers: TelemetryTracker[] = [];
constructor(trackers: TelemetryTracker[]) {
this.#trackers = trackers;
}
get #enabledTrackers() {
return this.#trackers.filter((t) => t.isEnabled());
}
isEnabled(): boolean {
return Boolean(this.#enabledTrackers.length);
}
setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
this.#enabledTrackers.forEach((t) => t.setCodeSuggestionsContext(uniqueTrackingId, context));
}
updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
this.#enabledTrackers.forEach((t) =>
t.updateCodeSuggestionsContext(uniqueTrackingId, contextUpdate),
);
}
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS) {
this.#enabledTrackers.forEach((t) => t.updateSuggestionState(uniqueTrackingId, newState));
}
rejectOpenedSuggestions() {
this.#enabledTrackers.forEach((t) => t.rejectOpenedSuggestions());
}
}
References:
- src/common/tracking/multi_tracker.test.ts:45
- src/node/main.ts:164
- src/browser/main.ts:110
- src/common/tracking/multi_tracker.test.ts:61
- src/common/tracking/multi_tracker.test.ts:70 |
You are a code assistant | Definition of 'DefaultWorkspaceService' in file src/common/workspace/workspace_service.ts in project gitlab-lsp | Definition:
export class DefaultWorkspaceService {
#virtualFileSystemService: DefaultVirtualFileSystemService;
#workspaceFilesMap = new Map<string, FileSet>();
#disposable: { dispose: () => void };
constructor(virtualFileSystemService: DefaultVirtualFileSystemService) {
this.#virtualFileSystemService = virtualFileSystemService;
this.#disposable = this.#setupEventListeners();
}
#setupEventListeners() {
return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => {
switch (eventType) {
case VirtualFileSystemEvents.WorkspaceFilesUpdate:
this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate);
break;
case VirtualFileSystemEvents.WorkspaceFileUpdate:
this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate);
break;
default:
break;
}
});
}
#handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) {
const files: FileSet = new Map();
for (const file of update.files) {
files.set(file.toString(), file);
}
this.#workspaceFilesMap.set(update.workspaceFolder.uri, files);
}
#handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) {
let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri);
if (!files) {
files = new Map();
this.#workspaceFilesMap.set(update.workspaceFolder.uri, files);
}
switch (update.event) {
case 'add':
case 'change':
files.set(update.fileUri.toString(), update.fileUri);
break;
case 'unlink':
files.delete(update.fileUri.toString());
break;
default:
break;
}
}
getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined {
return this.#workspaceFilesMap.get(workspaceFolder.uri);
}
dispose() {
this.#disposable.dispose();
}
}
References: |
You are a code assistant | Definition of 'AdvancedContextService' in file src/common/advanced_context/advanced_context_service.ts in project gitlab-lsp | Definition:
export const AdvancedContextService =
createInterfaceId<AdvancedContextService>('AdvancedContextService');
@Injectable(AdvancedContextService, [
ConfigService,
LsConnection,
DocumentService,
DocumentTransformerService,
SupportedLanguagesService,
])
export class DefaultAdvancedContextService implements AdvancedContextService {
#configService: ConfigService;
#documentTransformer: DocumentTransformerService;
#supportedLanguagesService: SupportedLanguagesService;
constructor(
configService: ConfigService,
connection: LsConnection,
documentService: DocumentService,
documentTransformer: DocumentTransformerService,
supportedLanguagesService: SupportedLanguagesService,
) {
this.#configService = configService;
this.#documentTransformer = documentTransformer;
this.#supportedLanguagesService = supportedLanguagesService;
const subscription = documentService.onDocumentChange(async ({ document }, handlerType) => {
await this.#updateAdvancedContext(document, handlerType);
});
connection.onShutdown(() => subscription.dispose());
}
/**
* Currently updates the LRU cache with the most recently accessed files in the workspace.
* We only update the advanced context for supported languages. We also ensure to run
* documents through the `DocumentTransformer` to ensure the secret redaction is applied.
*/
async #updateAdvancedContext(
document: TextDocument,
handlerType: TextDocumentChangeListenerType,
) {
const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT);
// eslint-disable-next-line default-case
switch (handlerType) {
case TextDocumentChangeListenerType.onDidClose: {
// We don't check if the language is supported for `onDidClose` because we want
// always attempt to delete the file from the cache.
const fileDeleted = lruCache.deleteFile(document.uri);
if (fileDeleted) {
log.debug(`Advanced Context: File ${document.uri} was deleted from the LRU cache`);
} else {
log.debug(`Advanced Context: File ${document.uri} was not found in the LRU cache`);
}
break;
}
case TextDocumentChangeListenerType.onDidChangeContent:
case TextDocumentChangeListenerType.onDidSave:
case TextDocumentChangeListenerType.onDidOpen:
case TextDocumentChangeListenerType.onDidSetActive: {
const languageEnabled = this.#supportedLanguagesService.isLanguageEnabled(
document.languageId,
);
if (!languageEnabled) {
return;
}
const context = this.#documentTransformer.getContext(
document.uri,
{ line: 0, character: 0 },
this.#configService.get().client.workspaceFolders ?? [],
undefined,
);
if (!context) {
log.debug(`Advanced Context: document context for ${document.uri} was not found`);
return;
}
lruCache.updateFile(context);
log.debug(`Advanced Context: uri ${document.uri} was updated in the MRU cache`);
break;
}
}
}
}
References: |
You are a code assistant | Definition of 'Feature' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp | Definition:
export type Feature = typeof CODE_SUGGESTIONS | typeof CHAT; // | typeof WORKFLOW;
export const NO_LICENSE = 'code-suggestions-no-license' as const;
export const DUO_DISABLED_FOR_PROJECT = 'duo-disabled-for-project' as const;
export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const;
export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const;
export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const;
export type StateCheckId =
| typeof NO_LICENSE
| typeof DUO_DISABLED_FOR_PROJECT
| typeof UNSUPPORTED_GITLAB_VERSION
| typeof UNSUPPORTED_LANGUAGE
| typeof DISABLED_LANGUAGE;
export interface FeatureStateCheck {
checkId: StateCheckId;
details?: string;
}
export interface FeatureState {
featureId: Feature;
engagedChecks: FeatureStateCheck[];
}
const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [
DUO_DISABLED_FOR_PROJECT,
UNSUPPORTED_LANGUAGE,
DISABLED_LANGUAGE,
];
const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT];
export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = {
[CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED,
[CHAT]: CHAT_CHECKS_PRIORITY_ORDERED,
// [WORKFLOW]: [],
};
References:
- src/common/feature_state/feature_state_management_types.ts:25 |
You are a code assistant | Definition of 'build' in file scripts/esbuild/common.ts in project gitlab-lsp | Definition:
async function build() {
await esbuild.build(config);
}
void build();
References:
- scripts/esbuild/browser.ts:26
- scripts/esbuild/desktop.ts:41
- scripts/esbuild/common.ts:31 |
You are a code assistant | Definition of 'DirectConnectionClient' in file src/common/suggestion_client/direct_connection_client.ts in project gitlab-lsp | Definition:
export class DirectConnectionClient implements SuggestionClient {
#api: GitLabApiClient;
#connectionDetails: IDirectConnectionDetails | undefined;
#configService: ConfigService;
#isValidApi = true;
#connectionDetailsCircuitBreaker = new ExponentialBackoffCircuitBreaker(
'Code Suggestions Direct connection details',
{
maxBackoffMs: HOUR,
initialBackoffMs: SECOND,
backoffMultiplier: 3,
},
);
#directConnectionCircuitBreaker = new ExponentialBackoffCircuitBreaker(
'Code Suggestions Direct Connection',
{
initialBackoffMs: SECOND,
maxBackoffMs: 10 * MINUTE,
backoffMultiplier: 5,
},
);
constructor(api: GitLabApiClient, configService: ConfigService) {
this.#api = api;
this.#configService = configService;
this.#api.onApiReconfigured(({ isInValidState }) => {
this.#connectionDetails = undefined;
this.#isValidApi = isInValidState;
this.#directConnectionCircuitBreaker.success(); // resets the circuit breaker
// TODO: fetch the direct connection details https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/239
});
}
#fetchDirectConnectionDetails = async () => {
if (this.#connectionDetailsCircuitBreaker.isOpen()) {
return;
}
let details;
try {
details = await this.#api.fetchFromApi<IDirectConnectionDetails>({
type: 'rest',
method: 'POST',
path: '/code_suggestions/direct_access',
supportedSinceInstanceVersion: {
version: '17.2.0',
resourceName: 'get direct connection details',
},
});
} catch (e) {
// 401 indicates that the user has GitLab Duo disabled and shout result in longer periods of open circuit
if (isFetchError(e) && e.status === 401) {
this.#connectionDetailsCircuitBreaker.megaError();
} else {
this.#connectionDetailsCircuitBreaker.error();
}
log.info(
`Failed to fetch direct connection details from GitLab instance. Code suggestion requests will be sent to your GitLab instance. Error ${e}`,
);
}
this.#connectionDetails = details;
this.#configService.merge({
client: { snowplowTrackerOptions: transformHeadersToSnowplowOptions(details?.headers) },
});
};
async #fetchUsingDirectConnection<T>(request: CodeSuggestionRequest): Promise<T> {
if (!this.#connectionDetails) {
throw new Error('Assertion error: connection details are undefined');
}
const suggestionEndpoint = `${this.#connectionDetails.base_url}/v2/completions`;
const start = Date.now();
const response = await fetch(suggestionEndpoint, {
method: 'post',
body: JSON.stringify(request),
keepalive: true,
headers: {
...this.#connectionDetails.headers,
Authorization: `Bearer ${this.#connectionDetails.token}`,
'X-Gitlab-Authentication-Type': 'oidc',
'X-Gitlab-Language-Server-Version': getLanguageServerVersion(),
'Content-Type': ' application/json',
},
signal: AbortSignal.timeout(5 * SECOND),
});
await handleFetchError(response, 'Direct Connection for code suggestions');
const data = await response.json();
const end = Date.now();
log.debug(`Direct connection (${suggestionEndpoint}) suggestion fetched in ${end - start}ms`);
return data;
}
async getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined> {
// TODO we would like to send direct request only for intent === COMPLETION
// however, currently we are not certain that the intent is completion
// when we finish the following two issues, we can be certain that the intent is COMPLETION
//
// https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/173
// https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/247
if (context.intent === GENERATION) {
return undefined;
}
if (!this.#isValidApi) {
return undefined;
}
if (this.#directConnectionCircuitBreaker.isOpen()) {
return undefined;
}
if (!this.#connectionDetails || areExpired(this.#connectionDetails)) {
this.#fetchDirectConnectionDetails().catch(
(e) => log.error(`#fetchDirectConnectionDetails error: ${e}`), // this makes eslint happy, the method should never throw
);
return undefined;
}
try {
const response = await this.#fetchUsingDirectConnection<SuggestionResponse>(
createV2Request(context, this.#connectionDetails.model_details),
);
return response && { ...response, isDirectConnection: true };
} catch (e) {
this.#directConnectionCircuitBreaker.error();
log.warn(
'Direct connection for code suggestions failed. Code suggestion requests will be sent to your GitLab instance.',
e,
);
}
return undefined;
}
}
References:
- src/common/suggestion_client/direct_connection_client.test.ts:25
- src/common/suggestion/suggestion_service.ts:161
- src/common/suggestion_client/direct_connection_client.test.ts:159
- src/common/suggestion_client/direct_connection_client.test.ts:112
- src/common/suggestion_client/direct_connection_client.test.ts:39
- src/common/suggestion/suggestion_service.test.ts:458
- src/common/suggestion_client/direct_connection_client.test.ts:62 |
You are a code assistant | Definition of 'setupTransportEventHandlers' in file packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts in project gitlab-lsp | Definition:
export const setupTransportEventHandlers = (
transport: Transport,
runtimeMessageBus: WebviewRuntimeMessageBus,
managedInstances: ManagedInstances,
): Disposable[] => [
transport.on('webview_instance_created', (address: WebviewAddress) => {
managedInstances.add(address.webviewInstanceId);
runtimeMessageBus.publish('webview:connect', address);
}),
transport.on('webview_instance_destroyed', (address: WebviewAddress) => {
managedInstances.delete(address.webviewInstanceId);
runtimeMessageBus.publish('webview:disconnect', address);
}),
transport.on('webview_instance_notification_received', (message) =>
runtimeMessageBus.publish('webview:notification', message),
),
transport.on('webview_instance_request_received', (message) =>
runtimeMessageBus.publish('webview:request', message),
),
transport.on('webview_instance_response_received', (message) =>
runtimeMessageBus.publish('webview:response', message),
),
];
References:
- packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:42
- packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:32
- packages/lib_webview/src/setup/transport/setup_transport.ts:20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.