Remove dependency on proposal APIs. Fixes #34, Fixes 14, and Supersedes #35

This commit is contained in:
ncoop57 2023-07-01 14:17:58 -04:00
parent 5c1ab1e704
commit 1b1edf6ccb
5 changed files with 492 additions and 245 deletions

View File

@ -12,13 +12,12 @@ function fetchCodeCompletionTexts(prompt, fileName, MODEL_NAME, API_KEY, USE_GPU
return new Promise((resolve, reject) => {
// Send post request to inference API
return (0, node_fetch_1.default)(API_URL, {
method: "post",
method: "POST",
body: JSON.stringify({
"inputs": prompt, "parameters": {
"max_new_tokens": 16, "return_full_text": false,
"do_sample": true, "temperature": 0.8, "top_p": 0.95,
"max_time": 10.0, "num_return_sequences": 3
// CHANGE(reshinth) : "use_gpu": USE_GPU is depreceated, refer https://huggingface.co/docs/api-inference/detailed_parameters#text-generation-task
}
}),
headers: headers

View File

@ -1,7 +1,4 @@
{
"enabledApiProposals": [
"inlineCompletions"
],
"name": "code-clippy",
"displayName": "Code Clippy",
"description": "Your friendly neighborhood Clippy, ready to help you with all your code needs :D!",
@ -27,13 +24,6 @@
"title": "Code Clippy Settings"
}
],
"menus": {
"editor/inlineCompletions/actions": [
{
"command": "extension.code-clippy-settings"
}
]
},
"configuration": {
"title": "Code Clippy Configuration",
"properties": {
@ -93,4 +83,4 @@
"node-fetch": "^2.6.1",
"openai": "^3.0.0"
}
}
}

View File

@ -6,7 +6,7 @@ export type FetchCodeCompletions = {
}
export function fetchCodeCompletionTexts(prompt: string, fileName: string, MODEL_NAME: string, API_KEY: string, USE_GPU: boolean): Promise<FetchCodeCompletions> {
console.log(MODEL_NAME)
console.log(MODEL_NAME);
const API_URL = `https://api-inference.huggingface.co/models/${MODEL_NAME}`;
// Setup header with API key
// eslint-disable-next-line @typescript-eslint/naming-convention
@ -14,43 +14,42 @@ export function fetchCodeCompletionTexts(prompt: string, fileName: string, MODEL
return new Promise((resolve, reject) => {
// Send post request to inference API
return fetch(API_URL, {
method: "post",
method: "POST",
body: JSON.stringify({
"inputs": prompt, "parameters": {
"max_new_tokens": 16, "return_full_text": false,
"do_sample": true, "temperature": 0.8, "top_p": 0.95,
"max_time": 10.0, "num_return_sequences": 3
// CHANGE(reshinth) : "use_gpu": USE_GPU is depreceated, refer https://huggingface.co/docs/api-inference/detailed_parameters#text-generation-task
}
}
}),
headers: headers
})
.then(res => res.json())
.then(json => {
if (Array.isArray(json)) {
const completions = Array<string>()
for (let i=0; i < json.length; i++) {
const completion = json[i].generated_text.trimStart()
if (completion.trim() === "") continue
.then(res => res.json())
.then(json => {
if (Array.isArray(json)) {
const completions = Array<string>();
for (let i = 0; i < json.length; i++) {
const completion = json[i].generated_text.trimStart();
if (completion.trim() === "") continue;
completions.push(
completion
)
completions.push(
completion
);
}
console.log(completions);
resolve({ completions });
}
console.log(completions)
resolve({ completions })
}
else {
console.log(json);
throw new Error(json["error"])
}
})
.catch(err => reject(err))
})
else {
console.log(json);
throw new Error(json["error"]);
}
})
.catch(err => reject(err));
});
}
export function fetchCodeCompletionTextsFaux(prompt: string): Promise<FetchCodeCompletions> {
console.log('fastertransformer')
console.log('fastertransformer');
return new Promise((resolve, reject) => {
const oa = new openai.OpenAIApi(
new openai.Configuration({
@ -64,30 +63,30 @@ export function fetchCodeCompletionTextsFaux(prompt: string): Promise<FetchCodeC
stop: ["\n\n"],
});
return response
.then(res => res.data.choices)
.then(choices => {
if (Array.isArray(choices)) {
const completions = Array<string>()
for (let i=0; i < choices.length; i++) {
const completion = choices[i].text?.trimStart()
if (completion === undefined) continue
if (completion?.trim() === "") continue
.then(res => res.data.choices)
.then(choices => {
if (Array.isArray(choices)) {
const completions = Array<string>();
for (let i = 0; i < choices.length; i++) {
const completion = choices[i].text?.trimStart();
if (completion === undefined) continue;
if (completion?.trim() === "") continue;
completions.push(
completion
);
}
console.log(completions);
resolve({ completions });
}
else {
console.log(choices);
throw new Error("Error");
}
})
.catch(err => reject(err));
});
}
completions.push(
completion
)
}
console.log(completions)
resolve({ completions })
}
else {
console.log(choices);
throw new Error("Error")
}
})
.catch(err => reject(err))
})
}

491
vscode.d.ts vendored
View File

@ -206,7 +206,7 @@ declare module 'vscode' {
/**
* Get a word-range at the given position. By default words are defined by
* common separators, like space, -, _, etc. In addition, per language custom
* [word definitions} can be defined. It
* [word definitions] can be defined. It
* is also possible to provide a custom regular expression.
*
* * *Note 1:* A custom regular expression must not match the empty string and
@ -733,7 +733,7 @@ declare module 'vscode' {
*/
OpenOpen = 0,
/**
* The decoration's range will not widen when edits occur at the start of end.
* The decoration's range will not widen when edits occur at the start or end.
*/
ClosedClosed = 1,
/**
@ -2483,19 +2483,32 @@ declare module 'vscode' {
}
/**
* The code action interface defines the contract between extensions and
* the [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature.
* Provides contextual actions for code. Code actions typically either fix problems or beautify/refactor code.
*
* A code action can be any command that is {@link commands.getCommands known} to the system.
* Code actions are surfaced to users in a few different ways:
*
* - The [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature, which shows
* a list of code actions at the current cursor position. The lightbulb's list of actions includes both quick fixes
* and refactorings.
* - As commands that users can run, such as `Refactor`. Users can run these from the command palette or with keybindings.
* - As source actions, such `Organize Imports`.
* - {@link CodeActionKind.QuickFix Quick fixes} are shown in the problems view.
* - Change applied on save by the `editor.codeActionsOnSave` setting.
*/
export interface CodeActionProvider<T extends CodeAction = CodeAction> {
/**
* Provide commands for the given document and range.
* Get code actions for a given range in a document.
*
* Only return code actions that are relevant to user for the requested range. Also keep in mind how the
* returned code actions will appear in the UI. The lightbulb widget and `Refactor` commands for instance show
* returned code actions as a list, so do not return a large number of code actions that will overwhelm the user.
*
* @param document The document in which the command was invoked.
* @param range The selector or range for which the command was invoked. This will always be a selection if
* there is a currently active editor.
* @param context Context carrying additional information.
* @param range The selector or range for which the command was invoked. This will always be a
* {@link Selection selection} if the actions are being requested in the currently active editor.
* @param context Provides additional information about what code actions are being requested. You can use this
* to see what specific type of code actions are being requested by the editor in order to return more relevant
* actions and avoid returning irrelevant code actions that the editor will discard.
* @param token A cancellation token.
*
* @return An array of code actions, such as quick fixes or refactorings. The lack of a result can be signaled
@ -3697,7 +3710,18 @@ declare module 'vscode' {
* the file is being created with.
* @param metadata Optional metadata for the entry.
*/
createFile(uri: Uri, options?: { readonly overwrite?: boolean; readonly ignoreIfExists?: boolean; readonly contents?: Uint8Array }, metadata?: WorkspaceEditEntryMetadata): void;
createFile(uri: Uri, options?: {
readonly overwrite?: boolean;
readonly ignoreIfExists?: boolean;
/**
* The initial contents of the new file.
*
* If creating a file from a {@link DocumentDropEditProvider drop operation}, you can
* pass in a {@link DataTransferFile} to improve performance by avoiding extra data copying.
*/
readonly contents?: Uint8Array | DataTransferFile;
}, metadata?: WorkspaceEditEntryMetadata): void;
/**
* Delete a file or folder.
@ -6486,7 +6510,7 @@ declare module 'vscode' {
/**
* Outputs the given trace message to the channel. Use this method to log verbose information.
*
* The message is only loggeed if the channel is configured to display {@link LogLevel.Trace trace} log level.
* The message is only logged if the channel is configured to display {@link LogLevel.Trace trace} log level.
*
* @param message trace message to log
*/
@ -6495,7 +6519,7 @@ declare module 'vscode' {
/**
* Outputs the given debug message to the channel.
*
* The message is only loggeed if the channel is configured to display {@link LogLevel.Debug debug} log level or lower.
* The message is only logged if the channel is configured to display {@link LogLevel.Debug debug} log level or lower.
*
* @param message debug message to log
*/
@ -6504,7 +6528,7 @@ declare module 'vscode' {
/**
* Outputs the given information message to the channel.
*
* The message is only loggeed if the channel is configured to display {@link LogLevel.Info info} log level or lower.
* The message is only logged if the channel is configured to display {@link LogLevel.Info info} log level or lower.
*
* @param message info message to log
*/
@ -6513,7 +6537,7 @@ declare module 'vscode' {
/**
* Outputs the given warning message to the channel.
*
* The message is only loggeed if the channel is configured to display {@link LogLevel.Warning warning} log level or lower.
* The message is only logged if the channel is configured to display {@link LogLevel.Warning warning} log level or lower.
*
* @param message warning message to log
*/
@ -6522,7 +6546,7 @@ declare module 'vscode' {
/**
* Outputs the given error or error message to the channel.
*
* The message is only loggeed if the channel is configured to display {@link LogLevel.Error error} log level or lower.
* The message is only logged if the channel is configured to display {@link LogLevel.Error error} log level or lower.
*
* @param error Error or error message to log
*/
@ -7419,6 +7443,11 @@ declare module 'vscode' {
* Controls whether the terminal is cleared before executing the task.
*/
clear?: boolean;
/**
* Controls whether the terminal is closed after executing the task.
*/
close?: boolean;
}
/**
@ -9030,7 +9059,7 @@ declare module 'vscode' {
}
/**
* Additional information used to implement {@linkcode CustomEditableDocument.backup}.
* Additional information used to implement {@linkcode CustomDocumentBackup}.
*/
interface CustomDocumentBackupContext {
/**
@ -9363,6 +9392,15 @@ declare module 'vscode' {
*/
export const onDidChangeTelemetryEnabled: Event<boolean>;
/**
* Creates a new {@link TelemetryLogger telemetry logger}.
*
* @param sender The telemetry sender that is used by the telemetry logger.
* @param options Options for the telemetry logger.
* @returns A new telemetry logger
*/
export function createTelemetryLogger(sender: TelemetrySender, options?: TelemetryLoggerOptions): TelemetryLogger;
/**
* The name of a remote. Defined by extensions, popular samples are `wsl` for the Windows
* Subsystem for Linux or `ssh-remote` for remotes using a secure shell.
@ -10120,22 +10158,23 @@ declare module 'vscode' {
/**
* Creates a status bar {@link StatusBarItem item}.
*
* @param alignment The alignment of the item.
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
* @return A new status bar item.
*/
export function createStatusBarItem(alignment?: StatusBarAlignment, priority?: number): StatusBarItem;
/**
* Creates a status bar {@link StatusBarItem item}.
*
* @param id The unique identifier of the item.
* @param id The identifier of the item. Must be unique within the extension.
* @param alignment The alignment of the item.
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
* @return A new status bar item.
*/
export function createStatusBarItem(id: string, alignment?: StatusBarAlignment, priority?: number): StatusBarItem;
/**
* Creates a status bar {@link StatusBarItem item}.
*
* @see {@link createStatusBarItem} for creating a status bar item with an identifier.
* @param alignment The alignment of the item.
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
* @return A new status bar item.
*/
export function createStatusBarItem(alignment?: StatusBarAlignment, priority?: number): StatusBarItem;
/**
* Creates a {@link Terminal} with a backing shell process. The cwd of the terminal will be the workspace
* directory if it exists.
@ -10353,6 +10392,44 @@ declare module 'vscode' {
* An optional interface to implement drag and drop in the tree view.
*/
dragAndDropController?: TreeDragAndDropController<T>;
/**
* By default, when the children of a tree item have already been fetched, child checkboxes are automatically managed based on the checked state of the parent tree item.
* If the tree item is collapsed by default (meaning that the children haven't yet been fetched) then child checkboxes will not be updated.
* To override this behavior and manage child and parent checkbox state in the extension, set this to `true`.
*
* Examples where {@link TreeViewOptions.manageCheckboxStateManually} is false, the default behavior:
*
* 1. A tree item is checked, then its children are fetched. The children will be checked.
*
* 2. A tree item's parent is checked. The tree item and all of it's siblings will be checked.
* - [ ] Parent
* - [ ] Child 1
* - [ ] Child 2
* When the user checks Parent, the tree will look like this:
* - [x] Parent
* - [x] Child 1
* - [x] Child 2
*
* 3. A tree item and all of it's siblings are checked. The parent will be checked.
* - [ ] Parent
* - [ ] Child 1
* - [ ] Child 2
* When the user checks Child 1 and Child 2, the tree will look like this:
* - [x] Parent
* - [x] Child 1
* - [x] Child 2
*
* 4. A tree item is unchecked. The parent will be unchecked.
* - [x] Parent
* - [x] Child 1
* - [x] Child 2
* When the user unchecks Child 1, the tree will look like this:
* - [ ] Parent
* - [ ] Child 1
* - [x] Child 2
*/
manageCheckboxStateManually?: boolean;
}
/**
@ -10392,6 +10469,8 @@ declare module 'vscode' {
/**
* A file associated with a {@linkcode DataTransferItem}.
*
* Instances of this type can only be created by the editor and not by extensions.
*/
export interface DataTransferFile {
/**
@ -10459,6 +10538,7 @@ declare module 'vscode' {
* Retrieves the data transfer item for a given mime type.
*
* @param mimeType The mime type to get the data transfer item for, such as `text/plain` or `image/png`.
* Mimes type look ups are case-insensitive.
*
* Special mime types:
* - `text/uri-list`  A string with `toString()`ed Uris separated by `\r\n`. To specify a cursor position in the file,
@ -10468,7 +10548,8 @@ declare module 'vscode' {
/**
* Sets a mime type to data transfer item mapping.
* @param mimeType The mime type to set the data for.
*
* @param mimeType The mime type to set the data for. Mimes types stored in lower case, with case-insensitive looks up.
* @param value The data transfer item for the given mime type.
*/
set(mimeType: string, value: DataTransferItem): void;
@ -10565,6 +10646,16 @@ declare module 'vscode' {
readonly value: number;
}
/**
* An event describing the change in a tree item's checkbox state.
*/
export interface TreeCheckboxChangeEvent<T> {
/**
* The items that were checked or unchecked.
*/
readonly items: ReadonlyArray<[T, TreeItemCheckboxState]>;
}
/**
* Represents a Tree view
*/
@ -10600,6 +10691,11 @@ declare module 'vscode' {
*/
readonly onDidChangeVisibility: Event<TreeViewVisibilityChangeEvent>;
/**
* An event to signal that an element or root has either been checked or unchecked.
*/
readonly onDidChangeCheckboxState: Event<TreeCheckboxChangeEvent<T>>;
/**
* An optional human-readable message that will be rendered in the view.
* Setting the message to null, undefined, or empty string will remove the message from the view.
@ -10781,6 +10877,12 @@ declare module 'vscode' {
*/
accessibilityInformation?: AccessibilityInformation;
/**
* {@link TreeItemCheckboxState TreeItemCheckboxState} of the tree item.
* {@link TreeDataProvider.onDidChangeTreeData onDidChangeTreeData} should be fired when {@link TreeItem.checkboxState checkboxState} changes.
*/
checkboxState?: TreeItemCheckboxState | { readonly state: TreeItemCheckboxState; readonly tooltip?: string; readonly accessibilityInformation?: AccessibilityInformation };
/**
* @param label A human-readable string describing this item
* @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None}
@ -10829,6 +10931,20 @@ declare module 'vscode' {
highlights?: [number, number][];
}
/**
* Checkbox state of the tree item
*/
export enum TreeItemCheckboxState {
/**
* Determines an item is unchecked
*/
Unchecked = 0,
/**
* Determines an item is checked
*/
Checked = 1
}
/**
* Value-object describing what options a terminal should use.
*/
@ -11021,7 +11137,7 @@ declare module 'vscode' {
* **Example:** Exit the terminal when "y" is pressed, otherwise show a notification.
* ```typescript
* const writeEmitter = new vscode.EventEmitter<string>();
* const closeEmitter = new vscode.EventEmitter<vscode.TerminalDimensions>();
* const closeEmitter = new vscode.EventEmitter<void>();
* const pty: vscode.Pseudoterminal = {
* onDidWrite: writeEmitter.event,
* onDidClose: closeEmitter.event,
@ -11034,7 +11150,8 @@ declare module 'vscode' {
* closeEmitter.fire();
* }
* };
* vscode.window.createTerminal({ name: 'Exit example', pty });
* const terminal = vscode.window.createTerminal({ name: 'Exit example', pty });
* terminal.show(true);
* ```
*/
onDidClose?: Event<void | number>;
@ -11220,6 +11337,12 @@ declare module 'vscode' {
*/
persistent: boolean;
/**
* A description for the environment variable collection, this will be used to describe the
* changes in the UI.
*/
description: string | MarkdownString | undefined;
/**
* Replace an environment variable with a value.
*
@ -12239,7 +12362,7 @@ declare module 'vscode' {
* If you want to monitor file events across all opened workspace folders:
*
* ```ts
* vscode.workspace.createFileSystemWatcher('**/*.js'));
* vscode.workspace.createFileSystemWatcher('**/*.js');
* ```
*
* *Note:* the array of workspace folders can be empty if no workspace is opened (empty window).
@ -12435,11 +12558,11 @@ declare module 'vscode' {
export const notebookDocuments: readonly NotebookDocument[];
/**
* Open a notebook. Will return early if this notebook is already {@link notebook.notebookDocuments loaded}. Otherwise
* the notebook is loaded and the {@linkcode notebook.onDidOpenNotebookDocument onDidOpenNotebookDocument}-event fires.
* Open a notebook. Will return early if this notebook is already {@link notebookDocuments loaded}. Otherwise
* the notebook is loaded and the {@linkcode onDidOpenNotebookDocument}-event fires.
*
* *Note* that the lifecycle of the returned notebook is owned by the editor and not by the extension. That means an
* {@linkcode notebook.onDidCloseNotebookDocument onDidCloseNotebookDocument}-event can occur at any time after.
* {@linkcode onDidCloseNotebookDocument}-event can occur at any time after.
*
* *Note* that opening a notebook does not show a notebook editor. This function only returns a notebook document which
* can be shown in a notebook editor but it can also be used for other things.
@ -12465,6 +12588,21 @@ declare module 'vscode' {
*/
export const onDidChangeNotebookDocument: Event<NotebookDocumentChangeEvent>;
/**
* An event that is emitted when a {@link NotebookDocument notebook document} will be saved to disk.
*
* *Note 1:* Subscribers can delay saving by registering asynchronous work. For the sake of data integrity the editor
* might save without firing this event. For instance when shutting down with dirty files.
*
* *Note 2:* Subscribers are called sequentially and they can {@link NotebookDocumentWillSaveEvent.waitUntil delay} saving
* by registering asynchronous work. Protection against misbehaving listeners is implemented as such:
* * there is an overall time budget that all listeners share and if that is exhausted no further listener is called
* * listeners that take a long time or produce errors frequently will not be called anymore
*
* The current thresholds are 1.5 seconds as overall time budget and a listener can misbehave 3 times before being ignored.
*/
export const onWillSaveNotebookDocument: Event<NotebookDocumentWillSaveEvent>;
/**
* An event that is emitted when a {@link NotebookDocument notebook} is saved.
*/
@ -13534,6 +13672,61 @@ declare module 'vscode' {
readonly cellChanges: readonly NotebookDocumentCellChange[];
}
/**
* An event that is fired when a {@link NotebookDocument notebook document} will be saved.
*
* To make modifications to the document before it is being saved, call the
* {@linkcode NotebookDocumentWillSaveEvent.waitUntil waitUntil}-function with a thenable
* that resolves to a {@link WorkspaceEdit workspace edit}.
*/
export interface NotebookDocumentWillSaveEvent {
/**
* A cancellation token.
*/
readonly token: CancellationToken;
/**
* The {@link NotebookDocument notebook document} that will be saved.
*/
readonly notebook: NotebookDocument;
/**
* The reason why save was triggered.
*/
readonly reason: TextDocumentSaveReason;
/**
* Allows to pause the event loop and to apply {@link WorkspaceEdit workspace edit}.
* Edits of subsequent calls to this function will be applied in order. The
* edits will be *ignored* if concurrent modifications of the notebook document happened.
*
* *Note:* This function can only be called during event dispatch and not
* in an asynchronous manner:
*
* ```ts
* workspace.onWillSaveNotebookDocument(event => {
* // async, will *throw* an error
* setTimeout(() => event.waitUntil(promise));
*
* // sync, OK
* event.waitUntil(promise);
* })
* ```
*
* @param thenable A thenable that resolves to {@link WorkspaceEdit workspace edit}.
*/
waitUntil(thenable: Thenable<WorkspaceEdit>): void;
/**
* Allows to pause the event loop until the provided thenable resolved.
*
* *Note:* This function can only be called during event dispatch.
*
* @param thenable A thenable that delays saving.
*/
waitUntil(thenable: Thenable<any>): void;
}
/**
* The summary of a notebook cell execution.
*/
@ -15068,7 +15261,7 @@ declare module 'vscode' {
*
* @param debugType The debug type for which the provider is registered.
* @param provider The {@link DebugConfigurationProvider debug configuration provider} to register.
* @param triggerKind The {@link DebugConfigurationProviderTrigger trigger} for which the 'provideDebugConfiguration' method of the provider is registered. If `triggerKind` is missing, the value `DebugConfigurationProviderTriggerKind.Initial` is assumed.
* @param triggerKind The {@link DebugConfigurationProviderTriggerKind trigger} for which the 'provideDebugConfiguration' method of the provider is registered. If `triggerKind` is missing, the value `DebugConfigurationProviderTriggerKind.Initial` is assumed.
* @return A {@link Disposable} that unregisters this provider when being disposed.
*/
export function registerDebugConfigurationProvider(debugType: string, provider: DebugConfigurationProvider, triggerKind?: DebugConfigurationProviderTriggerKind): Disposable;
@ -15222,6 +15415,14 @@ declare module 'vscode' {
Preview = 1
}
/**
* The state of a comment thread.
*/
export enum CommentThreadState {
Unresolved = 0,
Resolved = 1
}
/**
* A collection of {@link Comment comments} representing a conversation at a particular range in a document.
*/
@ -15279,6 +15480,11 @@ declare module 'vscode' {
*/
label?: string;
/**
* The optional state of a comment thread, which may affect how the comment is displayed.
*/
state?: CommentThreadState;
/**
* Dispose this comment thread.
*
@ -15527,18 +15733,35 @@ declare module 'vscode' {
readonly label: string;
}
/**
* Optional options to be used when calling {@link authentication.getSession} with the flag `forceNewSession`.
*/
export interface AuthenticationForceNewSessionOptions {
/**
* An optional message that will be displayed to the user when we ask to re-authenticate. Providing additional context
* as to why you are asking a user to re-authenticate can help increase the odds that they will accept.
*/
detail?: string;
}
/**
* Options to be used when getting an {@link AuthenticationSession} from an {@link AuthenticationProvider}.
*/
export interface AuthenticationGetSessionOptions {
/**
* Whether the existing user session preference should be cleared.
* Whether the existing session preference should be cleared.
*
* For authentication providers that support being signed into multiple accounts at once, the user will be
* prompted to select an account to use when {@link authentication.getSession getSession} is called. This preference
* is remembered until {@link authentication.getSession getSession} is called with this flag.
*
* Note:
* The preference is extension specific. So if one extension calls {@link authentication.getSession getSession}, it will not
* affect the session preference for another extension calling {@link authentication.getSession getSession}. Additionally,
* the preference is set for the current workspace and also globally. This means that new workspaces will use the "global"
* value at first and then when this flag is provided, a new value can be set for that workspace. This also means
* that pre-existing workspaces will not lose their preference if a new workspace sets this flag.
*
* Defaults to false.
*/
clearSessionPreference?: boolean;
@ -15570,7 +15793,7 @@ declare module 'vscode' {
*
* This defaults to false.
*/
forceNewSession?: boolean | { detail: string };
forceNewSession?: boolean | AuthenticationForceNewSessionOptions;
/**
* Whether we should show the indication to sign in in the Accounts menu.
@ -15720,7 +15943,7 @@ declare module 'vscode' {
* @param options The {@link AuthenticationGetSessionOptions} to use
* @returns A thenable that resolves to an authentication session
*/
export function getSession(providerId: string, scopes: readonly string[], options: AuthenticationGetSessionOptions & { forceNewSession: true | { detail: string } }): Thenable<AuthenticationSession>;
export function getSession(providerId: string, scopes: readonly string[], options: AuthenticationGetSessionOptions & { forceNewSession: true | AuthenticationForceNewSessionOptions }): Thenable<AuthenticationSession>;
/**
* Get an authentication session matching the desired scopes. Rejects if a provider with providerId is not
@ -15773,12 +15996,15 @@ declare module 'vscode' {
* Marks a string for localization. If a localized bundle is available for the language specified by
* {@link env.language} and the bundle has a localized value for this message, then that localized
* value will be returned (with injected {@link args} values for any templated values).
*
* @param message - The message to localize. Supports index templating where strings like `{0}` and `{1}` are
* replaced by the item at that index in the {@link args} array.
* @param args - The arguments to be used in the localized string. The index of the argument is used to
* match the template placeholder in the localized string.
* @returns localized string with injected arguments.
* @example `l10n.t('Hello {0}!', 'World');`
*
* @example
* l10n.t('Hello {0}!', 'World');
*/
export function t(message: string, ...args: Array<string | number | boolean>): string;
@ -15786,25 +16012,29 @@ declare module 'vscode' {
* Marks a string for localization. If a localized bundle is available for the language specified by
* {@link env.language} and the bundle has a localized value for this message, then that localized
* value will be returned (with injected {@link args} values for any templated values).
*
* @param message The message to localize. Supports named templating where strings like `{foo}` and `{bar}` are
* replaced by the value in the Record for that key (foo, bar, etc).
* @param args The arguments to be used in the localized string. The name of the key in the record is used to
* match the template placeholder in the localized string.
* @returns localized string with injected arguments.
* @example `l10n.t('Hello {name}', { name: 'Erich' });`
*
* @example
* l10n.t('Hello {name}', { name: 'Erich' });
*/
export function t(message: string, args: Record<string, any>): string;
/**
* Marks a string for localization. If a localized bundle is available for the language specified by
* {@link env.language} and the bundle has a localized value for this message, then that localized
* value will be returned (with injected args values for any templated values).
*
* @param options The options to use when localizing the message.
* @returns localized string with injected arguments.
*/
export function t(options: {
/**
* The message to localize. If {@link args} is an array, this message supports index templating where strings like
* `{0}` and `{1}` are replaced by the item at that index in the {@link args} array. If `args` is a `Record<string, any>`,
* The message to localize. If {@link options.args args} is an array, this message supports index templating where strings like
* `{0}` and `{1}` are replaced by the item at that index in the {@link options.args args} array. If `args` is a `Record<string, any>`,
* this supports named templating where strings like `{foo}` and `{bar}` are replaced by the value in
* the Record for that key (foo, bar, etc).
*/
@ -15909,6 +16139,13 @@ declare module 'vscode' {
*/
isDefault: boolean;
/**
* Whether this profile supports continuous running of requests. If so,
* then {@link TestRunRequest.continuous} may be set to `true`. Defaults
* to false.
*/
supportsContinuousRun: boolean;
/**
* Associated tag for the profile. If this is set, only {@link TestItem}
* instances with the same tag will be eligible to execute in this profile.
@ -15929,6 +16166,11 @@ declare module 'vscode' {
* associated with the request should be created before the function returns
* or the returned promise is resolved.
*
* If {@link supportsContinuousRun} is set, then {@link TestRunRequest.continuous}
* may be `true`. In this case, the profile should observe changes to
* source code and create new test runs by calling {@link TestController.createTestRun},
* until the cancellation is requested on the `token`.
*
* @param request Request information for the test run.
* @param cancellationToken Token that signals the used asked to abort the
* test run. If cancellation is requested on this token, all {@link TestRun}
@ -15951,7 +16193,7 @@ declare module 'vscode' {
*/
export interface TestController {
/**
* The id of the controller passed in {@link vscode.tests.createTestController}.
* The id of the controller passed in {@link tests.createTestController}.
* This must be globally unique.
*/
readonly id: string;
@ -15967,7 +16209,7 @@ declare module 'vscode' {
* "test tree."
*
* The extension controls when to add tests. For example, extensions should
* add tests for a file when {@link vscode.workspace.onDidOpenTextDocument}
* add tests for a file when {@link workspace.onDidOpenTextDocument}
* fires in order for decorations for tests within a file to be visible.
*
* However, the editor may sometimes explicitly request children using the
@ -15983,16 +16225,17 @@ declare module 'vscode' {
* @param runHandler Function called to start a test run.
* @param isDefault Whether this is the default action for its kind.
* @param tag Profile test tag.
* @param supportsContinuousRun Whether the profile supports continuous running.
* @returns An instance of a {@link TestRunProfile}, which is automatically
* associated with this controller.
*/
createRunProfile(label: string, kind: TestRunProfileKind, runHandler: (request: TestRunRequest, token: CancellationToken) => Thenable<void> | void, isDefault?: boolean, tag?: TestTag): TestRunProfile;
createRunProfile(label: string, kind: TestRunProfileKind, runHandler: (request: TestRunRequest, token: CancellationToken) => Thenable<void> | void, isDefault?: boolean, tag?: TestTag, supportsContinuousRun?: boolean): TestRunProfile;
/**
* A function provided by the extension that the editor may call to request
* children of a test item, if the {@link TestItem.canResolveChildren} is
* `true`. When called, the item should discover children and call
* {@link vscode.tests.createTestItem} as children are discovered.
* {@link TestController.createTestItem} as children are discovered.
*
* Generally the extension manages the lifecycle of test items, but under
* certain conditions the editor may request the children of a specific
@ -16101,12 +16344,19 @@ declare module 'vscode' {
*/
readonly profile: TestRunProfile | undefined;
/**
* Whether the profile should run continuously as source code changes. Only
* relevant for profiles that set {@link TestRunProfile.supportsContinuousRun}.
*/
readonly continuous?: boolean;
/**
* @param include Array of specific tests to run, or undefined to run all tests
* @param exclude An array of tests to exclude from the run.
* @param profile The run profile used for this request.
* @param continuous Whether to run tests continuously as source changes.
*/
constructor(include?: readonly TestItem[], exclude?: readonly TestItem[], profile?: TestRunProfile);
constructor(include?: readonly TestItem[], exclude?: readonly TestItem[], profile?: TestRunProfile, continuous?: boolean);
}
/**
@ -16180,7 +16430,8 @@ declare module 'vscode' {
/**
* Appends raw output from the test runner. On the user's request, the
* output will be displayed in a terminal. ANSI escape sequences,
* such as colors and text styles, are supported.
* such as colors and text styles, are supported. New lines must be given
* as CRLF (`\r\n`) rather than LF (`\n`).
*
* @param output Output text to append.
* @param location Indicate that the output was logged at the given
@ -16190,7 +16441,7 @@ declare module 'vscode' {
appendOutput(output: string, location?: Location, test?: TestItem): void;
/**
* Signals that the end of the test run. Any tests included in the run whose
* Signals the end of the test run. Any tests included in the run whose
* states have not been updated will have their state reset.
*/
end(): void;
@ -16276,7 +16527,7 @@ declare module 'vscode' {
/**
* Tags associated with this test item. May be used in combination with
* {@link TestRunProfile.tags}, or simply as an organizational feature.
* {@link TestRunProfile.tag tags}, or simply as an organizational feature.
*/
tags: readonly TestTag[];
@ -16589,7 +16840,7 @@ declare module 'vscode' {
* Whether or not the group is currently active.
*
* *Note* that only one tab group is active at a time, but that multiple tab
* groups can have an {@link TabGroup.aciveTab active tab}.
* groups can have an {@link activeTab active tab}.
*
* @see {@link Tab.isActive}
*/
@ -16616,7 +16867,7 @@ declare module 'vscode' {
}
/**
* Represents the main editor area which consists of multple groups which contain tabs.
* Represents the main editor area which consists of multiple groups which contain tabs.
*/
export interface TabGroups {
/**
@ -16659,6 +16910,144 @@ declare module 'vscode' {
*/
close(tabGroup: TabGroup | readonly TabGroup[], preserveFocus?: boolean): Thenable<boolean>;
}
/**
* A special value wrapper denoting a value that is safe to not clean.
* This is to be used when you can guarantee no identifiable information is contained in the value and the cleaning is improperly redacting it.
*/
export class TelemetryTrustedValue<T = any> {
readonly value: T;
constructor(value: T);
}
/**
* A telemetry logger which can be used by extensions to log usage and error telementry.
*
* A logger wraps around an {@link TelemetrySender sender} but it guarantees that
* - user settings to disable or tweak telemetry are respected, and that
* - potential sensitive data is removed
*
* It also enables an "echo UI" that prints whatever data is send and it allows the editor
* to forward unhandled errors to the respective extensions.
*
* To get an instance of a `TelemetryLogger`, use
* {@link env.createTelemetryLogger `createTelemetryLogger`}.
*/
export interface TelemetryLogger {
/**
* An {@link Event} which fires when the enablement state of usage or error telemetry changes.
*/
readonly onDidChangeEnableStates: Event<TelemetryLogger>;
/**
* Whether or not usage telemetry is enabled for this logger.
*/
readonly isUsageEnabled: boolean;
/**
* Whether or not error telemetry is enabled for this logger.
*/
readonly isErrorsEnabled: boolean;
/**
* Log a usage event.
*
* After completing cleaning, telemetry setting checks, and data mix-in calls `TelemetrySender.sendEventData` to log the event.
* Automatically supports echoing to extension telemetry output channel.
* @param eventName The event name to log
* @param data The data to log
*/
logUsage(eventName: string, data?: Record<string, any | TelemetryTrustedValue>): void;
/**
* Log an error event.
*
* After completing cleaning, telemetry setting checks, and data mix-in calls `TelemetrySender.sendEventData` to log the event. Differs from `logUsage` in that it will log the event if the telemetry setting is Error+.
* Automatically supports echoing to extension telemetry output channel.
* @param eventName The event name to log
* @param data The data to log
*/
logError(eventName: string, data?: Record<string, any | TelemetryTrustedValue>): void;
/**
* Log an error event.
*
* Calls `TelemetrySender.sendErrorData`. Does cleaning, telemetry checks, and data mix-in.
* Automatically supports echoing to extension telemetry output channel.
* Will also automatically log any exceptions thrown within the extension host process.
* @param error The error object which contains the stack trace cleaned of PII
* @param data Additional data to log alongside the stack trace
*/
logError(error: Error, data?: Record<string, any | TelemetryTrustedValue>): void;
/**
* Dispose this object and free resources.
*/
dispose(): void;
}
/**
* The telemetry sender is the contract between a telemetry logger and some telemetry service. **Note** that extensions must NOT
* call the methods of their sender directly as the logger provides extra guards and cleaning.
*
* ```js
* const sender: vscode.TelemetrySender = {...};
* const logger = vscode.env.createTelemetryLogger(sender);
*
* // GOOD - uses the logger
* logger.logUsage('myEvent', { myData: 'myValue' });
*
* // BAD - uses the sender directly: no data cleansing, ignores user settings, no echoing to the telemetry output channel etc
* sender.logEvent('myEvent', { myData: 'myValue' });
* ```
*/
export interface TelemetrySender {
/**
* Function to send event data without a stacktrace. Used within a {@link TelemetryLogger}
*
* @param eventName The name of the event which you are logging
* @param data A serializable key value pair that is being logged
*/
sendEventData(eventName: string, data?: Record<string, any>): void;
/**
* Function to send an error. Used within a {@link TelemetryLogger}
*
* @param error The error being logged
* @param data Any additional data to be collected with the exception
*/
sendErrorData(error: Error, data?: Record<string, any>): void;
/**
* Optional flush function which will give this sender a chance to send any remaining events
* as its {@link TelemetryLogger} is being disposed
*/
flush?(): void | Thenable<void>;
}
/**
* Options for creating a {@link TelemetryLogger}
*/
export interface TelemetryLoggerOptions {
/**
* Whether or not you want to avoid having the built-in common properties such as os, extension name, etc injected into the data object.
* Defaults to `false` if not defined.
*/
readonly ignoreBuiltInCommonProperties?: boolean;
/**
* Whether or not unhandled errors on the extension host caused by your extension should be logged to your sender.
* Defaults to `false` if not defined.
*/
readonly ignoreUnhandledErrors?: boolean;
/**
* Any additional common properties which should be injected into the data object.
*/
readonly additionalCommonProperties?: Record<string, any>;
}
}
/**

View File

@ -1,130 +0,0 @@
/*----------------------- * Copyright (c) Microsoft Corporation. All rights reserved.
----------------------------------------------------------------------
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
// https://github.com/microsoft/vscode/issues/124024 @hediet @alexdima
export namespace languages {
/**
* Registers an inline completion provider.
*/
export function registerInlineCompletionItemProvider(selector: DocumentSelector, provider: InlineCompletionItemProvider): Disposable;
}
export interface InlineCompletionItemProvider<T extends InlineCompletionItem = InlineCompletionItem> {
/**
* Provides inline completion items for the given position and document.
* If inline completions are enabled, this method will be called whenever the user stopped typing.
* It will also be called when the user explicitly triggers inline completions or asks for the next or previous inline completion.
* Use `context.triggerKind` to distinguish between these scenarios.
*/
provideInlineCompletionItems(document: TextDocument, position: Position, context: InlineCompletionContext, token: CancellationToken): ProviderResult<InlineCompletionList<T> | T[]>;
}
export interface InlineCompletionContext {
/**
* How the completion was triggered.
*/
readonly triggerKind: InlineCompletionTriggerKind;
/**
* Provides information about the currently selected item in the autocomplete widget if it is visible.
*
* If set, provided inline completions must extend the text of the selected item
* and use the same range, otherwise they are not shown as preview.
* As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document,
* the inline completion must also replace `.` and start with `.log`, for example `.log()`.
*
* Inline completion providers are requested again whenever the selected item changes.
*
* The user must configure `"editor.suggest.preview": true` for this feature.
*/
readonly selectedCompletionInfo: SelectedCompletionInfo | undefined;
}
export interface SelectedCompletionInfo {
range: Range;
text: string;
completionKind: CompletionItemKind;
isSnippetText: boolean;
}
/**
* How an {@link InlineCompletionItemProvider inline completion provider} was triggered.
*/
export enum InlineCompletionTriggerKind {
/**
* Completion was triggered automatically while editing.
* It is sufficient to return a single completion item in this case.
*/
Automatic = 0,
/**
* Completion was triggered explicitly by a user gesture.
* Return multiple completion items to enable cycling through them.
*/
Explicit = 1,
}
export class InlineCompletionList<T extends InlineCompletionItem = InlineCompletionItem> {
items: T[];
constructor(items: T[]);
}
export class InlineCompletionItem {
/**
* The text to replace the range with.
*
* The text the range refers to should be a prefix of this value and must be a subword (`AB` and `BEF` are subwords of `ABCDEF`, but `Ab` is not).
*/
text: string;
/**
* The range to replace.
* Must begin and end on the same line.
*
* Prefer replacements over insertions to avoid cache invalidation:
* Instead of reporting a completion that inserts an extension at the end of a word,
* the whole word should be replaced with the extended word.
*/
range?: Range;
/**
* An optional {@link Command} that is executed *after* inserting this completion.
*/
command?: Command;
constructor(text: string, range?: Range, command?: Command);
}
/**
* Be aware that this API will not ever be finalized.
*/
export namespace window {
export function getInlineCompletionItemController<T extends InlineCompletionItem>(provider: InlineCompletionItemProvider<T>): InlineCompletionController<T>;
}
/**
* Be aware that this API will not ever be finalized.
*/
export interface InlineCompletionController<T extends InlineCompletionItem> {
/**
* Is fired when an inline completion item is shown to the user.
*/
// eslint-disable-next-line vscode-dts-event-naming
readonly onDidShowCompletionItem: Event<InlineCompletionItemDidShowEvent<T>>;
}
/**
* Be aware that this API will not ever be finalized.
*/
export interface InlineCompletionItemDidShowEvent<T extends InlineCompletionItem> {
completionItem: T;
}
}