diff --git a/apps/ide/README.md b/apps/ide/README.md index 79c2e2966..e794a24bf 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -178,6 +178,7 @@ Following Electron's [security checklist](https://www.electronjs.org/docs/latest | No network request unless the person asks: the update check runs from Help > Check for Updates…, or at start-up only if `update.checkOnStartup` is turned on (off by default); it reads the public GitHub releases list, downloads nothing and only opens the release page in the browser | `src/main/updates/` (`updateRelease.ts` pure, `updateCheck.ts`) | Unit tests (`test/updateCheck.test.ts`: tags, drafts, pre-releases, versions); never run in the smoke run. | | Extensions (#251) are unpacked only from checked archives: entries under `extension/` only, no `..`, absolute paths, drive letters or links, size limits; an Open VSX download must match the registry's SHA-256; a native dialog shows publisher, verification, licence and whether it runs code before anything is installed; nothing goes online unless the person searches or installs | `src/main/extensions/` (`vsix.ts`, `openVsx.ts`, `extensionsService.ts`) | Unit tests (`test/extensions.test.ts`: zip-slip, symlink and garbage archives, wrong and missing checksums, http downloads, tampered `extensions.json`). | | The renderer may compile WebAssembly (`'wasm-unsafe-eval'`) for the TextMate regex engine of extension grammars (#258); `eval` stays blocked | `buildContentSecurityPolicy` | Unit tests; smoke checks `eval` throws. | +| Extensions' code (#259) runs only in the extension host, a separate Node process per window, never in the renderer or main; what it asks of main is checked there (files only inside the folder, links only http/https/mailto, secrets in the OS store per extension); only workbench activation events are accepted from the renderer | `src/extensionHost/`, `src/main/extensions/extensionHostManager.ts` | Unit tests (`test/extensionHost.test.ts`, with a real host process). | | The dev server URL is ignored in a packaged build | `src/main/index.ts` (`app.isPackaged`) | Code review. | Running as root (containers, some CI images) requires `--no-sandbox`, which the scripts add only in that case. It turns off Chromium's OS-level sandbox and `app.enableSandbox()`; the per-window `sandbox: true` preference and its assertion stay. @@ -362,7 +363,7 @@ The parsers (`statusParser.ts`, `blameParser.ts`) are pure and unit-tested on st ## VS Code extensions (stream `ide-extensions`, epic #251) -The Extensions view (activity bar, puzzle icon, `Ctrl/Cmd+Shift+X`) installs VS Code extensions from **Open VSX** (never the Visual Studio Marketplace, whose terms only allow Microsoft products; ADR [0002](../../adr/0002-vscode-extensions-in-the-ide.md)) or from a `.vsix` file, and enables, disables and uninstalls them. Colour themes, languages, TextMate grammars and snippets apply at once; extensions with code run in the extension host (#259, in progress). Design, state and how to try it: [`docs/ide/extensions.md`](../../docs/ide/extensions.md). +The Extensions view (activity bar, puzzle icon, `Ctrl/Cmd+Shift+X`) installs VS Code extensions from **Open VSX** (never the Visual Studio Marketplace, whose terms only allow Microsoft products; ADR [0002](../../adr/0002-vscode-extensions-in-the-ide.md)) or from a `.vsix` file, and enables, disables and uninstalls them. Colour themes, languages, TextMate grammars and snippets apply at once; extensions with code run in an extension host process per window (`src/extensionHost/`, #259), with their commands in the palette and their messages, pickers, progress and status bar items in the workbench. Design, state and how to try it: [`docs/ide/extensions.md`](../../docs/ide/extensions.md). ## AI agent hub (stream `ai-agents`) diff --git a/apps/ide/electron-builder.config.cjs b/apps/ide/electron-builder.config.cjs index 8d8708915..2ca32141b 100644 --- a/apps/ide/electron-builder.config.cjs +++ b/apps/ide/electron-builder.config.cjs @@ -2,7 +2,7 @@ // // npm run dist --workspace=code-xr-ide the current OS's installers // -// The app itself is apps/ide/out (main, preloads, renderer: every npm +// The app itself is apps/ide/out (main, preloads, renderer, extension host: every npm // dependency is bundled by Vite except node-pty), plus the three runtime // packages that run as files: node-pty (native), and typescript-language- // server with TypeScript, which run as a separate process (#21). Those three @@ -42,6 +42,8 @@ module.exports = { '**/node_modules/node-pty/**', '**/node_modules/typescript-language-server/**', '**/node_modules/typescript/**', + // #259: the extension host is forked as a script: a real file, not one inside the archive. + 'out/extensionHost/**', ], extraResources: [ { from: `${EXTENSION}/dist/code_analysis`, to: 'dist/code_analysis' }, diff --git a/apps/ide/scripts/build.mjs b/apps/ide/scripts/build.mjs index 1eeffe82b..14e0382c9 100644 --- a/apps/ide/scripts/build.mjs +++ b/apps/ide/scripts/build.mjs @@ -5,5 +5,6 @@ import { nodeTargetConfig, rendererConfig } from './viteConfigs.mjs'; await build(nodeTargetConfig('main')); await build(nodeTargetConfig('preload')); await build(nodeTargetConfig('scenePreload')); +await build(nodeTargetConfig('extensionHost')); await build(rendererConfig()); console.log('[code-xr-ide] built into apps/ide/out/'); diff --git a/apps/ide/scripts/dev.mjs b/apps/ide/scripts/dev.mjs index ceee80924..090c906de 100644 --- a/apps/ide/scripts/dev.mjs +++ b/apps/ide/scripts/dev.mjs @@ -43,9 +43,9 @@ function restartElectron() { startElectron(); } -// Watch main and both preloads (the window's and the scene view's, #16); restart Electron after each successful rebuild. -const pending = new Set(['main', 'preload', 'scenePreload']); -for (const target of /** @type {const} */ (['main', 'preload', 'scenePreload'])) { +// Watch main, both preloads (the window's and the scene view's, #16) and the extension host (#259); restart Electron after each successful rebuild. +const pending = new Set(['main', 'preload', 'scenePreload', 'extensionHost']); +for (const target of /** @type {const} */ (['main', 'preload', 'scenePreload', 'extensionHost'])) { const config = nodeTargetConfig(target, { dev: true }); config.build.watch = {}; const watcher = /** @type {import('vite').Rollup.RollupWatcher} */ (await build(config)); diff --git a/apps/ide/scripts/viteConfigs.mjs b/apps/ide/scripts/viteConfigs.mjs index 2fd35a80d..192a0855a 100644 --- a/apps/ide/scripts/viteConfigs.mjs +++ b/apps/ide/scripts/viteConfigs.mjs @@ -4,6 +4,7 @@ // out/main/index.cjs main process (Node, CommonJS) // out/preload/index.cjs preload (sandboxed: may only require 'electron') // out/renderer/ renderer (browser, served from codexr://app/) +// out/extensionHost/index.cjs extension host (#259: a Node child process on Electron's own Node) import { builtinModules } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -27,7 +28,7 @@ const NODE_EXTERNALS = ['electron', /^electron\//, ...builtinModules, ...builtin */ const MAIN_NATIVE_EXTERNALS = ['node-pty']; -/** @param {'main' | 'preload' | 'scenePreload'} target @param {{ dev?: boolean }} [opts] */ +/** @param {'main' | 'preload' | 'scenePreload' | 'extensionHost'} target @param {{ dev?: boolean }} [opts] */ export function nodeTargetConfig(target, opts = {}) { return { configFile: false, diff --git a/apps/ide/src/extensionHost/api.ts b/apps/ide/src/extensionHost/api.ts new file mode 100644 index 000000000..299224cc8 --- /dev/null +++ b/apps/ide/src/extensionHost/api.ts @@ -0,0 +1,1107 @@ +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import { MAIN_METHODS, type DialogRequest, type QuickPickItemData, type StatusBarItemData } from '../shared/extensionHostProtocol.ts'; +import { HOST_VSCODE_API_VERSION, type ExtensionId } from '../shared/extensions.ts'; +import { matchGlob } from './glob.ts'; +import type { ExtensionHost, ExtensionRecord } from './host.ts'; +import { missingNamespace, withFallback } from './inert.ts'; +import { TextDocumentModel } from './textDocument.ts'; +import * as types from './types.ts'; +import { CancellationTokenNone, Disposable, EventEmitter, FileSystemError, FileType, Uri, type CancellationToken } from './types.ts'; + +/** + * The `vscode` module as one extension sees it (#259). Built once per + * extension, so every call knows which extension made it (for the log, the + * status bar item keys, the secrets). What is implemented behaves like VS + * Code; the rest is reported once and replaced by an inert stand-in + * (inert.ts), so an extension keeps running with that feature missing. + * + * #260 adds the documents of the editor and the language features, #261 the + * tree views and webviews. + */ + +type Item = string | { title: string; isCloseAffordance?: boolean }; + +function isMessageOptions(value: unknown): value is { modal?: boolean; detail?: string } { + return typeof value === 'object' && value !== null && !('title' in value); +} + +function toFsError(error: unknown, uri: Uri): Error { + const code = (error as NodeJS.ErrnoException | null)?.code; + switch (code) { + case 'ENOENT': + return FileSystemError.FileNotFound(uri); + case 'EEXIST': + return FileSystemError.FileExists(uri); + case 'ENOTDIR': + return FileSystemError.FileNotADirectory(uri); + case 'EISDIR': + return FileSystemError.FileIsADirectory(uri); + case 'EACCES': + case 'EPERM': + return FileSystemError.NoPermissions(uri); + default: + return error instanceof Error ? error : new Error(String(error)); + } +} + +function fileUri(value: unknown): Uri { + if (value instanceof Uri) { + if (value.scheme !== 'file') { + throw FileSystemError.Unavailable(value); + } + return value; + } + throw new Error('Expected a Uri'); +} + +/** `vscode.l10n.t`: the extension's English strings with `{0}` / `{name}` filled in. */ +export function formatMessage(message: string, args: readonly unknown[] | Readonly>): string { + return message.replace(/\{([^}]+)\}/g, (match, key: string) => { + const value = Array.isArray(args) ? args[Number(key)] : (args as Record)[key]; + return value === undefined ? match : String(value); + }); +} + +export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): unknown { + const extensionId: ExtensionId = record.description.id; + const report = (api: string): void => host.reportMissing(extensionId, api); + const data = host.data; + // In `Uri.fsPath`'s spelling (a lower-case drive letter on Windows), so it compares with the paths of URIs. + const workspaceRoot = data.workspaceFolder ? Uri.file(data.workspaceFolder).fsPath : null; + const workspaceFolder = workspaceRoot ? { uri: Uri.file(workspaceRoot), name: path.basename(workspaceRoot), index: 0 } : undefined; + + /* ------------------------------ commands ------------------------------ */ + + const commands = withFallback('commands', { + registerCommand: (id: string, callback: (...args: unknown[]) => unknown, thisArg?: unknown) => host.registerCommand(extensionId, id, callback, thisArg), + registerTextEditorCommand: (id: string, callback: (...args: unknown[]) => unknown, thisArg?: unknown) => host.registerCommand(extensionId, id, (...args: unknown[]) => { + const editor = window.activeTextEditor; + if (!editor) { + host.log({ level: 'warn', extensionId, message: `Command ${id} needs an active text editor; none is known to extensions yet.` }); + return undefined; + } + return callback.call(thisArg, editor, { replace: () => undefined, insert: () => undefined, delete: () => undefined, setEndOfLine: () => undefined }, ...args); + }), + executeCommand: (id: string, ...args: unknown[]): Promise => host.executeCommand(id, args) as Promise, + getCommands: async (filterInternal = false): Promise => { + const ids = [...host.commands.keys()]; + return filterInternal ? ids.filter((id) => !id.startsWith('_')) : ids; + }, + }, report); + + /* ------------------------------ output channels ------------------------------ */ + + function createOutputChannel(name: string) { + let buffer = ''; + const logLevelChanged = new EventEmitter(); + const emit = (level: 'trace' | 'debug' | 'info' | 'warn' | 'error', message: string): void => host.log({ level, extensionId, channel: name, message }); + const flush = (): void => { + const lines = buffer.split(/\r?\n/); + buffer = lines.pop() ?? ''; + for (const line of lines) { + emit('info', line); + } + }; + const channel = { + name, + append(value: string) { + buffer += String(value); + flush(); + }, + appendLine(value: string) { + buffer += `${String(value)}\n`; + flush(); + }, + replace(value: string) { + buffer = ''; + channel.append(value); + }, + clear() { + buffer = ''; + }, + show() { + // The IDE's *Extensions* output channel holds every extension's lines. + }, + hide() { + // Nothing to hide: see show(). + }, + dispose() { + if (buffer !== '') { + emit('info', buffer); + buffer = ''; + } + }, + // LogOutputChannel + logLevel: 3, + onDidChangeLogLevel: logLevelChanged.event, + trace: (message: string, ...args: unknown[]) => emit('trace', [message, ...args.map(String)].join(' ')), + debug: (message: string, ...args: unknown[]) => emit('debug', [message, ...args.map(String)].join(' ')), + info: (message: string, ...args: unknown[]) => emit('info', [message, ...args.map(String)].join(' ')), + warn: (message: string, ...args: unknown[]) => emit('warn', [message, ...args.map(String)].join(' ')), + error: (error: string | Error, ...args: unknown[]) => emit('error', [error instanceof Error ? error.stack ?? error.message : error, ...args.map(String)].join(' ')), + }; + return channel; + } + + /* ------------------------------ messages, pickers ------------------------------ */ + + async function showMessage(severity: 'info' | 'warning' | 'error', message: string, rest: unknown[]): Promise { + const options = isMessageOptions(rest[0]) ? rest.shift() as { modal?: boolean; detail?: string } : {}; + const items = rest.filter((item): item is Item => typeof item === 'string' || (typeof item === 'object' && item !== null && typeof (item as { title?: unknown }).title === 'string')); + const labels = items.map((item) => (typeof item === 'string' ? item : item.title)); + const answer = await host.ui({ + kind: 'message', extensionId, severity, message: String(message), items: labels, + ...(options.detail ? { detail: options.detail } : {}), + ...(options.modal ? { modal: true } : {}), + }); + return typeof answer === 'number' ? items[answer] : undefined; + } + + async function showQuickPick(itemsOrPromise: unknown, options: { placeHolder?: string; title?: string; canPickMany?: boolean; onDidSelectItem?: (item: unknown) => unknown } = {}, token: CancellationToken = CancellationTokenNone): Promise { + const items = (await itemsOrPromise) as (string | { label: string; description?: string; detail?: string; picked?: boolean; kind?: number })[]; + if (token.isCancellationRequested || !Array.isArray(items)) { + return undefined; + } + const data: QuickPickItemData[] = items.map((item) => (typeof item === 'string' ? { label: item } : { + label: String(item.label), + ...(item.description ? { description: String(item.description) } : {}), + ...(item.detail ? { detail: String(item.detail) } : {}), + ...(item.picked ? { picked: true } : {}), + ...(item.kind === types.QuickPickItemKind.Separator ? { separator: true } : {}), + })); + const answer = await host.ui({ kind: 'quickPick', extensionId, items: data, canPickMany: options.canPickMany === true, ...(options.placeHolder ? { placeHolder: options.placeHolder } : {}), ...(options.title ? { title: options.title } : {}) }); + if (token.isCancellationRequested || !Array.isArray(answer)) { + return undefined; + } + const picked = (answer as number[]).map((index) => items[index]).filter((item) => item !== undefined); + if (options.canPickMany) { + return picked; + } + if (picked[0] !== undefined) { + await options.onDidSelectItem?.(picked[0]); + } + return picked[0]; + } + + async function showInputBox(options: { value?: string; prompt?: string; placeHolder?: string; title?: string; password?: boolean; validateInput?: (value: string) => unknown } = {}, token: CancellationToken = CancellationTokenNone): Promise { + let value = options.value; + let prompt = options.prompt; + // validateInput runs here, in the host: an invalid answer asks again with the problem as the prompt. + for (let attempt = 0; attempt < 10; attempt++) { + const answer = await host.ui({ + kind: 'inputBox', extensionId, password: options.password === true, + ...(value !== undefined ? { value } : {}), ...(prompt ? { prompt } : {}), ...(options.placeHolder ? { placeHolder: options.placeHolder } : {}), ...(options.title ? { title: options.title } : {}), + }); + if (token.isCancellationRequested || typeof answer !== 'string') { + return undefined; + } + const problem = await options.validateInput?.(answer); + const text = typeof problem === 'string' ? problem : typeof problem === 'object' && problem !== null ? String((problem as { message?: unknown }).message ?? '') : ''; + if (!text) { + return answer; + } + value = answer; + prompt = text; + } + return undefined; + } + + /** + * `window.createQuickPick` / `createInputBox`: the workbench shows one + * request per `show()`; accepting fires `onDidChangeSelection` (or + * `onDidChangeValue`) and `onDidAccept`, closing fires `onDidHide`. Items + * changed while the box is open are not redrawn (they are on the next show). + */ + function createQuickPick() { + const accept = new EventEmitter(); + const hideEmitter = new EventEmitter(); + const selectionChanged = new EventEmitter(); + const activeChanged = new EventEmitter(); + const valueChanged = new EventEmitter(); + let visible = false; + let generation = 0; + const pick = { + title: undefined as string | undefined, + placeholder: undefined as string | undefined, + value: '', + items: [] as { label: string; description?: string; detail?: string; picked?: boolean; kind?: number }[], + activeItems: [] as unknown[], + selectedItems: [] as unknown[], + canSelectMany: false, + matchOnDescription: false, + matchOnDetail: false, + keepScrollPosition: false, + busy: false, + enabled: true, + ignoreFocusOut: false, + step: undefined as number | undefined, + totalSteps: undefined as number | undefined, + buttons: [] as unknown[], + onDidAccept: accept.event, + onDidHide: hideEmitter.event, + onDidChangeSelection: selectionChanged.event, + onDidChangeActive: activeChanged.event, + onDidChangeValue: valueChanged.event, + onDidTriggerButton: new EventEmitter().event, + onDidTriggerItemButton: new EventEmitter().event, + show() { + if (visible) { + return; + } + visible = true; + const mine = ++generation; + const title = [pick.title, pick.step !== undefined && pick.totalSteps !== undefined ? `(${pick.step}/${pick.totalSteps})` : ''].filter(Boolean).join(' '); + void showQuickPick(pick.items, { ...(pick.placeholder ? { placeHolder: pick.placeholder } : {}), ...(title ? { title } : {}) }).then((chosen) => { + if (mine !== generation || !visible) { + return; + } + if (chosen !== undefined) { + pick.activeItems = [chosen]; + pick.selectedItems = [chosen]; + activeChanged.fire(pick.activeItems); + selectionChanged.fire(pick.selectedItems); + accept.fire(); + } + if (visible && mine === generation) { + visible = false; + hideEmitter.fire(); + } + }); + }, + hide() { + if (visible) { + visible = false; + generation++; + hideEmitter.fire(); + } + }, + dispose() { + pick.hide(); + accept.dispose(); + hideEmitter.dispose(); + }, + }; + return pick; + } + + function createInputBox() { + const accept = new EventEmitter(); + const hideEmitter = new EventEmitter(); + const valueChanged = new EventEmitter(); + let visible = false; + let generation = 0; + const box = { + title: undefined as string | undefined, + placeholder: undefined as string | undefined, + prompt: undefined as string | undefined, + value: '', + valueSelection: undefined as unknown, + password: false, + busy: false, + enabled: true, + ignoreFocusOut: false, + step: undefined as number | undefined, + totalSteps: undefined as number | undefined, + buttons: [] as unknown[], + validationMessage: undefined as unknown, + onDidAccept: accept.event, + onDidHide: hideEmitter.event, + onDidChangeValue: valueChanged.event, + onDidTriggerButton: new EventEmitter().event, + show() { + if (visible) { + return; + } + visible = true; + const mine = ++generation; + const message = typeof box.validationMessage === 'string' ? box.validationMessage : typeof box.validationMessage === 'object' && box.validationMessage !== null ? String((box.validationMessage as { message?: unknown }).message ?? '') : ''; + const title = [box.title, box.step !== undefined && box.totalSteps !== undefined ? `(${box.step}/${box.totalSteps})` : ''].filter(Boolean).join(' '); + void host.ui({ + kind: 'inputBox', extensionId, password: box.password, value: box.value, + ...(message || box.prompt ? { prompt: message || box.prompt || '' } : {}), + ...(box.placeholder ? { placeHolder: box.placeholder } : {}), + ...(title ? { title } : {}), + }).then(async (answer) => { + if (mine !== generation || !visible) { + return; + } + if (typeof answer === 'string') { + box.value = answer; + valueChanged.fire(answer); + // Validation runs on the value change, as in VS Code; let async validators settle. + await new Promise((resolve) => setTimeout(resolve, 0)); + accept.fire(); + await new Promise((resolve) => setTimeout(resolve, 0)); + if (visible && mine === generation && box.validationMessage) { + // Still open with a problem: ask again, the problem as the prompt. + visible = false; + box.show(); + return; + } + } + if (visible && mine === generation) { + visible = false; + hideEmitter.fire(); + } + }); + }, + hide() { + if (visible) { + visible = false; + generation++; + hideEmitter.fire(); + } + }, + dispose() { + box.hide(); + accept.dispose(); + hideEmitter.dispose(); + }, + }; + return box; + } + + async function showDialog(request: DialogRequest): Promise { + const answer = await host.rpc.request(MAIN_METHODS.showDialog, request); + return Array.isArray(answer) ? answer : null; + } + + /* ------------------------------ status bar, progress ------------------------------ */ + + function createStatusBarItem(idOrAlignment?: string | number, alignmentOrPriority?: number, maybePriority?: number) { + const hasId = typeof idOrAlignment === 'string'; + const alignment = (hasId ? alignmentOrPriority : idOrAlignment) ?? types.StatusBarAlignment.Left; + const priority = (hasId ? maybePriority : alignmentOrPriority) ?? 0; + const key = host.nextKey(extensionId); + const state = { text: '', tooltip: undefined as unknown, command: undefined as unknown, name: undefined as string | undefined, visible: false, disposed: false, color: undefined as unknown, backgroundColor: undefined as unknown, accessibilityInformation: undefined as unknown }; + let timer: ReturnType | null = null; + const push = (): void => { + if (state.disposed || timer) { + return; + } + // Coalesce the several property writes extensions make in a row. + timer = setTimeout(() => { + timer = null; + if (state.disposed) { + return; + } + const command = state.command as string | { command: string; arguments?: unknown[] } | undefined; + const tooltip = state.tooltip as string | { value: string } | undefined; + const item: StatusBarItemData = { + key, extensionId, text: state.text, alignment: alignment === types.StatusBarAlignment.Right ? 'right' : 'left', priority, visible: state.visible, + ...(tooltip ? { tooltip: typeof tooltip === 'string' ? tooltip : String(tooltip.value ?? '') } : {}), + ...(typeof command === 'string' ? { command } : command && typeof command.command === 'string' ? { command: command.command, commandArgs: command.arguments ?? [] } : {}), + ...(state.name ? { name: state.name } : {}), + }; + host.uiNotify({ kind: 'statusBarItem', item }); + }, 0); + }; + const item = { + id: hasId ? idOrAlignment : `${extensionId}.${key}`, + alignment, + priority, + show() { + state.visible = true; + push(); + }, + hide() { + state.visible = false; + push(); + }, + dispose() { + state.disposed = true; + host.uiNotify({ kind: 'statusBarItemDispose', key }); + }, + }; + for (const property of ['text', 'tooltip', 'command', 'name', 'color', 'backgroundColor', 'accessibilityInformation'] as const) { + Object.defineProperty(item, property, { + get: () => state[property], + set: (value: unknown) => { + (state as Record)[property] = value; + push(); + }, + enumerable: true, + }); + } + return item; + } + + function setStatusBarMessage(text: string, hideAfterOrThenable?: number | PromiseLike): Disposable { + const timeoutMs = typeof hideAfterOrThenable === 'number' ? hideAfterOrThenable : 0; + host.uiNotify({ kind: 'statusMessage', text: String(text), timeoutMs }); + const clear = new Disposable(() => host.uiNotify({ kind: 'statusMessage', text: '', timeoutMs: 0 })); + if (hideAfterOrThenable && typeof hideAfterOrThenable === 'object') { + void Promise.resolve(hideAfterOrThenable).finally(() => clear.dispose()); + } + return clear; + } + + async function withProgress(options: { location: unknown; title?: string; cancellable?: boolean }, task: (progress: { report(value: { message?: string; increment?: number }): void }, token: CancellationToken) => PromiseLike): Promise { + const key = host.nextKey(extensionId); + const displayName = record.description.packageJSON['displayName']; + const title = options.title ?? (typeof displayName === 'string' ? displayName : extensionId); + let percent: number | undefined; + let message: string | undefined; + const showsNotification = options.location === types.ProgressLocation.Notification; + const update = (): void => { + if (showsNotification) { + host.uiNotify({ kind: 'progress', key, title, ...(message ? { message } : {}), ...(percent !== undefined ? { percent } : {}) }); + } else { + host.uiNotify({ kind: 'statusMessage', text: message ? `${title}: ${message}` : title, timeoutMs: 0 }); + } + }; + update(); + const source = new types.CancellationTokenSource(); + try { + return await task({ + report(value) { + if (typeof value.increment === 'number') { + percent = Math.min(100, (percent ?? 0) + value.increment); + } + if (typeof value.message === 'string') { + message = value.message; + } + update(); + }, + }, source.token); + } finally { + source.dispose(); + host.uiNotify(showsNotification ? { kind: 'progressEnd', key } : { kind: 'statusMessage', text: '', timeoutMs: 0 }); + } + } + + /* ------------------------------ documents ------------------------------ */ + + async function openTextDocument(arg?: unknown): Promise { + if (arg === undefined || (typeof arg === 'object' && arg !== null && !(arg instanceof Uri))) { + const options = (arg ?? {}) as { content?: string; language?: string }; + const uri = Uri.from({ scheme: 'untitled', path: `Untitled-${host.nextKey(extensionId).split('/')[1]}` }); + const document = new TextDocumentModel(uri, options.language ?? 'plaintext', 1, options.content ?? ''); + host.documents.set(uri.toString(), document); + return document; + } + const uri = typeof arg === 'string' ? Uri.file(arg) : arg as Uri; + const known = host.documents.get(uri.toString()); + if (known && !known.isClosed) { + return known; + } + if (uri.scheme !== 'file') { + const provider = host.contentProviders.get(uri.scheme); + if (!provider) { + throw new Error(`cannot open ${uri.toString()}. Detail: There is no provider for the '${uri.scheme}' scheme`); + } + const content = await provider.provideTextDocumentContent(uri, CancellationTokenNone); + const document = new TextDocumentModel(uri, 'plaintext', 1, typeof content === 'string' ? content : ''); + host.documents.set(uri.toString(), document); + return document; + } + let text: string; + try { + text = await fsp.readFile(uri.fsPath, 'utf8'); + } catch (error) { + throw toFsError(error, uri); + } + const document = new TextDocumentModel(uri, host.languageOf(uri.fsPath), 1, text, async (doc) => { + await fsp.writeFile(doc.uri.fsPath, doc.getText()); + doc.isDirty = false; + return true; + }); + host.documents.set(uri.toString(), document); + return document; + } + + /* ------------------------------ file system ------------------------------ */ + + const fileSystem = { + stat: async (target: Uri) => { + const uri = fileUri(target); + try { + const lstat = await fsp.lstat(uri.fsPath); + const stat = lstat.isSymbolicLink() ? await fsp.stat(uri.fsPath).catch(() => lstat) : lstat; + const type = (stat.isDirectory() ? FileType.Directory : stat.isFile() ? FileType.File : FileType.Unknown) | (lstat.isSymbolicLink() ? FileType.SymbolicLink : 0); + return { type, ctime: stat.ctimeMs, mtime: stat.mtimeMs, size: stat.size }; + } catch (error) { + throw toFsError(error, uri); + } + }, + readDirectory: async (target: Uri) => { + const uri = fileUri(target); + try { + const entries = await fsp.readdir(uri.fsPath, { withFileTypes: true }); + return entries.map((entry) => [entry.name, (entry.isDirectory() ? FileType.Directory : entry.isFile() ? FileType.File : FileType.Unknown) | (entry.isSymbolicLink() ? FileType.SymbolicLink : 0)] as [string, number]); + } catch (error) { + throw toFsError(error, uri); + } + }, + createDirectory: async (target: Uri) => { + const uri = fileUri(target); + await fsp.mkdir(uri.fsPath, { recursive: true }).catch((error: unknown) => { + throw toFsError(error, uri); + }); + }, + readFile: async (target: Uri) => { + const uri = fileUri(target); + try { + return new Uint8Array(await fsp.readFile(uri.fsPath)); + } catch (error) { + throw toFsError(error, uri); + } + }, + writeFile: async (target: Uri, content: Uint8Array) => { + const uri = fileUri(target); + try { + await fsp.mkdir(path.dirname(uri.fsPath), { recursive: true }); + await fsp.writeFile(uri.fsPath, content); + } catch (error) { + throw toFsError(error, uri); + } + }, + delete: async (target: Uri, options: { recursive?: boolean } = {}) => { + const uri = fileUri(target); + try { + await fsp.rm(uri.fsPath, { recursive: options.recursive === true }); + } catch (error) { + throw toFsError(error, uri); + } + }, + rename: async (source: Uri, target: Uri, options: { overwrite?: boolean } = {}) => { + const from = fileUri(source); + const to = fileUri(target); + if (!options.overwrite && fs.existsSync(to.fsPath)) { + throw FileSystemError.FileExists(to); + } + await fsp.rename(from.fsPath, to.fsPath).catch((error: unknown) => { + throw toFsError(error, from); + }); + }, + copy: async (source: Uri, target: Uri, options: { overwrite?: boolean } = {}) => { + const from = fileUri(source); + const to = fileUri(target); + await fsp.cp(from.fsPath, to.fsPath, { recursive: true, force: options.overwrite === true, errorOnExist: options.overwrite !== true }).catch((error: unknown) => { + throw toFsError(error, from); + }); + }, + isWritableFileSystem: (scheme: string) => (scheme === 'file' ? true : undefined), + }; + + async function findFiles(include: unknown, exclude?: unknown, maxResults?: number, token: CancellationToken = CancellationTokenNone): Promise { + const patternOf = (value: unknown): { base: string; pattern: string } | null => { + if (typeof value === 'string') { + return workspaceRoot ? { base: workspaceRoot, pattern: value } : null; + } + if (value instanceof types.RelativePattern) { + return { base: value.baseUri.fsPath, pattern: value.pattern }; + } + return null; + }; + const included = patternOf(include); + if (!included) { + return []; + } + const excluded = exclude === null ? null : patternOf(exclude); + const skipDefault = exclude === undefined; + const results: Uri[] = []; + const limit = typeof maxResults === 'number' && maxResults > 0 ? maxResults : 10_000; + const walk = async (folder: string): Promise => { + if (results.length >= limit || token.isCancellationRequested) { + return; + } + let entries: fs.Dirent[]; + try { + entries = await fsp.readdir(folder, { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + if (results.length >= limit) { + return; + } + const full = path.join(folder, entry.name); + const relative = path.relative(included.base, full).split(path.sep).join('/'); + if (skipDefault && (entry.name === '.git' || entry.name === 'node_modules')) { + continue; + } + if (excluded && matchGlob(excluded.pattern, path.relative(excluded.base, full).split(path.sep).join('/'))) { + continue; + } + if (entry.isDirectory()) { + await walk(full); + } else if (entry.isFile() && matchGlob(included.pattern, relative)) { + results.push(Uri.file(full)); + } + } + }; + await walk(included.base); + return results; + } + + function createFileSystemWatcher(pattern: unknown, ignoreCreate = false, ignoreChange = false, ignoreDelete = false) { + const created = new EventEmitter(); + const changed = new EventEmitter(); + const deleted = new EventEmitter(); + const resolved = typeof pattern === 'string' ? (workspaceRoot ? { base: workspaceRoot, pattern } : null) : pattern instanceof types.RelativePattern ? { base: pattern.baseUri.fsPath, pattern: pattern.pattern } : null; + let watcher: fs.FSWatcher | null = null; + if (resolved && fs.existsSync(resolved.base)) { + const known = new Set(); + try { + watcher = fs.watch(resolved.base, { recursive: true, persistent: false }, (_event, name) => { + if (!name) { + return; + } + const relative = name.toString().split(path.sep).join('/'); + if (!matchGlob(resolved.pattern, relative) || relative.startsWith('.git/') || relative.includes('/node_modules/') || relative.startsWith('node_modules/')) { + return; + } + const full = path.join(resolved.base, name.toString()); + const uri = Uri.file(full); + const exists = fs.existsSync(full); + if (!exists) { + known.delete(full); + if (!ignoreDelete) { + deleted.fire(uri); + } + } else if (known.has(full)) { + if (!ignoreChange) { + changed.fire(uri); + } + } else { + known.add(full); + if (!ignoreCreate) { + created.fire(uri); + } + } + }); + watcher.on('error', () => undefined); + } catch { + watcher = null; + } + } + return { + ignoreCreateEvents: ignoreCreate, + ignoreChangeEvents: ignoreChange, + ignoreDeleteEvents: ignoreDelete, + onDidCreate: created.event, + onDidChange: changed.event, + onDidDelete: deleted.event, + dispose() { + watcher?.close(); + created.dispose(); + changed.dispose(); + deleted.dispose(); + }, + }; + } + + const asRelativePath = (pathOrUri: string | Uri, includeWorkspaceFolder?: boolean): string => { + const file = typeof pathOrUri === 'string' ? pathOrUri : pathOrUri.fsPath; + if (!workspaceRoot || !(file === workspaceRoot || file.startsWith(workspaceRoot + path.sep))) { + return typeof pathOrUri === 'string' ? pathOrUri : pathOrUri.fsPath; + } + const relative = path.relative(workspaceRoot, file).split(path.sep).join('/'); + return includeWorkspaceFolder ? `${path.basename(workspaceRoot)}/${relative}` : relative; + }; + + const workspaceEvents = { + onDidOpenTextDocument: new EventEmitter(), + onDidCloseTextDocument: new EventEmitter(), + onDidChangeTextDocument: new EventEmitter(), + onDidSaveTextDocument: new EventEmitter(), + onWillSaveTextDocument: new EventEmitter(), + onDidChangeWorkspaceFolders: new EventEmitter(), + onDidCreateFiles: new EventEmitter(), + onDidDeleteFiles: new EventEmitter(), + onDidRenameFiles: new EventEmitter(), + onWillCreateFiles: new EventEmitter(), + onWillDeleteFiles: new EventEmitter(), + onWillRenameFiles: new EventEmitter(), + }; + + const workspace = withFallback('workspace', { + get workspaceFolders() { + return workspaceFolder ? [workspaceFolder] : undefined; + }, + get name() { + return workspaceFolder?.name; + }, + get rootPath() { + return workspaceRoot ?? undefined; + }, + workspaceFile: undefined, + get isTrusted() { + return host.trusted; + }, + onDidGrantWorkspaceTrust: host.onDidGrantWorkspaceTrust.event, + getWorkspaceFolder: (uri: Uri) => (workspaceFolder && uri.scheme === 'file' && (uri.fsPath === workspaceRoot || uri.fsPath.startsWith((workspaceRoot ?? '') + path.sep)) ? workspaceFolder : undefined), + asRelativePath, + updateWorkspaceFolders: () => { + report('workspace.updateWorkspaceFolders'); + return false; + }, + getConfiguration: (section?: string) => host.configuration.get(section), + onDidChangeConfiguration: host.onDidChangeConfiguration.event, + get textDocuments() { + return [...host.documents.values()].filter((document) => !document.isClosed); + }, + openTextDocument, + fs: fileSystem, + findFiles, + createFileSystemWatcher, + registerTextDocumentContentProvider: (scheme: string, provider: { provideTextDocumentContent(uri: Uri, token: unknown): unknown }) => { + host.contentProviders.set(scheme, provider); + return new Disposable(() => { + if (host.contentProviders.get(scheme) === provider) { + host.contentProviders.delete(scheme); + } + }); + }, + applyEdit: () => { + // #260: edits go through the editor so unsaved text and undo stay right. + report('workspace.applyEdit'); + return Promise.resolve(false); + }, + saveAll: () => Promise.resolve(false), + onDidOpenTextDocument: workspaceEvents.onDidOpenTextDocument.event, + onDidCloseTextDocument: workspaceEvents.onDidCloseTextDocument.event, + onDidChangeTextDocument: workspaceEvents.onDidChangeTextDocument.event, + onDidSaveTextDocument: workspaceEvents.onDidSaveTextDocument.event, + onWillSaveTextDocument: workspaceEvents.onWillSaveTextDocument.event, + onDidChangeWorkspaceFolders: workspaceEvents.onDidChangeWorkspaceFolders.event, + onDidCreateFiles: workspaceEvents.onDidCreateFiles.event, + onDidDeleteFiles: workspaceEvents.onDidDeleteFiles.event, + onDidRenameFiles: workspaceEvents.onDidRenameFiles.event, + onWillCreateFiles: workspaceEvents.onWillCreateFiles.event, + onWillDeleteFiles: workspaceEvents.onWillDeleteFiles.event, + onWillRenameFiles: workspaceEvents.onWillRenameFiles.event, + notebookDocuments: [], + textDocumentsChanged: undefined, + }, report); + + /* ------------------------------ window ------------------------------ */ + + const windowEvents = { + onDidChangeActiveTextEditor: new EventEmitter(), + onDidChangeVisibleTextEditors: new EventEmitter(), + onDidChangeTextEditorSelection: new EventEmitter(), + onDidChangeTextEditorVisibleRanges: new EventEmitter(), + onDidChangeTextEditorOptions: new EventEmitter(), + onDidChangeTextEditorViewColumn: new EventEmitter(), + onDidChangeWindowState: new EventEmitter(), + onDidChangeActiveColorTheme: new EventEmitter(), + onDidOpenTerminal: new EventEmitter(), + onDidCloseTerminal: new EventEmitter(), + onDidChangeActiveTerminal: new EventEmitter(), + onDidChangeTerminalState: new EventEmitter(), + }; + + function editorFor(document: TextDocumentModel) { + const selection = new types.Selection(0, 0, 0, 0); + return { + document, + selection, + selections: [selection], + visibleRanges: [] as types.Range[], + options: { tabSize: 4, insertSpaces: true }, + viewColumn: types.ViewColumn.One, + edit: () => { + report('TextEditor.edit'); + return Promise.resolve(false); + }, + insertSnippet: () => { + report('TextEditor.insertSnippet'); + return Promise.resolve(false); + }, + setDecorations: () => undefined, + revealRange: () => undefined, + show: () => undefined, + hide: () => undefined, + }; + } + + const window = withFallback('window', { + activeTextEditor: undefined as unknown, + visibleTextEditors: [] as unknown[], + activeTerminal: undefined, + terminals: [], + state: { focused: true, active: true }, + activeColorTheme: { kind: types.ColorThemeKind.Dark }, + showInformationMessage: (message: string, ...rest: unknown[]) => showMessage('info', message, rest), + showWarningMessage: (message: string, ...rest: unknown[]) => showMessage('warning', message, rest), + showErrorMessage: (message: string, ...rest: unknown[]) => showMessage('error', message, rest), + showQuickPick, + showInputBox, + createQuickPick, + createInputBox, + showOpenDialog: async (options: { defaultUri?: Uri; openLabel?: string; canSelectFiles?: boolean; canSelectFolders?: boolean; canSelectMany?: boolean; filters?: Record; title?: string } = {}) => { + const paths = await showDialog({ + kind: 'open', + ...(options.title ? { title: options.title } : {}), + ...(options.defaultUri ? { defaultPath: options.defaultUri.fsPath } : {}), + ...(options.openLabel ? { openLabel: options.openLabel } : {}), + canSelectFiles: options.canSelectFiles !== false, + canSelectFolders: options.canSelectFolders === true, + canSelectMany: options.canSelectMany === true, + ...(options.filters ? { filters: options.filters } : {}), + }); + return paths ? paths.map((file) => Uri.file(file)) : undefined; + }, + showSaveDialog: async (options: { defaultUri?: Uri; saveLabel?: string; filters?: Record; title?: string } = {}) => { + const paths = await showDialog({ + kind: 'save', + ...(options.title ? { title: options.title } : {}), + ...(options.defaultUri ? { defaultPath: options.defaultUri.fsPath } : {}), + ...(options.saveLabel ? { openLabel: options.saveLabel } : {}), + ...(options.filters ? { filters: options.filters } : {}), + }); + return paths?.[0] ? Uri.file(paths[0]) : undefined; + }, + showWorkspaceFolderPick: () => Promise.resolve(workspaceFolder), + showTextDocument: async (target: unknown, columnOrOptions?: unknown) => { + const document = target instanceof TextDocumentModel ? target : await openTextDocument(target); + const options = typeof columnOrOptions === 'object' && columnOrOptions !== null ? columnOrOptions as { selection?: types.Range; preview?: boolean } : {}; + if (document.uri.scheme === 'file') { + await host.ui({ + kind: 'openFile', path: document.uri.fsPath, preview: options.preview !== false, + ...(options.selection ? { line: options.selection.start.line + 1, column: options.selection.start.character + 1 } : {}), + }); + } else { + report('window.showTextDocument (non-file document)'); + } + return editorFor(document); + }, + createOutputChannel, + createStatusBarItem, + setStatusBarMessage, + withProgress, + withScmProgress: (task: (progress: { report(value: unknown): void }) => PromiseLike) => task({ report: () => undefined }), + createTextEditorDecorationType: () => ({ key: host.nextKey(extensionId), dispose: () => undefined }), + registerUriHandler: () => new Disposable(() => undefined), + onDidChangeActiveTextEditor: windowEvents.onDidChangeActiveTextEditor.event, + onDidChangeVisibleTextEditors: windowEvents.onDidChangeVisibleTextEditors.event, + onDidChangeTextEditorSelection: windowEvents.onDidChangeTextEditorSelection.event, + onDidChangeTextEditorVisibleRanges: windowEvents.onDidChangeTextEditorVisibleRanges.event, + onDidChangeTextEditorOptions: windowEvents.onDidChangeTextEditorOptions.event, + onDidChangeTextEditorViewColumn: windowEvents.onDidChangeTextEditorViewColumn.event, + onDidChangeWindowState: windowEvents.onDidChangeWindowState.event, + onDidChangeActiveColorTheme: windowEvents.onDidChangeActiveColorTheme.event, + onDidOpenTerminal: windowEvents.onDidOpenTerminal.event, + onDidCloseTerminal: windowEvents.onDidCloseTerminal.event, + onDidChangeActiveTerminal: windowEvents.onDidChangeActiveTerminal.event, + onDidChangeTerminalState: windowEvents.onDidChangeTerminalState.event, + tabGroups: { + all: [], + activeTabGroup: { tabs: [], isActive: true, viewColumn: 1, activeTab: undefined }, + onDidChangeTabGroups: new EventEmitter().event, + onDidChangeTabs: new EventEmitter().event, + close: () => Promise.resolve(false), + }, + }, report); + + /* ------------------------------ env ------------------------------ */ + + const env = withFallback('env', { + appName: data.env.appName, + appRoot: data.env.appRoot, + appHost: data.env.appHost, + language: data.env.language, + machineId: data.env.machineId, + sessionId: data.env.sessionId, + uriScheme: data.env.uriScheme, + shell: data.env.shell, + uiKind: types.UIKind.Desktop, + remoteName: undefined, + isNewAppInstall: false, + // No telemetry, ever (project principle): extensions that honour this send none. + isTelemetryEnabled: false, + onDidChangeTelemetryEnabled: new EventEmitter().event, + onDidChangeShell: new EventEmitter().event, + logLevel: types.LogLevel.Info, + onDidChangeLogLevel: new EventEmitter().event, + createTelemetryLogger: () => ({ + logUsage: () => undefined, logError: () => undefined, dispose: () => undefined, isUsageEnabled: false, isErrorsEnabled: false, onDidChangeEnableStates: new EventEmitter().event, + }), + clipboard: { + readText: () => host.rpc.request(MAIN_METHODS.clipboardRead).then((text) => text ?? ''), + writeText: (text: string) => host.rpc.request(MAIN_METHODS.clipboardWrite, String(text)).then(() => undefined), + }, + openExternal: (target: Uri) => host.rpc.request(MAIN_METHODS.openExternal, target.toString(true)).then((opened) => opened === true), + asExternalUri: (target: Uri) => Promise.resolve(target), + }, report); + + /* ------------------------------ extensions ------------------------------ */ + + const extensions = withFallback('extensions', { + getExtension: (id: string) => host.extensionObject(id), + get all() { + return [...host.records.keys(), ...host.passive.map((extension) => extension.id)].map((id) => host.extensionObject(id)).filter(Boolean); + }, + get allAcrossExtensionHosts() { + return extensions.all; + }, + onDidChange: host.onDidChangeExtensions.event, + }, report); + + /* ------------------------------ languages (#260 adds the providers) ------------------------------ */ + + function createDiagnosticCollection(name = `${extensionId}.diagnostics`) { + const entries = new Map(); + const collection = { + name, + set(uriOrEntries: Uri | [Uri, unknown[] | undefined][], diagnostics?: unknown[]) { + if (Array.isArray(uriOrEntries)) { + for (const [uri, list] of uriOrEntries) { + collection.set(uri, list ?? []); + } + return; + } + if (!diagnostics || diagnostics.length === 0) { + entries.delete(uriOrEntries.toString()); + } else { + entries.set(uriOrEntries.toString(), [uriOrEntries, [...diagnostics]]); + } + }, + delete: (uri: Uri) => void entries.delete(uri.toString()), + clear: () => entries.clear(), + forEach: (callback: (uri: Uri, diagnostics: readonly unknown[], collection: unknown) => void, thisArg?: unknown) => { + for (const [uri, list] of entries.values()) { + callback.call(thisArg, uri, list, collection); + } + }, + get: (uri: Uri) => entries.get(uri.toString())?.[1], + has: (uri: Uri) => entries.has(uri.toString()), + dispose: () => entries.clear(), + [Symbol.iterator]: function* iterate() { + yield* [...entries.values()]; + }, + }; + return collection; + } + + const matchSelector = (selector: unknown, document: { languageId: string; uri: Uri }): number => { + const selectors = Array.isArray(selector) ? selector : [selector]; + let best = 0; + for (const one of selectors) { + if (typeof one === 'string') { + best = Math.max(best, one === document.languageId ? 10 : one === '*' ? 5 : 0); + } else if (typeof one === 'object' && one !== null) { + const filter = one as { language?: string; scheme?: string; pattern?: string | types.RelativePattern }; + let score = 0; + if (filter.language) { + score = filter.language === document.languageId ? 10 : filter.language === '*' ? 5 : -1; + } + if (score >= 0 && filter.scheme) { + score = filter.scheme === document.uri.scheme ? Math.max(score, 10) : filter.scheme === '*' ? Math.max(score, 5) : -1; + } + if (score >= 0 && filter.pattern) { + const pattern = typeof filter.pattern === 'string' ? filter.pattern : filter.pattern.pattern; + const base = typeof filter.pattern === 'string' ? '' : filter.pattern.baseUri.fsPath; + const subject = base ? path.relative(base, document.uri.fsPath).split(path.sep).join('/') : document.uri.fsPath.split(path.sep).join('/'); + score = matchGlob(pattern, subject) || matchGlob(pattern.startsWith('**/') ? pattern : `**/${pattern}`, subject) ? Math.max(score, 10) : -1; + } + best = Math.max(best, score); + } + } + return best; + }; + + const languages = withFallback('languages', { + getLanguages: () => Promise.resolve(host.allLanguages()), + createDiagnosticCollection, + getDiagnostics: () => [], + onDidChangeDiagnostics: new EventEmitter().event, + match: matchSelector, + setTextDocumentLanguage: (document: TextDocumentModel, languageId: string) => { + document.languageId = languageId; + return Promise.resolve(document); + }, + setLanguageConfiguration: () => new Disposable(() => undefined), + createLanguageStatusItem: (id: string) => ({ id, name: undefined, selector: undefined, severity: 0, text: '', detail: undefined, busy: false, command: undefined, accessibilityInformation: undefined, dispose: () => undefined }), + }, report); + + /* ------------------------------ l10n ------------------------------ */ + + const l10n = { + bundle: undefined, + uri: undefined, + t(messageOrOptions: string | { message: string; args?: unknown[] | Record }, ...args: unknown[]): string { + if (typeof messageOrOptions === 'object' && messageOrOptions !== null) { + return formatMessage(messageOrOptions.message, messageOrOptions.args ?? []); + } + const first = args[0]; + return formatMessage(String(messageOrOptions), args.length === 1 && typeof first === 'object' && first !== null && !Array.isArray(first) ? first as Record : args); + }, + }; + + /* ------------------------------ the rest: shapes only ------------------------------ */ + + const debug = missingNamespace('debug', report, { + activeDebugSession: undefined, + activeDebugConsole: { append: () => undefined, appendLine: () => undefined }, + breakpoints: [], + registerDebugConfigurationProvider: () => new Disposable(() => undefined), + registerDebugAdapterDescriptorFactory: () => new Disposable(() => undefined), + registerDebugAdapterTrackerFactory: () => new Disposable(() => undefined), + onDidStartDebugSession: new EventEmitter().event, + onDidTerminateDebugSession: new EventEmitter().event, + onDidChangeActiveDebugSession: new EventEmitter().event, + onDidReceiveDebugSessionCustomEvent: new EventEmitter().event, + onDidChangeBreakpoints: new EventEmitter().event, + startDebugging: () => { + report('debug.startDebugging'); + return Promise.resolve(false); + }, + }); + const tasks = missingNamespace('tasks', report, { + taskExecutions: [], + registerTaskProvider: () => new Disposable(() => undefined), + fetchTasks: () => Promise.resolve([]), + onDidStartTask: new EventEmitter().event, + onDidEndTask: new EventEmitter().event, + onDidStartTaskProcess: new EventEmitter().event, + onDidEndTaskProcess: new EventEmitter().event, + }); + const authentication = missingNamespace('authentication', report, { + getSession: () => Promise.resolve(undefined), + getAccounts: () => Promise.resolve([]), + onDidChangeSessions: new EventEmitter().event, + registerAuthenticationProvider: () => new Disposable(() => undefined), + }); + + const vscode: Record = { + version: HOST_VSCODE_API_VERSION, + ...types, + // Not part of the API surface. + CancellationTokenNone: undefined, + CancellationToken: { None: CancellationTokenNone, Cancelled: Object.freeze({ isCancellationRequested: true, onCancellationRequested: new EventEmitter().event }) }, + commands, + window, + workspace, + env, + extensions, + languages, + l10n, + debug, + tasks, + authentication, + scm: missingNamespace('scm', report, { inputBox: undefined }), + tests: missingNamespace('tests', report), + notebooks: missingNamespace('notebooks', report), + comments: missingNamespace('comments', report), + chat: missingNamespace('chat', report), + lm: missingNamespace('lm', report, { tools: [], onDidChangeChatModels: new EventEmitter().event, selectChatModels: () => Promise.resolve([]) }), + }; + delete vscode['CancellationTokenNone']; + return new Proxy(Object.freeze(vscode), { + get(target, property, receiver) { + if (typeof property === 'symbol' || property in target) { + return Reflect.get(target, property, receiver) as unknown; + } + if (property === 'then' || property === 'default' || property === '__esModule') { + return property === 'default' ? receiver : undefined; + } + report(property); + return undefined; + }, + }); +} diff --git a/apps/ide/src/extensionHost/configuration.ts b/apps/ide/src/extensionHost/configuration.ts new file mode 100644 index 000000000..d8f7243e2 --- /dev/null +++ b/apps/ide/src/extensionHost/configuration.ts @@ -0,0 +1,196 @@ +/** + * `vscode.workspace.getConfiguration` (#259): the defaults every extension + * declares in `contributes.configuration`, overlaid with the person's values. + * Keys are flat (`python.analysis.typeCheckingMode`); a section reads the + * subtree under it, as VS Code does. Pure: values come in, updates go out + * through the callback. + */ + +export type ConfigurationTargetName = 'user' | 'workspace'; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function clone(value: T): T { + return value === undefined ? value : structuredClone(value); +} + +/** The `properties` of a `contributes.configuration` (one object or an array of them), flattened to key -> default. */ +export function configurationDefaults(contributes: Readonly>): Map { + const defaults = new Map(); + const raw = contributes['configuration']; + const sections = Array.isArray(raw) ? raw : [raw]; + for (const section of sections) { + const properties = isRecord(section) ? section['properties'] : undefined; + if (!isRecord(properties)) { + continue; + } + for (const [key, schema] of Object.entries(properties)) { + if (!isRecord(schema)) { + continue; + } + if ('default' in schema) { + defaults.set(key, schema['default']); + } else { + // VS Code derives a default from the type when none is given. + const type = Array.isArray(schema['type']) ? schema['type'][0] : schema['type']; + const byType: Record = { string: '', boolean: false, number: 0, integer: 0, array: [], object: {}, null: null }; + if (typeof type === 'string' && type in byType) { + defaults.set(key, byType[type]); + } + } + } + } + const overrides = contributes['configurationDefaults']; + if (isRecord(overrides)) { + for (const [key, value] of Object.entries(overrides)) { + defaults.set(key, value); + } + } + return defaults; +} + +/** Sets `value` at the dotted `key` of a nested object. */ +function assign(target: Record, key: string, value: unknown): void { + const parts = key.split('.'); + let node = target; + for (const part of parts.slice(0, -1)) { + const next = node[part]; + if (!isRecord(next)) { + node[part] = {}; + } + node = node[part] as Record; + } + const last = parts[parts.length - 1] ?? key; + const existing = node[last]; + node[last] = isRecord(existing) && isRecord(value) ? { ...existing, ...clone(value) } : clone(value); +} + +export interface ConfigurationInspect { + readonly key: string; + readonly defaultValue?: T; + readonly globalValue?: T; + readonly workspaceValue?: T; + readonly workspaceFolderValue?: T; +} + +export interface WorkspaceConfiguration { + get(section: string, defaultValue?: T): T | undefined; + has(section: string): boolean; + inspect(section: string): ConfigurationInspect | undefined; + update(section: string, value: unknown, target?: boolean | number | null): Promise; + readonly [key: string]: unknown; +} + +export class ConfigurationModel { + private defaults = new Map(); + private user = new Map(); + private readonly onUpdate: (key: string, value: unknown, target: ConfigurationTargetName) => Promise; + + constructor(onUpdate: (key: string, value: unknown, target: ConfigurationTargetName) => Promise) { + this.onUpdate = onUpdate; + } + + setDefaults(contributes: readonly Readonly>[]): void { + this.defaults = new Map(); + for (const one of contributes) { + for (const [key, value] of configurationDefaults(one)) { + this.defaults.set(key, value); + } + } + } + + /** Replaces the person's values; returns the keys whose effective value changed. */ + setUserValues(values: Readonly>): string[] { + const next = new Map(Object.entries(values)); + const keys = new Set([...this.user.keys(), ...next.keys()]); + const changed = [...keys].filter((key) => JSON.stringify(this.user.get(key)) !== JSON.stringify(next.get(key))); + this.user = next; + return changed; + } + + private effective(): Map { + const merged = new Map(this.defaults); + for (const [key, value] of this.user) { + merged.set(key, value); + } + return merged; + } + + /** The value at a full dotted key: a leaf, or the subtree assembled from the keys under it. */ + valueAt(key: string): unknown { + const effective = this.effective(); + if (effective.has(key)) { + const value = effective.get(key); + // A leaf that is an object may still have keys under it set separately. + if (!isRecord(value)) { + return clone(value); + } + } + const prefix = `${key}.`; + const tree: Record = {}; + let found = false; + if (effective.has(key)) { + Object.assign(tree, clone(effective.get(key))); + found = true; + } + for (const [other, value] of effective) { + if (other.startsWith(prefix)) { + assign(tree, other.slice(prefix.length), value); + found = true; + } + } + return found ? tree : undefined; + } + + /** Whether a change of `changedKey` affects `section` (`onDidChangeConfiguration`'s `affectsConfiguration`). */ + static affects(changedKey: string, section: string): boolean { + return changedKey === section || changedKey.startsWith(`${section}.`) || section.startsWith(`${changedKey}.`); + } + + get(section?: string): WorkspaceConfiguration { + const base = section && section.trim() !== '' ? section : ''; + const full = (key: string): string => (base ? `${base}.${key}` : key); + const subtree = base ? this.valueAt(base) : (() => { + const tree: Record = {}; + for (const [key, value] of this.effective()) { + assign(tree, key, value); + } + return tree; + })(); + const result: Record = isRecord(subtree) ? subtree : {}; + const methods = { + get: (key: string, defaultValue?: T): T | undefined => { + const value = this.valueAt(full(key)); + return (value === undefined ? defaultValue : value) as T | undefined; + }, + has: (key: string): boolean => this.valueAt(full(key)) !== undefined, + inspect: (key: string): ConfigurationInspect | undefined => { + const name = full(key); + const defaultValue = this.defaults.get(name) as T | undefined; + const globalValue = this.user.get(name) as T | undefined; + return { + key: name, + ...(defaultValue !== undefined ? { defaultValue: clone(defaultValue) } : {}), + ...(globalValue !== undefined ? { globalValue: clone(globalValue) } : {}), + }; + }, + update: async (key: string, value: unknown, target?: boolean | number | null): Promise => { + // ConfigurationTarget: 1 Global, 2 Workspace, 3 WorkspaceFolder; `true` means Global. + const scope: ConfigurationTargetName = target === true || target === 1 || target === undefined || target === null ? 'user' : 'workspace'; + const name = full(key); + await this.onUpdate(name, value === undefined ? undefined : clone(value), scope); + if (value === undefined) { + this.user.delete(name); + } else { + this.user.set(name, clone(value)); + } + }, + }; + for (const [name, fn] of Object.entries(methods)) { + Object.defineProperty(result, name, { value: fn, enumerable: false }); + } + return Object.freeze(result) as WorkspaceConfiguration; + } +} diff --git a/apps/ide/src/extensionHost/glob.ts b/apps/ide/src/extensionHost/glob.ts new file mode 100644 index 000000000..94abe44a9 --- /dev/null +++ b/apps/ide/src/extensionHost/glob.ts @@ -0,0 +1,70 @@ +/** + * Glob patterns as VS Code's `findFiles`, file watchers and document + * selectors take them (#259): `*`, `?`, `**`, `{a,b}` and `[...]`, matched + * against a path relative to a base with `/` separators. Pure. + */ + +const cache = new Map(); + +function escapeRegExp(text: string): string { + return text.replace(/[.+^$()|\\]/g, '\\$&'); +} + +function translate(glob: string): string { + let out = ''; + let index = 0; + let braces = 0; + while (index < glob.length) { + const char = glob[index] ?? ''; + if (char === '*') { + if (glob[index + 1] === '*') { + // `**/` matches any number of folders (none included); a trailing `**` anything. + const slash = glob[index + 2] === '/'; + out += slash ? '(?:[^/]*/)*' : '.*'; + index += slash ? 3 : 2; + continue; + } + out += '[^/]*'; + } else if (char === '?') { + out += '[^/]'; + } else if (char === '{') { + braces++; + out += '(?:'; + } else if (char === '}' && braces > 0) { + braces--; + out += ')'; + } else if (char === ',' && braces > 0) { + out += '|'; + } else if (char === '[') { + const close = glob.indexOf(']', index + 1); + if (close > index + 1) { + const body = glob.slice(index + 1, close).replace(/\\/g, '\\\\'); + out += `[${body.startsWith('!') ? `^${body.slice(1)}` : body}]`; + index = close + 1; + continue; + } + out += '\\['; + } else { + out += escapeRegExp(char); + } + index++; + } + return out; +} + +export function globToRegExp(glob: string): RegExp { + let regexp = cache.get(glob); + if (!regexp) { + regexp = new RegExp(`^${translate(glob.replace(/\\/g, '/').replace(/^\.\//, ''))}$`); + if (cache.size > 500) { + cache.clear(); + } + cache.set(glob, regexp); + } + return regexp; +} + +// Whether `relativePath` (with `/`) matches `glob` as a whole: `*.ts` is a file at the base, `**/*.ts` one at any depth. +export function matchGlob(glob: string, relativePath: string): boolean { + return globToRegExp(glob).test(relativePath.replace(/\\/g, '/')); +} diff --git a/apps/ide/src/extensionHost/host.ts b/apps/ide/src/extensionHost/host.ts new file mode 100644 index 000000000..2bb8b9127 --- /dev/null +++ b/apps/ide/src/extensionHost/host.ts @@ -0,0 +1,529 @@ +import fs from 'node:fs'; +import Module from 'node:module'; +import path from 'node:path'; +import { + activationMatches, MAIN_METHODS, type HostActivationEvent, type HostExtensionDescription, type HostInitData, type HostLogLine, type HostPassiveExtension, type RpcEndpoint, type UiNotification, type UiRequest, +} from '../shared/extensionHostProtocol.ts'; +import type { ExtensionActivation, ExtensionId } from '../shared/extensions.ts'; +import { createVscodeApi } from './api.ts'; +import { ConfigurationModel } from './configuration.ts'; +import { FileMemento } from './memento.ts'; +import type { TextDocumentModel } from './textDocument.ts'; +import { BUILTIN_LANGUAGES } from './textDocument.ts'; +import { Disposable, EventEmitter, Uri } from './types.ts'; +import { fromWire, toWire } from './wire.ts'; + +/** + * The extension host (#259, ADR 0002): runs the extensions' code in its own + * Node process, one per window, never in the renderer. It + * + * - answers `require('vscode')` with an API object made for the extension + * that asks (so every call knows who made it); + * - activates each extension on its activation events, after the + * extensions it depends on, and deactivates them all on shutdown; + * - keeps the commands the extensions register and runs them for the + * workbench, and forwards what the workbench must show to the main process. + * + * Nothing here trusts the extensions: they run with the rights of the IDE's + * user (as in VS Code), which is why the main process only starts this host + * in a trusted folder unless every extension supports Restricted Mode (#263). + */ + +export interface ExtensionRecord { + readonly description: HostExtensionDescription; + state: ExtensionActivation; + error?: string; + exports: unknown; + activation: Promise | null; + module: { activate?: (context: unknown) => unknown; deactivate?: () => unknown } | null; + context: ExtensionContextImpl | null; + api: unknown; +} + +export interface ExtensionContextImpl { + readonly subscriptions: { dispose(): unknown }[]; + readonly globalState: FileMemento; + readonly workspaceState: FileMemento; +} + +interface RegisteredCommand { + readonly callback: (...args: unknown[]) => unknown; + readonly thisArg: unknown; + readonly extensionId: ExtensionId; +} + +type ModuleWithLoad = typeof Module & { _load(request: string, parent: { filename?: string } | null | undefined, isMain: boolean): unknown }; + +export class ExtensionHost { + readonly rpc: RpcEndpoint; + data!: HostInitData; + readonly records = new Map(); + passive: readonly HostPassiveExtension[] = []; + readonly commands = new Map(); + readonly configuration: ConfigurationModel; + readonly documents = new Map(); + /** Language id by file extension (`.toml` -> `toml`) and by file name. */ + readonly languagesByExtension = new Map(Object.entries(BUILTIN_LANGUAGES)); + readonly languagesByName = new Map(); + readonly onDidChangeConfiguration = new EventEmitter<{ affectsConfiguration(section: string, scope?: unknown): boolean }>(); + readonly onDidGrantWorkspaceTrust = new EventEmitter(); + readonly onDidChangeExtensions = new EventEmitter(); + readonly contentProviders = new Map(); + private readonly reported = new Set(); + private readonly firedEvents = new Set(); + private moduleHooked = false; + private sequence = 0; + trusted = false; + + constructor(rpc: RpcEndpoint) { + this.rpc = rpc; + this.configuration = new ConfigurationModel((key, value, target) => this.rpc.request(MAIN_METHODS.updateConfiguration, key, toWire(value), target).then(() => undefined)); + } + + init(data: HostInitData): void { + this.data = data; + this.trusted = data.trusted; + this.passive = data.passive; + for (const description of data.extensions) { + this.records.set(description.id, { description, state: 'inactive', exports: undefined, activation: null, module: null, context: null, api: null }); + } + this.configuration.setDefaults([...data.extensions.map((ext) => ext.packageJSON), ...data.passive.map((ext) => ext.packageJSON)].map((json) => (typeof json['contributes'] === 'object' && json['contributes'] !== null ? json['contributes'] as Record : {}))); + this.configuration.setUserValues(data.configuration); + for (const json of [...data.extensions, ...data.passive].map((ext) => ext.packageJSON)) { + this.learnLanguages(json); + } + this.hookRequire(); + this.log({ level: 'info', extensionId: null, message: `Extension host started (pid ${process.pid}) with ${data.extensions.length} extension(s) with code.` }); + } + + private learnLanguages(json: Readonly>): void { + const contributes = json['contributes']; + const languages = typeof contributes === 'object' && contributes !== null ? (contributes as Record)['languages'] : undefined; + if (!Array.isArray(languages)) { + return; + } + for (const language of languages as unknown[]) { + if (typeof language !== 'object' || language === null) { + continue; + } + const { id, extensions, filenames } = language as Record; + if (typeof id !== 'string') { + continue; + } + for (const extension of Array.isArray(extensions) ? extensions : []) { + if (typeof extension === 'string') { + this.languagesByExtension.set(extension.toLowerCase(), id); + } + } + for (const name of Array.isArray(filenames) ? filenames : []) { + if (typeof name === 'string') { + this.languagesByName.set(name.toLowerCase(), id); + } + } + } + } + + languageOf(file: string): string { + const base = path.basename(file).toLowerCase(); + const byName = this.languagesByName.get(base); + if (byName) { + return byName; + } + // Longest extension first: `.d.ts` before `.ts`. + const dots = [...base.matchAll(/\./g)].map((match) => match.index); + for (const dot of dots) { + const language = this.languagesByExtension.get(base.slice(dot)); + if (language) { + return language; + } + } + return 'plaintext'; + } + + allLanguages(): string[] { + return [...new Set([...this.languagesByExtension.values(), ...this.languagesByName.values(), 'plaintext'])].sort(); + } + + /* ------------------------------ logging ------------------------------ */ + + log(line: HostLogLine): void { + this.rpc.notify(MAIN_METHODS.log, line); + } + + /** An extension used API the host does not implement: said once per extension and name. */ + reportMissing(extensionId: ExtensionId, api: string): void { + const key = `${extensionId}\u0000${api}`; + if (this.reported.has(key)) { + return; + } + this.reported.add(key); + this.rpc.notify(MAIN_METHODS.notImplemented, extensionId, api); + } + + nextKey(extensionId: ExtensionId): string { + return `${extensionId}/${++this.sequence}`; + } + + ui(request: UiRequest): Promise { + return this.rpc.request(MAIN_METHODS.ui, request); + } + + uiNotify(notification: UiNotification): void { + this.rpc.notify(MAIN_METHODS.uiNotify, toWire(notification)); + } + + /* ------------------------------ require('vscode') ------------------------------ */ + + /** The extension a file belongs to: the one whose folder holds it (the deepest, for nested folders). */ + extensionOfFile(file: string | undefined): ExtensionRecord | undefined { + if (!file) { + return undefined; + } + let best: ExtensionRecord | undefined; + for (const record of this.records.values()) { + const location = record.description.location; + if ((file === location || file.startsWith(location + path.sep)) && (!best || location.length > best.description.location.length)) { + best = record; + } + } + return best; + } + + apiFor(record: ExtensionRecord): unknown { + record.api ??= createVscodeApi(record, this); + return record.api; + } + + private hookRequire(): void { + if (this.moduleHooked) { + return; + } + this.moduleHooked = true; + const loader = Module as ModuleWithLoad; + const original = loader._load.bind(loader); + loader._load = (request, parent, isMain) => { + if (request === 'vscode') { + const record = this.extensionOfFile(parent?.filename); + if (!record) { + // Code outside every extension (a shared dependency hoisted elsewhere): the first extension's view is the best guess. + const first = this.records.values().next().value; + if (!first) { + throw new Error('Cannot find module \'vscode\''); + } + return this.apiFor(first); + } + return this.apiFor(record); + } + return original(request, parent, isMain); + }; + } + + /* ------------------------------ activation ------------------------------ */ + + private setState(record: ExtensionRecord, state: ExtensionActivation, error?: string): void { + record.state = state; + if (error === undefined) { + delete record.error; + } else { + record.error = error; + } + const event: HostActivationEvent = { id: record.description.id, state, ...(error !== undefined ? { error } : {}) }; + this.rpc.notify(MAIN_METHODS.activation, event); + } + + /** Activates every extension listening for `event`; resolves when they have all settled. */ + async activateByEvent(event: string): Promise { + this.firedEvents.add(event); + const waiting: Promise[] = []; + for (const record of this.records.values()) { + if (record.state === 'inactive' && activationMatches(record.description.activationEvents, event)) { + waiting.push(this.activate(record.description.id)); + } + } + await Promise.all(waiting); + } + + /** Whether an event fired already (`*`, `onStartupFinished`, `workspaceContains:`): late activations replay them. */ + hasFired(event: string): boolean { + return this.firedEvents.has(event); + } + + activate(id: ExtensionId, chain: readonly ExtensionId[] = []): Promise { + const record = this.records.get(id); + if (!record) { + return Promise.resolve(); + } + record.activation ??= this.doActivate(record, [...chain, id]); + return record.activation; + } + + private async doActivate(record: ExtensionRecord, chain: readonly ExtensionId[]): Promise { + const { description } = record; + for (const dependency of description.extensionDependencies) { + if (chain.includes(dependency)) { + continue; // a cycle: VS Code refuses it too; activate what we can + } + if (this.records.has(dependency)) { + await this.activate(dependency, chain); + const dependencyRecord = this.records.get(dependency); + if (dependencyRecord?.state === 'failed') { + this.setState(record, 'failed', `Its dependency ${dependency} failed to activate.`); + return; + } + } else if (!this.passive.some((passive) => passive.id === dependency)) { + this.log({ level: 'warn', extensionId: description.id, message: `Depends on ${dependency}, which is not installed or not enabled.` }); + } + } + this.setState(record, 'activating'); + const started = Date.now(); + try { + const entry = this.resolveMain(description); + const loaded = Module.createRequire(entry)(entry) as ExtensionRecord['module']; + record.module = loaded ?? {}; + record.context = this.createContext(record); + const result = typeof record.module.activate === 'function' ? await record.module.activate.call(record.module, record.context) : undefined; + record.exports = result; + this.setState(record, 'active'); + this.log({ level: 'info', extensionId: description.id, message: `Activated in ${Date.now() - started} ms.` }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + this.setState(record, 'failed', message); + this.log({ level: 'error', extensionId: description.id, message: `Failed to activate: ${error instanceof Error && error.stack ? error.stack : message}` }); + } + } + + private resolveMain(description: HostExtensionDescription): string { + const base = path.resolve(description.location, description.main); + for (const candidate of [base, `${base}.js`, `${base}.cjs`, path.join(base, 'index.js')]) { + if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { + const real = fs.realpathSync(candidate); + const root = fs.realpathSync(description.location); + if (real !== root && !real.startsWith(root + path.sep)) { + throw new Error(`Its main file (${description.main}) is outside the extension's folder.`); + } + return real; + } + } + throw new Error(`Its main file (${description.main}) does not exist.`); + } + + private storageFolder(root: string | null, id: ExtensionId): string | null { + return root ? path.join(root, id) : null; + } + + private createContext(record: ExtensionRecord): ExtensionContextImpl { + const { description } = record; + const globalStorage = this.storageFolder(this.data.globalStorageRoot, description.id) as string; + const workspaceStorage = this.storageFolder(this.data.workspaceStorageRoot, description.id); + const logFolder = path.join(this.data.logRoot, description.id); + const globalState = new FileMemento(path.join(globalStorage, 'state.json')); + const workspaceState = new FileMemento(workspaceStorage ? path.join(workspaceStorage, 'state.json') : null); + const secretsChanged = new EventEmitter<{ key: string }>(); + const subscriptions: { dispose(): unknown }[] = []; + const extensionUri = Uri.file(description.location); + const host = this; + const variables = new Map(); + const environmentVariableCollection = { + persistent: true, + description: undefined as unknown, + replace: (variable: string, value: string, options?: unknown) => variables.set(variable, { value, type: 1, options }), + append: (variable: string, value: string, options?: unknown) => variables.set(variable, { value, type: 2, options }), + prepend: (variable: string, value: string, options?: unknown) => variables.set(variable, { value, type: 3, options }), + get: (variable: string) => variables.get(variable), + forEach: (callback: (variable: string, mutator: unknown, collection: unknown) => void) => variables.forEach((mutator, variable) => callback(variable, mutator, environmentVariableCollection)), + delete: (variable: string) => variables.delete(variable), + clear: () => variables.clear(), + getScoped: () => environmentVariableCollection, + [Symbol.iterator]: function* iterate() { + yield* [...variables.entries()]; + }, + }; + const context = { + subscriptions, + globalState, + workspaceState, + secrets: { + get: (key: string) => host.rpc.request(MAIN_METHODS.secretGet, description.id, key).then((value) => value ?? undefined), + store: async (key: string, value: string) => { + await host.rpc.request(MAIN_METHODS.secretStore, description.id, key, value); + secretsChanged.fire({ key }); + }, + delete: async (key: string) => { + await host.rpc.request(MAIN_METHODS.secretDelete, description.id, key); + secretsChanged.fire({ key }); + }, + keys: () => Promise.resolve([] as string[]), + onDidChange: secretsChanged.event, + }, + extensionUri, + extensionPath: description.location, + asAbsolutePath: (relative: string) => path.join(description.location, relative), + storageUri: workspaceStorage ? Uri.file(workspaceStorage) : undefined, + storagePath: workspaceStorage ?? undefined, + globalStorageUri: Uri.file(globalStorage), + globalStoragePath: globalStorage, + logUri: Uri.file(logFolder), + logPath: logFolder, + extensionMode: 1, // ExtensionMode.Production + environmentVariableCollection, + extension: this.extensionObject(description.id), + languageModelAccessInformation: { onDidChange: new EventEmitter().event, canSendRequest: () => undefined }, + }; + return context; + } + + /** `vscode.Extension` for an id (with code or not). */ + extensionObject(id: ExtensionId): unknown { + const record = this.records.get(id.toLowerCase()); + const passive = this.passive.find((extension) => extension.id === id.toLowerCase()); + const location = record?.description.location ?? passive?.location; + const packageJSON = record?.description.packageJSON ?? passive?.packageJSON; + if (!location || !packageJSON) { + return undefined; + } + const host = this; + const json = packageJSON; + return { + id: `${String(json['publisher'] ?? '')}.${String(json['name'] ?? '')}`, + extensionUri: Uri.file(location), + extensionPath: location, + packageJSON: json, + extensionKind: 2, // ExtensionKind.Workspace + get isActive() { + return record ? record.state === 'active' : true; + }, + get exports() { + return record?.exports; + }, + activate: async () => { + if (record) { + await host.activate(record.description.id); + return record.exports; + } + return undefined; + }, + }; + } + + /* ------------------------------ commands ------------------------------ */ + + registerCommand(extensionId: ExtensionId, id: string, callback: (...args: unknown[]) => unknown, thisArg?: unknown): Disposable { + if (typeof id !== 'string' || id.trim() === '') { + throw new Error('Invalid command id'); + } + if (this.commands.has(id)) { + throw new Error(`command '${id}' already exists`); + } + const entry: RegisteredCommand = { callback, thisArg, extensionId }; + this.commands.set(id, entry); + return new Disposable(() => { + if (this.commands.get(id) === entry) { + this.commands.delete(id); + } + }); + } + + /** Runs a command for an extension: its own registered ones, the built-in `vscode` ones, then the workbench's. */ + async executeCommand(id: string, args: readonly unknown[]): Promise { + const builtin = await this.builtinCommand(id, args); + if (builtin.handled) { + return builtin.result; + } + if (!this.commands.has(id)) { + await this.activateByEvent(`onCommand:${id}`); + } + const command = this.commands.get(id); + if (command) { + return command.callback.apply(command.thisArg, [...args]); + } + const result = await this.rpc.request(MAIN_METHODS.executeWorkbenchCommand, id, toWire(args)); + return fromWire(result); + } + + /** The `vscode.*` commands the host answers itself (`setContext`, `vscode.open`, ...). */ + private async builtinCommand(id: string, args: readonly unknown[]): Promise<{ handled: boolean; result?: unknown }> { + switch (id) { + case 'setContext': + this.uiNotify({ kind: 'contextKey', key: String(args[0]), value: toWire(args[1]) }); + return { handled: true }; + case 'vscode.open': + case 'vscode.openWith': { + const target = args[0] instanceof Uri ? args[0] : typeof args[0] === 'string' ? Uri.parse(args[0]) : null; + if (!target) { + throw new Error('vscode.open needs a Uri'); + } + if (target.scheme === 'http' || target.scheme === 'https' || target.scheme === 'mailto') { + await this.rpc.request(MAIN_METHODS.openExternal, target.toString(true)); + } else if (target.scheme === 'file') { + const options = args[1] as { selection?: { start?: { line?: number; character?: number } } } | undefined; + const start = options?.selection?.start; + await this.ui({ kind: 'openFile', path: target.fsPath, preview: true, ...(typeof start?.line === 'number' ? { line: start.line + 1, column: (start.character ?? 0) + 1 } : {}) }); + } else { + throw new Error(`vscode.open cannot open ${target.scheme}: URIs in the Code-XR IDE yet`); + } + return { handled: true }; + } + case 'vscode.openFolder': + throw new Error('Opening another folder from an extension is not supported; use File > Open Folder.'); + case 'workbench.action.openWalkthrough': + case 'workbench.action.focusActiveEditorGroup': + return { handled: true }; + default: + return { handled: false }; + } + } + + /** The workbench runs an extension's command (the palette, a status bar item, a key). */ + async executeFromWorkbench(id: string, args: readonly unknown[]): Promise { + if (!this.commands.has(id)) { + await this.activateByEvent(`onCommand:${id}`); + } + const command = this.commands.get(id); + if (!command) { + throw new Error(`command '${id}' not found`); + } + const result: unknown = await command.callback.apply(command.thisArg, (fromWire(args) as unknown[])); + return toWire(result); + } + + /* ------------------------------ configuration, trust ------------------------------ */ + + configurationChanged(values: Readonly>): void { + const changed = this.configuration.setUserValues(values); + if (changed.length > 0) { + this.onDidChangeConfiguration.fire({ affectsConfiguration: (section: string) => changed.some((key) => ConfigurationModel.affects(key, section)) }); + } + } + + trustChanged(trusted: boolean): void { + if (trusted && !this.trusted) { + this.trusted = true; + this.onDidGrantWorkspaceTrust.fire(); + } + } + + /* ------------------------------ shutdown ------------------------------ */ + + async shutdown(): Promise { + const active = [...this.records.values()].filter((record) => record.state === 'active' || record.state === 'activating'); + await Promise.all(active.map(async (record) => { + try { + const result = record.module?.deactivate?.(); + if (result instanceof Promise) { + await Promise.race([result, new Promise((resolve) => setTimeout(resolve, 5000))]); + } + } catch (error) { + this.log({ level: 'warn', extensionId: record.description.id, message: `deactivate() failed: ${String(error)}` }); + } + for (const subscription of record.context?.subscriptions ?? []) { + try { + subscription?.dispose(); + } catch { + // Keep disposing. + } + } + record.context?.globalState.flush(); + record.context?.workspaceState.flush(); + })); + } +} diff --git a/apps/ide/src/extensionHost/index.ts b/apps/ide/src/extensionHost/index.ts new file mode 100644 index 000000000..9beaf6ae2 --- /dev/null +++ b/apps/ide/src/extensionHost/index.ts @@ -0,0 +1,44 @@ +import { HOST_METHODS, RpcEndpoint, type HostInitData, type RpcMessage } from '../shared/extensionHostProtocol.ts'; +import { ExtensionHost } from './host.ts'; + +/** + * Entry point of the extension host process (#259). The main process forks + * it with Electron's own Node (`ELECTRON_RUN_AS_NODE`) and talks to it over + * the IPC channel Node sets up for a forked child. Without that channel (run + * by hand) there is nothing to do. + */ + +if (typeof process.send !== 'function') { + console.error('The Code-XR extension host must be started by the IDE.'); + process.exit(1); +} + +const send = (message: RpcMessage): void => { + process.send?.(message); +}; +const rpc = new RpcEndpoint(send); +const host = new ExtensionHost(rpc); + +rpc.handle(HOST_METHODS.init, (data) => host.init(data as HostInitData)); +rpc.handle(HOST_METHODS.activateByEvent, (event) => host.activateByEvent(String(event))); +rpc.handle(HOST_METHODS.executeCommand, (id, args) => host.executeFromWorkbench(String(id), Array.isArray(args) ? args : [])); +rpc.handle(HOST_METHODS.registeredCommands, () => [...host.commands.keys()]); +rpc.handle(HOST_METHODS.configurationChanged, (values) => host.configurationChanged((values ?? {}) as Record)); +rpc.handle(HOST_METHODS.trustChanged, (trusted) => host.trustChanged(trusted === true)); +rpc.handle(HOST_METHODS.shutdown, async () => { + await host.shutdown(); + setTimeout(() => process.exit(0), 50); +}); + +process.on('message', (message) => rpc.receive(message)); +// The IDE went away without saying goodbye: deactivate what can be and leave. +process.on('disconnect', () => { + void host.shutdown().finally(() => process.exit(0)); +}); +// An extension's stray rejection or exception must not take every other extension down. +process.on('unhandledRejection', (reason) => { + host.log({ level: 'error', extensionId: null, message: `Unhandled promise rejection in an extension: ${reason instanceof Error && reason.stack ? reason.stack : String(reason)}` }); +}); +process.on('uncaughtException', (error) => { + host.log({ level: 'error', extensionId: null, message: `Uncaught exception in an extension: ${error.stack ?? error.message}` }); +}); diff --git a/apps/ide/src/extensionHost/inert.ts b/apps/ide/src/extensionHost/inert.ts new file mode 100644 index 000000000..d538047d7 --- /dev/null +++ b/apps/ide/src/extensionHost/inert.ts @@ -0,0 +1,82 @@ +import { Disposable } from './types.ts'; + +/** + * Unimplemented VS Code API (#259, ADR 0002): instead of crashing an + * extension on `undefined is not a function`, the host hands back values that + * absorb every use, and reports the first use of each name so the + * *Extensions* output channel says what an extension missed. + */ + +const NOOP_EVENT = (): Disposable => new Disposable(() => undefined); + +/** + * A value that can be called, read and disposed at any depth: calling it or + * reading a property gives another one. `then` stays undefined so an `await` + * on it resolves at once instead of hanging. + */ +export function inert(): unknown { + const target = function inertValue(): unknown { + return inert(); + }; + return new Proxy(target, { + get(_target, property) { + if (property === 'then' || typeof property === 'symbol') { + return property === Symbol.toPrimitive ? () => '' : undefined; + } + if (property === 'dispose') { + return () => undefined; + } + if (property === 'toString' || property === 'toJSON') { + return () => ''; + } + if (property.startsWith('onDid') || property.startsWith('onWill')) { + return NOOP_EVENT; + } + return inert(); + }, + apply() { + return inert(); + }, + set() { + return true; + }, + }); +} + +/** What an unknown member of a namespace stands in with, by the shape its name implies. */ +export function stubFor(name: string): unknown { + if (/^on[A-Z]/.test(name)) { + return NOOP_EVENT; + } + if (/^(register|create|add)[A-Z]/.test(name)) { + return () => inert(); + } + if (/^(get|find|fetch|show|open|select|execute|request|resolve)[A-Z]?/.test(name)) { + return () => Promise.resolve(undefined); + } + return undefined; +} + +/** + * Wraps a namespace (`window`, `workspace`, ...) so a member the host does + * not implement is reported once (per name) and replaced by `stubFor(name)`. + */ +export function withFallback(namespace: string, implemented: T, report: (api: string) => void): T { + return new Proxy(implemented, { + get(target, property, receiver) { + if (typeof property === 'symbol' || property in target) { + return Reflect.get(target, property, receiver) as unknown; + } + if (property === 'then') { + return undefined; + } + report(`${namespace}.${property}`); + return stubFor(property); + }, + }); +} + +/** A whole namespace the host does not implement yet (`tests`, `chat`, ...): every member is a stub. */ +export function missingNamespace(namespace: string, report: (api: string) => void, known: Readonly> = {}): unknown { + return withFallback(namespace, { ...known }, report); +} diff --git a/apps/ide/src/extensionHost/memento.ts b/apps/ide/src/extensionHost/memento.ts new file mode 100644 index 000000000..abc4e5b6a --- /dev/null +++ b/apps/ide/src/extensionHost/memento.ts @@ -0,0 +1,83 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +/** + * `ExtensionContext.globalState` / `workspaceState` (#259): a key-value store + * per extension, kept in a JSON file in the extension's storage folder and + * written a moment after the last change (and on shutdown). + */ +export class FileMemento { + private readonly file: string | null; + private values: Record; + private timer: ReturnType | null = null; + private syncKeys: readonly string[] = []; + + /** `file` null keeps the values in memory only (no folder open, for the workspace state). */ + constructor(file: string | null) { + this.file = file; + this.values = {}; + if (file) { + try { + const parsed: unknown = JSON.parse(fs.readFileSync(file, 'utf8')); + if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) { + this.values = parsed as Record; + } + } catch { + // First use, or a damaged file: start empty. + } + } + } + + keys(): readonly string[] { + return Object.keys(this.values); + } + + get(key: string, defaultValue?: T): T | undefined { + const value = this.values[key]; + return value === undefined ? defaultValue : structuredClone(value) as T; + } + + update(key: string, value: unknown): Promise { + if (value === undefined) { + delete this.values[key]; + } else { + this.values[key] = structuredClone(value); + } + this.schedule(); + return Promise.resolve(); + } + + /** Settings Sync does not exist here; kept so extensions can call it. */ + setKeysForSync(keys: readonly string[]): void { + this.syncKeys = [...keys]; + } + + get keysForSync(): readonly string[] { + return this.syncKeys; + } + + private schedule(): void { + if (!this.file || this.timer) { + return; + } + this.timer = setTimeout(() => this.flush(), 200); + } + + flush(): void { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + if (!this.file) { + return; + } + try { + fs.mkdirSync(path.dirname(this.file), { recursive: true }); + const temp = `${this.file}.${process.pid}.tmp`; + fs.writeFileSync(temp, JSON.stringify(this.values)); + fs.renameSync(temp, this.file); + } catch (error) { + console.error(`Could not save the extension state to ${this.file}:`, error); + } + } +} diff --git a/apps/ide/src/extensionHost/textDocument.ts b/apps/ide/src/extensionHost/textDocument.ts new file mode 100644 index 000000000..d663de298 --- /dev/null +++ b/apps/ide/src/extensionHost/textDocument.ts @@ -0,0 +1,182 @@ +import type { Uri } from './types.ts'; +import { EndOfLine, Position, Range } from './types.ts'; + +/** + * `vscode.TextDocument` (#259, #260): the text of a file as extensions read + * it, with VS Code's line, offset and word helpers. The host keeps one per + * open document and applies the editor's changes to it (#260); documents an + * extension opens itself are read from disk. + */ + +const DEFAULT_WORD = /(-?\d*\.\d\w*)|([^`~!@#$%^&*()\-=+[{\]}\\|;:'",.<>/?\s]+)/g; + +export interface TextLine { + readonly lineNumber: number; + readonly text: string; + readonly range: Range; + readonly rangeIncludingLineBreak: Range; + readonly firstNonWhitespaceCharacterIndex: number; + readonly isEmptyOrWhitespace: boolean; +} + +export class TextDocumentModel { + readonly uri: Uri; + languageId: string; + version: number; + isDirty = false; + isClosed = false; + private text = ''; + private lineStarts: number[] = [0]; + private eolValue: EndOfLine = EndOfLine.LF; + private readonly saveImpl: (document: TextDocumentModel) => Promise; + + constructor(uri: Uri, languageId: string, version: number, text: string, save: (document: TextDocumentModel) => Promise = () => Promise.resolve(false)) { + this.uri = uri; + this.languageId = languageId; + this.version = version; + this.saveImpl = save; + this.setText(text); + } + + get fileName(): string { + return this.uri.fsPath; + } + get isUntitled(): boolean { + return this.uri.scheme === 'untitled'; + } + get eol(): EndOfLine { + return this.eolValue; + } + get lineCount(): number { + return this.lineStarts.length; + } + get encoding(): string { + return 'utf8'; + } + + setText(text: string): void { + this.text = text; + this.lineStarts = [0]; + for (let index = 0; index < text.length; index++) { + const char = text.charCodeAt(index); + if (char === 13 /* \r */) { + if (text.charCodeAt(index + 1) === 10) { + index++; + } + this.lineStarts.push(index + 1); + } else if (char === 10 /* \n */) { + this.lineStarts.push(index + 1); + } + } + this.eolValue = text.includes('\r\n') ? EndOfLine.CRLF : EndOfLine.LF; + } + + /** Replaces `range` with `text` (an edit of the editor, #260). */ + applyChange(range: Range, text: string): void { + const start = this.offsetAt(range.start); + const end = this.offsetAt(range.end); + this.setText(this.text.slice(0, start) + text + this.text.slice(end)); + } + + save(): Promise { + return this.saveImpl(this); + } + + private lineText(line: number): string { + const start = this.lineStarts[line] ?? this.text.length; + const next = this.lineStarts[line + 1]; + const raw = next === undefined ? this.text.slice(start) : this.text.slice(start, next); + return raw.replace(/\r?\n$|\r$/, ''); + } + + lineAt(lineOrPosition: number | Position): TextLine { + const line = typeof lineOrPosition === 'number' ? lineOrPosition : lineOrPosition.line; + if (line < 0 || line >= this.lineCount || !Number.isInteger(line)) { + throw new Error('Illegal value for `line`'); + } + const text = this.lineText(line); + const firstNonWhitespace = text.search(/\S/); + const nextStart = line + 1 < this.lineCount ? new Position(line + 1, 0) : new Position(line, text.length); + return { + lineNumber: line, + text, + range: new Range(line, 0, line, text.length), + rangeIncludingLineBreak: new Range(new Position(line, 0), nextStart), + firstNonWhitespaceCharacterIndex: firstNonWhitespace === -1 ? text.length : firstNonWhitespace, + isEmptyOrWhitespace: firstNonWhitespace === -1, + }; + } + + offsetAt(position: Position): number { + const valid = this.validatePosition(position); + return (this.lineStarts[valid.line] ?? 0) + valid.character; + } + + positionAt(offset: number): Position { + const clamped = Math.max(0, Math.min(Math.floor(offset), this.text.length)); + let low = 0; + let high = this.lineStarts.length - 1; + while (low < high) { + const middle = Math.ceil((low + high) / 2); + if ((this.lineStarts[middle] ?? 0) <= clamped) { + low = middle; + } else { + high = middle - 1; + } + } + const character = Math.min(clamped - (this.lineStarts[low] ?? 0), this.lineText(low).length); + return new Position(low, character); + } + + getText(range?: Range): string { + if (!range) { + return this.text; + } + const valid = this.validateRange(range); + return this.text.slice(this.offsetAt(valid.start), this.offsetAt(valid.end)); + } + + validatePosition(position: Position): Position { + if (this.lineCount === 0) { + return new Position(0, 0); + } + if (position.line < 0) { + return new Position(0, 0); + } + if (position.line >= this.lineCount) { + const last = this.lineCount - 1; + return new Position(last, this.lineText(last).length); + } + const length = this.lineText(position.line).length; + return position.character > length ? new Position(position.line, length) : position.character < 0 ? new Position(position.line, 0) : position; + } + + validateRange(range: Range): Range { + const start = this.validatePosition(range.start); + const end = this.validatePosition(range.end); + return start === range.start && end === range.end ? range : new Range(start, end); + } + + getWordRangeAtPosition(position: Position, regex?: RegExp): Range | undefined { + const valid = this.validatePosition(position); + const text = this.lineText(valid.line); + const pattern = new RegExp((regex ?? DEFAULT_WORD).source, (regex?.flags ?? 'g').includes('g') ? regex?.flags ?? 'g' : `${regex?.flags ?? ''}g`); + for (const match of text.matchAll(pattern)) { + const start = match.index; + const end = start + match[0].length; + if (match[0].length > 0 && start <= valid.character && valid.character <= end) { + return new Range(valid.line, start, valid.line, end); + } + } + return undefined; + } +} + +/** Language ids by file extension, for documents the editor has not opened (the extensions' own languages are added on top). */ +export const BUILTIN_LANGUAGES: Readonly> = { + '.ts': 'typescript', '.mts': 'typescript', '.cts': 'typescript', '.tsx': 'typescriptreact', '.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'javascriptreact', + '.json': 'json', '.jsonc': 'jsonc', '.md': 'markdown', '.py': 'python', '.html': 'html', '.htm': 'html', '.css': 'css', '.scss': 'scss', '.less': 'less', '.xml': 'xml', + '.yml': 'yaml', '.yaml': 'yaml', '.java': 'java', '.c': 'c', '.h': 'c', '.cpp': 'cpp', '.cc': 'cpp', '.hpp': 'cpp', '.cs': 'csharp', '.go': 'go', '.rs': 'rust', '.rb': 'ruby', + '.php': 'php', '.sh': 'shellscript', '.bash': 'shellscript', '.ps1': 'powershell', '.sql': 'sql', '.swift': 'swift', '.kt': 'kotlin', '.lua': 'lua', '.r': 'r', '.dart': 'dart', + '.vue': 'vue', '.txt': 'plaintext', '.ini': 'ini', '.toml': 'toml', '.dockerfile': 'dockerfile', +}; diff --git a/apps/ide/src/extensionHost/types.ts b/apps/ide/src/extensionHost/types.ts new file mode 100644 index 000000000..28002880d --- /dev/null +++ b/apps/ide/src/extensionHost/types.ts @@ -0,0 +1,1121 @@ +import { URI, Utils } from 'vscode-uri'; + +/** + * The classes and enums of the `vscode` module (#259), as plain values that + * behave like VS Code's own: extensions construct them, compare them with + * `instanceof` and read their fields. Enum values are VS Code's numbers, + * since extensions sometimes store or compare them as numbers. + */ + +/* ------------------------------ enums ------------------------------ */ + +type EnumKeys = Exclude; + +/** + * A TypeScript-style numeric enum without the `enum` syntax (the build only + * strips types): the names map to VS Code's numbers and the numbers back to + * the names, as `DiagnosticSeverity[0] === 'Error'`. + */ +function numericEnum>>(values: T): T & { readonly [value: number]: string } { + const result: Record = { ...values }; + for (const [name, value] of Object.entries(values)) { + result[value] = name; + } + return Object.freeze(result) as T & { readonly [value: number]: string }; +} + +/* --------------------------------- Uri --------------------------------- */ + +type UriWithJoin = typeof URI & { joinPath(base: URI, ...segments: string[]): URI }; +const uri = URI as UriWithJoin; +if (typeof uri.joinPath !== 'function') { + uri.joinPath = (base: URI, ...segments: string[]) => Utils.joinPath(base, ...segments); +} +/** `vscode.Uri`: vscode-uri's URI, the same class VS Code itself uses, plus `Uri.joinPath`. */ +export const Uri = uri; +export type Uri = URI; + +/* ------------------------------ Disposable ------------------------------ */ + +export class Disposable { + static from(...disposables: { dispose(): unknown }[]): Disposable { + return new Disposable(() => { + for (const disposable of disposables) { + try { + disposable?.dispose(); + } catch { + // Keep disposing the others. + } + } + }); + } + + private callOnDispose: (() => unknown) | undefined; + + constructor(callOnDispose: () => unknown) { + this.callOnDispose = callOnDispose; + } + + dispose(): unknown { + const callback = this.callOnDispose; + this.callOnDispose = undefined; + return callback?.(); + } +} + +/* ------------------------------ Events ------------------------------ */ + +export type Event = (listener: (e: T) => unknown, thisArgs?: unknown, disposables?: { dispose(): unknown }[]) => Disposable; + +export class EventEmitter { + private listeners: { fn: (e: T) => unknown; thisArgs: unknown }[] = []; + private disposed = false; + private eventFn: Event | undefined; + + get event(): Event { + this.eventFn ??= (listener, thisArgs, disposables) => { + if (this.disposed) { + return new Disposable(() => undefined); + } + const entry = { fn: listener, thisArgs }; + this.listeners.push(entry); + const result = new Disposable(() => { + this.listeners = this.listeners.filter((other) => other !== entry); + }); + disposables?.push(result); + return result; + }; + return this.eventFn; + } + + fire(data: T): void { + for (const { fn, thisArgs } of [...this.listeners]) { + try { + fn.call(thisArgs, data); + } catch (error) { + // One listener's error never stops the others, as in VS Code. + console.error(error); + } + } + } + + dispose(): void { + this.disposed = true; + this.listeners = []; + } +} + +/* --------------------------- Cancellation --------------------------- */ + +export interface CancellationToken { + readonly isCancellationRequested: boolean; + readonly onCancellationRequested: Event; +} + +const NONE_EVENT: Event = () => new Disposable(() => undefined); + +export const CancellationTokenNone: CancellationToken = Object.freeze({ isCancellationRequested: false, onCancellationRequested: NONE_EVENT }); + +export class CancellationTokenSource { + private emitter: EventEmitter | undefined; + private cancelled = false; + private tokenValue: CancellationToken | undefined; + + get token(): CancellationToken { + if (!this.tokenValue) { + const source = this; + this.tokenValue = { + get isCancellationRequested() { + return source.cancelled; + }, + get onCancellationRequested() { + source.emitter ??= new EventEmitter(); + return source.emitter.event; + }, + }; + } + return this.tokenValue; + } + + cancel(): void { + if (!this.cancelled) { + this.cancelled = true; + this.emitter?.fire(undefined); + } + } + + dispose(cancel = false): void { + if (cancel) { + this.cancel(); + } + this.emitter?.dispose(); + } +} + +export class CancellationError extends Error { + constructor() { + super('Canceled'); + this.name = 'Canceled'; + } +} + +/* ------------------------------ Positions ------------------------------ */ + +function checkNumber(value: unknown, name: string): number { + if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) { + throw new Error(`Illegal argument: ${name} must be a non-negative number`); + } + return value; +} + +export class Position { + readonly line: number; + readonly character: number; + + static isPosition(other: unknown): other is Position { + return other instanceof Position || (typeof other === 'object' && other !== null && typeof (other as Position).line === 'number' && typeof (other as Position).character === 'number'); + } + + constructor(line: number, character: number) { + this.line = checkNumber(line, 'line'); + this.character = checkNumber(character, 'character'); + } + + isBefore(other: Position): boolean { + return this.line < other.line || (this.line === other.line && this.character < other.character); + } + isBeforeOrEqual(other: Position): boolean { + return this.isBefore(other) || this.isEqual(other); + } + isAfter(other: Position): boolean { + return !this.isBeforeOrEqual(other); + } + isAfterOrEqual(other: Position): boolean { + return !this.isBefore(other); + } + isEqual(other: Position): boolean { + return this.line === other.line && this.character === other.character; + } + compareTo(other: Position): number { + return this.isBefore(other) ? -1 : this.isEqual(other) ? 0 : 1; + } + translate(lineDeltaOrChange?: number | { lineDelta?: number; characterDelta?: number }, characterDelta = 0): Position { + const change = typeof lineDeltaOrChange === 'object' ? lineDeltaOrChange : { lineDelta: lineDeltaOrChange ?? 0, characterDelta }; + return new Position(this.line + (change.lineDelta ?? 0), this.character + (change.characterDelta ?? 0)); + } + with(lineOrChange?: number | { line?: number; character?: number }, character?: number): Position { + const change = typeof lineOrChange === 'object' ? lineOrChange : { line: lineOrChange ?? this.line, character: character ?? this.character }; + return new Position(change.line ?? this.line, change.character ?? this.character); + } + toJSON(): { line: number; character: number } { + return { line: this.line, character: this.character }; + } +} + +export class Range { + readonly start: Position; + readonly end: Position; + + static isRange(other: unknown): other is Range { + return other instanceof Range || (typeof other === 'object' && other !== null && Position.isPosition((other as Range).start) && Position.isPosition((other as Range).end)); + } + + constructor(startOrLine: Position | number, endOrCharacter: Position | number, endLine?: number, endCharacter?: number) { + let start: Position; + let end: Position; + if (typeof startOrLine === 'number' && typeof endOrCharacter === 'number') { + start = new Position(startOrLine, endOrCharacter); + end = new Position(endLine ?? 0, endCharacter ?? 0); + } else if (startOrLine instanceof Position && endOrCharacter instanceof Position) { + start = startOrLine; + end = endOrCharacter; + } else if (Position.isPosition(startOrLine) && Position.isPosition(endOrCharacter)) { + start = new Position(startOrLine.line, startOrLine.character); + end = new Position(endOrCharacter.line, endOrCharacter.character); + } else { + throw new Error('Illegal arguments for Range'); + } + [this.start, this.end] = start.isBefore(end) || start.isEqual(end) ? [start, end] : [end, start]; + } + + get isEmpty(): boolean { + return this.start.isEqual(this.end); + } + get isSingleLine(): boolean { + return this.start.line === this.end.line; + } + contains(positionOrRange: Position | Range): boolean { + if (positionOrRange instanceof Range) { + return this.contains(positionOrRange.start) && this.contains(positionOrRange.end); + } + return positionOrRange.isAfterOrEqual(this.start) && positionOrRange.isBeforeOrEqual(this.end); + } + isEqual(other: Range): boolean { + return this.start.isEqual(other.start) && this.end.isEqual(other.end); + } + intersection(other: Range): Range | undefined { + const start = other.start.isAfter(this.start) ? other.start : this.start; + const end = other.end.isBefore(this.end) ? other.end : this.end; + return start.isAfter(end) ? undefined : new Range(start, end); + } + union(other: Range): Range { + return new Range(other.start.isBefore(this.start) ? other.start : this.start, other.end.isAfter(this.end) ? other.end : this.end); + } + with(startOrChange?: Position | { start?: Position; end?: Position }, end?: Position): Range { + const change = startOrChange instanceof Position || startOrChange === undefined ? { start: startOrChange ?? this.start, end: end ?? this.end } : startOrChange; + return new Range(change.start ?? this.start, change.end ?? this.end); + } + toJSON(): [Position, Position] { + return [this.start, this.end]; + } +} + +export class Selection extends Range { + readonly anchor: Position; + readonly active: Position; + + constructor(anchorOrLine: Position | number, activeOrCharacter: Position | number, activeLine?: number, activeCharacter?: number) { + const anchor = typeof anchorOrLine === 'number' ? new Position(anchorOrLine, activeOrCharacter as number) : anchorOrLine; + const active = typeof anchorOrLine === 'number' ? new Position(activeLine ?? 0, activeCharacter ?? 0) : activeOrCharacter as Position; + super(anchor, active); + this.anchor = anchor; + this.active = active; + } + + get isReversed(): boolean { + return this.anchor === this.end && !this.isEmpty; + } +} + +export class Location { + uri: Uri; + range: Range; + + constructor(uriValue: Uri, rangeOrPosition: Range | Position) { + this.uri = uriValue; + this.range = rangeOrPosition instanceof Position ? new Range(rangeOrPosition, rangeOrPosition) : rangeOrPosition; + } +} + +/* ------------------------------ Text edits ------------------------------ */ + +export const EndOfLine = numericEnum({ LF: 1, CRLF: 2 } as const); +export type EndOfLine = (typeof EndOfLine)[EnumKeys]; + +export class TextEdit { + static replace(range: Range, newText: string): TextEdit { + return new TextEdit(range, newText); + } + static insert(position: Position, newText: string): TextEdit { + return new TextEdit(new Range(position, position), newText); + } + static delete(range: Range): TextEdit { + return new TextEdit(range, ''); + } + static setEndOfLine(eol: EndOfLine): TextEdit { + const edit = new TextEdit(new Range(0, 0, 0, 0), ''); + edit.newEol = eol; + return edit; + } + + range: Range; + newText: string; + newEol?: EndOfLine; + + constructor(range: Range, newText: string) { + this.range = range; + this.newText = newText; + } +} + +export class SnippetString { + value: string; + + constructor(value = '') { + this.value = value; + } + + private static escape(text: string): string { + return text.replace(/[$}\\]/g, '\\$&'); + } + + private tabstop = 1; + + appendText(text: string): SnippetString { + this.value += SnippetString.escape(text); + return this; + } + appendTabstop(number = this.tabstop++): SnippetString { + this.value += `$${number}`; + return this; + } + appendPlaceholder(value: string | ((snippet: SnippetString) => unknown), number = this.tabstop++): SnippetString { + if (typeof value === 'function') { + const nested = new SnippetString(); + nested.tabstop = this.tabstop; + value(nested); + this.tabstop = nested.tabstop; + this.value += `\${${number}:${nested.value}}`; + } else { + this.value += `\${${number}:${SnippetString.escape(value)}}`; + } + return this; + } + appendChoice(values: readonly string[], number = this.tabstop++): SnippetString { + this.value += `\${${number}|${values.map((value) => value.replace(/[|,\\]/g, '\\$&')).join(',')}|}`; + return this; + } + appendVariable(name: string, defaultValue: string | ((snippet: SnippetString) => unknown)): SnippetString { + if (typeof defaultValue === 'function') { + const nested = new SnippetString(); + nested.tabstop = this.tabstop; + defaultValue(nested); + this.tabstop = nested.tabstop; + this.value += `\${${name}:${nested.value}}`; + } else { + this.value += `\${${name}:${SnippetString.escape(defaultValue)}}`; + } + return this; + } +} + +export class SnippetTextEdit { + static replace(range: Range, snippet: SnippetString): SnippetTextEdit { + return new SnippetTextEdit(range, snippet); + } + static insert(position: Position, snippet: SnippetString): SnippetTextEdit { + return new SnippetTextEdit(new Range(position, position), snippet); + } + range: Range; + snippet: SnippetString; + constructor(range: Range, snippet: SnippetString) { + this.range = range; + this.snippet = snippet; + } +} + +export interface WorkspaceEditEntry { + readonly kind: 'edit' | 'create' | 'delete' | 'rename'; + readonly uri: Uri; + readonly edit?: TextEdit; + readonly newUri?: Uri; + readonly options?: Readonly>; +} + +export class WorkspaceEdit { + private readonly items: WorkspaceEditEntry[] = []; + + get size(): number { + return new Set(this.items.map((entry) => entry.uri.toString())).size; + } + replace(target: Uri, range: Range, newText: string): void { + this.items.push({ kind: 'edit', uri: target, edit: new TextEdit(range, newText) }); + } + insert(target: Uri, position: Position, newText: string): void { + this.replace(target, new Range(position, position), newText); + } + delete(target: Uri, range: Range): void { + this.replace(target, range, ''); + } + has(target: Uri): boolean { + return this.items.some((entry) => entry.uri.toString() === target.toString()); + } + set(target: Uri, edits: readonly (TextEdit | SnippetTextEdit | [TextEdit, unknown])[] | null | undefined): void { + for (let index = this.items.length - 1; index >= 0; index--) { + const entry = this.items[index]; + if (entry?.kind === 'edit' && entry.uri.toString() === target.toString()) { + this.items.splice(index, 1); + } + } + for (const item of edits ?? []) { + const edit = Array.isArray(item) ? item[0] : item; + this.items.push({ kind: 'edit', uri: target, edit: edit instanceof SnippetTextEdit ? new TextEdit(edit.range, edit.snippet.value) : edit }); + } + } + get(target: Uri): TextEdit[] { + return this.items.filter((entry) => entry.kind === 'edit' && entry.uri.toString() === target.toString()).map((entry) => entry.edit as TextEdit); + } + createFile(target: Uri, options?: Record): void { + this.items.push({ kind: 'create', uri: target, ...(options ? { options } : {}) }); + } + deleteFile(target: Uri, options?: Record): void { + this.items.push({ kind: 'delete', uri: target, ...(options ? { options } : {}) }); + } + renameFile(oldUri: Uri, newUri: Uri, options?: Record): void { + this.items.push({ kind: 'rename', uri: oldUri, newUri, ...(options ? { options } : {}) }); + } + /** Every operation in order, for applying the edit (not VS Code API). */ + operations(): readonly WorkspaceEditEntry[] { + return this.items; + } + entries(): [Uri, TextEdit[]][] { + const map = new Map(); + for (const entry of this.items) { + if (entry.kind === 'edit' && entry.edit) { + const key = entry.uri.toString(); + const bucket = map.get(key) ?? [entry.uri, []]; + bucket[1].push(entry.edit); + map.set(key, bucket); + } + } + return [...map.values()]; + } +} + +/* ------------------------------ Markdown, icons ------------------------------ */ + +export class MarkdownString { + value: string; + isTrusted?: boolean | { enabledCommands: readonly string[] }; + supportThemeIcons?: boolean; + supportHtml?: boolean; + baseUri?: Uri; + + constructor(value = '', supportThemeIcons = false) { + this.value = value; + this.supportThemeIcons = supportThemeIcons; + } + appendText(value: string): MarkdownString { + this.value += value.replace(/[\\`*_{}[\]()#+\-.!<>|]/g, '\\$&').replace(/\n/g, '\n\n'); + return this; + } + appendMarkdown(value: string): MarkdownString { + this.value += value; + return this; + } + appendCodeblock(value: string, language = ''): MarkdownString { + this.value += `\n\`\`\`${language}\n${value}\n\`\`\`\n`; + return this; + } +} + +export class ThemeColor { + readonly id: string; + constructor(id: string) { + this.id = id; + } +} + +export class ThemeIcon { + static readonly File = new ThemeIcon('file'); + static readonly Folder = new ThemeIcon('folder'); + readonly id: string; + readonly color?: ThemeColor; + constructor(id: string, color?: ThemeColor) { + this.id = id; + if (color) { + this.color = color; + } + } +} + +/* ------------------------------ Diagnostics ------------------------------ */ + +export const DiagnosticSeverity = numericEnum({ Error: 0, Warning: 1, Information: 2, Hint: 3 } as const); +export type DiagnosticSeverity = (typeof DiagnosticSeverity)[EnumKeys]; +export const DiagnosticTag = numericEnum({ Unnecessary: 1, Deprecated: 2 } as const); +export type DiagnosticTag = (typeof DiagnosticTag)[EnumKeys]; + +export class DiagnosticRelatedInformation { + location: Location; + message: string; + constructor(location: Location, message: string) { + this.location = location; + this.message = message; + } +} + +export class Diagnostic { + range: Range; + message: string; + severity: DiagnosticSeverity; + source?: string; + code?: string | number | { value: string | number; target: Uri }; + relatedInformation?: DiagnosticRelatedInformation[]; + tags?: DiagnosticTag[]; + constructor(range: Range, message: string, severity: DiagnosticSeverity = DiagnosticSeverity.Error) { + this.range = range; + this.message = message; + this.severity = severity; + } +} + +/* ------------------------------ Language features ------------------------------ */ + +export const CompletionItemKind = numericEnum({ Text: 0, Method: 1, Function: 2, Constructor: 3, Field: 4, Variable: 5, Class: 6, Interface: 7, Module: 8, Property: 9, Unit: 10, Value: 11, Enum: 12, Keyword: 13, Snippet: 14, Color: 15, File: 16, Reference: 17, Folder: 18, EnumMember: 19, Constant: 20, Struct: 21, Event: 22, Operator: 23, TypeParameter: 24, User: 25, Issue: 26 } as const); +export type CompletionItemKind = (typeof CompletionItemKind)[EnumKeys]; +export const CompletionItemTag = numericEnum({ Deprecated: 1 } as const); +export type CompletionItemTag = (typeof CompletionItemTag)[EnumKeys]; +export const CompletionTriggerKind = numericEnum({ Invoke: 0, TriggerCharacter: 1, TriggerForIncompleteCompletions: 2 } as const); +export type CompletionTriggerKind = (typeof CompletionTriggerKind)[EnumKeys]; + +export class CompletionItem { + label: string | { label: string; detail?: string; description?: string }; + kind?: CompletionItemKind; + tags?: CompletionItemTag[]; + detail?: string; + documentation?: string | MarkdownString; + sortText?: string; + filterText?: string; + preselect?: boolean; + insertText?: string | SnippetString; + range?: Range | { inserting: Range; replacing: Range }; + commitCharacters?: string[]; + keepWhitespace?: boolean; + additionalTextEdits?: TextEdit[]; + command?: Command; + constructor(label: string | { label: string; detail?: string; description?: string }, kind?: CompletionItemKind) { + this.label = label; + if (kind !== undefined) { + this.kind = kind; + } + } +} + +export class CompletionList { + isIncomplete?: boolean; + items: CompletionItem[]; + constructor(items: CompletionItem[] = [], isIncomplete = false) { + this.items = items; + this.isIncomplete = isIncomplete; + } +} + +export class Hover { + contents: (MarkdownString | string | { language: string; value: string })[]; + range?: Range; + constructor(contents: MarkdownString | string | { language: string; value: string } | (MarkdownString | string | { language: string; value: string })[], range?: Range) { + this.contents = Array.isArray(contents) ? contents : [contents]; + if (range) { + this.range = range; + } + } +} + +export const SymbolKind = numericEnum({ File: 0, Module: 1, Namespace: 2, Package: 3, Class: 4, Method: 5, Property: 6, Field: 7, Constructor: 8, Enum: 9, Interface: 10, Function: 11, Variable: 12, Constant: 13, String: 14, Number: 15, Boolean: 16, Array: 17, Object: 18, Key: 19, Null: 20, EnumMember: 21, Struct: 22, Event: 23, Operator: 24, TypeParameter: 25 } as const); +export type SymbolKind = (typeof SymbolKind)[EnumKeys]; +export const SymbolTag = numericEnum({ Deprecated: 1 } as const); +export type SymbolTag = (typeof SymbolTag)[EnumKeys]; + +export class SymbolInformation { + name: string; + containerName: string; + kind: SymbolKind; + location: Location; + tags?: SymbolTag[]; + constructor(name: string, kind: SymbolKind, rangeOrContainer: Range | string, locationOrUri?: Location | Uri, containerName?: string) { + this.name = name; + this.kind = kind; + if (typeof rangeOrContainer === 'string') { + this.containerName = rangeOrContainer; + this.location = locationOrUri as Location; + } else { + this.containerName = containerName ?? ''; + this.location = new Location(locationOrUri as Uri, rangeOrContainer); + } + } +} + +export class DocumentSymbol { + name: string; + detail: string; + kind: SymbolKind; + range: Range; + selectionRange: Range; + children: DocumentSymbol[] = []; + tags?: SymbolTag[]; + constructor(name: string, detail: string, kind: SymbolKind, range: Range, selectionRange: Range) { + this.name = name; + this.detail = detail; + this.kind = kind; + this.range = range; + this.selectionRange = selectionRange; + } +} + +export class CodeActionKind { + static readonly Empty = new CodeActionKind(''); + static readonly QuickFix = new CodeActionKind('quickfix'); + static readonly Refactor = new CodeActionKind('refactor'); + static readonly RefactorExtract = new CodeActionKind('refactor.extract'); + static readonly RefactorInline = new CodeActionKind('refactor.inline'); + static readonly RefactorMove = new CodeActionKind('refactor.move'); + static readonly RefactorRewrite = new CodeActionKind('refactor.rewrite'); + static readonly Source = new CodeActionKind('source'); + static readonly SourceOrganizeImports = new CodeActionKind('source.organizeImports'); + static readonly SourceFixAll = new CodeActionKind('source.fixAll'); + static readonly Notebook = new CodeActionKind('notebook'); + readonly value: string; + constructor(value: string) { + this.value = value; + } + append(parts: string): CodeActionKind { + return new CodeActionKind(this.value ? `${this.value}.${parts}` : parts); + } + intersects(other: CodeActionKind): boolean { + return this.contains(other) || other.contains(this); + } + contains(other: CodeActionKind): boolean { + return this.value === '' || other.value === this.value || other.value.startsWith(`${this.value}.`); + } +} + +export const CodeActionTriggerKind = numericEnum({ Invoke: 1, Automatic: 2 } as const); +export type CodeActionTriggerKind = (typeof CodeActionTriggerKind)[EnumKeys]; + +export class CodeAction { + title: string; + kind?: CodeActionKind; + edit?: WorkspaceEdit; + diagnostics?: Diagnostic[]; + command?: Command; + isPreferred?: boolean; + disabled?: { reason: string }; + constructor(title: string, kind?: CodeActionKind) { + this.title = title; + if (kind) { + this.kind = kind; + } + } +} + +export class CodeLens { + range: Range; + command?: Command; + constructor(range: Range, command?: Command) { + this.range = range; + if (command) { + this.command = command; + } + } + get isResolved(): boolean { + return !!this.command; + } +} + +export const DocumentHighlightKind = numericEnum({ Text: 0, Read: 1, Write: 2 } as const); +export type DocumentHighlightKind = (typeof DocumentHighlightKind)[EnumKeys]; +export class DocumentHighlight { + range: Range; + kind: DocumentHighlightKind; + constructor(range: Range, kind = DocumentHighlightKind.Text) { + this.range = range; + this.kind = kind; + } +} + +export class FoldingRange { + start: number; + end: number; + kind?: FoldingRangeKind; + constructor(start: number, end: number, kind?: FoldingRangeKind) { + this.start = start; + this.end = end; + if (kind !== undefined) { + this.kind = kind; + } + } +} +export const FoldingRangeKind = numericEnum({ Comment: 1, Imports: 2, Region: 3 } as const); +export type FoldingRangeKind = (typeof FoldingRangeKind)[EnumKeys]; + +export class SignatureHelp { + signatures: SignatureInformation[] = []; + activeSignature = 0; + activeParameter = 0; +} +export class SignatureInformation { + label: string; + documentation?: string | MarkdownString; + parameters: ParameterInformation[] = []; + activeParameter?: number; + constructor(label: string, documentation?: string | MarkdownString) { + this.label = label; + if (documentation !== undefined) { + this.documentation = documentation; + } + } +} +export class ParameterInformation { + label: string | [number, number]; + documentation?: string | MarkdownString; + constructor(label: string | [number, number], documentation?: string | MarkdownString) { + this.label = label; + if (documentation !== undefined) { + this.documentation = documentation; + } + } +} +export const SignatureHelpTriggerKind = numericEnum({ Invoke: 1, TriggerCharacter: 2, ContentChange: 3 } as const); +export type SignatureHelpTriggerKind = (typeof SignatureHelpTriggerKind)[EnumKeys]; + +export class DocumentLink { + range: Range; + target?: Uri; + tooltip?: string; + constructor(range: Range, target?: Uri) { + this.range = range; + if (target) { + this.target = target; + } + } +} + +export class Color { + readonly red: number; + readonly green: number; + readonly blue: number; + readonly alpha: number; + constructor(red: number, green: number, blue: number, alpha: number) { + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = alpha; + } +} +export class ColorInformation { + range: Range; + color: Color; + constructor(range: Range, color: Color) { + this.range = range; + this.color = color; + } +} +export class ColorPresentation { + label: string; + textEdit?: TextEdit; + additionalTextEdits?: TextEdit[]; + constructor(label: string) { + this.label = label; + } +} + +export class InlayHint { + position: Position; + label: string; + kind?: InlayHintKind; + tooltip?: string | MarkdownString; + paddingLeft?: boolean; + paddingRight?: boolean; + constructor(position: Position, label: string, kind?: InlayHintKind) { + this.position = position; + this.label = label; + if (kind !== undefined) { + this.kind = kind; + } + } +} +export const InlayHintKind = numericEnum({ Type: 1, Parameter: 2 } as const); +export type InlayHintKind = (typeof InlayHintKind)[EnumKeys]; + +export class SelectionRange { + range: Range; + parent?: SelectionRange; + constructor(range: Range, parent?: SelectionRange) { + this.range = range; + if (parent) { + this.parent = parent; + } + } +} + +export class SemanticTokensLegend { + readonly tokenTypes: string[]; + readonly tokenModifiers: string[]; + constructor(tokenTypes: string[], tokenModifiers: string[] = []) { + this.tokenTypes = tokenTypes; + this.tokenModifiers = tokenModifiers; + } +} +export class SemanticTokens { + readonly resultId?: string; + readonly data: Uint32Array; + constructor(data: Uint32Array, resultId?: string) { + this.data = data; + if (resultId !== undefined) { + this.resultId = resultId; + } + } +} +export class SemanticTokensBuilder { + private readonly data: number[] = []; + private prevLine = 0; + private prevChar = 0; + private readonly legend: SemanticTokensLegend | undefined; + constructor(legend?: SemanticTokensLegend) { + this.legend = legend; + } + push(lineOrRange: number | Range, charOrType: number | string, lengthOrModifiers?: number | readonly string[], tokenType?: number, tokenModifiers = 0): void { + if (typeof lineOrRange === 'number') { + this.pushEncoded(lineOrRange, charOrType as number, lengthOrModifiers as number, tokenType ?? 0, tokenModifiers); + return; + } + const typeIndex = this.legend?.tokenTypes.indexOf(charOrType as string) ?? -1; + let modifiers = 0; + for (const modifier of (lengthOrModifiers as readonly string[] | undefined) ?? []) { + const index = this.legend?.tokenModifiers.indexOf(modifier) ?? -1; + if (index >= 0) { + modifiers |= 1 << index; + } + } + if (typeIndex >= 0) { + this.pushEncoded(lineOrRange.start.line, lineOrRange.start.character, lineOrRange.end.character - lineOrRange.start.character, typeIndex, modifiers); + } + } + private pushEncoded(line: number, char: number, length: number, tokenType: number, modifiers: number): void { + const deltaLine = line - this.prevLine; + const deltaChar = deltaLine === 0 ? char - this.prevChar : char; + this.data.push(deltaLine, deltaChar, length, tokenType, modifiers); + this.prevLine = line; + this.prevChar = char; + } + build(resultId?: string): SemanticTokens { + return new SemanticTokens(new Uint32Array(this.data), resultId); + } +} + +/* ------------------------------ Commands, UI ------------------------------ */ + +export interface Command { + title: string; + command: string; + tooltip?: string; + arguments?: unknown[]; +} + +export const StatusBarAlignment = numericEnum({ Left: 1, Right: 2 } as const); +export type StatusBarAlignment = (typeof StatusBarAlignment)[EnumKeys]; +export const ViewColumn = numericEnum({ Active: -1, Beside: -2, One: 1, Two: 2, Three: 3, Four: 4, Five: 5, Six: 6, Seven: 7, Eight: 8, Nine: 9 } as const); +export type ViewColumn = (typeof ViewColumn)[EnumKeys]; +export const ProgressLocation = numericEnum({ SourceControl: 1, Window: 10, Notification: 15 } as const); +export type ProgressLocation = (typeof ProgressLocation)[EnumKeys]; +export const QuickPickItemKind = numericEnum({ Separator: -1, Default: 0 } as const); +export type QuickPickItemKind = (typeof QuickPickItemKind)[EnumKeys]; +export const InputBoxValidationSeverity = numericEnum({ Info: 1, Warning: 2, Error: 3 } as const); +export type InputBoxValidationSeverity = (typeof InputBoxValidationSeverity)[EnumKeys]; +export const TextEditorRevealType = numericEnum({ Default: 0, InCenter: 1, InCenterIfOutsideViewport: 2, AtTop: 3 } as const); +export type TextEditorRevealType = (typeof TextEditorRevealType)[EnumKeys]; +export const TextEditorCursorStyle = numericEnum({ Line: 1, Block: 2, Underline: 3, LineThin: 4, BlockOutline: 5, UnderlineThin: 6 } as const); +export type TextEditorCursorStyle = (typeof TextEditorCursorStyle)[EnumKeys]; +export const TextEditorLineNumbersStyle = numericEnum({ Off: 0, On: 1, Relative: 2, Interval: 3 } as const); +export type TextEditorLineNumbersStyle = (typeof TextEditorLineNumbersStyle)[EnumKeys]; +export const TextEditorSelectionChangeKind = numericEnum({ Keyboard: 1, Mouse: 2, Command: 3 } as const); +export type TextEditorSelectionChangeKind = (typeof TextEditorSelectionChangeKind)[EnumKeys]; +export const DecorationRangeBehavior = numericEnum({ OpenOpen: 0, ClosedClosed: 1, OpenClosed: 2, ClosedOpen: 3 } as const); +export type DecorationRangeBehavior = (typeof DecorationRangeBehavior)[EnumKeys]; +export const OverviewRulerLane = numericEnum({ Left: 1, Center: 2, Right: 4, Full: 7 } as const); +export type OverviewRulerLane = (typeof OverviewRulerLane)[EnumKeys]; +export const ColorThemeKind = numericEnum({ Light: 1, Dark: 2, HighContrast: 3, HighContrastLight: 4 } as const); +export type ColorThemeKind = (typeof ColorThemeKind)[EnumKeys]; +export const TreeItemCollapsibleState = numericEnum({ None: 0, Collapsed: 1, Expanded: 2 } as const); +export type TreeItemCollapsibleState = (typeof TreeItemCollapsibleState)[EnumKeys]; +export const TreeItemCheckboxState = numericEnum({ Unchecked: 0, Checked: 1 } as const); +export type TreeItemCheckboxState = (typeof TreeItemCheckboxState)[EnumKeys]; + +export class TreeItem { + label?: string | { label: string; highlights?: [number, number][] }; + id?: string; + iconPath?: string | Uri | ThemeIcon | { light: string | Uri; dark: string | Uri }; + description?: string | boolean; + resourceUri?: Uri; + tooltip?: string | MarkdownString; + command?: Command; + collapsibleState?: TreeItemCollapsibleState; + contextValue?: string; + checkboxState?: TreeItemCheckboxState; + constructor(labelOrUri: string | { label: string } | Uri, collapsibleState: TreeItemCollapsibleState = TreeItemCollapsibleState.None) { + if (labelOrUri instanceof URI) { + this.resourceUri = labelOrUri; + } else { + this.label = labelOrUri; + } + this.collapsibleState = collapsibleState; + } +} + +export class StatementCoverage {} + +/* ------------------------------ Workspace, configuration ------------------------------ */ + +export const ConfigurationTarget = numericEnum({ Global: 1, Workspace: 2, WorkspaceFolder: 3 } as const); +export type ConfigurationTarget = (typeof ConfigurationTarget)[EnumKeys]; +export const FileType = numericEnum({ Unknown: 0, File: 1, Directory: 2, SymbolicLink: 64 } as const); +export type FileType = (typeof FileType)[EnumKeys]; +export const FilePermission = numericEnum({ Readonly: 1 } as const); +export type FilePermission = (typeof FilePermission)[EnumKeys]; +export const FileChangeType = numericEnum({ Changed: 1, Created: 2, Deleted: 3 } as const); +export type FileChangeType = (typeof FileChangeType)[EnumKeys]; +export const TextDocumentSaveReason = numericEnum({ Manual: 1, AfterDelay: 2, FocusOut: 3 } as const); +export type TextDocumentSaveReason = (typeof TextDocumentSaveReason)[EnumKeys]; +export const TextDocumentChangeReason = numericEnum({ Undo: 1, Redo: 2 } as const); +export type TextDocumentChangeReason = (typeof TextDocumentChangeReason)[EnumKeys]; + +export class FileSystemError extends Error { + static FileNotFound(messageOrUri?: string | Uri): FileSystemError { + return new FileSystemError(messageOrUri, 'FileNotFound'); + } + static FileExists(messageOrUri?: string | Uri): FileSystemError { + return new FileSystemError(messageOrUri, 'FileExists'); + } + static FileNotADirectory(messageOrUri?: string | Uri): FileSystemError { + return new FileSystemError(messageOrUri, 'FileNotADirectory'); + } + static FileIsADirectory(messageOrUri?: string | Uri): FileSystemError { + return new FileSystemError(messageOrUri, 'FileIsADirectory'); + } + static NoPermissions(messageOrUri?: string | Uri): FileSystemError { + return new FileSystemError(messageOrUri, 'NoPermissions'); + } + static Unavailable(messageOrUri?: string | Uri): FileSystemError { + return new FileSystemError(messageOrUri, 'Unavailable'); + } + readonly code: string; + constructor(messageOrUri?: string | Uri, code = 'Unknown') { + super(typeof messageOrUri === 'string' ? messageOrUri : messageOrUri ? `${code}: ${messageOrUri.toString()}` : code); + this.code = code; + this.name = `${code} (FileSystemError)`; + } +} + +export class RelativePattern { + baseUri: Uri; + base: string; + pattern: string; + constructor(base: string | Uri | { uri: Uri }, pattern: string) { + this.baseUri = typeof base === 'string' ? Uri.file(base) : base instanceof URI ? base : base.uri; + this.base = this.baseUri.fsPath; + this.pattern = pattern; + } +} + +/* ------------------------------ Extensions, env ------------------------------ */ + +export const ExtensionMode = numericEnum({ Production: 1, Development: 2, Test: 3 } as const); +export type ExtensionMode = (typeof ExtensionMode)[EnumKeys]; +export const ExtensionKind = numericEnum({ UI: 1, Workspace: 2 } as const); +export type ExtensionKind = (typeof ExtensionKind)[EnumKeys]; +export const UIKind = numericEnum({ Desktop: 1, Web: 2 } as const); +export type UIKind = (typeof UIKind)[EnumKeys]; +export const LogLevel = numericEnum({ Off: 0, Trace: 1, Debug: 2, Info: 3, Warning: 4, Error: 5 } as const); +export type LogLevel = (typeof LogLevel)[EnumKeys]; +export const EnvironmentVariableMutatorType = numericEnum({ Replace: 1, Append: 2, Prepend: 3 } as const); +export type EnvironmentVariableMutatorType = (typeof EnvironmentVariableMutatorType)[EnumKeys]; + +/* ------------------------------ Terminals, tasks, debug (shapes only) ------------------------------ */ + +export const TerminalLocation = numericEnum({ Panel: 1, Editor: 2 } as const); +export type TerminalLocation = (typeof TerminalLocation)[EnumKeys]; +export const TerminalExitReason = numericEnum({ Unknown: 0, Shutdown: 1, Process: 2, User: 3, Extension: 4 } as const); +export type TerminalExitReason = (typeof TerminalExitReason)[EnumKeys]; +export const TaskScope = numericEnum({ Global: 1, Workspace: 2 } as const); +export type TaskScope = (typeof TaskScope)[EnumKeys]; +export const TaskRevealKind = numericEnum({ Always: 1, Silent: 2, Never: 3 } as const); +export type TaskRevealKind = (typeof TaskRevealKind)[EnumKeys]; +export const TaskPanelKind = numericEnum({ Shared: 1, Dedicated: 2, New: 3 } as const); +export type TaskPanelKind = (typeof TaskPanelKind)[EnumKeys]; + +export class TaskGroup { + static readonly Clean = new TaskGroup('clean', 'Clean'); + static readonly Build = new TaskGroup('build', 'Build'); + static readonly Rebuild = new TaskGroup('rebuild', 'Rebuild'); + static readonly Test = new TaskGroup('test', 'Test'); + readonly id: string; + readonly label: string; + isDefault?: boolean; + constructor(id: string, label: string) { + this.id = id; + this.label = label; + } +} + +export class ShellExecution { + commandLine?: string; + command?: string; + args?: string[]; + options?: Record; + constructor(commandOrLine: string, argsOrOptions?: string[] | Record, options?: Record) { + if (Array.isArray(argsOrOptions)) { + this.command = commandOrLine; + this.args = argsOrOptions; + if (options) { + this.options = options; + } + } else { + this.commandLine = commandOrLine; + if (argsOrOptions) { + this.options = argsOrOptions; + } + } + } +} + +export class ProcessExecution { + process: string; + args: string[]; + options?: Record; + constructor(process: string, argsOrOptions?: string[] | Record, options?: Record) { + this.process = process; + this.args = Array.isArray(argsOrOptions) ? argsOrOptions : []; + const resolved = Array.isArray(argsOrOptions) ? options : argsOrOptions; + if (resolved) { + this.options = resolved; + } + } +} + +export class Task { + definition: Record; + scope: unknown; + name: string; + source: string; + execution?: ShellExecution | ProcessExecution; + problemMatchers: string[]; + group?: TaskGroup; + isBackground = false; + presentationOptions: Record = {}; + constructor(definition: Record, scope: unknown, name: string, source: string, execution?: ShellExecution | ProcessExecution, problemMatchers: string | string[] = []) { + this.definition = definition; + this.scope = scope; + this.name = name; + this.source = source; + if (execution) { + this.execution = execution; + } + this.problemMatchers = Array.isArray(problemMatchers) ? problemMatchers : [problemMatchers]; + } +} + +export class Breakpoint { + readonly id = `${Math.random()}`; + readonly enabled: boolean; + readonly condition?: string; + constructor(enabled = true, condition?: string) { + this.enabled = enabled; + if (condition !== undefined) { + this.condition = condition; + } + } +} +export class SourceBreakpoint extends Breakpoint { + readonly location: Location; + constructor(location: Location, enabled?: boolean, condition?: string) { + super(enabled, condition); + this.location = location; + } +} + +/* ------------------------------ Notebooks (shapes only) ------------------------------ */ + +export const NotebookCellKind = numericEnum({ Markup: 1, Code: 2 } as const); +export type NotebookCellKind = (typeof NotebookCellKind)[EnumKeys]; + +/* ------------------------------ Language status, misc ------------------------------ */ + +export const LanguageStatusSeverity = numericEnum({ Information: 0, Warning: 1, Error: 2 } as const); +export type LanguageStatusSeverity = (typeof LanguageStatusSeverity)[EnumKeys]; +export const CommentThreadCollapsibleState = numericEnum({ Collapsed: 0, Expanded: 1 } as const); +export type CommentThreadCollapsibleState = (typeof CommentThreadCollapsibleState)[EnumKeys]; +export const IndentAction = numericEnum({ None: 0, Indent: 1, IndentOutdent: 2, Outdent: 3 } as const); +export type IndentAction = (typeof IndentAction)[EnumKeys]; + +export class Comment {} diff --git a/apps/ide/src/extensionHost/wire.ts b/apps/ide/src/extensionHost/wire.ts new file mode 100644 index 000000000..711ef3553 --- /dev/null +++ b/apps/ide/src/extensionHost/wire.ts @@ -0,0 +1,87 @@ +import { Position, Range, Uri } from './types.ts'; + +/** + * Values crossing the process boundary (#259): command arguments and + * results travel as structured clones, so a `Uri`, `Position` or `Range` + * goes as a tagged plain object and comes back as an instance. Functions and + * cycles are dropped rather than failing the whole message. + */ + +interface WireUri { readonly $uri: string } +interface WirePosition { readonly $pos: [number, number] } +interface WireRange { readonly $range: [number, number, number, number] } + +export function toWire(value: unknown, seen = new WeakSet()): unknown { + if (value === null || value === undefined || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value ?? null; + } + if (typeof value === 'bigint') { + return Number(value); + } + if (typeof value === 'function' || typeof value === 'symbol') { + return null; + } + if (value instanceof Uri) { + return { $uri: value.toString() } satisfies WireUri; + } + if (value instanceof Range) { + return { $range: [value.start.line, value.start.character, value.end.line, value.end.character] } satisfies WireRange; + } + if (value instanceof Position) { + return { $pos: [value.line, value.character] } satisfies WirePosition; + } + if (typeof value !== 'object') { + return null; + } + if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof Date || value instanceof RegExp) { + return value; + } + if (seen.has(value)) { + return null; + } + seen.add(value); + let result: unknown; + if (Array.isArray(value)) { + result = value.map((item) => toWire(item, seen)); + } else { + const record: Record = {}; + for (const [key, item] of Object.entries(value)) { + if (typeof item !== 'function') { + record[key] = toWire(item, seen); + } + } + result = record; + } + // Only a cycle (a value inside itself) is dropped; the same object twice is kept. + seen.delete(value); + return result; +} + +export function fromWire(value: unknown): unknown { + if (value === null || typeof value !== 'object') { + return value; + } + if (Array.isArray(value)) { + return value.map(fromWire); + } + if (ArrayBuffer.isView(value) || value instanceof Date || value instanceof RegExp) { + return value; + } + const record = value as Record; + if (typeof record['$uri'] === 'string' && Object.keys(record).length === 1) { + return Uri.parse(record['$uri']); + } + const position = record['$pos']; + if (Array.isArray(position) && position.length === 2 && Object.keys(record).length === 1) { + return new Position(Number(position[0]), Number(position[1])); + } + const range = record['$range']; + if (Array.isArray(range) && range.length === 4 && Object.keys(record).length === 1) { + return new Range(Number(range[0]), Number(range[1]), Number(range[2]), Number(range[3])); + } + const result: Record = {}; + for (const [key, item] of Object.entries(record)) { + result[key] = fromWire(item); + } + return result; +} diff --git a/apps/ide/src/main/extensions/contributions.ts b/apps/ide/src/main/extensions/contributions.ts index bc53b5d2e..c65cd5b04 100644 --- a/apps/ide/src/main/extensions/contributions.ts +++ b/apps/ide/src/main/extensions/contributions.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { EXTENSION_THEME_PREFIX, type ContributedGrammar, type ContributedLanguage, type ContributedSnippet, type ContributedTheme, type ExtensionContributions, type GrammarContent, type ResolvedTheme, type ThemeTokenRule } from '../../shared/extensions.ts'; +import { EXTENSION_THEME_PREFIX, type ContributedGrammar, type ContributedLanguage, type ContributedSnippet, type ContributedCommand, type ContributedTheme, type ExtensionContributions, type GrammarContent, type ResolvedTheme, type ThemeTokenRule } from '../../shared/extensions.ts'; import { readJsonc, resolveInExtension, type LoadedExtension } from './extensionStore.ts'; import { parsePlist, type PlistValue } from './plist.ts'; @@ -73,6 +73,7 @@ export class ContributionIndex { const languages: ContributedLanguage[] = []; const grammars: ContributedGrammar[] = []; const snippets: ContributedSnippet[] = []; + const commands: ContributedCommand[] = []; for (const extension of this.extensions) { const c = extension.manifest.contributes; const extensionId = extension.manifest.id; @@ -144,8 +145,21 @@ export class ContributionIndex { this.onWarning(`${extensionId}: snippets ${String(entry.path)}: ${(error as Error).message}`); } } + // #259: the palette's commands, for the extensions whose code can run them. + if (extension.manifest.main) { + const hidden = new Set(list(record(c.menus)['commandPalette']).filter((entry) => entry.when === 'false' || entry.when === false).map((entry) => str(entry.command))); + for (const command of list(c.commands)) { + const id = str(command.command); + const title = typeof command.title === 'string' ? command.title : str(record(command.title)['value']); + if (!id || !title) { + continue; + } + const category = typeof command.category === 'string' ? command.category : str(record(command.category)['value']); + commands.push({ extensionId, command: id, title, category: category ?? null, hiddenFromPalette: hidden.has(id) }); + } + } } - return { themes, languages, grammars, snippets }; + return { themes, languages, grammars, snippets, commands }; } grammarContent(ref: string): GrammarContent | null { diff --git a/apps/ide/src/main/extensions/extensionHostManager.ts b/apps/ide/src/main/extensions/extensionHostManager.ts new file mode 100644 index 000000000..8cfc2655f --- /dev/null +++ b/apps/ide/src/main/extensions/extensionHostManager.ts @@ -0,0 +1,530 @@ +import { app, BrowserWindow, clipboard, dialog, shell, type IpcMainInvokeEvent, type WebContents } from 'electron'; +import { fork, type ChildProcess } from 'node:child_process'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import readline from 'node:readline'; +import { + activationEventsOf, HOST_METHODS, MAIN_METHODS, RpcEndpoint, + type DialogRequest, type HostActivationEvent, type HostInitData, type HostLogLine, type HostUiEvent, type UiNotification, type UiRequest, +} from '../../shared/extensionHostProtocol.ts'; +import { EXTENSION_IPC_CHANNELS, EXTENSION_IPC_EVENTS, isWorkbenchActivationEvent, type ExtensionActivation, type ExtensionId } from '../../shared/extensions.ts'; +import { KeyVault } from '../agents/keyVault.ts'; +import { electronCipher } from '../agents/electronCipher.ts'; +import { channelLog } from '../log.ts'; +import { serverEnvironment } from '../lsp/lspServers.ts'; +import { isOpenableExternalLink } from '../security.ts'; +import { addTrustChangeListener, isWorkspaceTrusted } from '../trust/workspaceTrust.ts'; +import { addFolderChangeListener, workspaceOrNull } from '../workspace/workspaceWindows.ts'; +import { matchGlob } from '../../extensionHost/glob.ts'; +import { ExtensionSettingsStore } from './extensionSettings.ts'; +import type { ActivationSource, ExtensionsService } from './extensionsService.ts'; +import type { LoadedExtension } from './extensionStore.ts'; + +type Handle = (channel: string, handler: (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown) => void; + +const extLog = channelLog('extensions'); + +/** Restarts after a crash before the host is left stopped (the person can still restart it by hand). */ +const MAX_CRASH_RESTARTS = 3; +const CRASH_WINDOW_MS = 5 * 60_000; +/** How long the extensions get to deactivate when a window closes or the host restarts. */ +const SHUTDOWN_GRACE_MS = 3000; +/** How long `workspaceContains:` may walk the folder before giving up. */ +const WORKSPACE_CONTAINS_BUDGET = 20_000; + +interface HostConnection { + readonly contents: WebContents; + readonly child: ChildProcess; + readonly rpc: RpcEndpoint; + readonly activations: Map; + readonly pendingUi: Map void>; + readonly ready: Promise; + stopping: boolean; +} + +/** + * The extension host of each window (#259, ADR 0002): a Node child process + * running on Electron's own Node (`ELECTRON_RUN_AS_NODE`), started once the + * workbench says it is ready, restarted when the folder, the installed + * extensions or the folder's trust change, and stopped with its window. + * + * It only runs the extensions this window may run (`ExtensionsService.mayRun`: + * enabled, and trusted folder or Restricted Mode support, #263). The host + * asks the main process for what only Electron can do (clipboard, dialogs, + * secrets, settings) and for what the person has to see (forwarded to the + * renderer as `extensionsHostUi`). + */ +export class ExtensionHostManager implements ActivationSource { + private readonly service: ExtensionsService; + private readonly hostScript: string; + private readonly isDevelopment: boolean; + private readonly hosts = new Map(); + /** Windows whose workbench said it is ready: only they get a host (and its UI requests). */ + private readonly readyWindows = new Set(); + private readonly crashes = new Map(); + private readonly settingsStore: ExtensionSettingsStore; + private readonly secrets: KeyVault; + private readonly machineId: string; + private readonly sessionId = crypto.randomUUID(); + private nextUiId = 1; + + constructor(options: { service: ExtensionsService; hostScript: string; isDevelopment: boolean }) { + this.service = options.service; + this.hostScript = options.hostScript; + this.isDevelopment = options.isDevelopment; + const root = this.service.store.root; + this.settingsStore = new ExtensionSettingsStore(path.join(root, 'settings.json')); + this.secrets = new KeyVault(path.join(root, 'secrets.json'), electronCipher()); + this.machineId = readOrCreateMachineId(path.join(root, 'machine-id')); + this.service.setActivationSource(this); + this.service.onDidChange(() => this.restartAll('the installed extensions changed')); + addFolderChangeListener((contents) => { + if (this.readyWindows.has(contents.id)) { + void this.restart(contents, 'the folder changed'); + } + }); + addTrustChangeListener((contents) => { + if (isWorkspaceTrusted(contents)) { + const connection = this.hosts.get(contents.id); + connection?.rpc.notify(HOST_METHODS.trustChanged, true); + // Extensions held back by Restricted Mode can run now. + if (this.runnable(contents).length !== this.runningCount(contents)) { + void this.restart(contents, 'the folder is trusted now'); + } + } else if (this.hosts.has(contents.id)) { + void this.restart(contents, 'the folder is in Restricted Mode now'); + } + }); + } + + /* ------------------------------ ActivationSource ------------------------------ */ + + activation(contents: WebContents, id: ExtensionId): { state: ExtensionActivation; error?: string } { + return this.hosts.get(contents.id)?.activations.get(id) ?? { state: 'inactive' }; + } + + /* ------------------------------ lifecycle ------------------------------ */ + + private runnable(contents: WebContents): LoadedExtension[] { + return this.service.enabled().filter((extension) => extension.manifest.main && this.service.mayRun(contents, extension)); + } + + private runningCount(contents: WebContents): number { + return this.hosts.get(contents.id)?.activations.size ?? 0; + } + + /** Starts the window's host if an extension with code may run and none is running yet. */ + async start(contents: WebContents): Promise { + if (contents.isDestroyed() || this.hosts.has(contents.id) || !this.readyWindows.has(contents.id)) { + return; + } + const runnable = this.runnable(contents); + if (runnable.length === 0) { + return; + } + if (!fs.existsSync(this.hostScript)) { + extLog.error(`The extension host is missing (${this.hostScript}); extensions with code cannot run.`); + return; + } + const folder = workspaceOrNull(contents)?.root ?? null; + const child = fork(this.hostScript, [], { + execPath: process.execPath, + cwd: folder ?? app.getPath('home'), + env: serverEnvironment(process.env, { ELECTRON_RUN_AS_NODE: '1', CODEXR_EXTENSION_HOST: '1' }), + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], + serialization: 'advanced', + ...(this.isDevelopment ? { execArgv: ['--enable-source-maps'] } : {}), + }); + const rpc = new RpcEndpoint((message) => { + if (child.connected) { + child.send(message); + } else { + throw new Error('The extension host is not connected.'); + } + }); + let markReady: () => void = () => undefined; + const connection: HostConnection = { + contents, + child, + rpc, + activations: new Map(runnable.map((extension) => [extension.manifest.id, { state: 'inactive' as const }])), + pendingUi: new Map(), + ready: new Promise((resolve) => { + markReady = resolve; + }), + stopping: false, + }; + this.hosts.set(contents.id, connection); + this.wire(connection); + child.on('message', (message) => rpc.receive(message)); + for (const stream of [child.stdout, child.stderr]) { + if (stream) { + readline.createInterface({ input: stream }).on('line', (line) => extLog.info(`[host] ${line}`)); + } + } + child.on('exit', (code, signal) => this.exited(connection, code, signal)); + child.on('error', (error) => extLog.error(`The extension host could not start: ${error.message}`)); + contents.once('destroyed', () => void this.stop(contents.id)); + + try { + await rpc.request(HOST_METHODS.init, this.initData(contents, runnable, folder)); + markReady(); + this.service.notify(contents); + await rpc.request(HOST_METHODS.activateByEvent, '*'); + await this.fireWorkspaceContains(connection, runnable, folder); + await rpc.request(HOST_METHODS.activateByEvent, 'onStartupFinished'); + } catch (error) { + if (!connection.stopping) { + extLog.error(`The extension host did not start: ${String(error)}`); + } + } + } + + private initData(contents: WebContents, runnable: readonly LoadedExtension[], folder: string | null): HostInitData { + const root = this.service.store.root; + const enabledIds = new Set(runnable.map((extension) => extension.manifest.id)); + return { + extensions: runnable.map((extension) => ({ + id: extension.manifest.id, + location: extension.location, + main: extension.manifest.main as string, + packageJSON: extension.manifest.raw, + activationEvents: activationEventsOf(extension.manifest.activationEvents, extension.manifest.contributes), + extensionDependencies: extension.manifest.extensionDependencies, + })), + passive: this.service.enabled().filter((extension) => !enabledIds.has(extension.manifest.id)).map((extension) => ({ id: extension.manifest.id, location: extension.location, packageJSON: extension.manifest.raw })), + workspaceFolder: folder, + trusted: isWorkspaceTrusted(contents), + configuration: this.settingsStore.values(), + globalStorageRoot: path.join(root, '.storage', 'global'), + workspaceStorageRoot: folder ? path.join(root, '.storage', 'workspace', crypto.createHash('sha256').update(folder).digest('hex').slice(0, 24)) : null, + logRoot: path.join(root, '.logs'), + env: { + appName: 'Code-XR IDE', + appRoot: app.getAppPath(), + appHost: 'desktop', + language: 'en', + machineId: this.machineId, + sessionId: this.sessionId, + uriScheme: 'codexr', + shell: process.platform === 'win32' ? (process.env['COMSPEC'] ?? 'cmd.exe') : (process.env['SHELL'] ?? '/bin/sh'), + version: app.getVersion(), + }, + isDevelopment: this.isDevelopment, + }; + } + + /** `workspaceContains:`: fired once per pattern that matches a file of the folder. */ + private async fireWorkspaceContains(connection: HostConnection, runnable: readonly LoadedExtension[], folder: string | null): Promise { + if (!folder) { + return; + } + const patterns = new Set(); + for (const extension of runnable) { + for (const event of extension.manifest.activationEvents) { + if (event.startsWith('workspaceContains:')) { + patterns.add(event.slice('workspaceContains:'.length)); + } + } + } + if (patterns.size === 0) { + return; + } + const pending = new Set(patterns); + let budget = WORKSPACE_CONTAINS_BUDGET; + const walk = (dir: string): void => { + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + if (pending.size === 0 || --budget <= 0) { + return; + } + if (entry.name === 'node_modules' || entry.name === '.git') { + continue; + } + const full = path.join(dir, entry.name); + const relative = path.relative(folder, full).split(path.sep).join('/'); + for (const pattern of [...pending]) { + if (matchGlob(pattern, relative)) { + pending.delete(pattern); + void connection.rpc.request(HOST_METHODS.activateByEvent, `workspaceContains:${pattern}`).catch(() => undefined); + } + } + if (entry.isDirectory()) { + walk(full); + } + } + }; + walk(folder); + } + + async stop(contentsId: number): Promise { + const connection = this.hosts.get(contentsId); + if (!connection) { + return; + } + connection.stopping = true; + this.hosts.delete(contentsId); + const exited = new Promise((resolve) => { + if (connection.child.exitCode !== null || connection.child.signalCode !== null) { + resolve(); + } else { + connection.child.once('exit', () => resolve()); + } + }); + await Promise.race([connection.rpc.request(HOST_METHODS.shutdown).catch(() => undefined), new Promise((resolve) => setTimeout(resolve, SHUTDOWN_GRACE_MS))]); + await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 500))]); + if (connection.child.exitCode === null && connection.child.signalCode === null) { + connection.child.kill(); + } + connection.rpc.dispose(); + for (const resolve of connection.pendingUi.values()) { + resolve(null); + } + } + + async restart(contents: WebContents, reason: string): Promise { + if (contents.isDestroyed()) { + return; + } + const had = this.hosts.has(contents.id); + await this.stop(contents.id); + if (had) { + extLog.info(`Restarting the extension host: ${reason}.`); + } + this.service.notify(contents); + await this.start(contents); + } + + private restartAll(reason: string): void { + for (const win of BrowserWindow.getAllWindows()) { + if (!win.isDestroyed() && this.readyWindows.has(win.webContents.id)) { + void this.restart(win.webContents, reason); + } + } + } + + private exited(connection: HostConnection, code: number | null, signal: string | null): void { + connection.rpc.dispose(); + for (const resolve of connection.pendingUi.values()) { + resolve(null); + } + if (connection.stopping || this.hosts.get(connection.contents.id) !== connection) { + return; + } + this.hosts.delete(connection.contents.id); + const reason = signal ? `signal ${signal}` : `exit code ${code ?? '?'}`; + extLog.error(`The extension host stopped unexpectedly (${reason}).`); + const contents = connection.contents; + if (contents.isDestroyed()) { + return; + } + const now = Date.now(); + const recent = (this.crashes.get(contents.id) ?? []).filter((time) => now - time < CRASH_WINDOW_MS); + recent.push(now); + this.crashes.set(contents.id, recent); + if (recent.length <= MAX_CRASH_RESTARTS) { + void this.start(contents); + } else { + this.sendUi(contents, { type: 'notify', notification: { kind: 'hostStopped', reason: `The extension host stopped ${recent.length} times in five minutes (${reason}); it was not restarted.` } }); + this.service.notify(contents); + } + } + + /* ------------------------------ host -> main ------------------------------ */ + + private sendUi(contents: WebContents, event: HostUiEvent): void { + if (!contents.isDestroyed()) { + contents.send(EXTENSION_IPC_EVENTS.extensionsHostUi, event); + } + } + + private askRenderer(connection: HostConnection, request: UiRequest): Promise { + const id = this.nextUiId++; + return new Promise((resolve) => { + connection.pendingUi.set(id, resolve); + this.sendUi(connection.contents, { type: 'request', id, request }); + }); + } + + private wire(connection: HostConnection): void { + const { rpc, contents } = connection; + const ownerWindow = (): BrowserWindow | null => BrowserWindow.fromWebContents(contents); + rpc.handle(MAIN_METHODS.log, (line) => { + const { level, extensionId, channel, message } = line as HostLogLine; + const prefix = `${extensionId ? `[${extensionId}]` : '[host]'}${channel ? ` [${channel}]` : ''}`; + const text = `${prefix} ${message}`; + if (level === 'error') { + extLog.error(text); + } else if (level === 'warn') { + extLog.warn(text); + } else { + extLog.info(text); + } + }); + rpc.handle(MAIN_METHODS.notImplemented, (extensionId, api) => { + extLog.warn(`[${String(extensionId)}] uses vscode.${String(api)}, which the Code-XR IDE does not implement yet; that part of the extension will not work.`); + }); + rpc.handle(MAIN_METHODS.activation, (event) => { + const { id, state, error } = event as HostActivationEvent; + connection.activations.set(id, { state, ...(error !== undefined ? { error } : {}) }); + this.service.notify(contents); + }); + rpc.handle(MAIN_METHODS.executeWorkbenchCommand, (id, args) => this.askRenderer(connection, { kind: 'command', id: String(id), args: Array.isArray(args) ? args : [] })); + rpc.handle(MAIN_METHODS.updateConfiguration, async (key, value) => { + if (typeof key !== 'string' || key.length > 300) { + throw new Error('Invalid setting key.'); + } + this.settingsStore.update(key, value === null ? undefined : value); + this.broadcastConfiguration(); + }); + rpc.handle(MAIN_METHODS.secretGet, (extensionId, key) => this.secrets.get(`${String(extensionId)}/${String(key)}`) ?? null); + rpc.handle(MAIN_METHODS.secretStore, async (extensionId, key, value) => { + await this.secrets.set(`${String(extensionId)}/${String(key)}`, String(value)); + }); + rpc.handle(MAIN_METHODS.secretDelete, async (extensionId, key) => { + await this.secrets.delete(`${String(extensionId)}/${String(key)}`); + }); + rpc.handle(MAIN_METHODS.clipboardRead, () => clipboard.readText()); + rpc.handle(MAIN_METHODS.clipboardWrite, (text) => clipboard.writeText(String(text))); + rpc.handle(MAIN_METHODS.openExternal, async (url) => { + if (!isOpenableExternalLink(url)) { + extLog.warn(`An extension asked to open ${String(url)}; only http, https and mailto links open outside the IDE.`); + return false; + } + await shell.openExternal(url); + return true; + }); + rpc.handle(MAIN_METHODS.showDialog, async (raw) => { + const request = raw as DialogRequest; + const win = ownerWindow(); + const filters = Object.entries(request.filters ?? {}).map(([name, extensions]) => ({ name, extensions: [...extensions] })); + if (request.kind === 'save') { + const options = { ...(request.title ? { title: request.title } : {}), ...(request.defaultPath ? { defaultPath: request.defaultPath } : {}), ...(request.openLabel ? { buttonLabel: request.openLabel } : {}), filters }; + const result = win ? await dialog.showSaveDialog(win, options) : await dialog.showSaveDialog(options); + return result.canceled || !result.filePath ? null : [result.filePath]; + } + const properties: ('openFile' | 'openDirectory' | 'multiSelections')[] = []; + if (request.canSelectFiles !== false) { + properties.push('openFile'); + } + if (request.canSelectFolders) { + properties.push('openDirectory'); + } + if (request.canSelectMany) { + properties.push('multiSelections'); + } + const options = { ...(request.title ? { title: request.title } : {}), ...(request.defaultPath ? { defaultPath: request.defaultPath } : {}), ...(request.openLabel ? { buttonLabel: request.openLabel } : {}), filters, properties }; + const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options); + return result.canceled ? null : result.filePaths; + }); + rpc.handle(MAIN_METHODS.ui, async (raw) => { + const request = raw as UiRequest; + if (request.kind === 'message' && request.modal) { + // A modal message is a native dialog, as in VS Code: it must be answered before anything else. + const win = ownerWindow(); + const buttons = [...request.items, 'Cancel']; + const options = { type: request.severity === 'info' ? 'info' as const : request.severity, message: request.message, ...(request.detail ? { detail: request.detail } : {}), buttons, cancelId: buttons.length - 1, defaultId: 0, noLink: true, title: request.extensionId }; + const { response } = win ? await dialog.showMessageBox(win, options) : await dialog.showMessageBox(options); + return response < request.items.length ? response : null; + } + if (request.kind === 'openFile') { + const folder = workspaceOrNull(contents)?.root; + if (!folder || !(request.path === folder || request.path.startsWith(folder + path.sep))) { + extLog.warn(`An extension asked to open ${request.path}, which is outside the folder; the IDE only opens files of the open folder.`); + return null; + } + return this.askRenderer(connection, { ...request, path: path.relative(folder, request.path).split(path.sep).join('/') }); + } + return this.askRenderer(connection, request); + }); + rpc.handle(MAIN_METHODS.uiNotify, (notification) => this.sendUi(contents, { type: 'notify', notification: notification as UiNotification })); + } + + private broadcastConfiguration(): void { + const values = this.settingsStore.values(); + for (const connection of this.hosts.values()) { + connection.rpc.notify(HOST_METHODS.configurationChanged, values); + } + } + + /* ------------------------------ renderer -> main ------------------------------ */ + + register(handle: Handle): void { + handle(EXTENSION_IPC_CHANNELS.extensionsHostReady, (event) => { + const contents = event.sender; + if (!this.readyWindows.has(contents.id)) { + this.readyWindows.add(contents.id); + contents.once('destroyed', () => this.readyWindows.delete(contents.id)); + } + // A reload of the page: the old host answered a renderer that is gone. + return this.hosts.has(contents.id) ? this.restart(contents, 'the window reloaded') : this.start(contents); + }); + handle(EXTENSION_IPC_CHANNELS.extensionsRestartHost, (event) => { + this.crashes.delete(event.sender.id); + return this.restart(event.sender, 'asked from the workbench'); + }); + handle(EXTENSION_IPC_CHANNELS.extensionsExecuteCommand, async (event, id, args) => { + if (typeof id !== 'string' || id.length > 300) { + throw new Error('Invalid command id.'); + } + let connection = this.hosts.get(event.sender.id); + if (!connection) { + await this.start(event.sender); + connection = this.hosts.get(event.sender.id); + } + if (!connection) { + throw new Error(`command '${id}' not found: no extension that may run in this folder provides it.`); + } + await connection.ready; + return connection.rpc.request(HOST_METHODS.executeCommand, id, Array.isArray(args) ? args : []); + }); + handle(EXTENSION_IPC_CHANNELS.extensionsActivateByEvent, async (event, activationEvent) => { + if (!isWorkbenchActivationEvent(activationEvent)) { + throw new Error('Invalid activation event.'); + } + const connection = this.hosts.get(event.sender.id); + if (connection) { + await connection.ready; + await connection.rpc.request(HOST_METHODS.activateByEvent, activationEvent); + } + }); + handle(EXTENSION_IPC_CHANNELS.extensionsHostReply, (event, id, result) => { + const connection = this.hosts.get(event.sender.id); + const resolve = typeof id === 'number' ? connection?.pendingUi.get(id) : undefined; + if (connection && resolve && typeof id === 'number') { + connection.pendingUi.delete(id); + resolve(result ?? null); + } + }); + } + + /** Stops every host (the app is quitting). */ + async stopAll(): Promise { + await Promise.all([...this.hosts.keys()].map((id) => this.stop(id))); + } +} + +function readOrCreateMachineId(file: string): string { + // A random id per installation, never derived from the hardware: extensions get a stable id, not a fingerprint. + try { + const existing = fs.readFileSync(file, 'utf8').trim(); + if (/^[0-9a-f]{64}$/.test(existing)) { + return existing; + } + } catch { + // First run. + } + const id = crypto.randomBytes(32).toString('hex'); + try { + fs.writeFileSync(file, id); + } catch { + // Read-only folder: a new id each run. + } + return id; +} diff --git a/apps/ide/src/main/extensions/extensionSettings.ts b/apps/ide/src/main/extensions/extensionSettings.ts new file mode 100644 index 000000000..b529ca59b --- /dev/null +++ b/apps/ide/src/main/extensions/extensionSettings.ts @@ -0,0 +1,55 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { readJsonc } from './extensionStore.ts'; + +/** + * The extensions' own settings (#259): what `getConfiguration().update()` + * writes and what the host reads back, by full key. They live in + * `/settings.json`, apart from the IDE's settings, whose schema + * only knows the IDE's keys and plain values; an extension's settings can + * be any JSON. The file accepts comments, so the person can edit it by hand. + */ +export class ExtensionSettingsStore { + private readonly file: string; + private data: Record = {}; + private loadedMtime = -1; + + constructor(file: string) { + this.file = file; + this.load(); + } + + private load(): void { + try { + const stat = fs.statSync(this.file); + if (stat.mtimeMs === this.loadedMtime) { + return; + } + const parsed = readJsonc(this.file); + this.data = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record : {}; + this.loadedMtime = stat.mtimeMs; + } catch { + this.data = {}; + } + } + + /** The values, re-read when the file changed on disk. */ + values(): Record { + this.load(); + return structuredClone(this.data); + } + + update(key: string, value: unknown): void { + this.load(); + if (value === undefined) { + delete this.data[key]; + } else { + this.data[key] = structuredClone(value); + } + fs.mkdirSync(path.dirname(this.file), { recursive: true }); + const temp = `${this.file}.${process.pid}.tmp`; + fs.writeFileSync(temp, `${JSON.stringify(this.data, null, 4)}\n`); + fs.renameSync(temp, this.file); + this.loadedMtime = fs.statSync(this.file).mtimeMs; + } +} diff --git a/apps/ide/src/main/extensions/extensionsService.ts b/apps/ide/src/main/extensions/extensionsService.ts index 554317dcd..386254804 100644 --- a/apps/ide/src/main/extensions/extensionsService.ts +++ b/apps/ide/src/main/extensions/extensionsService.ts @@ -98,6 +98,13 @@ export class ExtensionsService { return new ContributionIndex(this.enabled(), (message) => extLog.warn(message)); } + /** #259: the extension host's IPC handlers, registered with the service's own. */ + private hostHandlers: ((handle: Handle) => void) | null = null; + + attachHost(register: (handle: Handle) => void): void { + this.hostHandlers = register; + } + setActivationSource(source: ActivationSource): void { this.activations = source; } @@ -326,6 +333,7 @@ export class ExtensionsService { } register(handle: Handle): void { + this.hostHandlers?.(handle); handle(EXTENSION_IPC_CHANNELS.extensionsList, (event) => this.list(event.sender)); handle(EXTENSION_IPC_CHANNELS.extensionsSearch, async (_event, query) => { const q = (typeof query === 'object' && query !== null ? query : {}) as Partial; diff --git a/apps/ide/src/main/index.ts b/apps/ide/src/main/index.ts index b9d74558a..22c7077a4 100644 --- a/apps/ide/src/main/index.ts +++ b/apps/ide/src/main/index.ts @@ -1,8 +1,10 @@ import { app, BrowserWindow, nativeTheme } from 'electron'; +import fs from 'node:fs'; import path from 'node:path'; import { applyProcessHardening } from './hardening.ts'; import { registerAppSchemeAsPrivileged, serveRenderer } from './appProtocol.ts'; import { registerIpcHandlers } from './ipc.ts'; +import { ExtensionHostManager } from './extensions/extensionHostManager.ts'; import { ExtensionsService } from './extensions/extensionsService.ts'; import { fileStorage, memoryStorage, SettingsService } from './settings/settingsService.ts'; import { KeybindingsService } from './settings/keybindingsService.ts'; @@ -37,6 +39,12 @@ const OUT_DIR = path.resolve(__dirname, '..'); const PRELOAD_PATH = path.join(OUT_DIR, 'preload', 'index.cjs'); /** #16: the scene view's own preload (only `CodeXRHostBridge.openInEditor`). */ const SCENE_PRELOAD_PATH = path.join(OUT_DIR, 'scenePreload', 'index.cjs'); +/** + * #259: the extension host, a Node child process per window. Installers + * unpack it from the asar archive (electron-builder.config.cjs) so it runs + * from a real file, like the TypeScript language server. + */ +const EXTENSION_HOST_PATH = unpackedPath(path.join(OUT_DIR, 'extensionHost', 'index.cjs')); const RENDERER_DIR = path.join(OUT_DIR, 'renderer'); // The dev server is honoured only from an unpackaged build, so an installed @@ -130,6 +138,10 @@ async function start(): Promise { settings, disableExtensions: process.argv.includes('--disable-extensions'), }); + // #259: the extensions' code runs in a host process per window, never here or in the renderer. + const extensionHosts = new ExtensionHostManager({ service: extensions, hostScript: EXTENSION_HOST_PATH, isDevelopment }); + extensions.attachHost((handle) => extensionHosts.register(handle)); + app.on('will-quit', () => void extensionHosts.stopAll()); registerIpcHandlers(origins, isDevelopment, core, terminalHost, settings, keybindings, output, agentServices, lsp, extensions); // #171: the stored theme, before the first window paints. applyColorTheme((await settings.snapshot(null)).effective[COLOR_THEME_SETTING]); @@ -204,3 +216,9 @@ async function installDependencies(core: CoreServices): Promise { await core.python.ensureReady().catch((error: unknown) => log.error('Could not set up the Python environment.', error)); await core.cloudflared.ensureInstalled(); } + +/** The `app.asar.unpacked` copy of a file of the archive, when there is one. */ +function unpackedPath(file: string): string { + const unpacked = file.replace(`app.asar${path.sep}`, `app.asar.unpacked${path.sep}`); + return unpacked !== file && fs.existsSync(unpacked) ? unpacked : file; +} diff --git a/apps/ide/src/preload/index.ts b/apps/ide/src/preload/index.ts index d2b811b49..8b8d47a94 100644 --- a/apps/ide/src/preload/index.ts +++ b/apps/ide/src/preload/index.ts @@ -7,6 +7,7 @@ import { IDE_COMMANDS, IPC_CHANNELS, IPC_EVENTS, type AutoStartMode, type FileAn import { GIT_IPC_CHANNELS, GIT_IPC_EVENTS } from '../shared/git.ts'; import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentChatEvent, type AgentProfileInput, type ApprovalDecision, type EditReviewResult, type ChatAttachment, type McpServerInput, type ModelPrice, type BudgetSettings, type ProviderInput } from '../shared/agents.ts'; import { TASK_IPC_CHANNELS, TASK_IPC_EVENTS, type TaskFinished } from '../shared/tasks.ts'; +import type { HostUiEvent } from '../shared/extensionHostProtocol.ts'; import { EXTENSION_IPC_CHANNELS, EXTENSION_IPC_EVENTS, type ExtensionsChangedEvent, type ExtensionLogEvent, type GalleryQuery } from '../shared/extensions.ts'; import { DEBUG_IPC_CHANNELS, DEBUG_IPC_EVENTS, type DebugEvent, type DebugStepKind } from '../shared/debug.ts'; import { LSP_IPC_CHANNELS, LSP_IPC_EVENTS, type LspDiagnosticsEvent, type LspLanguage, type LspRequestMethod } from '../shared/lsp.ts'; @@ -131,6 +132,13 @@ const api: CodeXRApi = Object.freeze({ grammarContent: (ref: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsGrammarContent, ref), onDidChange: (listener: (event: ExtensionsChangedEvent) => void) => subscribe(EXTENSION_IPC_EVENTS.extensionsChanged, listener), onLog: (listener: (event: ExtensionLogEvent) => void) => subscribe(EXTENSION_IPC_EVENTS.extensionsLog, listener), + // #259: the extension host of this window. + hostReady: () => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsHostReady), + restartHost: () => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsRestartHost), + executeCommand: (id: string, args?: readonly unknown[]) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsExecuteCommand, id, args ? [...args] : []), + activateByEvent: (event: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsActivateByEvent, event), + hostReply: (id: number, result: unknown) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsHostReply, id, result), + onHostUi: (listener: (event: HostUiEvent) => void) => subscribe(EXTENSION_IPC_EVENTS.extensionsHostUi, listener), }), app: Object.freeze({ getInfo: () => ipcRenderer.invoke(IPC_CHANNELS.appGetInfo), diff --git a/apps/ide/src/renderer/commands/commandRegistry.ts b/apps/ide/src/renderer/commands/commandRegistry.ts index 91fb6ec17..ad888eb23 100644 --- a/apps/ide/src/renderer/commands/commandRegistry.ts +++ b/apps/ide/src/renderer/commands/commandRegistry.ts @@ -37,6 +37,12 @@ export interface CommandDefinition { readonly secondaryKeybindings?: readonly string[]; /** False for commands that should not appear under "recently used" (the palette itself). */ readonly recordRecent?: boolean; + /** + * #259: a command an extension contributes. Its id is the extension's + * (VS Code allows any non-empty id, `_` prefixes and all), so the + * `area.action` rule does not apply; ids still never repeat. + */ + readonly source?: 'extension'; /** Hidden from the palette and not runnable while false. */ readonly enabled?: () => boolean; run(): void | Promise; @@ -98,7 +104,7 @@ export function createCommandRegistry(onError: (id: string, error: unknown) => v return { register(command) { - if (!ID_PATTERN.test(command.id)) { + if (command.source === 'extension' ? !/^\S{1,300}$/.test(command.id) : !ID_PATTERN.test(command.id)) { throw new Error(`Invalid command ID "${command.id}": use area.action.`); } if (commands.has(command.id)) { diff --git a/apps/ide/src/renderer/commands/quickInput.ts b/apps/ide/src/renderer/commands/quickInput.ts index 5b6236c9c..8bea17c6d 100644 --- a/apps/ide/src/renderer/commands/quickInput.ts +++ b/apps/ide/src/renderer/commands/quickInput.ts @@ -18,6 +18,10 @@ export interface QuickInputProvider { accept(action: PaletteAction): void; /** The field's accessible name and placeholder. */ readonly label?: string; + /** #259: a placeholder other than the label (an extension's `placeHolder`). */ + readonly placeholder?: string; + /** #259: the text is a secret (an extension's `password: true`): the field masks it. */ + readonly password?: boolean; /** The entry to start on when the box opens (#171: the theme in use), instead of the first. */ readonly initialId?: string; /** The highlighted entry changed (#171: the theme picker previews it). */ @@ -210,7 +214,8 @@ export function createQuickInput(host: HTMLElement, options: QuickInputOptions): pendingInitialId = provider.initialId; const label = provider.label ?? defaultLabel; input.setAttribute('aria-label', label); - input.placeholder = provider.label ?? ''; + input.placeholder = provider.placeholder ?? provider.label ?? ''; + input.type = provider.password ? 'password' : 'text'; if (layer.hidden) { const focused = document.activeElement; returnFocus = focused instanceof HTMLElement && focused !== document.body ? focused : null; diff --git a/apps/ide/src/renderer/extensions/contributionsController.ts b/apps/ide/src/renderer/extensions/contributionsController.ts index f6b6b984e..657b6cb19 100644 --- a/apps/ide/src/renderer/extensions/contributionsController.ts +++ b/apps/ide/src/renderer/extensions/contributionsController.ts @@ -21,7 +21,7 @@ export interface ContributionsController { previewTheme(themeId: string | null): Promise; } -const EMPTY: ExtensionContributions = { themes: [], languages: [], grammars: [], snippets: [] }; +const EMPTY: ExtensionContributions = { themes: [], languages: [], grammars: [], snippets: [], commands: [] }; export function createContributionsController(api: ExtensionsApi, onError: (message: string) => void): ContributionsController { let contributions = EMPTY; diff --git a/apps/ide/src/renderer/extensions/extensionsWiring.ts b/apps/ide/src/renderer/extensions/extensionsWiring.ts index 616be5033..840fb627f 100644 --- a/apps/ide/src/renderer/extensions/extensionsWiring.ts +++ b/apps/ide/src/renderer/extensions/extensionsWiring.ts @@ -1,8 +1,11 @@ import type { CodeXRApi } from '../../shared/api.ts'; import type { ContributedTheme, InstalledExtension } from '../../shared/extensions.ts'; import type { CommandRegistry } from '../commands/commandRegistry.ts'; +import type { QuickInputProvider } from '../commands/quickInput.ts'; +import type { NotificationCenter } from '../notifications.ts'; import { createContributionsController, type ContributionsController } from './contributionsController.ts'; import { createExtensionsView, type ExtensionsView } from './extensionsView.ts'; +import { createHostBridge } from './hostBridge.ts'; import './extensions.css'; /** @@ -16,6 +19,8 @@ export interface ExtensionsWorkbench { readonly contributions: ContributionsController; /** The colour themes of the enabled extensions, for the theme picker. */ themes(): readonly ContributedTheme[]; + /** #259: Monaco is loaded: fire `onLanguage:` for every model's language from now on. */ + watchEditorLanguages(): void; } export interface ExtensionsWorkbenchDeps { @@ -28,6 +33,13 @@ export interface ExtensionsWorkbenchDeps { notify(kind: 'info' | 'warning' | 'error', message: string): void; /** Opens the colour theme picker (after installing a theme). */ selectColorTheme(): void; + /** #259: what the extension host shows through the workbench. */ + readonly notifications: NotificationCenter; + readonly statusLeft: HTMLElement; + readonly statusRight: HTMLElement; + openQuickInput(value: string, provider: QuickInputProvider): void; + /** Opens a file of the folder (relative path), at a 1-based line and column when given. */ + openFile(path: string, line?: number, column?: number): Promise; } export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWorkbench { @@ -57,16 +69,49 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork }, }); + // #259: the extension host's requests, status bar items and the palette's commands. + const bridge = createHostBridge({ + extensions: api.extensions, + registry: deps.registry, + notifications: deps.notifications, + statusLeft: deps.statusLeft, + statusRight: deps.statusRight, + openQuickInput: deps.openQuickInput, + openFile: deps.openFile, + setStatus: deps.onStatus, + searchExtensions: (query) => { + deps.showView(); + view.focusSearch(query); + }, + }); + let installed: readonly InstalledExtension[] = []; + const refresh = async (): Promise => { + await contributions.reload(); + bridge.setCommands(contributions.current().commands, installed); + }; api.extensions.onDidChange((event) => { + installed = event.installed; view.setInstalled(event.installed); - void contributions.reload(); + void refresh(); }); - void contributions.reload(); + void api.extensions.list().then((list) => { + installed = list; + return refresh(); + }).catch((error: unknown) => deps.notify('error', `Could not list the extensions: ${String(error)}`)); + const firedLanguages = new Set(); + const fireLanguage = (languageId: string): void => { + if (!firedLanguages.has(languageId)) { + firedLanguages.add(languageId); + api.extensions.activateByEvent(`onLanguage:${languageId}`).catch(() => undefined); + } + }; + api.extensions.onDidChange(() => firedLanguages.clear()); const commands = [ { id: 'extensions.showView', category: 'Extensions', title: 'Show Extensions', keybinding: 'CmdOrCtrl+Shift+X', run: () => { deps.showView(); view.focusSearch(); } }, { id: 'extensions.installVsix', category: 'Extensions', title: 'Install from VSIX…', run: () => { deps.showView(); void view.installVsix(); } }, { id: 'extensions.showInstalled', category: 'Extensions', title: 'Show Installed Extensions', run: () => { deps.showView(); view.focusSearch(''); } }, + { id: 'extensions.restartHost', category: 'Developer', title: 'Restart Extension Host', run: () => void api.extensions.restartHost() }, { id: 'extensions.searchThemes', category: 'Extensions', title: 'Browse Colour Themes in Open VSX', run: () => { deps.showView(); view.focusSearch('theme'); } }, { id: 'extensions.disableAll', @@ -83,5 +128,8 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork view, contributions, themes: () => contributions.current().themes, + watchEditorLanguages() { + void import('./monacoContributions.ts').then((part) => part.watchModelLanguages(fireLanguage)); + }, }; } diff --git a/apps/ide/src/renderer/extensions/hostBridge.ts b/apps/ide/src/renderer/extensions/hostBridge.ts new file mode 100644 index 000000000..1591fa973 --- /dev/null +++ b/apps/ide/src/renderer/extensions/hostBridge.ts @@ -0,0 +1,268 @@ +import type { HostUiEvent, StatusBarItemData, UiNotification, UiRequest } from '../../shared/extensionHostProtocol.ts'; +import type { ContributedCommand, ExtensionsApi, InstalledExtension } from '../../shared/extensions.ts'; +import type { CommandRegistry } from '../commands/commandRegistry.ts'; +import { pickListView, type PickItem } from '../commands/paletteModel.ts'; +import type { QuickInputProvider } from '../commands/quickInput.ts'; +import { el } from '../dom.ts'; +import type { NotificationCenter } from '../notifications.ts'; +import { builtinCommandFor, statusText } from './hostBridgeModel.ts'; + +/** + * The workbench's side of the extension host (#259): what an extension asks + * the person (messages with buttons, quick picks, input boxes), its status + * bar items and progress, the commands it contributes to the palette, and the + * workbench commands it runs. Every answer goes back with `hostReply`. + * + * Text from an extension is set with `textContent` only, never as HTML. + */ + +export interface HostBridgeDeps { + readonly extensions: ExtensionsApi; + readonly registry: CommandRegistry; + readonly notifications: NotificationCenter; + readonly statusLeft: HTMLElement; + readonly statusRight: HTMLElement; + openQuickInput(value: string, provider: QuickInputProvider): void; + openFile(path: string, line?: number, column?: number): Promise; + setStatus(message: string): void; + /** Shows the Extensions view with a search (`workbench.extensions.search`). */ + searchExtensions(query: string): void; +} + +export interface HostBridge { + /** The palette's commands of the extensions that may run in this window. */ + setCommands(commands: readonly ContributedCommand[], installed: readonly InstalledExtension[]): void; + /** The `setContext` keys extensions set (for `when` clauses). */ + contextKey(key: string): unknown; + dispose(): void; +} + +/** Resolves a promise once; later calls are ignored. */ +function once(resolve: (value: unknown) => void): (value: unknown) => void { + let done = false; + return (value) => { + if (!done) { + done = true; + resolve(value); + } + }; +} + +export function createHostBridge(deps: HostBridgeDeps): HostBridge { + const { extensions } = deps; + const items = new Map(); + const context = new Map(); + let commandDisposers: (() => void)[] = []; + let statusTimer: ReturnType | undefined; + + const reply = (id: number, result: unknown): void => { + extensions.hostReply(id, result ?? null).catch(() => undefined); + }; + + const runExtensionCommand = (command: string, args: readonly unknown[] = []): void => { + extensions.executeCommand(command, args).catch((error: unknown) => { + deps.notifications.notify('error', `Command '${command}' failed: ${error instanceof Error ? error.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(error)}`); + }); + }; + + /* ------------------------------ requests ------------------------------ */ + + async function answer(request: UiRequest): Promise { + switch (request.kind) { + case 'message': + return new Promise((resolve) => { + let settled = false; + const settle = (value: unknown): void => { + if (!settled) { + settled = true; + resolve(value); + } + }; + deps.notifications.notify(request.severity, request.message, { + detail: request.detail, + actions: request.items.map((label, index) => ({ label, run: () => settle(index) })), + onDismiss: () => settle(null), + }); + if (request.items.length === 0) { + // Nothing to choose: VS Code resolves once it is shown. + settle(null); + } + }); + case 'quickPick': + return new Promise((resolve) => { + const pickItems: PickItem[] = []; + request.items.forEach((item, index) => { + if (!item.separator) { + pickItems.push({ id: String(index), label: item.label, ...(item.description || item.detail ? { description: [item.description, item.detail].filter(Boolean).join(' · ') } : {}) }); + } + }); + const settle = once(resolve); + deps.openQuickInput('', { + label: request.title ?? request.placeHolder ?? 'Select an item', + ...(request.placeHolder ? { placeholder: request.placeHolder } : {}), + view: (value) => pickListView(pickItems, value), + accept: (action) => settle(action.kind === 'pick' ? [Number(action.id)] : null), + // The box closes before `accept` runs: wait a turn so an accepted pick wins. + onClose: () => queueMicrotask(() => settle(null)), + }); + }); + case 'inputBox': + return new Promise((resolve) => { + const settle = once(resolve); + deps.openQuickInput(request.value ?? '', { + label: request.title ?? request.prompt ?? 'Input', + ...(request.placeHolder ? { placeholder: request.placeHolder } : {}), + password: request.password, + view: (value) => ({ + entries: [{ + id: value, + label: request.password ? '' : value === '' ? '' : value, + highlights: [], + description: request.prompt ? `${request.prompt} (Press Enter to confirm or Escape to cancel)` : 'Press Enter to confirm or Escape to cancel', + runnable: true, + }], + action: (entry) => ({ kind: 'pick', id: entry.id }), + empty: '', + }), + accept: (action) => settle(action.kind === 'pick' ? action.id : null), + onClose: () => queueMicrotask(() => settle(null)), + }); + }); + case 'openFile': + await deps.openFile(request.path, request.line, request.column); + return true; + case 'command': + return runWorkbenchCommand(request.id, request.args); + } + } + + async function runWorkbenchCommand(id: string, args: readonly unknown[]): Promise { + const builtin = builtinCommandFor(id, args); + switch (builtin.kind) { + case 'search-extensions': + deps.searchExtensions(builtin.query); + return null; + case 'reload': + window.location.reload(); + return null; + case 'workbench': + if (!deps.registry.execute(builtin.id)) { + throw new Error(`command '${id}' not found`); + } + return null; + case 'unknown': + throw new Error(`command '${id}' not found`); + } + } + + /* ------------------------------ notifications ------------------------------ */ + + function renderItem(data: StatusBarItemData): void { + let entry = items.get(data.key); + if (!entry) { + const element = el('button', { className: 'status-item status-extension-item', attrs: { type: 'button', 'data-extension': data.extensionId } }); + element.addEventListener('click', () => { + const current = items.get(data.key)?.data; + if (current?.command) { + runExtensionCommand(current.command, current.commandArgs ?? []); + } + }); + entry = { data, element }; + items.set(data.key, entry); + } + entry.data = data; + const { element } = entry; + element.textContent = statusText(data.text); + element.title = data.tooltip ?? data.name ?? data.extensionId; + element.hidden = !data.visible || element.textContent === ''; + element.classList.toggle('is-clickable', !!data.command); + const slot = data.alignment === 'right' ? deps.statusRight : deps.statusLeft; + // Higher priority sits further left, as in VS Code. + const ordered = [...items.values()].filter((other) => other.data.alignment === data.alignment).sort((a, b) => b.data.priority - a.data.priority); + slot.replaceChildren(...ordered.map((other) => other.element)); + } + + function handleNotification(notification: UiNotification): void { + switch (notification.kind) { + case 'statusBarItem': + renderItem(notification.item); + return; + case 'statusBarItemDispose': + items.get(notification.key)?.element.remove(); + items.delete(notification.key); + return; + case 'statusMessage': + clearTimeout(statusTimer); + deps.setStatus(statusText(notification.text)); + if (notification.timeoutMs > 0) { + statusTimer = setTimeout(() => deps.setStatus(''), notification.timeoutMs); + } + return; + case 'progress': + deps.notifications.progress(`ext:${notification.key}`, { title: notification.title, message: notification.message, percent: notification.percent }); + return; + case 'progressEnd': + deps.notifications.endProgress(`ext:${notification.key}`); + return; + case 'contextKey': + context.set(notification.key, notification.value); + return; + case 'hostStopped': + deps.notifications.notify('error', notification.reason, { + actions: [{ label: 'Restart Extension Host', run: () => void extensions.restartHost() }], + }); + return; + } + } + + const unsubscribe = extensions.onHostUi((event: HostUiEvent) => { + if (event.type === 'notify') { + handleNotification(event.notification); + return; + } + answer(event.request).then( + (result) => reply(event.id, result), + (error: unknown) => { + deps.notifications.notify('error', String(error instanceof Error ? error.message : error)); + reply(event.id, null); + }, + ); + }); + extensions.hostReady().catch((error: unknown) => deps.notifications.notify('error', `The extension host could not start: ${String(error)}`)); + + return { + setCommands(commands, installed) { + for (const dispose of commandDisposers) { + dispose(); + } + commandDisposers = []; + const runnable = new Set(installed.filter((extension) => extension.state === 'enabled' && extension.hasCode).map((extension) => extension.id)); + for (const command of commands) { + if (command.hiddenFromPalette || !runnable.has(command.extensionId) || deps.registry.get(command.command)) { + continue; + } + commandDisposers.push(deps.registry.register({ + id: command.command, + title: command.title, + ...(command.category ? { category: command.category } : {}), + source: 'extension', + run: () => runExtensionCommand(command.command), + })); + } + // Items of extensions that are gone stay until their host says otherwise; drop them now. + for (const [key, entry] of items) { + if (!runnable.has(entry.data.extensionId)) { + entry.element.remove(); + items.delete(key); + } + } + }, + contextKey: (key) => context.get(key), + dispose() { + unsubscribe(); + for (const dispose of commandDisposers) { + dispose(); + } + }, + }; +} diff --git a/apps/ide/src/renderer/extensions/hostBridgeModel.ts b/apps/ide/src/renderer/extensions/hostBridgeModel.ts new file mode 100644 index 000000000..938be830e --- /dev/null +++ b/apps/ide/src/renderer/extensions/hostBridgeModel.ts @@ -0,0 +1,74 @@ +/** + * Pure parts of the host bridge (#259), unit-tested in Node: which workbench + * action a VS Code command an extension runs maps to, and the status bar text + * of an extension without its `$(icon)` references. + */ + +export type BuiltinCommand = + | { readonly kind: 'workbench'; readonly id: string } + | { readonly kind: 'search-extensions'; readonly query: string } + | { readonly kind: 'reload' } + | { readonly kind: 'unknown' }; + +/** VS Code's command ids that extensions run, and the IDE's command doing the same. */ +export const VSCODE_COMMAND_ALIASES: Readonly> = { + 'workbench.action.showCommands': 'workbench.commandPalette', + 'workbench.action.quickOpen': 'workbench.quickOpen', + 'workbench.action.gotoLine': 'editor.goToLine', + 'workbench.action.gotoSymbol': 'editor.goToSymbol', + 'editor.action.formatDocument': 'editor.formatDocument', + 'workbench.action.files.newUntitledFile': 'file.newFile', + 'workbench.action.files.save': 'file.save', + 'workbench.action.files.saveAll': 'file.saveAll', + 'workbench.action.files.openFolder': 'workspace.openFolder', + 'workbench.action.closeActiveEditor': 'editor.close', + 'workbench.action.closeAllEditors': 'editor.closeAll', + 'workbench.action.closeOtherEditors': 'editor.closeOthers', + 'workbench.action.nextEditor': 'editor.next', + 'workbench.action.previousEditor': 'editor.previous', + 'workbench.action.splitEditor': 'editor.splitRight', + 'workbench.action.splitEditorRight': 'editor.splitRight', + 'workbench.action.openSettings': 'workbench.openSettings', + 'workbench.action.openSettingsJson': 'workbench.openSettings', + 'workbench.action.openGlobalSettings': 'workbench.openSettings', + 'workbench.action.openGlobalKeybindings': 'workbench.openKeybindings', + 'workbench.action.selectTheme': 'workbench.selectTheme', + 'workbench.action.togglePanel': 'view.togglePanel', + 'workbench.action.toggleSidebarVisibility': 'view.toggleSideBar', + 'workbench.action.toggleZenMode': 'view.toggleZenMode', + 'workbench.action.terminal.toggleTerminal': 'terminal.toggle', + 'workbench.action.terminal.new': 'terminal.new', + 'workbench.action.output.toggleOutput': 'workbench.output.show', + 'workbench.actions.view.problems': 'workbench.problems.show', + 'workbench.action.problems.focus': 'workbench.problems.show', + 'workbench.view.explorer': 'view.showExplorer', + 'workbench.view.search': 'search.show', + 'workbench.view.extensions': 'extensions.showView', + 'workbench.action.tasks.runTask': 'workbench.action.tasks.runTask', + 'revealInExplorer': 'file.revealInExplorer', + 'copyFilePath': 'file.copyPath', + 'copyRelativeFilePath': 'file.copyRelativePath', + 'markdown.showPreviewToSide': 'markdown.showPreviewToSide', +}; + +/** + * The workbench's action for command `id` run by an extension with `args` + * (in the host's wire format). `vscode.open` and `setContext` never get here: + * the host handles them, since opening a file goes through the main + * process's folder check. + */ +export function builtinCommandFor(id: string, args: readonly unknown[]): BuiltinCommand { + switch (id) { + case 'workbench.extensions.search': + return { kind: 'search-extensions', query: typeof args[0] === 'string' ? args[0] : '' }; + case 'workbench.action.reloadWindow': + return { kind: 'reload' }; + default: + return { kind: 'workbench', id: VSCODE_COMMAND_ALIASES[id] ?? id }; + } +} + +/** An extension's status text with `$(name)` and `$(name~spin)` icon references removed (the IDE has no codicons). */ +export function statusText(text: string): string { + return text.replace(/\$\([a-z0-9-]+(?:~[a-z]+)?\)/gi, '').replace(/\s{2,}/g, ' ').trim(); +} diff --git a/apps/ide/src/renderer/extensions/monacoContributions.ts b/apps/ide/src/renderer/extensions/monacoContributions.ts index c2414d6c1..d307640f4 100644 --- a/apps/ide/src/renderer/extensions/monacoContributions.ts +++ b/apps/ide/src/renderer/extensions/monacoContributions.ts @@ -98,3 +98,18 @@ export function applyEditorTheme(theme: ResolvedTheme | null): void { monaco.editor.defineTheme(name, toMonacoTheme(theme) as monaco.editor.IStandaloneThemeData); setThemeOverride(name); } + +/** + * #259: calls `fire` with the language of every model, now and as models are + * created or change language, so the workbench can send `onLanguage:` events. + */ +export function watchModelLanguages(fire: (languageId: string) => void): void { + const watch = (model: monaco.editor.ITextModel): void => { + fire(model.getLanguageId()); + model.onDidChangeLanguage((event) => fire(event.newLanguage)); + }; + for (const model of monaco.editor.getModels()) { + watch(model); + } + monaco.editor.onDidCreateModel(watch); +} diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 9951f23df..191f1423e 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -91,6 +91,8 @@ function editorGroup(): Promise { editorsLoading ??= Promise.all([ import('./editor/editorGroup.ts'), import('./lsp/languageClient.ts'), import('./editor/outlineController.ts'), import('./viewers/fileViewers.ts'), ]).then(([{ createEditorGroup }, { installLanguageClient }, { createOutlineController }, { fileViewerResolver }]) => { + // #259: extensions activate on the languages of the files that open. + extensions.watchEditorLanguages(); // #21: before any model exists (lsp/languageClient.ts); go to definition opens tabs here. installLanguageClient(api.lsp, { openAt: (path, line, column, length) => editorGroup().then((group) => group.openAt(path, line, column, length)) }); editors = createEditorGroup(workbench.editorArea, api.workspace, { @@ -685,6 +687,11 @@ const extensions = installExtensions({ onStatus: (message) => workbench.setStatus(message), notify: (kind, message) => notifications.notify(kind, message), selectColorTheme: () => selectColorTheme(), + notifications, + statusLeft: workbench.extensionStatusLeft, + statusRight: workbench.extensionStatusRight, + openQuickInput: (value, provider) => quickInput.open(value, provider), + openFile: (path, line, column) => editorGroup().then((group) => (line === undefined ? group.open(path) : group.openAt(path, line, column ?? 1, 0))), }); registerDebugCommands(registry, debug, () => folderIsOpen, () => (editors?.activeLineCount() ?? null) !== null, () => workbench.showView('debug')); registerAgentCommands(registry, { showAgents: () => workbench.showView('agents'), addProvider: () => agentsView.addProvider(), newChat: () => void agentsView.newChat() }); diff --git a/apps/ide/src/renderer/notifications.ts b/apps/ide/src/renderer/notifications.ts index 512f6222d..0b6ea725b 100644 --- a/apps/ide/src/renderer/notifications.ts +++ b/apps/ide/src/renderer/notifications.ts @@ -23,6 +23,8 @@ export interface NotificationOptions { readonly actions?: readonly NotificationAction[]; /** Milliseconds before it closes on its own; 0 keeps it. Defaults: info 6 s, others 0. */ readonly timeoutMs?: number; + /** #259: it closed without an action (its X, or the timeout): an extension waiting on it gets `undefined`. */ + readonly onDismiss?: () => void; } export interface ProgressUpdate { @@ -113,11 +115,15 @@ export function createNotificationCenter(host: HTMLElement): NotificationCenter return button; }))); } - const root = shell(severity, body, () => handle.close()); + const dismiss = (): void => { + handle.close(); + options.onDismiss?.(); + }; + const root = shell(severity, body, dismiss); root.dataset['severity'] = severity; const timeout = options.timeoutMs ?? (severity === 'info' && !options.actions?.length ? INFO_TIMEOUT_MS : 0); if (timeout > 0) { - timer = setTimeout(() => handle.close(), timeout); + timer = setTimeout(dismiss, timeout); // Reading a toast keeps it. root.addEventListener('mouseenter', () => clearTimeout(timer)); } diff --git a/apps/ide/src/renderer/workbench.ts b/apps/ide/src/renderer/workbench.ts index d4b665188..f9a883da0 100644 --- a/apps/ide/src/renderer/workbench.ts +++ b/apps/ide/src/renderer/workbench.ts @@ -90,6 +90,9 @@ export interface Workbench { readonly panel: HTMLElement; /** The status bar's slot for the active editor's items (#166, editor/editorStatus.ts). */ readonly editorStatus: HTMLElement; + /** #259: the status bar items of extensions, left and right (extensions/hostBridge.ts fills them). */ + readonly extensionStatusLeft: HTMLElement; + readonly extensionStatusRight: HTMLElement; /** Sizes and visibility of the side bar, panel and scene column (#169, layout/layout.ts). */ readonly layout: WorkbenchLayout; } @@ -184,7 +187,9 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null const editorStatus = el('span', { className: 'status-editor', attrs: { 'data-testid': 'editor-status' } }); const branchStatus = el('span', { className: 'status-branch', attrs: { 'data-testid': 'branch-status' } }); const trustStatus = el('button', { className: 'status-item status-trust', attrs: { type: 'button', 'data-testid': 'trust-status', hidden: '' } }); - const statusBar = el('footer', { className: 'status-bar' }, [el('span', { className: 'status-left' }, [trustStatus, branchStatus, problemsItem, statusLeft]), el('span', { className: 'status-right' }, [editorStatus, pythonItem, statusRight])]); + const extensionStatusLeft = el('span', { className: 'status-extensions', attrs: { 'data-testid': 'extension-status-left' } }); + const extensionStatusRight = el('span', { className: 'status-extensions', attrs: { 'data-testid': 'extension-status-right' } }); + const statusBar = el('footer', { className: 'status-bar' }, [el('span', { className: 'status-left' }, [trustStatus, branchStatus, problemsItem, extensionStatusLeft, statusLeft]), el('span', { className: 'status-right' }, [extensionStatusRight, editorStatus, pythonItem, statusRight])]); const sceneArea = el('section', { className: 'scene-area', attrs: { 'aria-label': 'Analysis scene', 'data-testid': 'scene-area', hidden: '' } }); // #137: the bottom panel (hidden until the terminal opens). @@ -224,6 +229,8 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null }, panel, editorStatus, + extensionStatusLeft, + extensionStatusRight, layout, setStatus(message: string): void { statusLeft.textContent = message; diff --git a/apps/ide/src/shared/extensionHostProtocol.ts b/apps/ide/src/shared/extensionHostProtocol.ts new file mode 100644 index 000000000..f4e3e5799 --- /dev/null +++ b/apps/ide/src/shared/extensionHostProtocol.ts @@ -0,0 +1,384 @@ +/** + * The extension host (#259, ADR 0002): the messages between the main process + * and the host process that runs the extensions' code, and between the main + * process and the renderer for what the host asks the workbench to show. + * + * One small RPC both ways: a request carries an id and gets one response; a + * notification gets none. Values must survive structured cloning (the host + * talks over Node's IPC channel, the renderer over Electron's), so no + * functions, class instances or `undefined` inside arrays. + * + * Shared by main, the host and the renderer: no Node, Electron or DOM import. + */ + +import type { ExtensionActivation, ExtensionId } from './extensions.ts'; + +export type RpcMessage = + | { readonly kind: 'req'; readonly id: number; readonly method: string; readonly params: readonly unknown[] } + | { readonly kind: 'res'; readonly id: number; readonly ok: true; readonly result: unknown } + | { readonly kind: 'res'; readonly id: number; readonly ok: false; readonly error: string } + | { readonly kind: 'evt'; readonly method: string; readonly params: readonly unknown[] }; + +export function isRpcMessage(value: unknown): value is RpcMessage { + if (typeof value !== 'object' || value === null) { + return false; + } + const message = value as Record; + switch (message['kind']) { + case 'req': + return typeof message['id'] === 'number' && typeof message['method'] === 'string' && Array.isArray(message['params']); + case 'res': + return typeof message['id'] === 'number' && typeof message['ok'] === 'boolean'; + case 'evt': + return typeof message['method'] === 'string' && Array.isArray(message['params']); + default: + return false; + } +} + +type Handler = (...params: unknown[]) => unknown; + +/** + * One end of the RPC. `send` writes a message to the other end; `receive` is + * fed every message that arrives. A request whose method has no handler is + * answered with an error, so the caller never waits forever; `dispose` + * rejects every request still waiting (the other end went away). + */ +export class RpcEndpoint { + private readonly send: (message: RpcMessage) => void; + private readonly handlers = new Map(); + private readonly pending = new Map void; reject: (error: Error) => void }>(); + private nextId = 1; + private disposed = false; + + constructor(send: (message: RpcMessage) => void) { + this.send = send; + } + + /** Answers requests and notifications called `method`. */ + handle(method: string, handler: Handler): void { + this.handlers.set(method, handler); + } + + request(method: string, ...params: unknown[]): Promise { + if (this.disposed) { + return Promise.reject(new Error('The extension host is not running.')); + } + const id = this.nextId++; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject }); + try { + this.send({ kind: 'req', id, method, params }); + } catch (error) { + this.pending.delete(id); + reject(error instanceof Error ? error : new Error(String(error))); + } + }); + } + + notify(method: string, ...params: unknown[]): void { + if (!this.disposed) { + try { + this.send({ kind: 'evt', method, params }); + } catch { + // The other end is gone; dispose() follows from its exit. + } + } + } + + receive(message: unknown): void { + if (!isRpcMessage(message) || this.disposed) { + return; + } + if (message.kind === 'res') { + const waiting = this.pending.get(message.id); + this.pending.delete(message.id); + if (waiting) { + if (message.ok) { + waiting.resolve(message.result); + } else { + waiting.reject(new Error(message.error)); + } + } + return; + } + const handler = this.handlers.get(message.method); + if (message.kind === 'evt') { + try { + const result = handler?.(...message.params); + if (result instanceof Promise) { + result.catch(() => undefined); + } + } catch { + // A notification has nobody to tell. + } + return; + } + const { id } = message; + if (!handler) { + this.reply({ kind: 'res', id, ok: false, error: `Unknown method "${message.method}".` }); + return; + } + Promise.resolve() + .then(() => handler(...message.params)) + .then( + (result) => this.reply({ kind: 'res', id, ok: true, result: result === undefined ? null : result }), + (error: unknown) => this.reply({ kind: 'res', id, ok: false, error: error instanceof Error ? error.message : String(error) }), + ); + } + + private reply(message: RpcMessage): void { + if (this.disposed) { + return; + } + try { + this.send(message); + } catch (error) { + if (message.kind === 'res' && message.ok) { + // The result could not be cloned: say so instead of leaving the caller waiting. + try { + this.send({ kind: 'res', id: message.id, ok: false, error: `The result could not be sent: ${error instanceof Error ? error.message : String(error)}` }); + } catch { + // Gone. + } + } + } + } + + dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + for (const waiting of this.pending.values()) { + waiting.reject(new Error('The extension host stopped.')); + } + this.pending.clear(); + this.handlers.clear(); + } +} + +/* ------------------------------------------------------------------ */ +/* main -> host */ +/* ------------------------------------------------------------------ */ + +/** An extension with code, as the host needs it. */ +export interface HostExtensionDescription { + readonly id: ExtensionId; + /** The extension's folder (absolute). */ + readonly location: string; + /** `main`, relative to `location`. */ + readonly main: string; + /** The whole `package.json`, localised (`vscode.extensions.getExtension(id).packageJSON`). */ + readonly packageJSON: Readonly>; + /** Declared and implicit activation events (`onCommand:` for contributed commands, ...). */ + readonly activationEvents: readonly string[]; + readonly extensionDependencies: readonly ExtensionId[]; +} + +/** An extension without code: `vscode.extensions.all` lists it too. */ +export interface HostPassiveExtension { + readonly id: ExtensionId; + readonly location: string; + readonly packageJSON: Readonly>; +} + +export interface HostInitData { + readonly extensions: readonly HostExtensionDescription[]; + readonly passive: readonly HostPassiveExtension[]; + /** The folder this window has open, absolute, or null. */ + readonly workspaceFolder: string | null; + readonly trusted: boolean; + /** User values of the extensions' settings, by full key. */ + readonly configuration: Readonly>; + /** Per-extension storage: `//` for global state, `///` for the folder's. */ + readonly globalStorageRoot: string; + readonly workspaceStorageRoot: string | null; + readonly logRoot: string; + readonly env: { + readonly appName: string; + readonly appRoot: string; + readonly appHost: string; + readonly language: string; + readonly machineId: string; + readonly sessionId: string; + readonly uriScheme: string; + readonly shell: string; + readonly version: string; + }; + readonly isDevelopment: boolean; +} + +export const HOST_METHODS = { + /** (HostInitData) -> void */ + init: 'init', + /** (event: string) -> void. Activates every extension listening for it; resolves once they have activated. */ + activateByEvent: 'activateByEvent', + /** (id: string, args: unknown[]) -> unknown. A command an extension registered. */ + executeCommand: 'executeCommand', + /** () -> string[]: the commands the extensions registered. */ + registeredCommands: 'registeredCommands', + /** (values: Record, changed: string[]) -> void */ + configurationChanged: 'configurationChanged', + /** (trusted: boolean) -> void */ + trustChanged: 'trustChanged', + /** () -> void. Deactivates every extension, then the host exits. */ + shutdown: 'shutdown', +} as const; + +/* ------------------------------------------------------------------ */ +/* host -> main */ +/* ------------------------------------------------------------------ */ + +export interface HostLogLine { + readonly level: 'trace' | 'debug' | 'info' | 'warn' | 'error'; + /** The extension it is about, or null for the host itself. */ + readonly extensionId: ExtensionId | null; + /** An output channel an extension created, if the line comes from one. */ + readonly channel?: string; + readonly message: string; +} + +export interface HostActivationEvent { + readonly id: ExtensionId; + readonly state: ExtensionActivation; + readonly error?: string; +} + +export const MAIN_METHODS = { + /** (HostLogLine) notification */ + log: 'log', + /** (HostActivationEvent) notification */ + activation: 'activation', + /** (extensionId, apiName) notification: an extension used API the host does not implement (logged once). */ + notImplemented: 'notImplemented', + /** (id, args) -> unknown: a command that no extension registered, for the workbench. */ + executeWorkbenchCommand: 'executeWorkbenchCommand', + /** (key, value, target: 'user' | 'workspace') -> void */ + updateConfiguration: 'updateConfiguration', + /** (extensionId, key) -> string | null */ + secretGet: 'secretGet', + /** (extensionId, key, value) -> void */ + secretStore: 'secretStore', + /** (extensionId, key) -> void */ + secretDelete: 'secretDelete', + /** () -> string */ + clipboardRead: 'clipboardRead', + /** (text) -> void */ + clipboardWrite: 'clipboardWrite', + /** (url) -> boolean: opens it outside the IDE (http, https, mailto only). */ + openExternal: 'openExternal', + /** (DialogRequest) -> string[] | null: a native open or save dialog; paths are absolute. */ + showDialog: 'showDialog', + /** (UiRequest) -> unknown: something the workbench has to show (see UI_METHODS). */ + ui: 'ui', + /** (UiNotification) notification: status bar items, progress, status messages. */ + uiNotify: 'uiNotify', +} as const; + +/* ------------------------------------------------------------------ */ +/* main <-> renderer: what the host asks the workbench */ +/* ------------------------------------------------------------------ */ + +export type MessageSeverity = 'info' | 'warning' | 'error'; + +export interface QuickPickItemData { + readonly label: string; + readonly description?: string; + readonly detail?: string; + readonly picked?: boolean; + /** A separator row (`QuickPickItemKind.Separator`): shown, never picked. */ + readonly separator?: boolean; +} + +export interface DialogRequest { + readonly kind: 'open' | 'save'; + readonly title?: string; + readonly defaultPath?: string; + readonly openLabel?: string; + readonly canSelectFiles?: boolean; + readonly canSelectFolders?: boolean; + readonly canSelectMany?: boolean; + /** Name -> extensions without the dot, as `showOpenDialog`'s `filters`. */ + readonly filters?: Readonly>; +} + +/** A request from an extension that waits for the person; answered with the result. */ +export type UiRequest = + | { readonly kind: 'message'; readonly extensionId: ExtensionId; readonly severity: MessageSeverity; readonly message: string; readonly detail?: string; readonly modal?: boolean; readonly items: readonly string[] } + | { readonly kind: 'quickPick'; readonly extensionId: ExtensionId; readonly items: readonly QuickPickItemData[]; readonly placeHolder?: string; readonly title?: string; readonly canPickMany: boolean } + | { readonly kind: 'inputBox'; readonly extensionId: ExtensionId; readonly value?: string; readonly prompt?: string; readonly placeHolder?: string; readonly title?: string; readonly password: boolean } + | { readonly kind: 'openFile'; readonly path: string; readonly line?: number; readonly column?: number; readonly preview: boolean } + /** A command no extension registered: the workbench's own, or a built-in `vscode.*` one it maps. Args went through the host's wire format. */ + | { readonly kind: 'command'; readonly id: string; readonly args: readonly unknown[] }; + +export interface StatusBarItemData { + /** Unique per host: `/`. */ + readonly key: string; + readonly extensionId: ExtensionId; + readonly text: string; + readonly tooltip?: string; + readonly command?: string; + readonly commandArgs?: readonly unknown[]; + readonly alignment: 'left' | 'right'; + readonly priority: number; + readonly visible: boolean; + readonly name?: string; +} + +/** Fire-and-forget updates for the workbench. */ +export type UiNotification = + | { readonly kind: 'statusBarItem'; readonly item: StatusBarItemData } + | { readonly kind: 'statusBarItemDispose'; readonly key: string } + | { readonly kind: 'statusMessage'; readonly text: string; readonly timeoutMs: number } + | { readonly kind: 'progress'; readonly key: string; readonly title: string; readonly message?: string; readonly percent?: number } + | { readonly kind: 'progressEnd'; readonly key: string } + | { readonly kind: 'contextKey'; readonly key: string; readonly value: unknown } + | { readonly kind: 'hostStopped'; readonly reason: string }; + +/** Main -> renderer: one UI request of the host (answer with `extensionsHostReply`), or a notification. */ +export type HostUiEvent = + | { readonly type: 'request'; readonly id: number; readonly request: UiRequest } + | { readonly type: 'notify'; readonly notification: UiNotification }; + +/** + * The implicit activation events VS Code has added since 1.74: a contributed + * command, view or language activates its extension without declaring it. + */ +export function activationEventsOf(declared: readonly string[], contributes: Readonly>): string[] { + const events = new Set(declared.filter((event) => typeof event === 'string' && event.trim() !== '')); + const list = (value: unknown): Record[] => (Array.isArray(value) ? value.filter((item): item is Record => typeof item === 'object' && item !== null) : []); + for (const command of list(contributes['commands'])) { + if (typeof command['command'] === 'string') { + events.add(`onCommand:${command['command']}`); + } + } + const views = contributes['views']; + if (typeof views === 'object' && views !== null) { + for (const container of Object.values(views as Record)) { + for (const view of list(container)) { + if (typeof view['id'] === 'string') { + events.add(`onView:${view['id']}`); + } + } + } + } + for (const language of list(contributes['languages'])) { + if (typeof language['id'] === 'string') { + events.add(`onLanguage:${language['id']}`); + } + } + return [...events]; +} + +/** Whether `event` (as fired, e.g. `onLanguage:python`) wakes an extension that declared `declared`. */ +export function activationMatches(declared: readonly string[], event: string): boolean { + if (declared.includes('*') && event !== 'onStartupFinished') { + return true; + } + if (declared.includes(event)) { + return true; + } + // `onLanguage` alone (no id) fires on any language. + return event.startsWith('onLanguage:') && declared.includes('onLanguage'); +} diff --git a/apps/ide/src/shared/extensions.ts b/apps/ide/src/shared/extensions.ts index a4e5cc89e..fefaedc31 100644 --- a/apps/ide/src/shared/extensions.ts +++ b/apps/ide/src/shared/extensions.ts @@ -9,6 +9,8 @@ * Shared by main, preload and renderer: no Node, Electron or DOM import. */ +import type { HostUiEvent } from './extensionHostProtocol.ts'; + /** `publisher.name`, lower-cased: VS Code compares extension ids without case. */ export type ExtensionId = string; @@ -212,12 +214,23 @@ export interface ContributedSnippet { readonly description: string; } +/** A command of `contributes.commands` (#259): the palette lists it, the extension host runs it. */ +export interface ContributedCommand { + readonly extensionId: ExtensionId; + readonly command: string; + readonly title: string; + readonly category: string | null; + /** `menus.commandPalette` hides it (`"when": "false"`): it runs, but the palette does not list it. */ + readonly hiddenFromPalette: boolean; +} + /** Everything declarative the workbench applies from the enabled extensions. */ export interface ExtensionContributions { readonly themes: readonly ContributedTheme[]; readonly languages: readonly ContributedLanguage[]; readonly grammars: readonly ContributedGrammar[]; readonly snippets: readonly ContributedSnippet[]; + readonly commands: readonly ContributedCommand[]; } export interface ExtensionsChangedEvent { @@ -254,6 +267,22 @@ export interface ExtensionsApi { grammarContent(ref: string): Promise; onDidChange(listener: (event: ExtensionsChangedEvent) => void): () => void; onLog(listener: (event: ExtensionLogEvent) => void): () => void; + /** #259: the workbench is ready; starts this window's extension host if an extension with code may run. */ + hostReady(): Promise; + /** Stops and starts this window's extension host again (after a crash, or on request). */ + restartHost(): Promise; + /** Runs a command an extension contributes or registers (activating it first). */ + executeCommand(id: string, args?: readonly unknown[]): Promise; + /** Fires an activation event of the workbench: `onLanguage:`, `onView:`, `onUri`. */ + activateByEvent(event: string): Promise; + /** Answers a request of the host (`onHostUi`'s `request`), with its result or null when dismissed. */ + hostReply(id: number, result: unknown): Promise; + onHostUi(listener: (event: HostUiEvent) => void): () => void; +} + +/** Activation events the renderer may fire (the others are the main process's or the host's own). */ +export function isWorkbenchActivationEvent(value: unknown): value is string { + return typeof value === 'string' && value.length <= 300 && /^(onLanguage|onView|onWebviewPanel|onCustomEditor|onFileSystem):[\w.\-/+#@]+$|^onUri$/.test(value); } export const EXTENSION_IPC_CHANNELS = { @@ -270,11 +299,17 @@ export const EXTENSION_IPC_CHANNELS = { extensionsContributions: 'codexr:extensions:contributions', extensionsTheme: 'codexr:extensions:theme', extensionsGrammarContent: 'codexr:extensions:grammar-content', + extensionsHostReady: 'codexr:extensions:host-ready', + extensionsRestartHost: 'codexr:extensions:restart-host', + extensionsExecuteCommand: 'codexr:extensions:execute-command', + extensionsActivateByEvent: 'codexr:extensions:activate-by-event', + extensionsHostReply: 'codexr:extensions:host-reply', } as const; export const EXTENSION_IPC_EVENTS = { extensionsChanged: 'codexr:extensions:changed', extensionsLog: 'codexr:extensions:log', + extensionsHostUi: 'codexr:extensions:host-ui', } as const; /** The default registry, and the setting that changes it. */ diff --git a/apps/ide/test/extensionHost.test.ts b/apps/ide/test/extensionHost.test.ts new file mode 100644 index 000000000..e72223b27 --- /dev/null +++ b/apps/ide/test/extensionHost.test.ts @@ -0,0 +1,494 @@ +import { after, before, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { fork, type ChildProcess } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + activationEventsOf, activationMatches, HOST_METHODS, MAIN_METHODS, RpcEndpoint, + type HostActivationEvent, type HostInitData, type HostLogLine, type RpcMessage, type UiNotification, type UiRequest, +} from '../src/shared/extensionHostProtocol.ts'; +import { isWorkbenchActivationEvent } from '../src/shared/extensions.ts'; +import { ConfigurationModel, configurationDefaults } from '../src/extensionHost/configuration.ts'; +import { matchGlob } from '../src/extensionHost/glob.ts'; +import { inert, stubFor, withFallback } from '../src/extensionHost/inert.ts'; +import { TextDocumentModel } from '../src/extensionHost/textDocument.ts'; +import { DiagnosticSeverity, Position, Range, Selection, SnippetString, Uri, WorkspaceEdit } from '../src/extensionHost/types.ts'; +import { fromWire, toWire } from '../src/extensionHost/wire.ts'; +import { formatMessage } from '../src/extensionHost/api.ts'; +import { ExtensionSettingsStore } from '../src/main/extensions/extensionSettings.ts'; +import { builtinCommandFor, statusText } from '../src/renderer/extensions/hostBridgeModel.ts'; +import { createCommandRegistry } from '../src/renderer/commands/commandRegistry.ts'; + +const HOST_ENTRY = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'extensionHost', 'index.ts'); + +let tmp = ''; +before(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-host-test-')); +}); +after(() => { + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +describe('extension host protocol (#259)', () => { + function pair(): [RpcEndpoint, RpcEndpoint] { + let a: RpcEndpoint | null = null; + let b: RpcEndpoint | null = null; + // Asynchronous delivery, as over a real channel. + a = new RpcEndpoint((message) => queueMicrotask(() => b?.receive(structuredClone(message)))); + b = new RpcEndpoint((message) => queueMicrotask(() => a?.receive(structuredClone(message)))); + return [a, b]; + } + + it('answers requests both ways, reports errors and unknown methods', async () => { + const [main, host] = pair(); + host.handle('add', (x, y) => Number(x) + Number(y)); + host.handle('fail', () => { + throw new Error('boom'); + }); + main.handle('echo', async (value) => value); + assert.equal(await main.request('add', 2, 3), 5); + await assert.rejects(main.request('fail'), /boom/); + await assert.rejects(main.request('nope'), /Unknown method "nope"/); + assert.deepEqual(await host.request('echo', { a: [1] }), { a: [1] }); + assert.equal(await host.request('echo', undefined), null, 'undefined travels as null'); + }); + + it('delivers notifications and rejects what is pending on dispose', async () => { + const [main, host] = pair(); + const seen: unknown[] = []; + main.handle('log', (line) => seen.push(line)); + host.notify('log', 'hello'); + await new Promise((resolve) => setTimeout(resolve, 5)); + assert.deepEqual(seen, ['hello']); + host.handle('slow', () => new Promise(() => undefined)); + const waiting = main.request('slow'); + main.dispose(); + await assert.rejects(waiting, /stopped/); + await assert.rejects(main.request('slow'), /not running/); + main.receive({ kind: 'nonsense' } as unknown as RpcMessage); + }); + + it('adds the implicit activation events and matches fired events', () => { + const events = activationEventsOf(['onStartupFinished'], { + commands: [{ command: 'acme.run', title: 'Run' }], + views: { explorer: [{ id: 'acme.tree', name: 'Tree' }] }, + languages: [{ id: 'kit' }], + }); + assert.deepEqual(events.sort(), ['onCommand:acme.run', 'onLanguage:kit', 'onStartupFinished', 'onView:acme.tree']); + assert.equal(activationMatches(['*'], 'onLanguage:python'), true); + assert.equal(activationMatches(['*'], 'onStartupFinished'), false, '* extensions are already active by then'); + assert.equal(activationMatches(['onLanguage'], 'onLanguage:python'), true); + assert.equal(activationMatches(['onLanguage:go'], 'onLanguage:python'), false); + }); + + it('only lets the renderer fire workbench activation events', () => { + assert.equal(isWorkbenchActivationEvent('onLanguage:python'), true); + assert.equal(isWorkbenchActivationEvent('onView:acme.tree'), true); + assert.equal(isWorkbenchActivationEvent('onUri'), true); + assert.equal(isWorkbenchActivationEvent('*'), false); + assert.equal(isWorkbenchActivationEvent('onCommand:acme.run'), false); + assert.equal(isWorkbenchActivationEvent('workspaceContains:**/x'), false); + assert.equal(isWorkbenchActivationEvent('onLanguage:a b'), false); + }); +}); + +describe('vscode API values (#259)', () => { + it('keeps VS Code\'s enum numbers and reverse names', () => { + assert.equal(DiagnosticSeverity.Error, 0); + assert.equal(DiagnosticSeverity.Hint, 3); + assert.equal(DiagnosticSeverity[1], 'Warning'); + }); + + it('orders ranges, builds selections and snippets', () => { + const range = new Range(3, 4, 1, 2); + assert.deepEqual([range.start.line, range.end.line], [1, 3], 'start and end are swapped into order'); + assert.equal(range.contains(new Position(2, 0)), true); + assert.equal(new Range(0, 0, 0, 5).intersection(new Range(0, 6, 0, 8)), undefined); + const selection = new Selection(2, 0, 1, 0); + assert.equal(selection.isReversed, true); + assert.equal(new SnippetString().appendText('$x').appendPlaceholder('name').appendTabstop(0).value, '\\$x${1:name}$0'); + assert.equal(Uri.joinPath(Uri.file('/a/b'), 'c', 'd.txt').fsPath.replace(/\\/g, '/'), '/a/b/c/d.txt'); + }); + + it('collects workspace edits by file', () => { + const edit = new WorkspaceEdit(); + const uri = Uri.file('/w/a.txt'); + edit.insert(uri, new Position(0, 0), 'x'); + edit.delete(uri, new Range(1, 0, 1, 2)); + assert.equal(edit.size, 1); + assert.equal(edit.entries()[0]?.[1].length, 2); + assert.equal(edit.has(Uri.file('/w/b.txt')), false); + }); + + it('carries Uri, Position and Range across the process boundary and drops functions and cycles', () => { + const cyclic: Record = { name: 'x', run: () => 1 }; + cyclic['self'] = cyclic; + const shared = { n: 1 }; + const wire = toWire({ uri: Uri.file('/w/a.ts'), at: new Position(1, 2), range: new Range(0, 0, 1, 1), cyclic, list: [shared, shared] }); + const back = fromWire(structuredClone(wire)) as Record; + assert.ok(back['uri'] instanceof Uri); + assert.equal((back['uri'] as Uri).path, '/w/a.ts'); + assert.ok(back['at'] instanceof Position); + assert.ok(back['range'] instanceof Range); + assert.deepEqual(back['cyclic'], { name: 'x', self: null }); + assert.deepEqual(back['list'], [{ n: 1 }, { n: 1 }], 'the same object twice is not a cycle'); + }); + + it('stands in for missing API without throwing', async () => { + const reported: string[] = []; + const ns = withFallback('window', { known: 1 }, (api) => reported.push(api)) as Record; + assert.equal(ns['known'], 1); + const created = (ns['createWebviewPanel'] as () => Record)(); + (created['webview'] as Record)['html'] = 'x'; + (created['onDidDispose'] as (listener: () => void) => { dispose(): void })(() => undefined).dispose(); + assert.equal(await (ns['showSomething'] as () => Promise)(), undefined); + assert.equal(typeof (ns['onDidChangeThing'] as () => { dispose(): void })().dispose, 'function'); + assert.deepEqual(reported, ['window.createWebviewPanel', 'window.showSomething', 'window.onDidChangeThing']); + assert.equal(stubFor('mystery'), undefined); + const value = inert(); + assert.equal(await Promise.resolve(value), value, 'an inert value is not a thenable: awaiting it does not hang'); + }); + + it('formats l10n messages', () => { + assert.equal(formatMessage('Hello {0}, {1}!', ['a', 2]), 'Hello a, 2!'); + assert.equal(formatMessage('Hi {name}', { name: 'Ada' }), 'Hi Ada'); + assert.equal(formatMessage('{0} {missing}', ['x']), 'x {missing}'); + }); +}); + +describe('glob patterns (#259)', () => { + it('matches VS Code globs', () => { + assert.equal(matchGlob('**/*.ts', 'src/a/b.ts'), true); + assert.equal(matchGlob('**/*.ts', 'b.ts'), true); + assert.equal(matchGlob('*.ts', 'src/b.ts'), false); + assert.equal(matchGlob('**/{package.json,tsconfig.json}', 'a/tsconfig.json'), true); + assert.equal(matchGlob('src/[ab].js', 'src/b.js'), true); + assert.equal(matchGlob('src/[!ab].js', 'src/b.js'), false); + assert.equal(matchGlob('**/node_modules/**', 'x/node_modules/y/z.js'), true); + assert.equal(matchGlob('a?.txt', 'ab.txt'), true); + assert.equal(matchGlob('requirements.txt', 'requirements.txt'), true); + }); +}); + +describe('extension configuration (#259)', () => { + const contributes = { + configuration: [{ + properties: { + 'acme.enabled': { type: 'boolean', default: true }, + 'acme.paths': { type: 'array' }, + 'acme.format.indent': { type: 'number', default: 2 }, + 'acme.format.style': { type: 'string', default: 'k&r' }, + }, + }], + configurationDefaults: { 'acme.format.indent': 4 }, + }; + + it('reads the defaults and the type-derived ones', () => { + const defaults = configurationDefaults(contributes); + assert.equal(defaults.get('acme.enabled'), true); + assert.deepEqual(defaults.get('acme.paths'), []); + assert.equal(defaults.get('acme.format.indent'), 4, 'configurationDefaults wins'); + }); + + it('serves sections, user values, inspect and update', async () => { + const updates: unknown[][] = []; + const model = new ConfigurationModel(async (key, value, target) => { + updates.push([key, value, target]); + }); + model.setDefaults([contributes]); + model.setUserValues({ 'acme.format.style': 'allman' }); + const acme = model.get('acme'); + assert.equal(acme.get('enabled'), true); + assert.equal(acme.get('format.style'), 'allman'); + assert.deepEqual(acme.get('format'), { indent: 4, style: 'allman' }); + assert.equal(acme['enabled'], true, 'values are readable as properties too'); + assert.equal(acme.get('missing', 'fallback'), 'fallback'); + assert.equal(acme.has('format.indent'), true); + assert.deepEqual(acme.inspect('format.style'), { key: 'acme.format.style', defaultValue: 'k&r', globalValue: 'allman' }); + assert.equal(model.get().get('acme.format.indent'), 4); + await acme.update('enabled', false, true); + assert.deepEqual(updates, [['acme.enabled', false, 'user']]); + assert.equal(model.get('acme').get('enabled'), false); + assert.deepEqual(model.setUserValues({ 'acme.enabled': false }), ['acme.format.style']); + assert.equal(ConfigurationModel.affects('acme.format.style', 'acme'), true); + assert.equal(ConfigurationModel.affects('acme.format.style', 'acme.format.style'), true); + assert.equal(ConfigurationModel.affects('acme.format', 'acme.format.style'), true); + assert.equal(ConfigurationModel.affects('other.x', 'acme'), false); + }); + + it('stores the extensions\' settings apart, comments allowed', () => { + const file = path.join(tmp, 'ext-settings', 'settings.json'); + const store = new ExtensionSettingsStore(file); + assert.deepEqual(store.values(), {}); + store.update('acme.list', [1, 2]); + store.update('acme.flag', true); + store.update('acme.flag', undefined); + assert.deepEqual(store.values(), { 'acme.list': [1, 2] }); + fs.writeFileSync(file, '{\n // edited by hand\n "acme.list": [3],\n}\n'); + fs.utimesSync(file, new Date(), new Date(Date.now() + 5000)); + assert.deepEqual(new ExtensionSettingsStore(file).values(), { 'acme.list': [3] }); + }); +}); + +describe('text documents (#259)', () => { + it('maps offsets, lines and words, CRLF included', () => { + const doc = new TextDocumentModel(Uri.file('/w/a.ts'), 'typescript', 1, 'const a = 1;\r\nlet bb = a + 2;\n\n'); + assert.equal(doc.lineCount, 4); + assert.equal(doc.eol, 2); + assert.equal(doc.lineAt(1).text, 'let bb = a + 2;'); + assert.equal(doc.lineAt(1).firstNonWhitespaceCharacterIndex, 0); + assert.equal(doc.lineAt(2).isEmptyOrWhitespace, true); + assert.deepEqual(doc.positionAt(16).toJSON(), { line: 1, character: 2 }); + assert.equal(doc.offsetAt(new Position(1, 4)), 18); + assert.equal(doc.getText(new Range(1, 4, 1, 6)), 'bb'); + assert.equal(doc.getText(doc.getWordRangeAtPosition(new Position(1, 5))), 'bb'); + assert.deepEqual(doc.validatePosition(new Position(9, 9)).toJSON(), { line: 3, character: 0 }); + assert.throws(() => doc.lineAt(7), /Illegal value/); + doc.applyChange(new Range(0, 6, 0, 7), 'alpha'); + assert.equal(doc.lineAt(0).text, 'const alpha = 1;'); + }); +}); + +describe('workbench side of the host (#259)', () => { + it('maps VS Code\'s commands onto the IDE\'s', () => { + assert.deepEqual(builtinCommandFor('workbench.action.files.save', []), { kind: 'workbench', id: 'file.save' }); + assert.deepEqual(builtinCommandFor('workbench.extensions.search', ['@installed']), { kind: 'search-extensions', query: '@installed' }); + assert.deepEqual(builtinCommandFor('workbench.action.reloadWindow', []), { kind: 'reload' }); + assert.deepEqual(builtinCommandFor('terminal.new', []), { kind: 'workbench', id: 'terminal.new' }); + }); + + it('drops codicon references from status texts', () => { + assert.equal(statusText('$(sync~spin) Indexing $(check)'), 'Indexing'); + assert.equal(statusText('Plain'), 'Plain'); + }); + + it('accepts any extension command id, still unique', () => { + const registry = createCommandRegistry(); + registry.register({ id: '_acme.internal_Thing', title: 'Thing', source: 'extension', run: () => undefined }); + assert.throws(() => registry.register({ id: '_acme.internal_Thing', title: 'Again', source: 'extension', run: () => undefined }), /Duplicate/); + assert.throws(() => registry.register({ id: 'has space', title: 'Bad', source: 'extension', run: () => undefined }), /Invalid command ID/); + assert.throws(() => registry.register({ id: '_acme.x', title: 'Not an extension', run: () => undefined }), /Invalid command ID/); + }); +}); + +/* ------------------------------ the host process ------------------------------ */ + +const EXTENSION_JS = String.raw` +const vscode = require('vscode'); +const helper = require('./lib/helper.js'); +exports.activate = async function activate(context) { + const out = vscode.window.createOutputChannel('Demo'); + out.appendLine('activated in ' + vscode.env.appName); + context.subscriptions.push(vscode.commands.registerCommand('demo.greet', async (name) => { + const config = vscode.workspace.getConfiguration('demo'); + const answer = await vscode.window.showInformationMessage(helper.greeting(name, config.get('punctuation')), 'Yes', 'No'); + await context.globalState.update('lastAnswer', answer); + return { answer, uri: vscode.Uri.file('/x/y.txt'), sameApi: require('vscode') === vscode }; + })); + context.subscriptions.push(vscode.commands.registerCommand('demo.workbench', () => vscode.commands.executeCommand('workbench.action.files.save', 1))); + context.subscriptions.push(vscode.commands.registerCommand('demo.missing', () => { + const panel = vscode.window.createWebviewPanel('demo', 'Demo', vscode.ViewColumn.One, {}); + panel.webview.html = '

x

'; + return typeof panel.dispose; + })); + context.subscriptions.push(vscode.commands.registerCommand('demo.state', () => ({ last: context.globalState.get('lastAnswer'), storage: context.globalStorageUri.fsPath }))); + context.subscriptions.push(vscode.commands.registerCommand('demo.update', async () => { + await vscode.workspace.getConfiguration('demo').update('punctuation', '?', vscode.ConfigurationTarget.Global); + return vscode.workspace.getConfiguration('demo').get('punctuation'); + })); + context.subscriptions.push(vscode.commands.registerCommand('demo.files', async () => { + const found = await vscode.workspace.findFiles('**/*.md'); + const doc = await vscode.workspace.openTextDocument(found[0]); + return { count: found.length, language: doc.languageId, firstLine: doc.lineAt(0).text, rel: vscode.workspace.asRelativePath(found[0]) }; + })); + const item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 10); + item.text = '$(check) Demo'; + item.command = 'demo.greet'; + item.show(); + return { api: 42 }; +}; +exports.deactivate = function deactivate() { + require('fs').writeFileSync(process.env.DEMO_DEACTIVATED, 'yes'); +}; +`; + +const DEPENDENT_JS = String.raw` +const vscode = require('vscode'); +exports.activate = function () { + const demo = vscode.extensions.getExtension('acme.demo'); + vscode.commands.registerCommand('dep.check', () => ({ active: demo.isActive, exports: demo.exports })); +}; +`; + +const BROKEN_JS = 'exports.activate = () => { throw new Error("broken on purpose"); };'; + +function writeExtension(id: string, packageJSON: Record, files: Record): string { + const folder = path.join(tmp, 'extensions', id); + fs.mkdirSync(folder, { recursive: true }); + fs.writeFileSync(path.join(folder, 'package.json'), JSON.stringify(packageJSON)); + for (const [name, content] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(folder, name)), { recursive: true }); + fs.writeFileSync(path.join(folder, name), content); + } + return folder; +} + +describe('the extension host process (#259)', () => { + let child: ChildProcess; + let main: RpcEndpoint; + const logs: HostLogLine[] = []; + const activations: HostActivationEvent[] = []; + const missing: string[] = []; + const ui: UiRequest[] = []; + const notifications: UiNotification[] = []; + const workbenchCommands: unknown[][] = []; + const configUpdates: unknown[][] = []; + let deactivatedMarker = ''; + + before(async () => { + const workspace = path.join(tmp, 'workspace'); + fs.mkdirSync(path.join(workspace, 'docs'), { recursive: true }); + fs.writeFileSync(path.join(workspace, 'docs', 'readme.md'), '# Title\nbody\n'); + fs.mkdirSync(path.join(workspace, 'node_modules', 'x'), { recursive: true }); + fs.writeFileSync(path.join(workspace, 'node_modules', 'x', 'skip.md'), '# no'); + deactivatedMarker = path.join(tmp, 'deactivated.txt'); + const demoJson = { + publisher: 'acme', name: 'demo', version: '1.0.0', main: './out/extension.js', engines: { vscode: '^1.80.0' }, + activationEvents: ['onStartupFinished'], + contributes: { + commands: [{ command: 'demo.greet', title: 'Greet' }], + configuration: { properties: { 'demo.punctuation': { type: 'string', default: '!' } } }, + }, + }; + const demo = writeExtension('acme.demo-1.0.0', demoJson, { 'out/extension.js': EXTENSION_JS, 'out/lib/helper.js': 'exports.greeting = (name, p) => "Hello " + name + p;' }); + const depJson = { publisher: 'acme', name: 'dep', version: '1.0.0', main: 'index.js', engines: { vscode: '^1.80.0' }, activationEvents: ['onCommand:dep.check'], extensionDependencies: ['acme.demo'] }; + const dep = writeExtension('acme.dep-1.0.0', depJson, { 'index.js': DEPENDENT_JS }); + const brokenJson = { publisher: 'acme', name: 'broken', version: '1.0.0', main: 'index.js', engines: { vscode: '^1.80.0' }, activationEvents: ['onLanguage:markdown'] }; + const broken = writeExtension('acme.broken-1.0.0', brokenJson, { 'index.js': BROKEN_JS }); + + child = fork(HOST_ENTRY, [], { + execArgv: ['--experimental-strip-types', '--no-warnings'], + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], + serialization: 'advanced', + env: { ...process.env, DEMO_DEACTIVATED: deactivatedMarker }, + }); + child.stderr?.on('data', (chunk: Buffer) => process.stderr.write(`[host stderr] ${chunk.toString()}`)); + main = new RpcEndpoint((message) => child.send(message)); + child.on('message', (message) => main.receive(message)); + main.handle(MAIN_METHODS.log, (line) => logs.push(line as HostLogLine)); + main.handle(MAIN_METHODS.activation, (event) => activations.push(event as HostActivationEvent)); + main.handle(MAIN_METHODS.notImplemented, (_id, api) => missing.push(String(api))); + main.handle(MAIN_METHODS.ui, (request) => { + ui.push(request as UiRequest); + return (request as UiRequest).kind === 'message' ? 0 : null; + }); + main.handle(MAIN_METHODS.uiNotify, (notification) => notifications.push(notification as UiNotification)); + main.handle(MAIN_METHODS.executeWorkbenchCommand, (id, args) => { + workbenchCommands.push([id, args]); + return 'saved'; + }); + main.handle(MAIN_METHODS.updateConfiguration, (key, value, target) => { + configUpdates.push([key, value, target]); + }); + const init: HostInitData = { + extensions: [ + { id: 'acme.demo', location: demo, main: demoJson.main, packageJSON: demoJson, activationEvents: activationEventsOf(demoJson.activationEvents, demoJson.contributes), extensionDependencies: [] }, + { id: 'acme.dep', location: dep, main: depJson.main, packageJSON: depJson, activationEvents: depJson.activationEvents, extensionDependencies: ['acme.demo'] }, + { id: 'acme.broken', location: broken, main: brokenJson.main, packageJSON: brokenJson, activationEvents: brokenJson.activationEvents, extensionDependencies: [] }, + ], + passive: [], + workspaceFolder: workspace, + trusted: true, + configuration: {}, + globalStorageRoot: path.join(tmp, 'storage', 'global'), + workspaceStorageRoot: path.join(tmp, 'storage', 'ws'), + logRoot: path.join(tmp, 'logs'), + env: { appName: 'Code-XR IDE', appRoot: tmp, appHost: 'desktop', language: 'en', machineId: 'm', sessionId: 's', uriScheme: 'codexr', shell: '/bin/sh', version: '0.0.0' }, + isDevelopment: false, + }; + await main.request(HOST_METHODS.init, init); + }); + + after(async () => { + if (child.exitCode === null) { + child.kill(); + } + }); + + it('activates on onStartupFinished, with its output channel and status bar item', async () => { + await main.request(HOST_METHODS.activateByEvent, '*'); + assert.equal(activations.length, 0, 'nothing listens for *'); + await main.request(HOST_METHODS.activateByEvent, 'onStartupFinished'); + assert.deepEqual(activations.map((event) => `${event.id}:${event.state}`), ['acme.demo:activating', 'acme.demo:active']); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.ok(logs.some((line) => line.channel === 'Demo' && line.message === 'activated in Code-XR IDE')); + const item = notifications.find((notification) => notification.kind === 'statusBarItem'); + assert.ok(item && item.kind === 'statusBarItem'); + assert.equal(item.item.text, '$(check) Demo'); + assert.equal(item.item.alignment, 'right'); + assert.equal(item.item.command, 'demo.greet'); + assert.deepEqual(await main.request(HOST_METHODS.registeredCommands), ['demo.greet', 'demo.workbench', 'demo.missing', 'demo.state', 'demo.update', 'demo.files']); + }); + + it('runs a command for the workbench: a message with buttons, configuration, state, its own require', async () => { + const result = await main.request>(HOST_METHODS.executeCommand, 'demo.greet', ['Ada']); + assert.equal(result['answer'], 'Yes'); + assert.deepEqual(result['uri'], { $uri: 'file:///x/y.txt' }); + assert.equal(result['sameApi'], true, 'require("vscode") gives an extension the same object every time'); + const message = ui.find((request) => request.kind === 'message'); + assert.ok(message && message.kind === 'message'); + assert.equal(message.message, 'Hello Ada!'); + assert.deepEqual(message.items, ['Yes', 'No']); + assert.equal(message.extensionId, 'acme.demo'); + const state = await main.request>(HOST_METHODS.executeCommand, 'demo.state', []); + assert.equal(state['last'], 'Yes'); + // `Uri.fsPath` lower-cases a Windows drive letter, as VS Code's does. + const expectedStorage = path.join(tmp, 'storage', 'global', 'acme.demo'); + assert.equal(process.platform === 'win32' ? String(state['storage']).toLowerCase() : state['storage'], process.platform === 'win32' ? expectedStorage.toLowerCase() : expectedStorage); + }); + + it('writes configuration through the main process and sees the change', async () => { + assert.equal(await main.request(HOST_METHODS.executeCommand, 'demo.update', []), '?'); + assert.deepEqual(configUpdates, [['demo.punctuation', '?', 'user']]); + main.notify(HOST_METHODS.configurationChanged, { 'demo.punctuation': '.' }); + await main.request(HOST_METHODS.executeCommand, 'demo.greet', ['Bo']); + const last = ui.filter((request) => request.kind === 'message').at(-1); + assert.equal(last?.kind === 'message' ? last.message : null, 'Hello Bo.'); + }); + + it('sends unknown commands to the workbench, args on the wire', async () => { + assert.equal(await main.request(HOST_METHODS.executeCommand, 'demo.workbench', []), 'saved'); + assert.deepEqual(workbenchCommands, [['workbench.action.files.save', [1]]]); + }); + + it('reports unimplemented API and keeps the extension running', async () => { + assert.equal(await main.request(HOST_METHODS.executeCommand, 'demo.missing', []), 'function'); + assert.deepEqual(missing, ['window.createWebviewPanel']); + }); + + it('finds and opens workspace files, skipping node_modules', async () => { + const result = await main.request>(HOST_METHODS.executeCommand, 'demo.files', []); + assert.deepEqual(result, { count: 1, language: 'markdown', firstLine: '# Title', rel: 'docs/readme.md' }); + }); + + it('activates dependencies first, by command, and reports a failed activation', async () => { + const check = await main.request>(HOST_METHODS.executeCommand, 'dep.check', []); + assert.deepEqual(check, { active: true, exports: { api: 42 } }); + await main.request(HOST_METHODS.activateByEvent, 'onLanguage:markdown'); + const failed = activations.find((event) => event.id === 'acme.broken' && event.state === 'failed'); + assert.ok(failed); + assert.match(failed.error ?? '', /broken on purpose/); + await assert.rejects(main.request(HOST_METHODS.executeCommand, 'nobody.has.this', []), /not found/); + }); + + it('deactivates the extensions on shutdown and exits', async () => { + const exited = new Promise((resolve) => child.once('exit', (code) => resolve(code))); + await main.request(HOST_METHODS.shutdown); + assert.equal(await exited, 0); + assert.equal(fs.readFileSync(deactivatedMarker, 'utf8'), 'yes'); + const stateFile = path.join(tmp, 'storage', 'global', 'acme.demo', 'state.json'); + assert.deepEqual(JSON.parse(fs.readFileSync(stateFile, 'utf8')), { lastAnswer: 'Yes' }); + }); +}); diff --git a/apps/ide/tsconfig.node.json b/apps/ide/tsconfig.node.json index 837fd7e07..b7bcb450c 100644 --- a/apps/ide/tsconfig.node.json +++ b/apps/ide/tsconfig.node.json @@ -9,5 +9,5 @@ "@codexr/logging/*": ["./.core-types/platform/logging/*"] } }, - "include": ["src/main/**/*.ts", "src/preload/**/*.ts", "src/scenePreload/**/*.ts", "src/shared/**/*.ts", "test/**/*.ts"] + "include": ["src/main/**/*.ts", "src/preload/**/*.ts", "src/scenePreload/**/*.ts", "src/extensionHost/**/*.ts", "src/shared/**/*.ts", "test/**/*.ts"] } diff --git a/docs/ide/extensions.md b/docs/ide/extensions.md index 50e49e023..a656ae210 100644 --- a/docs/ide/extensions.md +++ b/docs/ide/extensions.md @@ -11,7 +11,8 @@ Epic #251. Decision: [ADR 0002](../../adr/0002-vscode-extensions-in-the-ide.md). | Enable, disable, uninstall, disable all | Done | #254, #255 | | Colour themes (JSON, JSON with comments, `include` chains, `.tmTheme`) | Done | #257 | | Languages, `language-configuration.json`, TextMate grammars (with injections and embedded languages), snippets | Done | #258 | -| Extensions with code (commands, messages, output, configuration, documents, diagnostics, language features) | Next | #259, #260 | +| Extensions with code: the extension host, commands in the palette, messages, quick picks and input boxes, progress, status bar items, output channels, configuration, state and secrets, files and `findFiles` | Done | #259 | +| Documents of the editor, diagnostics, language features (completion, hover, definitions...) | Next | #260 | | Tree views, view containers, webviews | Planned | #261 | | The Code-XR extension itself | Planned | #262 | | File icon themes, product icon themes | Not yet: listed in the details page | — | @@ -26,8 +27,13 @@ extensions/extensionsView.ts --IPC--> extensions/extensionsService.ts extensions.json extensions/monacoContributions.ts ├─ vsix.ts (yauzl) .-/ extensions/textmate.ts (+ onig.wasm) ├─ openVsx.ts ---- https ----> Open VSX registry - ├─ contributions.ts (themes, grammars, snippets) - └─ manifest.ts, plist.ts (pure) +extensions/hostBridge.ts <--IPC--> ├─ contributions.ts (themes, grammars, snippets, commands) + ├─ manifest.ts, plist.ts (pure) + └─ extensionHostManager.ts settings.json, secrets.json, + │ fork, Node IPC .storage/, .logs/, machine-id + v + extension host process (one per window) + src/extensionHost/: host.ts, api.ts (the `vscode` module), types.ts ``` - **Contract:** `src/shared/extensions.ts` (`ExtensionsApi`, `EXTENSION_IPC_CHANNELS`, the types), exposed as `window.codexr.extensions`. @@ -46,11 +52,23 @@ The main process reads the files the manifest names, always through `resolveInEx - **TextMate grammars.** `vscode-textmate` with the Oniguruma engine as WebAssembly (`vscode-oniguruma`, `onig.wasm` served by the app). A grammar loads when Monaco first meets its language. Injections (`injectTo`) and embedded languages are passed through. Tokens carry their innermost scope, which theme rules match by prefix. Lines over 20,000 characters are not tokenized and a line gives up after 500 ms, as in VS Code. An extension's grammar replaces Monaco's own tokenizer for that language. - **Snippets.** A completion provider per language with the snippets (`prefix`, `body`, `description`, `scope`), inserted as Monaco snippets. +## The extension host (#259) + +- **Process.** `ExtensionHostManager` forks `out/extensionHost/index.cjs` with Electron's own Node (`ELECTRON_RUN_AS_NODE`, so no Node is needed on the machine), one per window, once the workbench says it is ready. It restarts the host when the installed extensions, the folder or its trust change, after a crash (three times in five minutes, then it asks), and from *Developer: Restart Extension Host*. Closing the window calls every `deactivate()` (3 s at most) before the process ends. +- **Protocol.** `src/shared/extensionHostProtocol.ts`: a small request/response RPC over Node's IPC channel with structured cloning. `Uri`, `Position` and `Range` cross it as tagged objects (`extensionHost/wire.ts`). +- **`require('vscode')`.** The host hooks Node's module loader: an extension asking for `vscode` gets an API object made for it (`api.ts`), so every call knows who made it. Unimplemented API never throws: namespaces fall back to inert stand-ins (`inert.ts`) and the *Extensions* output channel says once per extension which API it missed (`[acme.x] uses vscode.window.createWebviewPanel, which the Code-XR IDE does not implement yet`). +- **Activation.** Declared events plus the implicit ones (`onCommand:` for contributed commands, `onView:`, `onLanguage:`). Fired by the main process (`*`, `workspaceContains:`, `onStartupFinished`), by the renderer (`onLanguage:` as files open; only workbench events are accepted from it) and by running a command. Dependencies (`extensionDependencies`) activate first; a failed activation shows in the Extensions view with its error. +- **What extensions can use now.** `commands` (register, execute, the IDE's commands under their VS Code ids such as `workbench.action.files.save`, `setContext`, `vscode.open`), `window` (information/warning/error messages with buttons, modal ones as native dialogs, `showQuickPick`, `showInputBox`, `createQuickPick`, `createInputBox`, open/save dialogs, `withProgress`, status bar items, `setStatusBarMessage`, output channels including log channels, `showTextDocument` for files of the folder), `workspace` (folder, `getConfiguration` with defaults from `contributes.configuration`, `onDidChangeConfiguration`, `fs`, `findFiles`, `openTextDocument` from disk, `createFileSystemWatcher`, text document content providers, trust), `env` (clipboard, `openExternal` for http/https/mailto, a random `machineId`, telemetry always off), `extensions`, `l10n` and `ExtensionContext` (`globalState`, `workspaceState`, `secrets` in the OS store, storage and log folders). Classes and enums of the API (`Range`, `Uri`, `Diagnostic`, `CompletionItem`, `TreeItem`...) behave like VS Code's. +- **Extension settings** live in `/extensions/settings.json` (JSON with comments, editable by hand), apart from the IDE's own settings, whose schema only knows the IDE's keys. +- **Palette.** Each enabled extension's `contributes.commands` appear in the palette (*Category: Title*), except those `menus.commandPalette` hides with `"when": "false"`. `when` clauses and `contributes.keybindings` are not applied yet. + ## Security - CSP: `script-src 'self' 'wasm-unsafe-eval'` (WebAssembly only; `eval` and `new Function` stay blocked, which the smoke run checks). - Nothing an extension declares runs in the renderer: themes and grammars are data; snippets are text. -- Extensions with code will run in a separate extension host process (#259), activated only in trusted folders unless they declare support for Restricted Mode (#263). +- Extensions with code run in the extension host process, never in the renderer or the main process. They have the rights of the person's account, as in VS Code: install only extensions you trust. In a folder in Restricted Mode only the extensions that declare `capabilities.untrustedWorkspaces.supported` run (#263 finishes that story). +- What the host asks of the main process is checked there: files open only inside the folder, external links only for http, https and mailto, settings keys are bounded, secrets are encrypted by the OS store (`safeStorage`) and kept per extension. +- No telemetry: `env.isTelemetryEnabled` is false and `createTelemetryLogger` sends nothing. ## How to try it @@ -59,5 +77,8 @@ The main process reads the files the manifest names, always through `resolveInEx 3. *Preferences: Color Theme* and pick the new theme; the editor and the workbench change colour. 4. Install a language extension (for example `tamasfe.even-better-toml` for the grammar, or a `.vsix` of VS Code's built-in `ini`/`swift` extensions), open a file of it: the status bar names the language and the file is highlighted. 5. Disable or uninstall from the row; the theme falls back to the OS one. +6. Extensions with code: trust the folder, install an extension with commands (for example a `.vsix` of one of Microsoft's [extension samples](https://github.com/microsoft/vscode-extension-samples), or anything from Open VSX), then run its commands from the palette (F1). Messages, pickers, progress and status bar items appear in the workbench; *View: Output* > *Extensions* shows what each extension logs and the API it is missing. + +The unit tests are `apps/ide/test/extensions.test.ts` (manifest, VSIX reader with zip-slip and symlink archives, store, contributions, Open VSX client against a fake registry), `apps/ide/test/extensionsRenderer.test.ts` (theme conversion, language configuration, the view model) and `apps/ide/test/extensionHost.test.ts` (the RPC, the API's values, configuration, documents, and a real host process running three test extensions: activation by event, by command and through dependencies, a failed activation, messages, configuration writes, state on disk, workbench commands, missing API, `findFiles`, `deactivate`). -The unit tests are `apps/ide/test/extensions.test.ts` (manifest, VSIX reader with zip-slip and symlink archives, store, contributions, Open VSX client against a fake registry) and `apps/ide/test/extensionsRenderer.test.ts` (theme conversion, language configuration, the view model). +Checked in the real IDE (Electron under xvfb) with five of Microsoft's extension samples compiled from source: *helloworld-minimal* (palette command and message), *progress* (`*` activation, progress notification), *statusbar* (status bar item), *configuration* (two quick picks, then `getConfiguration().update`) and *quickinput* (`showQuickPick` and its follow-up messages).