|
| 1 | +import type { CompletionItemKind, CompletionList, LanguageServicePlugin, LanguageServicePluginInstance } from '@volar/language-service' |
| 2 | +import type { IWorkspaceState } from '../types' |
| 3 | +import { isDependencyFile } from 'npmx-language-core/utils' |
| 4 | +import { URI } from 'vscode-uri' |
| 5 | +import { getConfig } from '../config' |
| 6 | +import { getResolvedDependencyAtOffset } from '../utils/range' |
| 7 | +import { formatUpgradeVersion } from '../utils/version' |
| 8 | + |
| 9 | +const PRERELEASE_PATTERN = /-.+/ |
| 10 | + |
| 11 | +export function create(workspaceState: IWorkspaceState): LanguageServicePlugin { |
| 12 | + return { |
| 13 | + name: 'npmx-version-completion', |
| 14 | + capabilities: { |
| 15 | + completionProvider: { |
| 16 | + triggerCharacters: [':', '^', '~', '.'], |
| 17 | + }, |
| 18 | + }, |
| 19 | + create(context): LanguageServicePluginInstance { |
| 20 | + return { |
| 21 | + async provideCompletionItems(document, position): Promise<CompletionList | undefined> { |
| 22 | + const completionVersion = await getConfig(context, 'npmx.completion.version') |
| 23 | + if (completionVersion === 'off') |
| 24 | + return |
| 25 | + |
| 26 | + const uri = URI.parse(document.uri) |
| 27 | + if (uri.scheme !== 'file' || !isDependencyFile(uri.path)) |
| 28 | + return |
| 29 | + |
| 30 | + const dependencies = await workspaceState.getResolvedDependencies(document.uri) |
| 31 | + if (!dependencies) |
| 32 | + return |
| 33 | + |
| 34 | + const offset = document.offsetAt(position) |
| 35 | + const dep = getResolvedDependencyAtOffset(dependencies, offset) |
| 36 | + if (!dep || dep.resolvedProtocol !== 'npm') |
| 37 | + return |
| 38 | + |
| 39 | + const pkg = await dep.packageInfo() |
| 40 | + if (!pkg) |
| 41 | + return |
| 42 | + |
| 43 | + const excludePrerelease = await getConfig(context, 'npmx.completion.excludePrerelease') |
| 44 | + const items: CompletionList['items'] = [] |
| 45 | + |
| 46 | + for (const version in pkg.versionsMeta) { |
| 47 | + const meta = pkg.versionsMeta[version]! |
| 48 | + |
| 49 | + if (meta.deprecated != null) |
| 50 | + continue |
| 51 | + |
| 52 | + if (excludePrerelease && PRERELEASE_PATTERN.test(version)) |
| 53 | + continue |
| 54 | + |
| 55 | + if (completionVersion === 'provenance-only' && !meta.provenance) |
| 56 | + continue |
| 57 | + |
| 58 | + const text = formatUpgradeVersion(dep, version) |
| 59 | + |
| 60 | + const tag = pkg.versionToTag.get(version) |
| 61 | + |
| 62 | + items.push({ |
| 63 | + label: text, |
| 64 | + kind: 12 satisfies typeof CompletionItemKind.Value, |
| 65 | + insertText: text, |
| 66 | + detail: tag, |
| 67 | + }) |
| 68 | + } |
| 69 | + |
| 70 | + return { isIncomplete: false, items } |
| 71 | + }, |
| 72 | + } |
| 73 | + }, |
| 74 | + } |
| 75 | +} |
0 commit comments