From b030e54791917cad857434977fae32d737b2897b Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 9 Nov 2026 23:01:46 -0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(manifest):=20=E7=A7=BB=E9=99=A4=20langu?= =?UTF-8?q?ageImport=EF=BC=8C=E6=94=B9=E7=94=B1=E6=8F=92=E4=BB=B6=E5=87=BD?= =?UTF-8?q?=E6=95=B0=20languageImport.settings=20=E6=8F=90=E4=BE=9B=20Java?= =?UTF-8?q?=20=E5=AF=BC=E5=85=A5=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 2 + NOTICE | 4 + README.md | 23 +- .../backend/main.mjs | 7 + .../backend/settings.mjs | 85 ++ .../backend/vendor/lithe-plugin-sdk/LICENSE | 203 +++ .../vendor/lithe-plugin-sdk/backend.mjs | 1085 +++++++++++++++++ .../vendor/lithe-plugin-sdk/diagnostics.mjs | 34 + .../vendor/lithe-plugin-sdk/errors.mjs | 101 ++ .../vendor/lithe-plugin-sdk/framing.mjs | 74 ++ .../backend/vendor/lithe-plugin-sdk/host.mjs | 447 +++++++ .../vendor/lithe-plugin-sdk/index.d.ts | 714 +++++++++++ .../backend/vendor/lithe-plugin-sdk/index.mjs | 8 + .../vendor/lithe-plugin-sdk/process.mjs | 188 +++ .../vendor/lithe-plugin-sdk/protocol.mjs | 293 +++++ .../backend/vendor/lithe-plugin-sdk/state.mjs | 148 +++ io.github.lithe-idea.gradle-build/plugin.json | 15 +- sdk.lock.json | 65 + test/settings.test.mjs | 62 + 19 files changed, 3550 insertions(+), 8 deletions(-) create mode 100644 io.github.lithe-idea.gradle-build/backend/main.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/settings.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/LICENSE create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs create mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs create mode 100644 sdk.lock.json create mode 100644 test/settings.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 31a3cdf..9b090e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,6 +28,8 @@ jobs: java-version: 17 - name: Check manifest and build the archive run: node scripts/package.mjs + - name: Test the settings backend + run: node --test test/settings.test.mjs - name: Download Gradle ${{ matrix.gradle }} env: VERSION: ${{ matrix.gradle }} diff --git a/NOTICE b/NOTICE index 1a58410..7731bc5 100644 --- a/NOTICE +++ b/NOTICE @@ -12,5 +12,9 @@ Version 2.0, at revision 158b854d47ac9af2bbd99c0d7c354a5875cb6f81: Copyright 2000-2023 JetBrains s.r.o. and contributors. +The official Node.js SDK in io.github.lithe-idea.gradle-build/backend/vendor/ +lithe-plugin-sdk/ comes from Lithe-IDEA/lithe-plugin-docs at the revision pinned +in sdk.lock.json, licensed under the Apache License, Version 2.0. + Gradle is a trademark of Gradle, Inc. This plugin is not affiliated with or endorsed by Gradle, Inc. diff --git a/README.md b/README.md index a725487..79f3b2a 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ IntelliJ IDEA 一样按项目列出任务分组和依赖配置,运行任务、应用和测试。 这是一个**社区插件**,用 Lithe 的声明式构建系统接口(插件 API 3 的 `buildSystems`)实现, 只带一个 Gradle 初始化脚本,没有任何宿主代码。工具窗口由 macOS 宿主用 SwiftUI 原生渲染,插件不提供 Web 入口; -`languageImport` 把 Offline 和 Gradle User Home 选项传给 Java 语言服务器的 Gradle 导入。 +插件另带一个很小的 Node 后端,向 Java Support 提供 Gradle 的导入设置(见下文“Java 语言服务器的导入设置”)。 > English: Gradle support for Lithe through the declarative `buildSystems` plugin API — projects with their tasks by > group, JavaExec tasks as run entries, test runs with JUnit reports, compiler diagnostics and per-configuration @@ -33,6 +33,22 @@ IntelliJ IDEA 一样按项目列出任务分组和依赖配置,运行任务、 以及 GroupId 和 ArtifactId。模板在 `io.github.lithe-idea.gradle-build/templates/java/`,从 Java Support 插件移来, 生成的文件与原来相同。条目要求 `java` 语言和 `gradle` 构建系统同时可用,所以生成的项目需要安装 Java Support 插件提供 Java 语言支持。 +## Java 语言服务器的导入设置 + +旧版清单里的 `buildSystems[].languageImport` 已从插件契约删除。现在 Gradle 插件导出插件函数 `languageImport.settings` +(版本 1,`context: "workspace"`),Java Support 在启动 JDT LS 前调用它,只接受 `java.import.gradle.` 等白名单前缀内的键。 +后端只读取工作区里的文件,不运行 Gradle、不写任何文件: + +| 来源 | 导出的键 | +| --- | --- | +| 环境变量 `GRADLE_USER_HOME`(绝对路径) | `java.import.gradle.user.home` | +| `gradle.properties` 的 `org.gradle.java.home`(绝对路径) | `java.import.gradle.java.home` | +| `gradle.properties` 的 `org.gradle.jvmargs` | `java.import.gradle.jvmArguments` | + +`gradle.properties` 先读 Gradle User Home 里的,再读项目根的,项目根优先。`workspaceRoot` 必须落在已打开的本地工作区文件夹内, +否则函数拒绝(`gradle.invalidRoot`)。工具栏的 Offline 与 Gradle User Home 选项只保存在宿主里,插件后端读不到, +所以它们不再传给 JDT LS,需要宿主把已存选项交给插件函数后才能恢复。后端需要 Node.js 20.3 或更新版本。 + ## 依赖的程序 插件不带 Gradle,使用你项目或电脑上的 Gradle,按以下顺序查找: @@ -59,7 +75,7 @@ IntelliJ IDEA 一样按项目列出任务分组和依赖配置,运行任务、 ## 安装 -`v0.1.1` 修复重复运行测试时报告显示为零的问题,需要兼容 `buildSystems` 插件 API 3 的 Lithe preview 开发版。 +`v0.1.2` 移除宿主已删除的 `languageImport` 字段并改用插件函数提供导入设置;`v0.1.1` 修复重复运行测试时报告显示为零的问题。均需要兼容 `buildSystems` 插件 API 3 的 Lithe preview 开发版。 Lithe Store 条目合并后,可在 **设置 → 插件 → 插件市场** 搜索 “Gradle”,安装并按提示重启; 条目合并前可下载 Release 的 ZIP,从 Lithe 开发版的 **⚙ → 从磁盘安装插件…** 安装。 Lithe 已预置 Lithe Store 社区插件源;如果你之前移除了它,先在 **⚙ → 管理插件仓库…** 中重新添加 @@ -72,6 +88,7 @@ Lithe 已预置 Lithe Store 社区插件源;如果你之前移除了它,先 ```text io.github.lithe-idea.gradle-build/plugin.json # 插件描述,目录名必须等于插件 id io.github.lithe-idea.gradle-build/lithe.init.gradle # 初始化脚本,导出模型和依赖树 +io.github.lithe-idea.gradle-build/backend/ # languageImport.settings 后端(Node)和固定版本的官方 SDK(sdk.lock.json) io.github.lithe-idea.gradle-build/icons/ # 工具窗口和工具栏图标(来源见 NOTICE) io.github.lithe-idea.gradle-build/templates/java/ # New Project 的 Gradle Java 项目模板(Kotlin/Groovy DSL、示例代码) test/fixtures/multi/ # 两个子项目的示例构建,供集成测试使用 @@ -105,7 +122,7 @@ GRADLE=/path/to/gradle node scripts/test.mjs ## 诊断日志 -此插件只声明 Gradle 命令及模型导出脚本,没有独立的常驻后端或日志 writer。 +此插件的 Gradle 命令及模型导出脚本由宿主执行,后端只在 Java Support 调用 `languageImport.settings` 时启动,用官方 SDK 自动记录该函数的结构化操作事实(不含路径和属性值)。 启用结构化日志 v2 的 Lithe macOS preview 由宿主将构建、运行与测试的进程终态、退出码和耗时 记录到当前会话的 `run` 通道;Gradle 的编译输出和测试报告继续留在 Build Output 与测试界面。 模型与依赖树 JSON 是工作流数据,不是日志,仍通过宿主提供的临时输出文件返回。 diff --git a/io.github.lithe-idea.gradle-build/backend/main.mjs b/io.github.lithe-idea.gradle-build/backend/main.mjs new file mode 100644 index 0000000..4edf8ed --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/main.mjs @@ -0,0 +1,7 @@ +// Gradle plugin backend: serves `languageImport.settings` to the Java plugin. +import { createBackend, PluginError } from './vendor/lithe-plugin-sdk/index.mjs'; +import { registerSettingsFunction } from './settings.mjs'; + +const backend = createBackend({ name: 'gradle-build', version: '0.1.2' }); +registerSettingsFunction(backend, PluginError); +await backend.listen(); diff --git a/io.github.lithe-idea.gradle-build/backend/settings.mjs b/io.github.lithe-idea.gradle-build/backend/settings.mjs new file mode 100644 index 0000000..5a837ca --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/settings.mjs @@ -0,0 +1,85 @@ +// `languageImport.settings` of the Gradle plugin: the JDT LS import settings +// that Gradle's own configuration files imply. Nothing here runs Gradle, +// writes a file or reads a path outside the workspace and the user's Gradle +// home. Ownership and lifecycle: README.md ("Java 语言服务器的导入设置"). +import { readFile, realpath } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { isAbsolute, join, relative, resolve, sep } from 'node:path'; + +const MAX_PROPERTIES_BYTES = 256 * 1024; + +const inside = (root, path) => { + const value = relative(root, path); + return value === '' || (!isAbsolute(value) && value !== '..' && !value.startsWith(`..${sep}`)); +}; + +/** Reads `key=value` pairs of a Java properties file; later lines win. */ +export function parseProperties(text) { + const result = {}; + for (const raw of text.replace(/\\\r?\n\s*/g, '').split(/\r?\n/)) { + const line = raw.trimStart(); + if (line === '' || line.startsWith('#') || line.startsWith('!')) continue; + const match = /^((?:\\.|[^\s:=\\])+)\s*[:=]?\s*(.*)$/.exec(line); + if (!match) continue; + const unescape = (value) => value.replace(/\\(.)/g, '$1'); + result[unescape(match[1])] = unescape(match[2].trimEnd()); + } + return result; +} + +async function properties(path) { + try { + const text = await readFile(path, 'utf8'); + return text.length > MAX_PROPERTIES_BYTES ? {} : parseProperties(text); + } catch { + return {}; + } +} + +/** The Gradle user home as Gradle resolves it without a command line. */ +export function gradleUserHome(environment) { + const value = environment.GRADLE_USER_HOME; + return typeof value === 'string' && isAbsolute(value) ? value : join(homedir(), '.gradle'); +} + +/** + * Settings for the Gradle build at `root`. `gradle.properties` of the project + * wins over the one in the Gradle user home, as in Gradle itself. + */ +export async function settingsFor(root, environment = process.env) { + const home = gradleUserHome(environment); + const merged = { ...(await properties(join(home, 'gradle.properties'))), ...(await properties(join(root, 'gradle.properties'))) }; + const settings = {}; + if (typeof environment.GRADLE_USER_HOME === 'string' && isAbsolute(environment.GRADLE_USER_HOME)) { + settings['java.import.gradle.user.home'] = home; + } + const javaHome = merged['org.gradle.java.home']; + if (javaHome && isAbsolute(javaHome)) settings['java.import.gradle.java.home'] = javaHome; + const jvmArguments = merged['org.gradle.jvmargs']; + if (jvmArguments) settings['java.import.gradle.jvmArguments'] = jvmArguments; + return { settings }; +} + +/** The function handler: only roots inside an open local workspace are read. */ +export function registerSettingsFunction(backend, PluginError, environment = process.env) { + backend.function('languageImport.settings', async (params, context) => { + context.throwIfCancelled(); + const requested = params?.workspaceRoot; + if (typeof requested !== 'string' || !isAbsolute(requested)) { + throw new PluginError('gradle.invalidRoot', 'workspaceRoot must be an absolute path.'); + } + if (!context.workspaceContext) throw new PluginError('gradle.noWorkspaceContext', 'The call carries no workspace context.'); + let root; + try { + root = await realpath(resolve(requested)); + const { folders = [] } = await context.host.workspace.getFolders(context.workspaceContext); + const allowed = []; + for (const folder of folders) if (typeof folder.path === 'string') allowed.push(await realpath(folder.path).catch(() => null)); + if (!allowed.some((folder) => folder && inside(folder, root))) throw new Error('outside'); + } catch { + throw new PluginError('gradle.invalidRoot', 'workspaceRoot is not inside an open workspace folder.'); + } + context.throwIfCancelled(); + return settingsFor(root, environment); + }); +} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/LICENSE b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/LICENSE new file mode 100644 index 0000000..69bef1d --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/LICENSE @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and + for which the editorial revisions, annotations, elaborations, + or other modifications represent, as a whole, an original work + of authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely link + (or bind by name) to the interfaces of, the Work and Derivative Works + thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of + its distribution, then any Derivative Works that You + distribute must include a readable copy of the attribution + notices contained within such NOTICE file, excluding those + notices that do not pertain to any part of the Derivative + Works, in at least one of the following places: within a + NOTICE text file distributed as part of the Derivative Works; + within the Source form or documentation, if provided along with + the Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing + the origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as + a result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[ ]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs new file mode 100644 index 0000000..2bf9490 --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs @@ -0,0 +1,1085 @@ +// The plugin backend session: one process the host starts from the plugin's +// manifest and talks to over stdio with the LSP base protocol. The SDK owns +// everything Lithe manages uniformly -- the lifecycle, protocol negotiation, +// cancellation, error codes, and the `lithe/*` namespace -- and leaves the +// plugin free to decide what its handlers do. +// +// Contracts: contract/v1/README.md ("Build providers", "Plugin functions", +// "Host services" and "VCS providers"), and Lithe's +// shared/contracts/vcs-provider-v1.md. + +import { format } from 'node:util'; +import { performance } from 'node:perf_hooks'; +import { diagnostics, KNOWN_OPERATIONS, requestOperationId } from './diagnostics.mjs'; +import { encodeFrame, FrameDecoder, FramingError, MALFORMED } from './framing.mjs'; +import { HostError, PluginError, PluginSdkError, toResponseError } from './errors.mjs'; +import { createHost, HostChannel } from './host.mjs'; +import { killAllProcesses, runProcess } from './process.mjs'; +import { + BUILD_VERSION, + BUILD_METHOD_VERSIONS, + boundedText, + ERROR_CODES, + FUNCTIONS_VERSION, + HOST_NOTIFICATIONS, + isContextReference, + isFunctionId, + isReservedMethod, + isVcsId, + LIMITS, + METHODS, + RELAY_VERSION, + VCS_OPERATIONS, + VCS_REQUIRED_OPERATIONS, + VCS_VERSION, +} from './protocol.mjs'; + +/** Canonical result format of each typed build request. */ +const BUILD_FORMATS = Object.freeze({ + [METHODS.buildModel]: 'litheBuildModel', + [METHODS.buildDependencies]: 'litheDependencies', + [METHODS.buildDiscoverTests]: 'litheTestDiscovery', +}); + +/** Host notifications the SDK routes itself; see `onCommand`, `onContextsChanged`, and `host.subscribe`. */ +const ROUTED_NOTIFICATIONS = Object.freeze(Object.values(HOST_NOTIFICATIONS)); + +/** VCS capabilities that describe the VCS rather than a request it answers. */ +const VCS_TRAITS = Object.freeze(['push', 'staging']); + +/** + * Creates a backend. Declare handlers, then call `listen()`. + * + * @param {object} [options] + * @param {string} [options.name] Reported as `serverInfo.name` and used as the log prefix. + * @param {string} [options.version] Reported as `serverInfo.version`. + * @param {object} [options.capabilities] Standard LSP server capabilities, for a + * backend that is also a language server. `experimental.litheBuild`, + * `experimental.litheFunctions`, `experimental.litheVcs`, and `experimental.litheKeymapImport` are negotiated by + * the SDK and cannot be set here. + */ +export function createBackend(options = {}) { + return new Backend(options); +} + +class Backend { + #logging = false; + #loggingReady = false; + #earlyDiagnostics = []; + #quietSuccess = new Set(); + #name; + #version; + #capabilities; + #functions = new Map(); + #keymapProviders = new Map(); + #selectedKeymapProviders = new Set(); + #buildHandlers = new Map(); + #buildVersion = null; + #functionsVersion = null; + /** The declared VCS provider: `{ id, handlers: Map, capabilities }`. */ + #vcs = null; + #requestHandlers = new Map(); + #notificationHandlers = new Map(); + #commandHandlers = new Map(); + #contextsHandler = null; + #hostNotificationHandlers = new Map(); + #channel; + #initializeHooks = []; + #shutdownHooks = []; + /** `idle` → `listening` → `initializing` → `ready` → `shuttingDown` → `exited`. */ + #phase = 'idle'; + #negotiated = Object.freeze({ functions: false, build: false, vcs: false }); + #initializeParams = null; + /** Host requests being handled, by JSON-RPC ID. */ + #incoming = new Map(); + /** Requests this backend sent to the host, by JSON-RPC ID. */ + #outgoing = new Map(); + #nextRequestId = 1; + /** Serializes register/unregister so the host sees them in call order. */ + #registrations = Promise.resolve(); + #output = null; + #errorOutput = process.stderr; + #finish = null; + + /** Typed build-provider handlers (`lithe/build/*`). */ + build; + + /** + * Host services (`lithe/host/*`) of plugin-function protocols 2 to 4, + * usable once the session is ready. A handler's `context.host` is the + * same object bound to its call. + */ + host; + + constructor({ name = 'lithe-plugin-backend', version, capabilities = {} } = {}) { + const experimental = capabilities.experimental ?? {}; + if ('litheLogging' in experimental || 'litheBuild' in experimental || 'litheFunctions' in experimental || 'litheVcs' in experimental || 'litheKeymapImport' in experimental) { + throw new PluginSdkError( + 'sdk.capabilities.reserved', + 'litheLogging, litheBuild, litheFunctions, litheVcs, and litheKeymapImport are negotiated by the SDK; declare handlers instead.', + ); + } + this.#name = String(name); + this.#version = version === undefined ? undefined : String(version); + this.#capabilities = capabilities; + this.build = Object.freeze({ + /** Answers `lithe/build/model` with a `litheBuildModel` document. */ + model: (handler) => this.#declareBuild(METHODS.buildModel, handler), + /** Answers `lithe/build/dependencies` with a `litheDependencies` document. */ + dependencies: (handler) => this.#declareBuild(METHODS.buildDependencies, handler), + /** Runs a bounded task in the provider; the host owns its operation. */ + execute: (handler) => this.#declareBuild(METHODS.buildExecute, handler), + test: (handler) => this.#declareBuild(METHODS.buildTest, handler), + discoverTests: (handler) => this.#declareBuild(METHODS.buildDiscoverTests, handler), + /** Prepares a plan; the application itself belongs to the host. */ + prepareRun: (handler) => this.#declareBuild(METHODS.buildPrepareRun, handler), + prepareDebug: (handler) => this.#declareBuild(METHODS.buildPrepareDebug, handler), + }); + this.#channel = new HostChannel({ + version: () => this.#functionsVersion ?? 0, + ready: () => this.#phase === 'ready', + send: (method, params) => this.#send(method, params), + notify: (method, params) => this.#write({ jsonrpc: '2.0', method, params }), + log: () => this.#diagnostics().degraded('notification', 'event_handler_failed'), + }); + this.host = createHost(this.#channel); + } + + /** Protocols the host agreed to in `initialize`; all false before it. */ + get negotiated() { + return this.#negotiated; + } + + /** Selected build protocol version, or null when unavailable. */ + get buildVersion() { return this.#buildVersion; } + + /** Selected plugin-function protocol version (1-4), or null when unavailable. */ + get functionsVersion() { return this.#functionsVersion; } + + /** The host's `initialize` params, or null before it arrives. */ + get initializeParams() { + return this.#initializeParams; + } + + /** IDs of the functions this backend currently serves, sorted. */ + get functionIDs() { + return [...this.#functions.keys()].sort(); + } + + /** + * Declares a plugin function offered from the start, in the `initialize` + * answer. To add one later, use `registerFunction`. + * + * @param {string} id Dot-separated lowerCamelCase segments, such as `snapshot.refresh`. + * @param {(params: object, context: object) => unknown} handler + */ + function(id, handler) { + if (!this.#beforeAnswer()) { + throw new PluginSdkError('sdk.function.lateDeclaration', 'After initialize, add functions with registerFunction().'); + } + this.#checkNewFunction(id, handler); + this.#functions.set(id, handler); + return this; + } + + /** Declares an independent typed shortcut import provider. */ + keymapImportProvider(id, handler) { + if (!this.#beforeAnswer() || !validKeymapProvider(id) || typeof handler !== 'function' + || this.#keymapProviders.has(id) || this.#keymapProviders.size >= 8) { + throw new PluginSdkError('sdk.keymap.invalidRegistration', 'Invalid or duplicate shortcut import provider.'); + } + this.#keymapProviders.set(id, handler); + return this; + } + + /** + * Declares the VCS this backend provides and the operations it answers, + * before `listen()`. Each handler gets the operation's arguments plus + * `root: { path }` and `tool: { executable } | null`, and returns the reply + * object of shared/contracts/vcs-provider-v1.md. Declaring a handler + * negotiates its capability; `status`, `baseContent`, `checkin`, and + * `rollback` are required. + * + * @param {string} id The VCS ID of the manifest's `vcsProviders` entry, such as `svn`. + * @param {Record} handlers Keyed by operation name. + * @param {object} [traits] + * @param {boolean} [traits.push] Check-in is local and publishing is a separate step. + * @param {boolean} [traits.staging] Changes carry a staged/unstaged dimension. + */ + vcs(id, handlers, traits = {}) { + if (this.#phase !== 'idle') { + throw new PluginSdkError('sdk.vcs.lateDeclaration', 'Declare the VCS provider before listen().'); + } + if (this.#vcs) throw new PluginSdkError('sdk.vcs.duplicate', 'A backend provides one VCS.'); + if (!isVcsId(id)) { + throw new PluginSdkError( + 'sdk.vcs.invalidID', + `VCS ID ${JSON.stringify(id)} must be lowercase letters, digits, and "-", start with a letter, and be at most ${LIMITS.maxVcsIdBytes} bytes.`, + ); + } + if (id === 'git') throw new PluginSdkError('sdk.vcs.reserved', 'git is provided by Lithe.'); + const methods = new Map(); + const capabilities = {}; + for (const [operation, handler] of Object.entries(handlers ?? {})) { + const declared = VCS_OPERATIONS[operation]; + if (!declared) throw new PluginSdkError('sdk.vcs.unknownOperation', `${operation} is not a VCS operation.`); + if (typeof handler !== 'function') throw new TypeError(`The ${operation} handler must be a function.`); + methods.set(declared.method, handler); + capabilities[declared.capability] = VCS_VERSION; + } + const missing = VCS_REQUIRED_OPERATIONS.filter((operation) => !methods.has(VCS_OPERATIONS[operation].method)); + if (missing.length > 0) { + throw new PluginSdkError('sdk.vcs.missingOperation', `A VCS provider must answer ${missing.join(', ')}.`); + } + for (const [trait, enabled] of Object.entries(traits)) { + if (!VCS_TRAITS.includes(trait)) throw new PluginSdkError('sdk.vcs.unknownTrait', `${trait} is not a VCS trait.`); + if (enabled) capabilities[trait] = VCS_VERSION; + } + this.#vcs = { id, methods, capabilities: sortedKeys(capabilities) }; + return this; + } + + /** Handles a standard LSP request, for a backend that is also a language server. */ + onRequest(method, handler) { + this.#declareHandler(this.#requestHandlers, method, handler); + return this; + } + + /** Handles a standard LSP notification. */ + onNotification(method, handler) { + this.#declareHandler(this.#notificationHandlers, method, handler); + return this; + } + + /** + * Handles `lithe/host/commands/didRun` for one of the plugin's commands + * (protocol 3). The handler gets `{ commandID, workspaceContext }`, the + * context of the window it ran in or null. It is an event: the host waits + * for no result. + */ + onCommand(commandID, handler) { + if (typeof commandID !== 'string' || !/^[a-z0-9.-]{1,128}$/.test(commandID)) { + throw new PluginSdkError('sdk.command.invalidID', `Command ID ${JSON.stringify(commandID)} must be 1-128 of [a-z0-9.-].`); + } + if (typeof handler !== 'function') throw new TypeError('A command handler must be a function.'); + this.#commandHandlers.set(commandID, handler); + return this; + } + + /** + * Handles `lithe/host/workspace/didChangeContexts` (protocol 3) with + * `{ revision }`; call `host.workspace.listContexts()` for the contexts. + */ + onContextsChanged(handler) { + if (typeof handler !== 'function') throw new TypeError('A handler must be a function.'); + this.#contextsHandler = handler; + return this; + } + + /** + * Handles a `lithe/host/*` notification a later host adds. Commands, + * context changes, and subscription events have their own APIs. + */ + onHostNotification(method, handler) { + if (typeof method !== 'string' || !method.startsWith('lithe/host/')) { + throw new PluginSdkError('sdk.method.invalid', `${method} is not a host notification.`); + } + if (ROUTED_NOTIFICATIONS.includes(method)) { + throw new PluginSdkError('sdk.method.reserved', `${method} is routed by the SDK; use onCommand, onContextsChanged, or host.subscribe.`); + } + if (typeof handler !== 'function') throw new TypeError('A handler must be a function.'); + this.#hostNotificationHandlers.set(method, handler); + return this; + } + + /** Runs before the `initialize` answer, with `{ params, negotiated }`. */ + onInitialize(hook) { + this.#initializeHooks.push(hook); + return this; + } + + /** Runs on `shutdown`, after running calls were cancelled. */ + onShutdown(hook) { + this.#shutdownHooks.push(hook); + return this; + } + + /** + * Adds a function. Before the `initialize` answer (including from an + * `onInitialize` hook) it joins the initial list; afterwards the host must + * accept it first. + */ + registerFunction(id, handler) { + if (this.#beforeAnswer()) { + return settle(() => { + this.#checkNewFunction(id, handler); + this.#functions.set(id, handler); + }); + } + return this.#queueRegistration(async () => { + this.#requireFunctions(); + this.#checkNewFunction(id, handler); + // Installed before the request: the host may invoke it as soon as its + // registry changed, before this backend reads the reply. + this.#functions.set(id, handler); + try { + await this.#request(METHODS.functionRegister, { functions: [{ id }] }); + } catch (error) { + this.#functions.delete(id); + this.#quietSuccess.delete(id); + throw error; + } + }); + } + + /** Withdraws a function. The host ends its running calls as revoked. */ + unregisterFunction(id) { + if (this.#beforeAnswer()) { + return settle(() => { + if (!this.#functions.delete(id)) { + throw new PluginSdkError('sdk.function.unknown', `Function ${id} is not registered.`); + } + this.#quietSuccess.delete(id); + }); + } + return this.#queueRegistration(async () => { + this.#requireFunctions(); + if (!this.#functions.has(id)) { + throw new PluginSdkError('sdk.function.unknown', `Function ${id} is not registered.`); + } + await this.#request(METHODS.functionUnregister, { ids: [id] }); + this.#functions.delete(id); + this.#quietSuccess.delete(id); + for (const call of this.#incoming.values()) { + if (call.functionID === id) call.controller.abort(); + } + }); + } + + /** Sends a standard LSP request to the host. `lithe/*` methods are reserved. */ + sendRequest(method, params) { + this.#checkOutgoing(method); + return this.#request(method, params); + } + + /** Sends a standard LSP notification to the host. `lithe/*` methods are reserved. */ + sendNotification(method, params) { + this.#checkOutgoing(method); + this.#write({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) }); + } + + get diagnostics() { return this.#diagnostics(); } + + suppressSuccessDiagnostics(operation) { + if (!KNOWN_OPERATIONS.has(operation) && !this.#functions.has(operation)) throw new PluginSdkError('sdk.logging.invalidOperation', 'Suppress a registered operation.'); + this.#quietSuccess.add(operation); + return this; + } + + #diagnostics(operationId) { + return diagnostics((params) => { + if (!this.#logging) return; + if (!this.#loggingReady) { if (this.#earlyDiagnostics.length < 8) this.#earlyDiagnostics.push(params); return; } + this.#write({ jsonrpc: '2.0', method: 'lithe/log', params }); + }, (id) => this.#functions.has(id), operationId); + } + + /** + * Serves the host until it sends `exit` or closes the input stream, and + * resolves with the process exit code. With the default `exit`, the process + * then exits with that code. + * + * @param {object} [io] + * @param {NodeJS.ReadableStream} [io.input] Defaults to stdin. + * @param {NodeJS.WritableStream} [io.output] Defaults to stdout. + * @param {NodeJS.WritableStream} [io.errorOutput] Defaults to stderr. + * @param {((code: number) => void) | null} [io.exit] Defaults to `process.exit`; null only resolves. + */ + listen({ input = process.stdin, output = process.stdout, errorOutput = process.stderr, exit = (code) => process.exit(code) } = {}) { + if (this.#phase !== 'idle') { + throw new PluginSdkError('sdk.listen.repeated', 'A backend listens once.'); + } + this.#phase = 'listening'; + this.#output = output; + this.#errorOutput = errorOutput; + if (output === process.stdout) redirectConsole(errorOutput); + + return new Promise((resolve) => { + this.#finish = (code) => { + if (this.#phase === 'exited') return; + this.#phase = 'exited'; + this.#abortAll(); + killAllProcesses(); + // Before the pending requests fail, so a freed slot starts nothing. + this.#channel.close(); + for (const pending of this.#outgoing.values()) { + pending.reject(new PluginSdkError('sdk.session.closed', 'The session ended.')); + } + this.#outgoing.clear(); + input.off?.('data', onData); + resolve(code); + exit?.(code); + }; + const decoder = new FrameDecoder(); + const onData = (chunk) => { + let messages; + try { + messages = decoder.push(chunk); + } catch (error) { + if (!(error instanceof FramingError)) throw error; + this.#diagnostics().terminal('notification', {code:'framing_error'}, 0); + this.#finish(1); + return; + } + for (const message of messages) this.#dispatch(message); + }; + input.on('data', onData); + input.once('end', () => this.#finish(this.#phase === 'shuttingDown' ? 0 : 1)); + input.once('error', () => this.#finish(1)); + }); + } + + #dispatch(message) { + if (message === MALFORMED) { + this.#respond(null, undefined, { code: ERROR_CODES.parseError, message: 'The message is not valid JSON.' }); + return; + } + // Valid JSON that is not a message object, such as `null` or a batch. + if (typeof message !== 'object' || message === null || Array.isArray(message)) { + this.#respond(null, undefined, { code: ERROR_CODES.invalidRequest, message: 'The message is not a JSON-RPC object.' }); + return; + } + const hasID = message.id !== undefined && message.id !== null; + if (typeof message.method !== 'string') { + if (hasID) this.#settleOutgoing(message); + return; + } + if (hasID) { + this.#handleRequest(message); + } else { + this.#handleNotification(message); + } + } + + #handleRequest({ id, method, params }) { + if (method === METHODS.initialize) { + void this.#initialize(id, params ?? {}); + return; + } + if (method === METHODS.shutdown) { + void this.#shutdown(id); + return; + } + if (this.#phase === 'listening' || this.#phase === 'initializing') { + this.#respond(id, undefined, { code: ERROR_CODES.serverNotInitialized, message: 'The backend is not initialized.' }); + return; + } + if (this.#phase !== 'ready') { + this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'The backend is shutting down.' }); + return; + } + if (method === METHODS.functionInvoke) { + this.#invokeFunction(id, params ?? {}); + return; + } + if (method === 'lithe/keymap/import') { + this.#invokeKeymap(id, params); + return; + } + const build = this.#buildHandlers.get(method); + if (build && this.#buildVersion >= BUILD_METHOD_VERSIONS[method]) { + this.#invokeBuild(id, method, params ?? {}, build); + return; + } + const vcs = this.#negotiated.vcs ? this.#vcs.methods.get(method) : undefined; + if (vcs) { + this.#run(id, null, (context) => vcs(params ?? {}, this.#vcsContext(context)), (result) => vcsResult(method, result), undefined, method, params?.operationID); + return; + } + const handler = this.#requestHandlers.get(method); + if (handler) { + this.#run(id, null, (context) => handler(params, context), (result) => result ?? null); + return; + } + this.#respond(id, undefined, { code: ERROR_CODES.methodNotFound, message: `Unsupported method: ${method}` }); + } + + #handleNotification({ method, params }) { + if (method === METHODS.exit) { + this.#finish(this.#phase === 'shuttingDown' ? 0 : 1); + return; + } + if (method === METHODS.cancelRequest) { + this.#incoming.get(requestKey(params?.id))?.controller.abort(); + return; + } + if (this.#phase !== 'ready' || method === METHODS.initialized) return; + if (typeof method === 'string' && method.startsWith('lithe/host/')) { + this.#hostNotification(method, params); + return; + } + const handler = this.#notificationHandlers.get(method); + if (!handler) return; + Promise.resolve() + .then(() => handler(params)) + .catch((error) => this.#diagnostics().terminal('notification', { code: failureKind(error) }, 0)); + } + + /** + * Routes a host notification. Core checked its shape and the session's + * grant; one this SDK does not know is ignored, as the contract asks. + */ + #hostNotification(method, params) { + if ((this.#functionsVersion ?? 0) < 3 || !isObject(params)) return; + if (method === HOST_NOTIFICATIONS.subscriptionNotify) { + this.#channel.deliver(params); + return; + } + let handler; + let event = params; + if (method === HOST_NOTIFICATIONS.commandDidRun) { + handler = this.#commandHandlers.get(params.commandID); + event = { commandID: params.commandID, workspaceContext: isContextReference(params.context) ? params.context : null }; + if (!handler) { + this.#diagnostics().degraded('notification', 'command_unhandled'); + return; + } + } else if (method === HOST_NOTIFICATIONS.didChangeContexts) { + handler = this.#contextsHandler; + } else { + handler = this.#hostNotificationHandlers.get(method); + } + if (!handler) return; + Promise.resolve() + .then(() => handler(event)) + .catch((error) => this.#diagnostics().terminal('notification', { code: failureKind(error) }, 0)); + } + + async #initialize(id, params) { + if (this.#phase !== 'listening') { + this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'initialize was already received.' }); + return; + } + this.#phase = 'initializing'; + this.#initializeParams = params; + const offered = params.capabilities?.experimental ?? {}; + this.#loggingReady = false; + this.#earlyDiagnostics = []; + this.#logging = offered.litheLogging?.versions?.includes(1) === true; + if (!this.#logging) { + this.#phase = 'listening'; + this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'The backend requires litheLogging version 1.' }); + return; + } + const offers = (entry, version) => Array.isArray(entry?.versions) && entry.versions.includes(version); + const highest = (entry, latest) => Array.from({ length: latest }, (_, index) => latest - index) + .find((version) => offers(entry, version)) ?? null; + this.#buildVersion = this.#buildHandlers.size > 0 ? highest(offered.litheBuild, BUILD_VERSION) : null; + this.#functionsVersion = highest(offered.litheFunctions, FUNCTIONS_VERSION); + this.#negotiated = Object.freeze({ + functions: this.#functionsVersion !== null, + build: this.#buildVersion !== null, + vcs: this.#vcs !== null && offers(offered.litheVcs, VCS_VERSION), + }); + try { + for (const hook of this.#initializeHooks) { + await hook({ params, negotiated: this.#negotiated }); + } + } catch (error) { + if (this.#phase === 'initializing') this.#phase = 'listening'; + this.#respond(id, undefined, toResponseError(error)); + return; + } + // A shutdown or exit that arrived while a hook ran ended the session; + // finishing initialize must not reopen it. + if (this.#phase !== 'initializing') { + this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'The session ended during initialize.' }); + return; + } + if (!this.#negotiated.functions && this.#functions.size > 0) { + this.#diagnostics().degraded('initialize', 'functions_unavailable'); + } + const experimental = { ...(this.#capabilities.experimental ?? {}), litheLogging: { version: 1 } }; + if (offers(offered.litheKeymapImport, 1) && Array.isArray(offered.litheKeymapImport?.providers) + && offered.litheKeymapImport.providers.length <= 8) { + this.#selectedKeymapProviders = new Set(offered.litheKeymapImport.providers.filter((id) => this.#keymapProviders.has(id))); + if (this.#selectedKeymapProviders.size) { + experimental.litheKeymapImport = { version: 1, providers: [...this.#selectedKeymapProviders].sort() }; + } + } + if (this.#negotiated.build) experimental.litheBuild = { version: this.#buildVersion }; + if (this.#negotiated.vcs) { + experimental.litheVcs = { version: VCS_VERSION, vcs: this.#vcs.id, capabilities: this.#vcs.capabilities }; + } else if (this.#vcs) { + this.#diagnostics().degraded('initialize', 'vcs_unavailable'); + } + if (this.#negotiated.functions) { + experimental.litheFunctions = { + version: this.#functionsVersion, + functions: this.functionIDs.map((functionID) => ({ id: functionID })), + }; + } + this.#phase = 'ready'; + this.#respond(id, { + capabilities: { ...this.#capabilities, experimental }, + serverInfo: { name: this.#name, ...(this.#version ? { version: this.#version } : {}) }, + }); + this.#loggingReady = true; + for (const params of this.#earlyDiagnostics.splice(0)) this.#write({ jsonrpc: '2.0', method: 'lithe/log', params }); + } + + async #shutdown(id) { + if (this.#phase !== 'ready' && this.#phase !== 'listening' && this.#phase !== 'initializing') { + this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'shutdown was already received.' }); + return; + } + this.#phase = 'shuttingDown'; + this.#abortAll(); + for (const hook of this.#shutdownHooks) { + try { + await hook(); + } catch (error) { + this.#diagnostics().terminal('shutdown', { code: failureKind(error) }, 0); + } + } + killAllProcesses(); + this.#respond(id, null); + } + + #invokeBuild(id, method, params, handler) { + if (Object.hasOwn(params ?? {}, 'modelInputs') && this.#buildVersion < 6) { + this.#respond(id, undefined, { code: ERROR_CODES.invalidParams, message: 'Model inputs require build protocol 6.' }); + return; + } + const progressing = [METHODS.buildExecute, METHODS.buildTest, METHODS.buildPrepareRun, METHODS.buildPrepareDebug].includes(method); + if (!params || typeof params !== 'object' || Array.isArray(params) + || (progressing && typeof params.operationID !== 'string')) { + this.#respond(id, undefined, { code: ERROR_CODES.invalidParams, message: 'A build request needs object params and its wire operationID.' }); + return; + } + const operationID = params.operationID; + let reporting = true; + this.#run(id, null, (context) => handler(params, progressing ? { + ...context, + operationID, + progress: ({ message, percentage, output } = {}) => { + if (!reporting || context.signal.aborted) return; + const report = { operationID }; + if (message !== undefined) report.message = boundedText(message, LIMITS.maxBuildMessageBytes); + if (output !== undefined) report.output = boundedText(output, LIMITS.maxBuildOutputBytes); + if (Number.isFinite(percentage)) report.percentage = Math.min(100, Math.max(0, Math.round(percentage))); + this.#write({ jsonrpc: '2.0', method: METHODS.buildProgress, params: report }); + }, + } : context), (result) => buildResult(method, result), () => { reporting = false; }, method, operationID); + } + + #invokeKeymap(id, params) { + if (!isObject(params) || Object.keys(params).length !== 2 || !validKeymapProvider(params.providerID) + || !validSnapshotToken(params.snapshotID) || !this.#selectedKeymapProviders.has(params.providerID)) { + this.#respond(id, undefined, { code: ERROR_CODES.invalidParams, message: 'Invalid shortcut import request.' }); + return; + } + const handler = this.#keymapProviders.get(params.providerID); + this.#run(id, null, (context) => handler(keymapSnapshot(params, context.host), context), functionResult, undefined, 'lithe/keymap/import'); + } + + #invokeFunction(id, { functionID, operationID, params, context: workspaceContext, caller }) { + const handler = this.#negotiated.functions ? this.#functions.get(functionID) : undefined; + if (!handler) { + this.#respond(id, undefined, { code: ERROR_CODES.invalidParams, message: `Function ${functionID} is not registered.` }); + return; + } + let reporting = true; + const progress = ({ message, percentage } = {}) => { + if (!reporting) return; + const report = { operationID }; + if (message !== undefined) report.message = boundedText(message); + if (Number.isFinite(percentage)) report.percentage = Math.min(100, Math.max(0, Math.round(percentage))); + this.#write({ jsonrpc: '2.0', method: METHODS.functionProgress, params: report }); + }; + // Calls this handler makes through the relay belong to this call. Core + // needs a string of 1-128 bytes; without one the calls carry no parent. + const parentOperationId = typeof operationID === 'string' && operationID.length > 0 + && Buffer.byteLength(operationID) <= LIMITS.maxParentOperationIdBytes ? operationID : undefined; + this.#run( + id, + functionID, + (context) => handler(params ?? {}, { + ...context, + functionID, + operationID, + // The page's window, from protocol 3; null for a call without one. + workspaceContext: isContextReference(workspaceContext) ? workspaceContext : null, + // The calling plugin, from protocol 4 and only for a relayed call; null otherwise. + caller: (this.#functionsVersion ?? 0) >= RELAY_VERSION ? callerReference(caller) : null, + host: createHost(this.#channel, context.signal, parentOperationId), + progress, + }), + functionResult, + () => { + reporting = false; + }, + functionID, + operationID, + ); + } + + /** Runs one handler with its own cancellation and answers exactly once. */ + #run(id, functionID, invoke, shape, onSettled, operation = functionID ?? 'function-call', operationId) { + const started = performance.now(); + const diagnostic = this.#diagnostics(requestOperationId(operationId, id)); + let quietSuccess = false; + const controller = new AbortController(); + const key = requestKey(id); + this.#incoming.set(key, { controller, functionID }); + const { signal } = controller; + const context = { + signal, + diagnostics: diagnostic, + suppressSuccessDiagnostics: () => { quietSuccess = true; }, + throwIfCancelled: () => signal.throwIfAborted(), + run: (command, args, options = {}) => { + const running = runProcess(command, args, { + ...options, + signal: options.signal ? AbortSignal.any([signal, options.signal]) : signal, + }); + // A tool the handler did not await is stopped when the call ends; its + // rejection then must not end the backend as an unhandled rejection. + running.catch(() => {}); + return running; + }, + host: createHost(this.#channel, signal), + }; + Promise.resolve() + .then(() => invoke(context)) + .then( + (value) => { + signal.throwIfAborted(); + return { result: shape(value) }; + }, + (error) => { + return { error: toResponseError(error, signal) }; + }, + ) + .catch((error) => { + // Shaping the result failed, for example a build result in another format. + return { error: toResponseError(error, signal) }; + }) + .then(({ result, error }) => { + if (!signal.aborted && (error || (!quietSuccess && !this.#quietSuccess.has(operation)))) diagnostic.terminal(operation, error ? { code: error.data?.code ?? 'internal_error' } : null, performance.now() - started); + onSettled?.(); + this.#incoming.delete(key); + // Work belongs to its call: tools still running when the handler + // settled, such as the siblings of a failed `Promise.all`, end now. + // Other calls have their own controllers and keep running. + controller.abort(new PluginSdkError('sdk.call.ended', 'The call ended.')); + this.#respond(id, result, error); + }); + } + + /** + * The request context of a VCS handler. Its `run` reports every finished + * command to the host as `lithe/vcs/execution`, for the project console, + * unless the call passes `report: false`. Arguments are reported as given, + * so they must never carry a credential. + */ + #vcsContext(context) { + const report = (command, args, started, outcome) => { + const params = { + command: [String(command), ...args.map(String)], + exitCode: outcome.exitCode ?? null, + durationMilliseconds: Math.max(0, Math.round(performance.now() - started)), + stderr: boundedText(outcome.stderr ?? '', LIMITS.maxExecutionErrorOutputBytes), + }; + this.#write({ jsonrpc: '2.0', method: METHODS.vcsExecution, params }); + }; + return { + ...context, + run: (command, args = [], { report: reporting = true, ...options } = {}) => { + const started = performance.now(); + const running = context.run(command, args, options); + if (!reporting) return running; + const reported = running.then( + (result) => { + report(command, args, started, result); + return result; + }, + (error) => { + if (!context.signal.aborted) report(command, args, started, { exitCode: null, stderr: error?.message }); + throw error; + }, + ); + reported.catch(() => {}); + return reported; + }, + }; + } + + #declareBuild(method, handler) { + if (this.#phase !== 'idle') { + throw new PluginSdkError('sdk.build.lateDeclaration', 'Declare build handlers before listen().'); + } + if (typeof handler !== 'function') throw new TypeError('A build handler must be a function.'); + this.#buildHandlers.set(method, handler); + return this; + } + + #declareHandler(handlers, method, handler) { + if (typeof method !== 'string' || isReservedMethod(method)) { + throw new PluginSdkError('sdk.method.reserved', `${method} is managed by the SDK and Lithe.`); + } + if (typeof handler !== 'function') throw new TypeError('A handler must be a function.'); + handlers.set(method, handler); + } + + #checkNewFunction(id, handler) { + if (!isFunctionId(id)) { + throw new PluginSdkError( + 'sdk.function.invalidID', + `Function ID ${JSON.stringify(id)} must be dot-separated lowerCamelCase segments of at most 128 bytes.`, + ); + } + if (typeof handler !== 'function') throw new TypeError('A function handler must be a function.'); + if (this.#functions.has(id)) { + throw new PluginSdkError('sdk.function.duplicate', `Function ${id} is already declared.`); + } + if (this.#functions.size >= LIMITS.maxFunctions) { + throw new PluginSdkError('sdk.function.limit', `A backend serves at most ${LIMITS.maxFunctions} functions.`); + } + } + + /** True until the `initialize` answer fixes the initial function list. */ + #beforeAnswer() { + return this.#phase === 'idle' || this.#phase === 'listening' || this.#phase === 'initializing'; + } + + #requireFunctions() { + if (this.#phase !== 'ready' || !this.#negotiated.functions) { + throw new PluginSdkError('sdk.functions.unavailable', 'The host has not negotiated plugin functions.'); + } + } + + #queueRegistration(change) { + const next = this.#registrations.then(change); + this.#registrations = next.catch(() => {}); + return next; + } + + #checkOutgoing(method) { + if (typeof method !== 'string' || isReservedMethod(method)) { + throw new PluginSdkError( + 'sdk.method.reserved', + `${method} is reserved. A backend never asks the host to run a domain operation or a function.`, + ); + } + if (this.#phase !== 'ready') { + throw new PluginSdkError('sdk.session.notReady', 'The session is not initialized.'); + } + } + + #request(method, params) { + return this.#send(method, params).response; + } + + /** Writes a request to the host; `response` settles with its answer. */ + #send(method, params) { + const id = `sdk-${this.#nextRequestId++}`; + const response = new Promise((resolve, reject) => { + this.#outgoing.set(id, { resolve, reject, method }); + this.#write({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }); + }); + return { id, response }; + } + + #settleOutgoing({ id, result, error }) { + const pending = this.#outgoing.get(id); + if (!pending) return; + this.#outgoing.delete(id); + if (error) { + pending.reject(HostError.fromResponse(pending.method, error)); + } else { + pending.resolve(result ?? null); + } + } + + #abortAll() { + for (const call of this.#incoming.values()) call.controller.abort(); + } + + #respond(id, result, error) { + if (this.#phase === 'exited') return; + try { + this.#write(error ? { jsonrpc: '2.0', id, error } : { jsonrpc: '2.0', id, result: result ?? null }); + } catch (failure) { + // A result JSON cannot encode, such as a BigInt or a cycle, must not + // become an unhandled rejection that ends the whole session. + this.#diagnostics().terminal('result-encoding', { code: 'result_encoding_failed' }, 0); + this.#write({ jsonrpc: '2.0', id, error: toResponseError(failure) }); + } + } + + #write(message) { + if (!this.#output || this.#phase === 'exited') return; + this.#output.write(encodeFrame(message)); + } +} + +// Errors can include request bodies, credentials and paths. Only the category +// crosses the diagnostic boundary; the response keeps its existing error contract. +function failureKind(error) { + return error instanceof PluginError ? 'plugin_error' : 'internal_error'; +} + +/** Runs `change` now and reports its outcome as a promise. */ +function settle(change) { + try { + change(); + return Promise.resolve(); + } catch (error) { + return Promise.reject(error); + } +} + +/** The JSON-RPC ID as a map key; numbers and strings never collide. */ +function requestKey(id) { + return `${typeof id}:${id}`; +} + +/** + * Stamps the canonical format on a build result, so a handler can return the + * plain document. A result in another format is a backend bug: Core would + * refuse it as `plugin.build.invalidOutput`, so it fails here with a clear log. + */ +function buildResult(method, result) { + const expected = BUILD_FORMATS[method]; + if (!isObject(result)) { + throw new PluginSdkError('sdk.build.invalidResult', `${method} must return a reply object.`); + } + let document = result; + if (expected) { + if (result.format !== undefined && result.format !== expected) { + throw new PluginSdkError('sdk.build.invalidResult', `${method} returned format ${result.format}, not ${expected}.`); + } + if (result.version !== undefined && result.version !== 1) { + throw new PluginSdkError('sdk.build.invalidResult', `${method} returned version ${result.version}, not 1.`); + } + document = { ...result, format: expected, version: 1 }; + } + if ([METHODS.buildExecute, METHODS.buildTest].includes(method) + && (!Number.isInteger(result.exitCode) || result.exitCode < -2147483648 || result.exitCode > 2147483647 + || typeof result.output !== 'string' || Buffer.byteLength(result.output) > LIMITS.maxBuildResultBytes)) { + throw new PluginSdkError('sdk.build.invalidResult', `${method} needs an int32 exitCode and bounded output.`); + } + if (method === METHODS.buildPrepareRun + && (!isObject(result.executable) || !['toolchain', 'command'].includes(result.executable.kind) + || typeof result.executable.value !== 'string' || typeof result.workingDirectory !== 'string' + || !Array.isArray(result.arguments) || !result.arguments.every((value) => typeof value === 'string') + || !isObject(result.environment) || !Object.values(result.environment).every((value) => typeof value === 'string'))) { + throw new PluginSdkError('sdk.build.invalidResult', `${method} needs a portable launch plan.`); + } + if (method === METHODS.buildPrepareDebug + && (typeof result.program !== 'string' || typeof result.workingDirectory !== 'string' + || !Array.isArray(result.arguments) || !result.arguments.every((value) => typeof value === 'string') + || !isObject(result.environment) || !Object.values(result.environment).every((value) => typeof value === 'string') + || Object.keys(result).some((key) => !['program', 'arguments', 'workingDirectory', 'environment'].includes(key)))) { + throw new PluginSdkError('sdk.build.invalidResult', `${method} needs native debug target facts, without an adapter or DAP arguments.`); + } + // Workspace containment and domain facts remain Core/provider responsibilities. + if (Buffer.byteLength(JSON.stringify(document)) > LIMITS.maxBuildResultBytes) { + throw new PluginSdkError('sdk.build.invalidResult', `${method} exceeds the build-result size limit.`); + } + return document; +} + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** `{ pluginID }` for the exact top-level `caller` Core writes into a relayed call, else null. */ +function callerReference(value) { + if (!isObject(value) || Object.keys(value).length !== 1) return null; + return typeof value.pluginID === 'string' && value.pluginID.length > 0 + ? Object.freeze({ pluginID: value.pluginID }) + : null; +} + +function validKeymapProvider(id) { + return typeof id === 'string' && /^[a-z][a-z0-9-]{0,63}$/.test(id); +} + +function validSnapshotToken(id) { + return typeof id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(id); +} + +function keymapSnapshot({ providerID, snapshotID }, host) { + const scope = { providerID, snapshotID }; + const invalid = () => new PluginSdkError('sdk.keymap.invalidResponse', 'Invalid shortcut source response.'); + return Object.freeze({ + providerID, snapshotID, + async listInputs() { + const result = await host.request('lithe/host/keymapImport/listInputs', scope); + if (!Array.isArray(result?.files) || result.files.length > 128 || result.files.some((file) => + !validSnapshotToken(file?.id) || typeof file.path !== 'string' || !file.path || Buffer.byteLength(file.path) > 4096 + || !Number.isSafeInteger(file.byteCount) || file.byteCount < 0 || file.byteCount > 1048576)) throw invalid(); + return result.files.map(({ id, path, byteCount }) => ({ id, path, byteCount })); + }, + async readChunk(fileID, offset, maximumBytes) { + if (!validSnapshotToken(fileID) || !Number.isSafeInteger(offset) || offset < 0 || offset > 1048576 + || !Number.isInteger(maximumBytes) || maximumBytes < 1 || maximumBytes > 131072) throw invalid(); + const result = await host.request('lithe/host/keymapImport/readChunk', { ...scope, fileID, offset, maximumBytes }); + if (typeof result?.data !== 'string' || result.data.length > 174764) throw invalid(); + const bytes = Buffer.from(result.data, 'base64'); + if (bytes.length > maximumBytes || bytes.toString('base64') !== result.data) throw invalid(); + return bytes; + }, + }); +} + +/** + * A VCS reply must be a JSON object; Core validates its fields and refuses + * anything else as `plugin.vcs.invalidOutput`, so it fails here with a log. + */ +function vcsResult(method, result) { + if (result === undefined) return {}; + if (result === null || typeof result !== 'object' || Array.isArray(result)) { + throw new PluginSdkError('sdk.vcs.invalidResult', `${method} must return a reply object.`); + } + return result; +} + +/** A copy of `object` with its keys sorted, for a stable `initialize` answer. */ +function sortedKeys(object) { + return Object.fromEntries(Object.entries(object).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))); +} + +/** + * A function result as the JSON value Core accepts. A value JSON cannot + * encode, or one over Core's 1 MiB limit, fails here as a backend bug with a + * log line, instead of breaking the response frame or being refused by Core. + */ +function functionResult(result) { + let encoded; + try { + encoded = JSON.stringify(result ?? null); + } catch (error) { + throw new PluginSdkError('sdk.function.invalidResult', `The result is not JSON: ${error.message}`); + } + if (encoded === undefined) { + throw new PluginSdkError('sdk.function.invalidResult', 'The result is not a JSON value.'); + } + if (Buffer.byteLength(encoded) > LIMITS.maxResultBytes) { + throw new PluginSdkError('sdk.function.invalidResult', `The result exceeds ${LIMITS.maxResultBytes} bytes.`); + } + return result ?? null; +} + +/** + * Sends `console.log`, `info`, and `debug` to stderr. Stdout carries the + * protocol; a stray line there would corrupt the stream and end the session. + */ +function redirectConsole(errorOutput) { + const write = (...parts) => errorOutput.write(`${format(...parts)}\n`); + console.log = write; + console.info = write; + console.debug = write; +} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs new file mode 100644 index 0000000..8fcdc99 --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs @@ -0,0 +1,34 @@ +// Typed plugin diagnostics use the host's catalog and writer. No payload text crosses this API. +import { PluginSdkError } from './errors.mjs'; + +export const KNOWN_OPERATIONS = new Set([ + 'initialize', 'shutdown', 'notification', 'function-call', 'result-encoding', + ...['model', 'dependencies', 'execute', 'test', 'discoverTests', 'prepareRun', 'prepareDebug'].map((name) => `lithe/build/${name}`), + ...['status', 'baseContent', 'history', 'fileHistory', 'annotate', 'checkin', 'rollback', 'update', 'fileOperation', 'resolve', 'cleanup'].map((name) => `lithe/vcs/${name}`), + 'lithe/keymap/import', +]); +const token = (value, maximum) => typeof value === 'string' && value.length > 0 && value.length <= maximum && /^[A-Za-z0-9._:/\-$]+$/.test(value); +export function requestOperationId(operationId, requestId) { + if (token(operationId, 128)) return operationId; + const fallback = typeof requestId === 'string' ? requestId : Number.isSafeInteger(requestId) ? String(requestId) : undefined; + return token(fallback, 128) ? fallback : undefined; +} +export function diagnostics(send, registered, operationId) { + const record = (kind, operation, code, count, durationMs) => { + if (!KNOWN_OPERATIONS.has(operation) && !registered(operation)) throw new PluginSdkError('sdk.logging.invalidOperation', 'Diagnostics need a registered operation.'); + if (code !== undefined && !token(code, 64)) throw new PluginSdkError('sdk.logging.invalidCode', 'Diagnostics need a controlled code.'); + if (count !== undefined && (!Number.isSafeInteger(count) || count < 0)) throw new PluginSdkError('sdk.logging.invalidCount', 'Diagnostics need a nonnegative safe count.'); + const params = { kind, operation: operation.length <= 64 ? operation : 'function-call' }; + if (code !== undefined) params.code = code; + if (count !== undefined) params.count = count; + if (durationMs !== undefined) params.durationMs = Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.floor(durationMs))); + if (token(operationId, 128)) params.operationId = operationId; + send(params); + }; + return Object.freeze({ + degraded: (operation, code, count) => record('degraded', operation, code, count), + recovered: (operation, code, count) => record('recovered', operation, code, count), + terminal: (operation, error, durationMs = 0) => record(error ? 'operationFailed' : 'operationFinished', operation, + error ? (token(error.code, 64) ? error.code : 'internal_error') : undefined, undefined, durationMs), + }); +} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs new file mode 100644 index 0000000..048cae0 --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs @@ -0,0 +1,101 @@ +import { boundedText, ERROR_CODES, HOST_ERRORS, isPluginErrorCode } from './protocol.mjs'; + +/** + * A failure a handler reports on purpose. Core ends the call with the stable + * `plugin.function.failed` code and forwards `code` as `pluginErrorCode`, so + * the plugin's own UI can tell its failures apart. Lithe never branches on it. + */ +export class PluginError extends Error { + /** + * @param {string} code Identifier of at most 64 bytes, such as `maven.snapshotLocked`. + * @param {string} message User-facing text; Core keeps the first 1024 bytes. + * @param {object} [options] `{ cause }`, retained in memory and omitted from automatic diagnostics. + */ + constructor(code, message, options) { + super(message, options); + if (!isPluginErrorCode(code)) { + throw new TypeError( + `Plugin error code ${JSON.stringify(code)} must start with a letter, use letters, digits, ".", "_" or "-", and be at most 64 bytes.`, + ); + } + this.name = 'PluginError'; + this.code = code; + } +} + +/** An SDK usage error, raised synchronously to the plugin author. */ +export class PluginSdkError extends Error { + constructor(code, message) { + super(message); + this.name = 'PluginSdkError'; + this.code = code; + } +} + +const HOST_CODES = new Map(Object.entries(HOST_ERRORS).map(([code, rpcCode]) => [rpcCode, code])); + +/** + * The host refused or failed a request this backend sent. `code` is the + * stable `error.data.code`, such as `plugin.host.contextExpired`; `rpcCode` + * the JSON-RPC number; `details` the object a version 3 host may add, such + * as `{ option }` or `{ retryAfterMilliseconds }`. + */ +export class HostError extends PluginSdkError { + constructor(code, message, { rpcCode, details, method } = {}) { + super(code, message); + this.name = 'HostError'; + this.rpcCode = rpcCode; + this.details = details; + this.method = method; + } + + /** + * The failure for a JSON-RPC error answer. A host method without a known + * code is a host failure: from version 3 a number names one code, and an + * unknown number is `plugin.host.failed`. + */ + static fromResponse(method, error) { + const data = error?.data; + const isHost = method.startsWith('lithe/host/'); + const code = typeof data?.code === 'string' + ? data.code + : isHost + ? HOST_CODES.get(error?.code) ?? 'plugin.host.failed' + : 'sdk.host.error'; + const details = data?.details !== null && typeof data?.details === 'object' && !Array.isArray(data.details) + ? data.details + : undefined; + return new HostError(code, typeof error?.message === 'string' ? error.message : `${method} failed.`, { + rpcCode: error?.code, + details, + method, + }); + } +} + +/** True for the rejection an aborted `AbortSignal` produces. */ +export function isAbort(error, signal) { + return Boolean(signal?.aborted) && (error === signal.reason || error?.name === 'AbortError'); +} + +/** + * The JSON-RPC error object for a handler failure. Only `PluginError` carries + * a plugin code; any other exception becomes a generic internal error so that + * stack traces and machine paths never reach the host's UI. A `PluginError` + * message is shown to the user as written, so it must not contain them either. + */ +export function toResponseError(error, signal) { + if (isAbort(error, signal)) { + return { code: ERROR_CODES.requestCancelled, message: 'The request was cancelled.' }; + } + if (error instanceof PluginError) { + return { + code: ERROR_CODES.requestFailed, + message: boundedText(error.message), + data: { code: error.code }, + }; + } + // Unexpected exceptions often embed absolute paths (ENOENT) or internals; + // the caller logs only a fixed failure category to stderr. + return { code: ERROR_CODES.internalError, message: 'The plugin backend failed unexpectedly.' }; +} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs new file mode 100644 index 0000000..ccfe774 --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs @@ -0,0 +1,74 @@ +// LSP base-protocol framing: `Content-Length` headers followed by a UTF-8 +// JSON body. Lithe talks to every plugin backend this way, so the SDK owns +// the framing and plugin code never writes to stdout itself. + +const HEADER_END = Buffer.from('\r\n\r\n', 'ascii'); + +/** Largest header block accepted from the host. */ +const MAX_HEADER_BYTES = 8192; + +/** Largest body accepted from the host. Larger frames end the session. */ +export const MAX_FRAME_BYTES = 64 * 1024 * 1024; + +/** Stands for a body that is not JSON; compared by identity, so no host message can mimic it. */ +export const MALFORMED = Object.freeze({ malformed: true }); + +/** A framing error the session cannot recover from. */ +export class FramingError extends Error {} + +/** Incrementally splits a byte stream into decoded JSON-RPC messages. */ +export class FrameDecoder { + #buffer = Buffer.alloc(0); + + /** + * Appends `chunk` and returns every complete message it finished. A body + * that is not JSON is returned as `MALFORMED` so the caller can + * report it without losing the framing position. + */ + push(chunk) { + this.#buffer = this.#buffer.length === 0 ? Buffer.from(chunk) : Buffer.concat([this.#buffer, chunk]); + const messages = []; + for (;;) { + const headerEnd = this.#buffer.indexOf(HEADER_END); + // The same bound whether the header arrived whole or in pieces. + if (headerEnd > MAX_HEADER_BYTES || (headerEnd < 0 && this.#buffer.length > MAX_HEADER_BYTES)) { + throw new FramingError('The message header is too long.'); + } + if (headerEnd < 0) return messages; + const length = contentLength(this.#buffer.subarray(0, headerEnd).toString('ascii')); + const bodyStart = headerEnd + HEADER_END.length; + if (this.#buffer.length < bodyStart + length) { + return messages; + } + const body = this.#buffer.subarray(bodyStart, bodyStart + length).toString('utf8'); + this.#buffer = this.#buffer.subarray(bodyStart + length); + try { + messages.push(JSON.parse(body)); + } catch { + messages.push(MALFORMED); + } + } + } +} + +function contentLength(header) { + for (const line of header.split('\r\n')) { + const separator = line.indexOf(':'); + if (separator < 0) continue; + if (line.slice(0, separator).trim().toLowerCase() !== 'content-length') continue; + const value = line.slice(separator + 1).trim(); + if (!/^\d+$/.test(value)) break; + const length = Number(value); + if (length > MAX_FRAME_BYTES) { + throw new FramingError(`A message of ${length} bytes exceeds the ${MAX_FRAME_BYTES}-byte limit.`); + } + return length; + } + throw new FramingError('A message has no valid Content-Length header.'); +} + +/** Encodes one JSON-RPC message as a complete frame. */ +export function encodeFrame(message) { + const body = Buffer.from(JSON.stringify(message), 'utf8'); + return Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, 'ascii'), body]); +} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs new file mode 100644 index 0000000..fb0fff1 --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs @@ -0,0 +1,447 @@ +// Host services of plugin-function protocols 2 to 4: the `lithe/host/*` +// requests a backend sends to Lithe, the subscriptions some of them create, +// and the `host` object handlers use. The backend owns the wire; this module +// owns what Core expects of a well-behaved client -- at most 16 unanswered +// host requests, cancellation through `$/cancelRequest` from version 3, +// subscription events routed by ID, and the relay methods only from version 4. +// +// Contract: contract/v1/README.md, "Host services (protocol version 2)" and +// the version 3 and 4 sections after it. + +import { HostError, PluginSdkError } from './errors.mjs'; +import { + CONTEXT_VERSION, + HOST_METHODS, + HOST_SERVICES_VERSION, + isContextReference, + isCredentialKey, + isFunctionId, + isRelayMethod, + LIMITS, + METHODS, + RELAY_VERSION, +} from './protocol.mjs'; + +/** Events kept for a subscription whose creating request is still unanswered. */ +const MAX_EARLY_EVENTS = 128; + +const CREDENTIAL_METHODS = Object.freeze([ + HOST_METHODS.credentialsGet, + HOST_METHODS.credentialsSet, + HOST_METHODS.credentialsDelete, +]); + +/** + * The session's host-request state. `transport` is the backend's wire: + * `{ version(), ready(), send(method, params) -> { id, response }, notify(method, params), log(...) }`. + */ +export class HostChannel { + #transport; + #inFlight = 0; + /** Requests waiting for a free slot, in call order: `{ start, fail }`. */ + #queue = []; + /** Live subscriptions by ID: `{ onEvent, lastSequence }`. */ + #subscriptions = new Map(); + /** Subscribing requests not yet answered; early events wait only while there are some. */ + #subscribing = 0; + #early = []; + #capabilities = null; + #closed = false; + + constructor(transport) { + this.#transport = transport; + } + + /** The negotiated plugin-function version, or 0 before or without one. */ + get version() { + return this.#transport.version(); + } + + request(method, params, { signal } = {}) { + if (typeof method !== 'string' || !method.startsWith('lithe/host/')) { + return Promise.reject(new PluginSdkError('sdk.host.method', `${method} is not a host method; host requests are lithe/host/*.`)); + } + if (this.#closed || !this.#transport.ready()) { + return Promise.reject(new PluginSdkError('sdk.session.notReady', 'The session is not initialized.')); + } + if (this.version < HOST_SERVICES_VERSION) { + // The answer Core would give, without the round trip. + return Promise.reject(new HostError( + 'plugin.host.unavailable', + 'The host did not negotiate plugin-function protocol 2 or later, which offers host services.', + { rpcCode: -32601, method }, + )); + } + if (isRelayMethod(method) && this.version < RELAY_VERSION) { + // Unlike other methods added after version 3, these two are bound to a + // version: Core answers a version 3 backend -32601, so no frame is sent. + return Promise.reject(new HostError( + 'plugin.host.unavailable', + 'The relay needs plugin-function protocol 4.', + { rpcCode: -32601, method }, + )); + } + if (signal?.aborted) return Promise.reject(signal.reason); + return new Promise((resolve, reject) => { + // `queued` → `sent` → `done`; a request settles for its caller once. + let state = 'queued'; + let id; + const done = () => { + state = 'done'; + signal?.removeEventListener('abort', onAbort); + }; + const entry = { + start: () => { + state = 'sent'; + this.#inFlight += 1; + const sent = this.#transport.send(method, params); + id = sent.id; + sent.response + .then( + (result) => { + if (state === 'done') return; + done(); + resolve(result); + }, + (error) => { + if (state === 'done') return; + done(); + reject(error); + }, + ) + .finally(() => { + // The slot frees when Core answers, also after a cancellation: + // from version 3 Core answers it at once, before version 3 the + // host still finishes the request. + this.#inFlight -= 1; + this.#drain(); + }); + }, + fail: (error) => { + if (state === 'done') return; + done(); + reject(error); + }, + }; + const onAbort = () => { + if (state === 'done') return; + if (state === 'queued') { + this.#queue.splice(this.#queue.indexOf(entry), 1); + } else if (this.version >= CONTEXT_VERSION) { + this.#transport.notify(METHODS.cancelRequest, { id }); + } + // A cancelled mutation may already have taken effect; it is never + // sent again. + done(); + reject(signal.reason); + }; + signal?.addEventListener('abort', onAbort, { once: true }); + this.#queue.push(entry); + this.#drain(); + }); + } + + /** + * Sends a request whose result is `{ subscriptionID }` and routes that + * subscription's events to `onEvent(event, { subscriptionID, sequence, gap })`. + */ + async subscribe(method, params, onEvent, options) { + if (onEvent !== undefined && typeof onEvent !== 'function') { + throw new TypeError('A subscription event handler must be a function.'); + } + this.#subscribing += 1; + try { + const result = await this.request(method, params, options); + const subscriptionID = result?.subscriptionID; + if (!isCredentialKey(subscriptionID)) { + throw new PluginSdkError('sdk.host.invalidResult', `${method} answered without a subscriptionID.`); + } + const subscription = { onEvent: onEvent ?? (() => {}), lastSequence: 0, live: true }; + this.#subscriptions.set(subscriptionID, subscription); + // Events the host sent before this answer was read. + const early = this.#early.filter((event) => event.subscriptionID === subscriptionID); + this.#early = this.#early.filter((event) => event.subscriptionID !== subscriptionID); + for (const event of early) this.#emit(subscriptionID, subscription, event); + return Object.freeze({ + subscriptionID, + get disposed() { + return !subscription.live; + }, + dispose: () => this.dispose(subscriptionID), + }); + } finally { + this.#subscribing -= 1; + if (this.#subscribing === 0) this.#early = []; + } + } + + /** Stops routing a subscription's events at once and asks the host to dispose it. */ + async dispose(subscriptionID) { + const subscription = this.#subscriptions.get(subscriptionID); + if (subscription) subscription.live = false; + this.#subscriptions.delete(subscriptionID); + if (this.#closed || !this.#transport.ready()) return; + await this.request(HOST_METHODS.subscriptionsDispose, { subscriptionID }); + } + + /** Routes one `lithe/host/subscriptions/notify`. */ + deliver({ subscriptionID, sequence, event }) { + const subscription = this.#subscriptions.get(subscriptionID); + if (subscription) { + this.#emit(subscriptionID, subscription, { sequence, event }); + } else if (this.#subscribing > 0) { + if (this.#early.length < MAX_EARLY_EVENTS) { + this.#early.push({ subscriptionID, sequence, event }); + } else { + this.#transport.log('Dropped an early subscription event: queue_full'); + } + } + // Otherwise the subscription was disposed; nothing follows a disposal. + } + + /** The cached `getCapabilities` answer; Core answers it itself, from version 3. */ + capabilities() { + if (this.version < CONTEXT_VERSION) { + return Promise.reject(new HostError( + 'plugin.host.unavailable', + 'Capability discovery needs plugin-function protocol 3.', + { rpcCode: -32601, method: HOST_METHODS.getCapabilities }, + )); + } + this.#capabilities ??= this.request(HOST_METHODS.getCapabilities).catch((error) => { + this.#capabilities = null; + throw error; + }); + return this.#capabilities; + } + + /** + * Whether this session may call `method`. From version 3 the answer comes + * from `getCapabilities`; version 2 has no discovery, so it reports the + * methods version 2 defines, and a missing grant still fails the request. + */ + async supports(method) { + if (this.version >= CONTEXT_VERSION) { + const { services } = await this.capabilities(); + return Object.values(services ?? {}).some((service) => Array.isArray(service?.methods) && service.methods.includes(method)); + } + return this.version >= HOST_SERVICES_VERSION && CREDENTIAL_METHODS.includes(method); + } + + /** Ends the channel with the session: queued requests fail, subscriptions end. */ + close() { + this.#closed = true; + for (const entry of this.#queue.splice(0)) { + entry.fail(new PluginSdkError('sdk.session.closed', 'The session ended.')); + } + for (const subscription of this.#subscriptions.values()) subscription.live = false; + this.#subscriptions.clear(); + this.#early = []; + this.#capabilities = null; + } + + #emit(subscriptionID, subscription, { sequence, event }) { + const gap = sequence !== subscription.lastSequence + 1; + subscription.lastSequence = sequence; + Promise.resolve() + .then(() => subscription.onEvent(event, { subscriptionID, sequence, gap })) + .catch(() => this.#transport.log('A subscription listener failed: internal_error')); + } + + #drain() { + while (!this.#closed && this.#inFlight < LIMITS.maxPendingHostRequests && this.#queue.length > 0) { + this.#queue.shift().start(); + } + } +} + +/** + * The `host` object: typed host services over `channel`. A handler's + * `context.host` passes the call's signal, so its unanswered host requests + * are cancelled when the call ends. It also passes the `operationID` of the + * `lithe/function/invoke` being served as `parentOperationId`, which + * `functions.invoke` sends as the new call's parent unless the caller names + * another. A host object without them (`backend.host`) has no default parent. + */ +export function createHost(channel, callSignal, parentOperationId) { + const withSignal = (options = {}) => { + if (!callSignal) return options; + return { ...options, signal: options.signal ? AbortSignal.any([callSignal, options.signal]) : callSignal }; + }; + const request = (method, params, options) => channel.request(method, params, withSignal(options)); + const subscribe = (method, params, onEvent, options) => channel.subscribe(method, params, onEvent, withSignal(options)); + /** A method whose params name a workspace context. */ + const scoped = (method) => async (context, params = {}, options) => + request(method, { ...params, context: contextReference(context) }, options); + + return Object.freeze({ + get version() { + return channel.version; + }, + request: async (method, params, options) => request(method, params, options), + subscribe: async (method, params, onEvent, options) => subscribe(method, params, onEvent, options), + capabilities: () => channel.capabilities(), + supports: (method) => channel.supports(method), + credentials: Object.freeze({ + async get(key, options) { + checkCredentialKey(key); + const result = await request(HOST_METHODS.credentialsGet, { key }, options); + if (result === null) return null; + if (typeof result?.secret !== 'string') { + throw new PluginSdkError('sdk.host.invalidResult', 'The host answered credentials/get without a secret.'); + } + return result.secret; + }, + async set(key, secret, options) { + checkCredentialKey(key); + if (typeof secret !== 'string' || Buffer.byteLength(secret) > LIMITS.maxCredentialSecretBytes) { + throw new PluginSdkError('sdk.credentials.invalidSecret', 'A secret is a string of at most 16 KiB.'); + } + await request(HOST_METHODS.credentialsSet, { key, secret }, options); + }, + async delete(key, options) { + checkCredentialKey(key); + await request(HOST_METHODS.credentialsDelete, { key }, options); + }, + }), + subscriptions: Object.freeze({ + dispose: async (subscriptionID) => channel.dispose(subscriptionID), + }), + workspace: Object.freeze({ + listContexts: async (options) => request(HOST_METHODS.workspaceListContexts, {}, options), + getContext: async (context, options) => + request(HOST_METHODS.workspaceGetContext, { context: contextReference(context) }, options), + getFolders: async (context, options) => + request(HOST_METHODS.workspaceGetFolders, { context: contextReference(context) }, options), + readDirectory: scoped(HOST_METHODS.workspaceReadDirectory), + stat: scoped(HOST_METHODS.workspaceStat), + readFile: scoped(HOST_METHODS.workspaceReadFile), + watch: async (context, params, onEvent, options) => + subscribe(HOST_METHODS.workspaceWatch, { ...params, context: contextReference(context) }, onEvent, options), + findFiles: scoped(HOST_METHODS.workspaceFindFiles), + findText: scoped(HOST_METHODS.workspaceFindText), + }), + functions: Object.freeze({ + providers: async (functionID, options) => { + checkRelayFunctionId(functionID); + return request(HOST_METHODS.functionsProviders, { functionID }, options); + }, + invoke: async (context, call, options) => + request(HOST_METHODS.functionsInvoke, relayInvokeParams(context, call, parentOperationId), options), + }), + documents: Object.freeze({ + list: scoped(HOST_METHODS.documentsList), + getSnapshot: scoped(HOST_METHODS.documentsGetSnapshot), + }), + editor: Object.freeze({ + getActive: scoped(HOST_METHODS.editorGetActive), + getSelections: scoped(HOST_METHODS.editorGetSelections), + applyEdits: scoped(HOST_METHODS.editorApplyEdits), + replaceSelections: scoped(HOST_METHODS.editorReplaceSelections), + insertText: scoped(HOST_METHODS.editorInsertText), + open: scoped(HOST_METHODS.editorOpen), + reveal: scoped(HOST_METHODS.editorReveal), + registerActions: async (context, params, options) => + subscribe(HOST_METHODS.editorRegisterActions, { ...params, context: contextReference(context) }, undefined, options), + }), + preview: Object.freeze({ + openHTML: scoped(HOST_METHODS.previewOpenHTML), + }), + browser: Object.freeze({ + openExternal: scoped(HOST_METHODS.browserOpenExternal), + }), + terminal: Object.freeze({ + create: scoped(HOST_METHODS.terminalCreate), + show: scoped(HOST_METHODS.terminalShow), + close: scoped(HOST_METHODS.terminalClose), + reopen: scoped(HOST_METHODS.terminalReopen), + dispose: scoped(HOST_METHODS.terminalDispose), + onExit: async (context, terminalID, onEvent, options) => + subscribe(HOST_METHODS.terminalOnExit, { context: contextReference(context), terminalID }, onEvent, options), + }), + window: Object.freeze({ + showInformation: scoped(HOST_METHODS.windowShowInformation), + showWarning: scoped(HOST_METHODS.windowShowWarning), + showError: scoped(HOST_METHODS.windowShowError), + }), + }); +} + +/** + * `{ contextID, generation }` of a context reference or of a full context + * from `listContexts` or `getContext`, so either can be passed on. + */ +export function contextReference(value) { + const reference = { contextID: value?.contextID, generation: value?.generation }; + if (!isContextReference(reference)) { + throw new PluginSdkError( + 'sdk.host.invalidContext', + 'A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, ".", "_", ":" or "-", and a positive generation.', + ); + } + return reference; +} + +function checkCredentialKey(key) { + if (!isCredentialKey(key)) { + throw new PluginSdkError( + 'sdk.credentials.invalidKey', + 'A credential key is 1-128 ASCII letters, digits, ".", "_", ":" or "-".', + ); + } +} + +function invalidRelayCall(message) { + return new PluginSdkError('sdk.functions.invalidCall', message); +} + +function checkRelayFunctionId(functionID) { + if (!isFunctionId(functionID)) { + throw invalidRelayCall('A function ID is dot-separated lowerCamelCase segments of at most 128 bytes, such as "project.describe".'); + } +} + +function isParentOperationId(value) { + return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= LIMITS.maxParentOperationIdBytes; +} + +/** + * The params of one `lithe/host/functions/invoke`, built from the whitelisted + * fields of `call` only, so a caller cannot add a field of its own (Core + * refuses `caller` and writes it itself). Checks what Core checks first; a + * mistake throws before any frame is written. `params` stays absent unless + * given. The parent is the call's own `parentOperationID`, else the operation + * being served (`defaultParent`), else absent. + */ +function relayInvokeParams(context, call, defaultParent) { + if (call === null || typeof call !== 'object' || Array.isArray(call)) { + throw invalidRelayCall('A relayed call is { pluginID, functionID, params?, timeoutMilliseconds?, parentOperationID? }.'); + } + const { pluginID, functionID, params, timeoutMilliseconds, parentOperationID } = call; + if (typeof pluginID !== 'string' || pluginID.length === 0) { + throw invalidRelayCall('pluginID is the ID of the plugin that provides the function, a non-empty string.'); + } + checkRelayFunctionId(functionID); + const wire = { pluginID, functionID, context: contextReference(context) }; + if (params !== undefined) { + if (params === null || typeof params !== 'object' || Array.isArray(params)) { + throw invalidRelayCall('params are a JSON object.'); + } + wire.params = params; + } + if (timeoutMilliseconds !== undefined) { + if (!Number.isSafeInteger(timeoutMilliseconds) || timeoutMilliseconds < 1) { + throw invalidRelayCall('timeoutMilliseconds is a positive integer.'); + } + wire.timeoutMilliseconds = timeoutMilliseconds; + } + if (parentOperationID !== undefined) { + if (!isParentOperationId(parentOperationID)) { + throw invalidRelayCall('parentOperationID is a string of 1-128 bytes.'); + } + wire.parentOperationID = parentOperationID; + } else if (defaultParent !== undefined) { + wire.parentOperationID = defaultParent; + } + return wire; +} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts new file mode 100644 index 0000000..3217197 --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts @@ -0,0 +1,714 @@ +// Type declarations for the Lithe plugin backend SDK. Keep in sync with the +// `.mjs` sources; `sdk/node/test/support.test.mjs` checks the exported names. + +/** Any value JSON can carry. */ +export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }; +export type JsonObject = { [key: string]: JsonValue }; + +export interface RunProcessOptions { + cwd?: string; + /** Replaces the environment when given; Lithe's process markers are carried over regardless. */ + env?: Record; + /** Aborting it ends the whole process tree and rejects with its reason. */ + signal?: AbortSignal; + /** Captured bytes per stream; default 1 MiB. */ + maxOutputBytes?: number; + onStdout?: (chunk: string) => void; + onStderr?: (chunk: string) => void; + /** Delay between the polite and forced stop; default 2000. */ + killGraceMilliseconds?: number; +} + +export interface ProcessResult { + exitCode: number | null; + signal: string | null; + stdout: string; + stderr: string; + truncated: boolean; +} + +/** Typed facts for the host-owned litheLogging 1 event catalog. */ +export interface Diagnostics { + degraded(operation: string, code: string, count?: number): void; + recovered(operation: string, code: string, count?: number): void; +} + +/** Shared by every handler. */ +export interface RequestContext { + /** Aborted when the host cancels the call, the call times out, the session ends, or the call has settled. */ + signal: AbortSignal; + throwIfCancelled(): void; + /** `runProcess` bound to this call: its tree ends when the call is cancelled or settles. */ + run(command: string, args?: string[], options?: RunProcessOptions): Promise; + /** Fixed facts, correlated with the host operation; never accepts payload text. */ + readonly diagnostics: Diagnostics; + /** Omits only this call's successful fact; failures remain visible. */ + suppressSuccessDiagnostics(): void; + /** `backend.host` bound to this call: its unanswered host requests are cancelled when the call ends. */ + host: Host; +} + +/** `{ contextID, generation }`: one generation of one workspace context (protocol 3). */ +export interface ContextReference { + contextID: string; + generation: number; +} + +export interface WorkspaceFolder { + /** Stable per plugin and location; reveals nothing about the path. */ + rootID: string; + name: string; + /** Present only for a local authority. */ + path?: string; +} + +/** One open workspace in one window. */ +export interface WorkspaceContext extends ContextReference { + name: string; + authority: { kind: 'local' | 'remote'; id?: string }; + folders: WorkspaceFolder[]; + /** Private to the plugin and the workspace; only `getContext` returns, and creates, it. */ + stateDirectory?: string; + [key: string]: unknown; +} + +export interface HostCapabilities { + protocolVersion: number; + backendAuthority: 'local'; + /** Each service this session may use, with the requests it may send and the notifications it may receive. */ + services: Record; + limits: { + pendingHostRequests: number; + functionResultBytes: number; + hostRequestBytes: number; + hostResultBytes: number; + errorMessageBytes: number; + errorDetailsBytes: number; + notificationBytes: number; + [key: string]: number; + }; + [key: string]: unknown; +} + +export interface HostRequestOptions { + /** Aborting it rejects with its reason; from protocol 3 the host is also told to stop. Never retried. */ + signal?: AbortSignal; +} + +export interface SubscriptionEventInfo { + subscriptionID: string; + sequence: number; + /** True when `sequence` does not follow the previous event: events were missed. */ + gap: boolean; +} + +export type SubscriptionHandler = (event: JsonObject, info: SubscriptionEventInfo) => unknown; + +export interface Subscription { + readonly subscriptionID: string; + readonly disposed: boolean; + /** Stops routing events at once and asks the host to dispose the subscription. */ + dispose(): Promise; +} + +/** A file or folder under a root of `getFolders`; `path` uses `/` and is relative to the root. */ +export interface WorkspaceResource { + rootID: string; + path: string; +} + +/** One-based UTF-16 position. */ +export interface TextPosition { + line: number; + column: number; +} + +/** Half-open range. */ +export interface TextRange { + start: TextPosition; + end: TextPosition; +} + +export interface TextSelection { + anchor: TextPosition; + active: TextPosition; +} + +export interface DocumentSummary { + documentID: string; + version: number; + /** Workspace-relative, or null outside the root. */ + path: string | null; + languageID: string | null; + isReadOnly: boolean; + isDirty: boolean; + encoding: string; + lineEnding: string; + [key: string]: unknown; +} + +export interface EditResult { + documentID: string; + version: number; + applied: boolean; + [key: string]: unknown; +} + +export interface OpenParams { + resource: WorkspaceResource; + activation?: 'select' | 'background'; + range?: TextRange; + tab?: 'regular'; +} + +export interface FindPage { + matches: T[]; + nextCursor: string | null; + isTruncated: boolean; + source: 'disk'; + [key: string]: unknown; +} + +type Scoped = (context: ContextReference, params: P, options?: HostRequestOptions) => Promise; +type ScopedOptional = (context: ContextReference, params?: P, options?: HostRequestOptions) => Promise; + +/** One enabled plugin that exports a function, from `host.functions.providers`. */ +export interface FunctionProvider { + pluginID: string; + /** The contract version of the exported function. */ + version: number; +} + +export interface FunctionProvidersResult { + /** Enabled plugins other than the caller, sorted by plugin ID. */ + providers: FunctionProvider[]; +} + +/** One cross-plugin call, the argument of `host.functions.invoke`. */ +export interface FunctionCall { + /** The providing plugin, one of `providers(functionID)`. */ + pluginID: string; + functionID: string; + /** A JSON object; not sent when omitted, which Core reads as `{}`. */ + params?: JsonObject; + /** A positive integer. Core defaults it to 60000 and caps it at 600000. */ + timeoutMilliseconds?: number; + /** + * The `operationID` of the call this one belongs to, a string of 1-128 bytes. + * Inside a function handler `context.host` fills it with the call being + * served; `backend.host` has no default. + */ + parentOperationID?: string; +} + +export interface FunctionInvokeResult { + /** The provider's result; `null` is a result. */ + value: JsonValue; +} + +/** + * Host services of plugin-function protocols 2 to 4. Every method rejects + * with `HostError` when the host refuses; from protocol 3 check + * `supports(method)` instead of assuming a method from the version. + * A full `WorkspaceContext` may be passed wherever a reference is expected. + */ +export interface Host { + /** The negotiated plugin-function version, or 0 before or without one. */ + readonly version: number; + /** Sends any `lithe/host/*` request, including ones a later host adds. */ + request(method: string, params?: JsonObject, options?: HostRequestOptions): Promise; + /** Sends a request answering `{ subscriptionID }` and routes that subscription's events. */ + subscribe(method: string, params: JsonObject, onEvent?: SubscriptionHandler, options?: HostRequestOptions): Promise; + /** The session's capabilities; protocol 3, cached. */ + capabilities(): Promise; + /** Whether this session may call `method`. Under protocol 2, which has no discovery, the methods it defines. */ + supports(method: string): Promise; + /** Protocol 2; permission `credentials.store`. Kept in the platform's secret store, per plugin. */ + readonly credentials: { + /** The stored secret, or null. */ + get(key: string, options?: HostRequestOptions): Promise; + set(key: string, secret: string, options?: HostRequestOptions): Promise; + delete(key: string, options?: HostRequestOptions): Promise; + }; + readonly subscriptions: { + dispose(subscriptionID: string): Promise; + }; + readonly workspace: { + /** Permission `workspace.metadata`. Entries carry no `stateDirectory`. */ + listContexts(options?: HostRequestOptions): Promise<{ revision: number; contexts: WorkspaceContext[] }>; + getContext(context: ContextReference, options?: HostRequestOptions): Promise; + getFolders(context: ContextReference, options?: HostRequestOptions): Promise<{ folders: WorkspaceFolder[] }>; + /** Permission `workspace.files.read`. */ + readDirectory: Scoped<{ resource: WorkspaceResource; cursor?: string; limit?: number }, { + entries: { name: string; resource: WorkspaceResource; kind: string }[]; + nextCursor: string | null; + }>; + stat: Scoped<{ resource: WorkspaceResource }, { resource: WorkspaceResource; kind: string; size: number; modifiedMilliseconds: number }>; + readFile: Scoped<{ resource: WorkspaceResource; maximumBytes?: number }, { + resource: WorkspaceResource; + source: 'disk'; + byteCount: number; + isTruncated: boolean; + identity: JsonValue; + text?: string; + encoding?: string; + base64?: string; + }>; + /** Permission `workspace.files.watch`. Events carry `{ rootID, changedPaths, requiresRescan }`. */ + watch( + context: ContextReference, + params: { resource: WorkspaceResource; recursive?: boolean }, + onEvent: SubscriptionHandler, + options?: HostRequestOptions, + ): Promise; + /** Permission `workspace.search`; `resource` names the root (`path: ""`). */ + findFiles: Scoped<{ resource: WorkspaceResource; query: string; fileMask?: string; cursor?: string; limit?: number }, FindPage>; + findText: Scoped<{ + resource: WorkspaceResource; + pattern: string; + fileMask?: string; + caseSensitive?: boolean; + wholeWords?: boolean; + regularExpression?: boolean; + cursor?: string; + limit?: number; + }, FindPage<{ resource: WorkspaceResource; line: number; preview: string; range: TextRange | null }>>; + }; + /** Permission `documents.read`. */ + readonly documents: { + list: ScopedOptional; + getSnapshot: Scoped<{ documentID: string }, { document: DocumentSummary; text: string }>; + }; + readonly editor: { + getActive: ScopedOptional; + getSelections: Scoped<{ documentID: string }, { documentID: string; version: number; selections: TextSelection[]; primaryIndex: number }>; + /** Permission `editor.edit`. Not replayed on cancellation or timeout: the edit may have committed. */ + applyEdits: Scoped<{ documentID: string; expectedVersion: number; edits: { range: TextRange; text: string }[] }, EditResult>; + replaceSelections: Scoped<{ documentID: string; expectedVersion: number; selections: TextSelection[]; replacements: string[] }, EditResult>; + insertText: Scoped<{ documentID: string; expectedVersion: number; at: TextPosition; text: string }, EditResult>; + /** Permission `editor.open`. */ + open: Scoped; + reveal: Scoped; + /** Permission `editor.actions`; the host later calls `function` to collect actions. */ + registerActions( + context: ContextReference, + params: { id: string; function: string; selector: { fileExtensions?: string[]; fileNames?: string[] } }, + options?: HostRequestOptions, + ): Promise; + }; + /** Permission `preview.open`. */ + readonly preview: { + openHTML: Scoped<{ resource: WorkspaceResource; presentation?: 'editorAndPreview' | 'previewOnly'; range?: TextRange }, JsonObject>; + }; + /** Permission `browser.open`; exactly one of `url` or `resource`. */ + readonly browser: { + openExternal: Scoped< + { url: string } | { resource: WorkspaceResource; unsaved?: 'openSavedFile' | 'requireSaved' }, + { opened: true; source: 'web' | 'disk'; hasUnsavedChanges?: boolean } + >; + }; + /** + * Protocol 4; the manifest's `pluginFunctions.calls`. Calls between plugins, + * relayed through Core. Under protocol 3 or earlier both reject at once with + * `HostError` `plugin.host.unavailable`, and nothing is sent. Argument + * mistakes reject with `PluginSdkError` `sdk.functions.invalidCall`, or + * `sdk.host.invalidContext` for the context, before anything is sent. + */ + readonly functions: { + /** The enabled plugins other than this one that export `functionID`. */ + providers(functionID: string, options?: HostRequestOptions): Promise; + /** Calls one provider's function in a workspace context. A provider's own failure is `plugin.function.failed`. */ + invoke(context: ContextReference, call: FunctionCall, options?: HostRequestOptions): Promise; + }; + /** Permission `terminal.create`; only terminals owned by this backend session and context. */ + readonly terminal: { + create: Scoped<{ executable: string; arguments?: string[]; title?: string; cwd?: WorkspaceResource; + environment?: Record; show?: boolean; retainedContextBytes?: number }, { terminalID: string; generation: number }>; + show: Scoped<{ terminalID: string }, null>; + close: Scoped<{ terminalID: string; retainedContextBytes?: number }, { retainedContextBytes: number }>; + reopen: Scoped<{ terminalID: string; show?: boolean }, { terminalID: string; generation: number; restoredContextBytes: number }>; + dispose: Scoped<{ terminalID: string }, null>; + onExit(context: ContextReference, terminalID: string, + onEvent: (event: { type: 'exit'; terminalID: string; exitCode: number | null; reason: 'exited' | 'closed'; generation: number }, metadata: SubscriptionEventInfo) => void, + options?: HostRequestOptions): Promise; + }; + /** Permission `window.messages`. `selectedIndex` is zero-based, or null on dismissal. */ + readonly window: { + showInformation: Scoped<{ text: string; actions?: string[] }, { selectedIndex: number | null }>; + showWarning: Scoped<{ text: string; actions?: string[] }, { selectedIndex: number | null }>; + showError: Scoped<{ text: string; actions?: string[] }, { selectedIndex: number | null }>; + }; +} + +export interface CommandEvent { + commandID: string; + /** The context of the window the command ran in, or null. */ + workspaceContext: ContextReference | null; +} + +export interface ProgressReport { + /** Cut to 1024 bytes. */ + message?: string; + /** Rounded and clamped to 0-100. */ + percentage?: number; +} + +export interface FunctionContext extends RequestContext { + functionID: string; + /** Opaque per-call ID chosen by Lithe. */ + operationID: string; + /** The context of the page's window (protocol 3), or null. */ + workspaceContext: ContextReference | null; + /** + * The plugin that called this function through the relay (protocol 4), or + * null: the host started the call, or the session negotiated less than 4. + * Decide by this field, never by a plugin ID inside `params`. + */ + readonly caller: { readonly pluginID: string } | null; + /** Reports progress; ignored once the call has ended. */ + progress(report: ProgressReport): void; +} + +export type FunctionHandler = (params: JsonObject, context: FunctionContext) => unknown | Promise; +export type BuildHandler = (params: BuildRequestParams, context: RequestContext) => JsonObject | Promise; + +/** A file captured under the selected shortcut source. `path` is a relative label. */ +export interface KeymapSourceFile { id: string; path: string; byteCount: number } +export interface KeymapImportSnapshot { + readonly providerID: string; + readonly snapshotID: string; + listInputs(): Promise; + readChunk(fileID: string, offset: number, maximumBytes: number): Promise; +} +export interface KeymapImportBinding { + commandID: string; + keys: Array<{ key: string; modifiers: Array<'control' | 'alt' | 'shift' | 'meta'> }>; +} +export type KeymapImportHandler = (snapshot: KeymapImportSnapshot, context: RequestContext) => + { bindings: KeymapImportBinding[] } | Promise<{ bindings: KeymapImportBinding[] }>; + +/** Params of `lithe/build/model` and `lithe/build/dependencies`. */ +export interface BuildRequestParams { + /** Read-only host snapshot; missing producers remain unavailable. Requires protocol 6. */ + modelInputs?: BuildModelInputs; + buildSystemID: string; + root: string; + options: JsonObject; + optionArguments: string[]; + environment: Record; + /** Dependencies only: the selected project, or null for the workspace. */ + project?: { name: string; path: string } | null; + /** True when the user or a sync-file change asked to reload; skip any snapshot. */ + refresh?: boolean; + /** The build tool the host resolved; absent when it could not, so look it up yourself. */ + tool?: { executable: string }; + [key: string]: unknown; +} + +/** Public normalized facts. Tasks, run plans, settings and optionValues never cross this boundary. */ +export interface BuildSharedModel { + projects: { id: string; name: string; path: string; displayName?: string; parentID?: string; properties: Record }[]; + targets: { id: string; projectID: string; name: string; path: string; tags: string[]; properties: Record }[]; + contentRoots: { projectID: string; path: string; kind: string }[]; +} +export type BuildModelInputInstance = + | { root: string; state: 'ready'; model: BuildSharedModel; configurationFingerprint: string; options: JsonObject } + | { root: string; state: 'loading' | 'stale' | 'failed' }; +export interface BuildModelInputs { + version: 1; + /** Opaque workspace-activation revision; discard cached work after it changes. */ + revision: number; + inputs: { pluginID: string; buildSystemID: string; state: 'available' | 'unavailable'; instances: BuildModelInputInstance[] }[]; +} + +/** Current upstream model selection, preserved as data rather than shell text. */ +export interface BuildSelection { + name: string; + path: string; + tags?: string[]; + properties?: JsonObject; +} + +export interface BuildExecutionParams extends BuildRequestParams { + task: string; + project?: BuildSelection | null; + target?: BuildSelection | null; + userArguments: string[]; + operationID: string; +} + +export interface BuildTestParams extends BuildRequestParams { + project?: BuildSelection | null; + target?: BuildSelection | null; + suite?: string; + case?: string; + userArguments: string[]; + operationID: string; +} + +export interface BuildRunParams extends BuildRequestParams { + run: string; + project: BuildSelection; + target: BuildSelection; + userArguments: string[]; + operationID: string; +} + +export interface BuildProgressReport extends ProgressReport { + /** Cut to 64 KiB of UTF-8 per notification. Build messages are cut to 4096 bytes. */ + output?: string; +} + +export interface BuildContext extends RequestContext { + /** The Core-assigned wire identity, never a plugin-selected value. */ + operationID: string; + /** Dropped after cancellation or completion. */ + progress(report: BuildProgressReport): void; +} + +export interface BuildExecutionResult { exitCode: number; output: string; } +export interface BuildTestDiscovery { + format?: 'litheTestDiscovery'; + version?: 1; + tests: { suite: string; case: string; project?: BuildSelection; target?: BuildSelection }[]; +} +export interface BuildRunPreparation { + executable: { kind: 'toolchain' | 'command'; value: string }; + arguments: string[]; + workingDirectory: string; + environment: Record; +} +export type BuildExecutionHandler = (params: BuildExecutionParams, context: BuildContext) => BuildExecutionResult | Promise; +export type BuildTestHandler = (params: BuildTestParams, context: BuildContext) => BuildExecutionResult | Promise; +export type BuildDiscoveryHandler = (params: BuildRequestParams, context: RequestContext) => BuildTestDiscovery | Promise; +export interface BuildDebugPreparation { + program: string; + arguments: string[]; + workingDirectory: string; + environment: Record; +} +export type BuildDebugHandler = (params: BuildRunParams, context: BuildContext) => BuildDebugPreparation | Promise; +export type BuildRunHandler = (params: BuildRunParams, context: BuildContext) => BuildRunPreparation | Promise; + +/** Params every VCS handler receives, on top of its operation's arguments. */ +export interface VcsRequestParams { + root: { path: string }; + /** The VCS client the host resolved; null when it could not, so report `vcs.tool.unavailable`. */ + tool: { executable: string } | null; + [key: string]: unknown; +} + +export interface VcsRunOptions extends RunProcessOptions { + /** Report the finished command as `lithe/vcs/execution`; default true. */ + report?: boolean; +} + +export interface VcsContext extends RequestContext { + /** `RequestContext.run` that also reports each finished command to the host's console. */ + run(command: string, args?: string[], options?: VcsRunOptions): Promise; +} + +export type VcsHandler = (params: VcsRequestParams, context: VcsContext) => JsonObject | void | Promise; + +/** Handlers keyed by operation; see shared/contracts/vcs-provider-v1.md for each reply. */ +export interface VcsHandlers { + status: VcsHandler; + baseContent: VcsHandler; + checkin: VcsHandler; + rollback: VcsHandler; + history?: VcsHandler; + fileHistory?: VcsHandler; + annotate?: VcsHandler; + update?: VcsHandler; + fileOperation?: VcsHandler; + resolve?: VcsHandler; + cleanup?: VcsHandler; +} + +export interface VcsTraits { + /** Check-in is local and publishing is a separate step. */ + push?: boolean; + /** Changes carry a staged/unstaged dimension. */ + staging?: boolean; +} + +export interface Negotiated { + functions: boolean; + build: boolean; + vcs: boolean; +} + +export interface BackendOptions { + name?: string; + version?: string; + /** Standard LSP server capabilities; the SDK negotiates its experimental protocols. */ + capabilities?: JsonObject; +} + +export interface ListenOptions { + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + errorOutput?: NodeJS.WritableStream; + /** Defaults to `process.exit`; null only resolves the returned promise. */ + exit?: ((code: number) => void) | null; +} + +export interface Backend { + readonly negotiated: Negotiated; + readonly initializeParams: JsonObject | null; + /** Highest common version (1-6), or null before/without negotiation. */ + readonly buildVersion: number | null; + /** Highest common plugin-function version (1-4), or null before/without negotiation. */ + readonly functionsVersion: number | null; + readonly functionIDs: string[]; + /** Host services; usable once the session is ready. */ + readonly host: Host; + readonly build: { + model(handler: BuildHandler): Backend; + dependencies(handler: BuildHandler): Backend; + execute(handler: BuildExecutionHandler): Backend; + test(handler: BuildTestHandler): Backend; + discoverTests(handler: BuildDiscoveryHandler): Backend; + prepareRun(handler: BuildRunHandler): Backend; + prepareDebug(handler: BuildDebugHandler): Backend; + }; + vcs(id: string, handlers: VcsHandlers, traits?: VcsTraits): Backend; + function(id: string, handler: FunctionHandler): Backend; + /** Declares an independent shortcut import provider before initialize. */ + keymapImportProvider(id: string, handler: KeymapImportHandler): Backend; + registerFunction(id: string, handler: FunctionHandler): Promise; + unregisterFunction(id: string): Promise; + onRequest(method: string, handler: (params: unknown, context: RequestContext) => unknown): Backend; + onNotification(method: string, handler: (params: unknown) => unknown): Backend; + /** Handles `lithe/host/commands/didRun` for one of the plugin's commands (protocol 3). */ + onCommand(commandID: string, handler: (event: CommandEvent) => unknown): Backend; + /** Handles `lithe/host/workspace/didChangeContexts` (protocol 3). */ + onContextsChanged(handler: (event: { revision: number }) => unknown): Backend; + /** Handles a `lithe/host/*` notification a later host adds. */ + onHostNotification(method: string, handler: (params: JsonObject) => unknown): Backend; + onInitialize(hook: (event: { params: JsonObject; negotiated: Negotiated }) => unknown): Backend; + onShutdown(hook: () => unknown): Backend; + sendRequest(method: string, params?: unknown): Promise; + sendNotification(method: string, params?: unknown): void; + readonly diagnostics: Diagnostics; + suppressSuccessDiagnostics(operation: string): this; + listen(options?: ListenOptions): Promise; +} + +export function createBackend(options?: BackendOptions): Backend; + +export class PluginError extends Error { + constructor(code: string, message: string, options?: { cause?: unknown }); + readonly code: string; +} + +export class PluginSdkError extends Error { + readonly code: string; +} + +/** The host refused or failed a request this backend sent. */ +export class HostError extends PluginSdkError { + /** `error.data.code`, such as `plugin.host.contextExpired`. */ + readonly code: string; + /** The JSON-RPC error number. */ + readonly rpcCode: number | undefined; + /** Protocol 3 details, such as `{ option }` or `{ retryAfterMilliseconds }`. */ + readonly details: JsonObject | undefined; + readonly method: string | undefined; +} + +export function runProcess(command: string, args?: string[], options?: RunProcessOptions): Promise; + +export interface StateStore { + readonly directory: string; + read(key: string, fallback?: T): T | undefined; + write(key: string, value: JsonValue): void; + delete(key: string): void; +} + +export function openStateStore(directory: string, options?: { packageDirectory?: string | null }): StateStore; + +export function isFunctionId(value: unknown): boolean; + +/** + * Host failure codes and the JSON-RPC number each has from protocol 3. The + * `plugin.function.*` codes belong to the relay (protocol 4). + */ +export const HOST_ERRORS: Readonly<{ + 'plugin.host.unavailable': -32601; + 'plugin.host.invalidParams': -32602; + 'plugin.host.failed': -32603; + 'plugin.host.cancelled': -32800; + 'plugin.host.permissionDenied': -32010; + 'plugin.host.contextExpired': -32011; + 'plugin.host.authorityUnsupported': -32012; + 'plugin.host.versionConflict': -32013; + 'plugin.host.limitExceeded': -32014; + 'plugin.host.timeout': -32015; + 'plugin.host.notFound': -32016; + 'plugin.host.readOnly': -32017; + 'plugin.host.unsupportedOption': -32018; + 'plugin.host.preconditionFailed': -32019; + 'plugin.host.busy': -32020; + 'plugin.host.rateLimited': -32021; + 'plugin.host.languageServerUnavailable': -32022; + 'plugin.host.languageServerError': -32023; + 'plugin.host.methodNotDeclared': -32024; + 'plugin.host.toolUnresolved': -32025; + 'plugin.host.foreignContribution': -32026; + 'plugin.function.notDeclared': -32027; + 'plugin.function.notExported': -32028; + 'plugin.function.providerDisabled': -32029; + 'plugin.function.versionMismatch': -32030; + 'plugin.function.callCycle': -32065; + 'plugin.function.depthExceeded': -32066; + 'plugin.function.tooManyCalls': -32067; + 'plugin.function.payloadTooLarge': -32068; + 'plugin.function.providerUnavailable': -32069; + 'plugin.function.failed': -32070; + 'plugin.function.invalidResult': -32071; +}>; + +/** Host request method names of protocols 2 to 4. */ +export const HOST_METHODS: Readonly>; + +export function isVcsId(value: unknown): boolean; + +/** Provider error codes Core passes on; use them as `PluginError` codes. */ +export const VCS_ERRORS: Readonly<{ + authenticationFailed: 'vcs.authentication.failed'; + conflict: 'vcs.conflict'; + outOfDate: 'vcs.outOfDate'; + toolUnavailable: 'vcs.tool.unavailable'; + workingCopyLocked: 'vcs.workingCopy.locked'; + workingCopyUnsupported: 'vcs.workingCopy.unsupported'; +}>; + +export const LIMITS: Readonly<{ + maxFunctions: number; + maxFunctionIdBytes: number; + maxPluginErrorCodeBytes: number; + maxMessageBytes: number; + maxResultBytes: number; + maxBuildResultBytes: number; + maxBuildMessageBytes: number; + maxBuildOutputBytes: number; + maxVcsIdBytes: number; + maxExecutionErrorOutputBytes: number; + maxCredentialKeyBytes: number; + maxCredentialSecretBytes: number; + maxPendingHostRequests: number; + relayDefaultTimeoutMilliseconds: number; + relayMaxTimeoutMilliseconds: number; + maxParentOperationIdBytes: number; +}>; diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs new file mode 100644 index 0000000..6c1d1dd --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs @@ -0,0 +1,8 @@ +// Official Node.js SDK for Lithe plugin backends. +// Guide: sdk/node/README.md. Wire contract: contract/v1/README.md. + +export { createBackend } from './backend.mjs'; +export { HostError, PluginError, PluginSdkError } from './errors.mjs'; +export { runProcess } from './process.mjs'; +export { openStateStore } from './state.mjs'; +export { HOST_ERRORS, HOST_METHODS, isFunctionId, isVcsId, LIMITS, VCS_ERRORS } from './protocol.mjs'; diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs new file mode 100644 index 0000000..03f59df --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs @@ -0,0 +1,188 @@ +// Child processes a backend starts for one call. Lithe's host offers no +// process capability in protocol version 1, so a backend runs its tools +// itself; this helper makes sure that the call ending, cancelling it, or the +// backend shutting down also ends the whole process tree it started. When the +// backend itself is killed no JavaScript runs; the host then ends what is left +// through its own process lifecycle, which owns that boundary. + +import { spawn } from 'node:child_process'; +import { StringDecoder } from 'node:string_decoder'; + +const isWindows = process.platform === 'win32'; + +/** Every process tree started through `runProcess` that has not exited. */ +const running = new Set(); + +/** + * Variables Lithe sets on the backend so it can find and end every process + * the backend started, even one that left its process group. A tool always + * inherits them, also when the plugin replaces the environment. + */ +const HOST_MARKERS = ['LITHE_PROCESS_SCOPE', 'LITHE_PLUGIN_BACKEND_SCOPE']; + +function withHostMarkers(env) { + const result = { ...env }; + for (const name of HOST_MARKERS) { + if (process.env[name] === undefined) delete result[name]; + else result[name] = process.env[name]; + } + return result; +} + +/** + * Runs `command` without a shell and resolves with its exit status and + * captured output. Aborting `signal` ends the process tree and rejects with + * the signal's reason. A non-zero exit resolves; the caller decides what it + * means for its tool. + * + * @param {string} command Executable path or name. + * @param {string[]} [args] + * @param {object} [options] + * @param {string} [options.cwd] + * @param {Record} [options.env] Replaces the environment when given; the + * host's process markers are carried over regardless. + * @param {AbortSignal} [options.signal] + * @param {number} [options.maxOutputBytes] Captured bytes per stream; default 1 MiB. + * @param {(chunk: string) => void} [options.onStdout] + * @param {(chunk: string) => void} [options.onStderr] + * @param {number} [options.killGraceMilliseconds] Delay between the polite and forced stop; default 2000. + */ +export function runProcess(command, args = [], options = {}) { + const { cwd, env, signal, onStdout, onStderr } = options; + const maxOutputBytes = options.maxOutputBytes ?? 1 << 20; + const killGraceMilliseconds = options.killGraceMilliseconds ?? 2000; + if (signal?.aborted) return Promise.reject(signal.reason); + + return new Promise((resolve, reject) => { + const child = spawn(command, args, { + cwd, + env: env && withHostMarkers(env), + shell: false, + windowsHide: true, + // Its own process group on POSIX, so a stop reaches grandchildren too. + detached: !isWindows, + stdio: ['ignore', 'pipe', 'pipe'], + }); + const entry = { child, stopping: false, forceTimer: null }; + running.add(entry); + const stdout = capture(maxOutputBytes, onStdout); + const stderr = capture(maxOutputBytes, onStderr); + child.stdout.on('data', stdout.push); + child.stderr.on('data', stderr.push); + + const onAbort = () => stopTree(entry, killGraceMilliseconds); + signal?.addEventListener('abort', onAbort, { once: true }); + + let settled = false; + const finish = (outcome) => { + if (settled) return; + settled = true; + // A stopped tree stays registered until its forced stop: the leader + // can exit on SIGTERM while a grandchild in its group ignores it. + if (!entry.stopping) { + // The leader ended on its own; members it left behind in its group, + // such as a background worker, end with it. + signalTree(child, 'SIGKILL', { evenAfterExit: true }); + running.delete(entry); + } + signal?.removeEventListener('abort', onAbort); + stdout.end(); + stderr.end(); + outcome(); + }; + child.once('error', (error) => finish(() => reject(error))); + child.once('close', (exitCode, exitSignal) => + finish(() => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + resolve({ + exitCode, + signal: exitSignal, + stdout: stdout.text(), + stderr: stderr.text(), + truncated: stdout.truncated() || stderr.truncated(), + }); + }), + ); + }); +} + +/** + * Forcibly ends every process tree still running. The backend calls it on + * shutdown, on `exit`, and when the host closes stdin, so no tool outlives + * the session that started it. + */ +export function killAllProcesses() { + for (const entry of running) { + clearTimeout(entry.forceTimer); + signalTree(entry.child, 'SIGKILL', { evenAfterExit: true }); + } + running.clear(); +} + +/** Number of process trees still running or being stopped, for tests and diagnostics. */ +export function runningProcessCount() { + return running.size; +} + +function stopTree(entry, graceMilliseconds) { + if (entry.stopping) return; + entry.stopping = true; + signalTree(entry.child, 'SIGTERM'); + entry.forceTimer = setTimeout(() => { + running.delete(entry); + signalTree(entry.child, 'SIGKILL', { evenAfterExit: true }); + }, graceMilliseconds); + entry.forceTimer.unref?.(); +} + +/** + * Signals the child's whole tree. `evenAfterExit` still signals the POSIX + * process group after its leader exited, which reaches members that survived + * the polite stop. While any member lives the group ID cannot be reused; + * once all exited the signal fails with ESRCH, which is ignored. + */ +function signalTree(child, signalName, { evenAfterExit = false } = {}) { + if (child.pid === undefined) return; + const exited = child.exitCode !== null || child.signalCode !== null; + if (exited && (isWindows || !evenAfterExit)) return; + try { + if (isWindows) { + // taskkill /T is the only stock way to end a Windows process tree. + spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); + } else { + process.kill(-child.pid, signalName); + } + } catch { + // The group already exited between the check and the signal. + } +} + +function capture(limit, listener) { + const chunks = []; + // Keeps a multi-byte character split across chunks whole in `listener`. + const decoder = new StringDecoder('utf8'); + let size = 0; + let truncated = false; + const deliver = (text) => { + if (text) listener?.(text); + }; + return { + push(chunk) { + deliver(decoder.write(chunk)); + if (size >= limit) { + truncated = true; + return; + } + const kept = chunk.subarray(0, limit - size); + truncated ||= kept.length < chunk.length; + chunks.push(kept); + size += kept.length; + }, + end: () => deliver(decoder.end()), + text: () => Buffer.concat(chunks).toString('utf8'), + truncated: () => truncated, + }; +} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs new file mode 100644 index 0000000..f96cad3 --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs @@ -0,0 +1,293 @@ +// Wire constants and validation shared with Lithe's Rust Core +// (rust/lithe-core/src/lsp/interface/plugin_function.rs and +// rust/lithe-core/src/vcs/ in the Lithe repository). The SDK checks the +// same rules locally so a plugin author sees a mistake when registering a +// handler instead of as a refused session at runtime. + +/** Protocol versions this SDK can answer: the highest of each. */ +export const FUNCTIONS_VERSION = 4; +export const BUILD_VERSION = 6; +export const VCS_VERSION = 1; + +/** First plugin-function version with host services (credentials). */ +export const HOST_SERVICES_VERSION = 2; +/** First plugin-function version with workspace contexts, discovery, and host notifications. */ +export const CONTEXT_VERSION = 3; +/** First plugin-function version with cross-plugin calls relayed through Core and the callee's `caller`. */ +export const RELAY_VERSION = 4; + +export const METHODS = Object.freeze({ + initialize: 'initialize', + initialized: 'initialized', + shutdown: 'shutdown', + exit: 'exit', + cancelRequest: '$/cancelRequest', + functionInvoke: 'lithe/function/invoke', + functionRegister: 'lithe/function/register', + functionUnregister: 'lithe/function/unregister', + functionProgress: 'lithe/function/progress', + buildModel: 'lithe/build/model', + buildDependencies: 'lithe/build/dependencies', + buildExecute: 'lithe/build/execute', + buildTest: 'lithe/build/test', + buildDiscoverTests: 'lithe/build/discoverTests', + buildPrepareRun: 'lithe/build/prepareRun', + buildPrepareDebug: 'lithe/build/prepareDebug', + buildProgress: 'lithe/build/progress', + vcsExecution: 'lithe/vcs/execution', +}); + +/** + * Backend-to-host requests of plugin-function protocols 2 to 4. From + * version 3 the host adds methods without a new version; `host.request` + * sends any `lithe/host/*` method, and `getCapabilities` says which ones + * this session may call. The two `functions` methods are the exception: + * they need version 4. + */ +export const HOST_METHODS = Object.freeze({ + credentialsGet: 'lithe/host/credentials/get', + credentialsSet: 'lithe/host/credentials/set', + credentialsDelete: 'lithe/host/credentials/delete', + getCapabilities: 'lithe/host/getCapabilities', + subscriptionsDispose: 'lithe/host/subscriptions/dispose', + workspaceListContexts: 'lithe/host/workspace/listContexts', + workspaceGetContext: 'lithe/host/workspace/getContext', + workspaceGetFolders: 'lithe/host/workspace/getFolders', + workspaceReadDirectory: 'lithe/host/workspace/readDirectory', + workspaceStat: 'lithe/host/workspace/stat', + workspaceReadFile: 'lithe/host/workspace/readFile', + workspaceWatch: 'lithe/host/workspace/watch', + workspaceFindFiles: 'lithe/host/workspace/findFiles', + workspaceFindText: 'lithe/host/workspace/findText', + documentsList: 'lithe/host/documents/list', + documentsGetSnapshot: 'lithe/host/documents/getSnapshot', + editorRegisterActions: 'lithe/host/editor/registerActions', + editorGetActive: 'lithe/host/editor/getActive', + editorGetSelections: 'lithe/host/editor/getSelections', + editorApplyEdits: 'lithe/host/editor/applyEdits', + editorReplaceSelections: 'lithe/host/editor/replaceSelections', + editorInsertText: 'lithe/host/editor/insertText', + editorOpen: 'lithe/host/editor/open', + editorReveal: 'lithe/host/editor/reveal', + previewOpenHTML: 'lithe/host/preview/openHTML', + browserOpenExternal: 'lithe/host/browser/openExternal', + windowShowInformation: 'lithe/host/window/showInformation', + windowShowWarning: 'lithe/host/window/showWarning', + windowShowError: 'lithe/host/window/showError', + terminalCreate: 'lithe/host/terminal/create', + terminalShow: 'lithe/host/terminal/show', + terminalClose: 'lithe/host/terminal/close', + terminalReopen: 'lithe/host/terminal/reopen', + terminalDispose: 'lithe/host/terminal/dispose', + terminalOnExit: 'lithe/host/terminal/onExit', + functionsProviders: 'lithe/host/functions/providers', + functionsInvoke: 'lithe/host/functions/invoke', +}); + +/** Host-to-backend notifications of protocol 3. */ +export const HOST_NOTIFICATIONS = Object.freeze({ + didChangeContexts: 'lithe/host/workspace/didChangeContexts', + subscriptionNotify: 'lithe/host/subscriptions/notify', + commandDidRun: 'lithe/host/commands/didRun', +}); + +/** + * Host failure codes (`error.data.code`) and the JSON-RPC number Core sends + * with each to a version 3 or 4 backend. A number never changes meaning; a + * later host adds codes after the last one listed here. The + * `plugin.function.*` codes are the relay's own (protocol 4). + */ +export const HOST_ERRORS = Object.freeze({ + 'plugin.host.unavailable': -32601, + 'plugin.host.invalidParams': -32602, + 'plugin.host.failed': -32603, + 'plugin.host.cancelled': -32800, + 'plugin.host.permissionDenied': -32010, + 'plugin.host.contextExpired': -32011, + 'plugin.host.authorityUnsupported': -32012, + 'plugin.host.versionConflict': -32013, + 'plugin.host.limitExceeded': -32014, + 'plugin.host.timeout': -32015, + 'plugin.host.notFound': -32016, + 'plugin.host.readOnly': -32017, + 'plugin.host.unsupportedOption': -32018, + 'plugin.host.preconditionFailed': -32019, + 'plugin.host.busy': -32020, + 'plugin.host.rateLimited': -32021, + 'plugin.host.languageServerUnavailable': -32022, + 'plugin.host.languageServerError': -32023, + 'plugin.host.methodNotDeclared': -32024, + 'plugin.host.toolUnresolved': -32025, + 'plugin.host.foreignContribution': -32026, + 'plugin.function.notDeclared': -32027, + 'plugin.function.notExported': -32028, + 'plugin.function.providerDisabled': -32029, + 'plugin.function.versionMismatch': -32030, + 'plugin.function.callCycle': -32065, + 'plugin.function.depthExceeded': -32066, + 'plugin.function.tooManyCalls': -32067, + 'plugin.function.payloadTooLarge': -32068, + 'plugin.function.providerUnavailable': -32069, + 'plugin.function.failed': -32070, + 'plugin.function.invalidResult': -32071, +}); + +/** Minimum negotiated version of each typed build operation. */ +export const BUILD_METHOD_VERSIONS = Object.freeze({ + [METHODS.buildModel]: 1, + [METHODS.buildDependencies]: 1, + [METHODS.buildExecute]: 2, + [METHODS.buildTest]: 3, + [METHODS.buildDiscoverTests]: 3, + [METHODS.buildPrepareRun]: 4, + [METHODS.buildPrepareDebug]: 5, +}); + +/** + * VCS-provider operations: the handler name a plugin declares, the request + * Core sends for it, and the capability declaring the handler negotiates. + * Contract: shared/contracts/vcs-provider-v1.md. + */ +export const VCS_OPERATIONS = Object.freeze({ + status: Object.freeze({ method: 'lithe/vcs/status', capability: 'status' }), + baseContent: Object.freeze({ method: 'lithe/vcs/baseContent', capability: 'baseContent' }), + history: Object.freeze({ method: 'lithe/vcs/history', capability: 'history' }), + fileHistory: Object.freeze({ method: 'lithe/vcs/fileHistory', capability: 'fileHistory' }), + annotate: Object.freeze({ method: 'lithe/vcs/annotate', capability: 'annotate' }), + checkin: Object.freeze({ method: 'lithe/vcs/checkin', capability: 'checkin' }), + rollback: Object.freeze({ method: 'lithe/vcs/rollback', capability: 'rollback' }), + update: Object.freeze({ method: 'lithe/vcs/update', capability: 'update' }), + fileOperation: Object.freeze({ method: 'lithe/vcs/fileOperation', capability: 'fileOperations' }), + resolve: Object.freeze({ method: 'lithe/vcs/resolve', capability: 'conflicts' }), + cleanup: Object.freeze({ method: 'lithe/vcs/cleanup', capability: 'cleanup' }), +}); + +/** Handlers every VCS provider must declare; Core refuses a provider without them. */ +export const VCS_REQUIRED_OPERATIONS = Object.freeze(['status', 'baseContent', 'checkin', 'rollback']); + +/** + * The provider error codes Core passes on (`error.data.code`). Throw a + * `PluginError` with one of them; any other code reaches the host as + * `vcs.provider.failed`. + */ +export const VCS_ERRORS = Object.freeze({ + authenticationFailed: 'vcs.authentication.failed', + conflict: 'vcs.conflict', + outOfDate: 'vcs.outOfDate', + toolUnavailable: 'vcs.tool.unavailable', + workingCopyLocked: 'vcs.workingCopy.locked', + workingCopyUnsupported: 'vcs.workingCopy.unsupported', +}); + +/** JSON-RPC and LSP error codes the SDK answers with. */ +export const ERROR_CODES = Object.freeze({ + parseError: -32700, + invalidRequest: -32600, + methodNotFound: -32601, + invalidParams: -32602, + internalError: -32603, + serverNotInitialized: -32002, + requestFailed: -32000, + requestCancelled: -32800, +}); + +export const LIMITS = Object.freeze({ + maxFunctions: 256, + maxFunctionIdBytes: 128, + maxPluginErrorCodeBytes: 64, + maxMessageBytes: 1024, + maxResultBytes: 1 << 20, + maxBuildResultBytes: 32 * 1024 * 1024, + maxBuildMessageBytes: 4096, + maxBuildOutputBytes: 65536, + maxVcsIdBytes: 32, + maxExecutionErrorOutputBytes: 16 * 1024, + maxCredentialKeyBytes: 128, + maxCredentialSecretBytes: 16 * 1024, + maxPendingHostRequests: 16, + // The relay's bounds are Core's to enforce; the SDK only names them. + relayDefaultTimeoutMilliseconds: 60000, + relayMaxTimeoutMilliseconds: 600000, + maxParentOperationIdBytes: 128, +}); + +/** True for the two host methods that need plugin-function protocol 4. */ +export function isRelayMethod(method) { + return method === HOST_METHODS.functionsProviders || method === HOST_METHODS.functionsInvoke; +} + +/** Dot-separated lowerCamelCase segments, for example `snapshot.refresh`. */ +export function isFunctionId(value) { + return ( + typeof value === 'string' && + value.length > 0 && + Buffer.byteLength(value) <= LIMITS.maxFunctionIdBytes && + value.split('.').every((segment) => /^[a-z][A-Za-z0-9]*$/.test(segment)) + ); +} + +/** A VCS ID: lowercase ASCII letters, digits, and `-`, starting with a letter, such as `svn`. */ +export function isVcsId(value) { + return typeof value === 'string' && value.length <= LIMITS.maxVcsIdBytes && /^[a-z][a-z0-9-]*$/.test(value); +} + +/** + * The key alphabet of protocols 2 to 4: 1-128 ASCII letters, digits, `.`, + * `_`, `:`, or `-`. Credential keys, context IDs, and subscription IDs use it. + */ +export function isCredentialKey(value) { + return typeof value === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(value); +} + +/** `{ contextID, generation }`, exactly, naming one generation of one workspace context. */ +export function isContextReference(value) { + return ( + value !== null && + typeof value === 'object' && + !Array.isArray(value) && + Object.keys(value).length === 2 && + isCredentialKey(value.contextID) && + Number.isSafeInteger(value.generation) && + value.generation >= 1 + ); +} + +/** The plugin error code alphabet Core forwards as `pluginErrorCode`. */ +export function isPluginErrorCode(value) { + return ( + typeof value === 'string' && + Buffer.byteLength(value) <= LIMITS.maxPluginErrorCodeBytes && + /^[A-Za-z][A-Za-z0-9._-]*$/.test(value) + ); +} + +/** Cuts `value` to `limit` UTF-8 bytes without splitting a character. */ +export function boundedText(value, limit = LIMITS.maxMessageBytes) { + const text = String(value ?? ''); + if (Buffer.byteLength(text) <= limit) return text; + let used = 0; + let end = 0; + for (const character of text) { + const size = Buffer.byteLength(character); + if (used + size > limit) break; + used += size; + end += character.length; + } + return text.slice(0, end); +} + +/** + * Methods reserved for the SDK. A plugin cannot install its own handler for + * these, or send them to the host: the lifecycle belongs to the host's + * session management, and `lithe/*` belongs to Lithe's typed contracts. + */ +export function isReservedMethod(method) { + return ( + method === METHODS.initialize || + method === METHODS.initialized || + method === METHODS.shutdown || + method === METHODS.exit || + method === METHODS.cancelRequest || + method.startsWith('lithe/') + ); +} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs new file mode 100644 index 0000000..f648bb3 --- /dev/null +++ b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs @@ -0,0 +1,148 @@ +// Durable plugin state. The host gives every backend writable directories +// through the `${stateDir}` and `${workspaceStateDir}` launch variables; the +// installed package and the host's installation are read-only, because +// signatures and delta updates are computed over their exact bytes. + +import { + closeSync, + existsSync, + fsyncSync, + mkdirSync, + openSync, + readFileSync, + realpathSync, + renameSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { randomBytes } from 'node:crypto'; +import { PluginSdkError } from './errors.mjs'; + +/** Version of the envelope each value is stored in. */ +const STORE_FORMAT = 1; +const KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + +/** + * Opens a key-value store in `directory`, creating the directory. Values are + * JSON; each key is one file replaced atomically, so a crash leaves either the + * old or the new value, never half of one. + * + * @param {string} directory Absolute path, normally the value of `${workspaceStateDir}`. + * @param {object} [options] + * @param {string | null} [options.packageDirectory] The installed plugin package, + * which the store refuses to write into. Defaults to the nearest directory + * containing `plugin.json` above the running entry script. + */ +export function openStateStore(directory, options = {}) { + if (typeof directory !== 'string' || !isAbsolute(directory)) { + throw new PluginSdkError('sdk.state.invalidDirectory', 'The state directory must be an absolute path passed by the host.'); + } + const packageDirectory = options.packageDirectory === undefined ? findPackageDirectory() : options.packageDirectory; + // Checked before creating anything, so a refused path leaves the package untouched. + const root = canonical(directory); + if (packageDirectory && isInside(root, canonical(packageDirectory))) { + throw new PluginSdkError( + 'sdk.state.readOnlyPackage', + 'The state directory is inside the plugin package, which is read-only. Use ${stateDir} or ${workspaceStateDir}.', + ); + } + mkdirSync(root, { recursive: true }); + return new StateStore(root); +} + +class StateStore { + #root; + + constructor(root) { + this.#root = root; + } + + /** The resolved directory, for a backend that keeps its own files next to the store. */ + get directory() { + return this.#root; + } + + /** The stored value, or `fallback` when the key is missing or unreadable. */ + read(key, fallback = undefined) { + const path = this.#path(key); + if (!existsSync(path)) return fallback; + try { + const envelope = JSON.parse(readFileSync(path, 'utf8')); + if (envelope?.litheStateStore !== STORE_FORMAT || !('value' in envelope)) return fallback; + return envelope.value; + } catch { + return fallback; + } + } + + /** Stores `value`, which must be JSON-serializable, replacing the previous one. */ + write(key, value) { + const path = this.#path(key); + // `undefined`, a function, or a symbol would vanish from the envelope and + // silently replace the stored value with nothing; refuse it and keep the file. + if (JSON.stringify(value) === undefined) { + throw new PluginSdkError('sdk.state.invalidValue', `The value for ${key} is not JSON-serializable.`); + } + const body = JSON.stringify({ litheStateStore: STORE_FORMAT, value }); + const temporary = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`; + try { + writeFileSync(temporary, body, { encoding: 'utf8', mode: 0o600 }); + const handle = openSync(temporary, 'r'); + try { + fsyncSync(handle); + } finally { + closeSync(handle); + } + renameSync(temporary, path); + } catch (error) { + rmSync(temporary, { force: true }); + throw error; + } + } + + /** Removes the key; a missing key is not an error. */ + delete(key) { + rmSync(this.#path(key), { force: true }); + } + + #path(key) { + if (typeof key !== 'string' || !KEY.test(key) || key.endsWith('.tmp')) { + throw new PluginSdkError( + 'sdk.state.invalidKey', + `State key ${JSON.stringify(key)} must be 1-128 letters, digits, ".", "_" or "-", start with a letter or digit, and not end with ".tmp".`, + ); + } + return join(this.#root, `${key}.json`); + } +} + +function isInside(path, parent) { + const difference = relative(parent, path); + return difference === '' || (!difference.startsWith(`..${sep}`) && difference !== '..' && !isAbsolute(difference)); +} + +/** Resolves symbolic links of the longest existing prefix of `path`. */ +function canonical(path) { + const missing = []; + let current = resolve(path); + while (!existsSync(current)) { + const parent = dirname(current); + if (parent === current) break; + missing.unshift(basename(current)); + current = parent; + } + return join(realpathSync(current), ...missing); +} + +function findPackageDirectory() { + const entry = process.argv[1]; + if (!entry) return null; + let current = dirname(resolve(entry)); + for (;;) { + if (existsSync(join(current, 'plugin.json'))) return current; + const parent = dirname(current); + if (parent === current) return null; + current = parent; + } +} diff --git a/io.github.lithe-idea.gradle-build/plugin.json b/io.github.lithe-idea.gradle-build/plugin.json index 34e9550..e8816bf 100644 --- a/io.github.lithe-idea.gradle-build/plugin.json +++ b/io.github.lithe-idea.gradle-build/plugin.json @@ -2,17 +2,23 @@ "schemaVersion": 2, "id": "io.github.lithe-idea.gradle-build", "displayName": "Gradle", - "version": "0.1.1", + "version": "0.1.2", "pluginAPIVersion": 3, - "requires": { "buildSystems": 1, "projectGenerators": 1 }, + "requires": { "backend": 2, "buildSystems": 1, "pluginFunctions": 1, "projectGenerators": 1, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", "signatureRequirement": "none" }, - "permissions": ["process.build", "project.generate"], + "permissions": ["backend.launch", "process.build", "project.generate", "workspace.metadata"], "activationEvents": ["onBuildSystem:gradle"], "languages": [], + "backend": { + "launch": { "kind": "runtime", "tool": "node", "minimumVersion": "20.3", "entry": "backend/main.mjs" } + }, + "pluginFunctions": { + "exports": [{ "id": "languageImport.settings", "version": 1, "context": "workspace" }] + }, "buildSystems": [ { "id": "gradle", @@ -170,8 +176,7 @@ "settings.gradle.kts" ] }, - "layout": { "excluded": [".gradle", "build"] }, - "languageImport": { "kind": "gradle", "options": { "offline": "offline", "gradleUserHome": "gradleUserHome" } } + "layout": { "excluded": [".gradle", "build"] } } ], "projectGenerators": [ diff --git a/sdk.lock.json b/sdk.lock.json new file mode 100644 index 0000000..80f08b6 --- /dev/null +++ b/sdk.lock.json @@ -0,0 +1,65 @@ +{ + "schemaVersion": 1, + "source": { + "repository": "https://github.com/Lithe-IDEA/lithe-plugin-docs", + "revision": "db17c719bad755b420600c897615c67ed8cab67c", + "sdkVersion": "0.4.0" + }, + "files": [ + { + "upstream": "LICENSE", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/LICENSE", + "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21" + }, + { + "upstream": "sdk/node/src/backend.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs", + "sha256": "e5a6419c7ec8a8367c9f602ac0e8478f51ee7f1756e3bc0188c50ca1a1a677e5" + }, + { + "upstream": "sdk/node/src/diagnostics.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs", + "sha256": "2735350b0e9658729311d18e9632cb38f93a01576ed0de61c66eefc8dd89e73f" + }, + { + "upstream": "sdk/node/src/errors.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs", + "sha256": "e756aa0a88f1807ffdc985f3aed307f283c2a59902a287e22dd408dae5179bd2" + }, + { + "upstream": "sdk/node/src/framing.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs", + "sha256": "ec745be1ecf4cf24d521c5aa3108da2bbbfb9156f2197fcb5158de1f1bc9cfd1" + }, + { + "upstream": "sdk/node/src/host.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs", + "sha256": "4f4feaa8e3fdfa7f765e48b9ca53365126b0f57c5857d0b46208fccaa82e9e4e" + }, + { + "upstream": "sdk/node/src/index.d.ts", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts", + "sha256": "d229e44b7cec125f1a1f388312aabe64cb0ac089e13c0a2cb91ff88a019f50c2" + }, + { + "upstream": "sdk/node/src/index.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs", + "sha256": "79042db2ac6e0ac896ff0a1643ee540217b7b84fab4d1b1b82ad4246263d16af" + }, + { + "upstream": "sdk/node/src/process.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs", + "sha256": "a72f78cbfbb8d98b2d44ebea7f869038a3e34ebe7ee000f63cdd36fb2aaece66" + }, + { + "upstream": "sdk/node/src/protocol.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs", + "sha256": "f145f8c156c8831dc3f3b8076553d677484b59e63da7c1d8ceea16b5fa24b68f" + }, + { + "upstream": "sdk/node/src/state.mjs", + "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs", + "sha256": "946618214fbcb736c76ee85c87e0b969fe853fbab215f7c192990f2edf2035a4" + } + ] +} diff --git a/test/settings.test.mjs b/test/settings.test.mjs new file mode 100644 index 0000000..4059042 --- /dev/null +++ b/test/settings.test.mjs @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { parseProperties, registerSettingsFunction, settingsFor } from '../io.github.lithe-idea.gradle-build/backend/settings.mjs'; + +class PluginError extends Error { constructor(code, message) { super(message); this.code = code; } } + +async function scratch(t) { + const directory = await realpath(await mkdtemp(join(tmpdir(), 'lithe-gradle-settings-'))); + t.after(() => rm(directory, { recursive: true, force: true })); + return directory; +} + +function handlerFor(folders, environment = {}) { + let handler; + registerSettingsFunction({ function: (id, fn) => { assert.equal(id, 'languageImport.settings'); handler = fn; } }, PluginError, environment); + const context = { throwIfCancelled() {}, workspaceContext: { contextID: 'c', generation: 1 }, host: { workspace: { getFolders: async () => ({ folders }) } } }; + return (params, overrides = {}) => handler(params, { ...context, ...overrides }); +} + +test('properties parser keeps escapes and ignores comments', () => { + assert.deepEqual(parseProperties('# c\n! c\norg.gradle.jvmargs=-Xmx2g \\\n -Dfile.encoding=UTF-8\nkey : v\\:x\n'), + { 'org.gradle.jvmargs': '-Xmx2g -Dfile.encoding=UTF-8', key: 'v:x' }); +}); + +test('project gradle.properties overrides the user home and only known keys are exported', async (t) => { + const root = await scratch(t), home = await scratch(t); + await writeFile(join(home, 'gradle.properties'), 'org.gradle.jvmargs=-Xmx1g\norg.gradle.java.home=/jdk/home\norg.gradle.parallel=true\n'); + await writeFile(join(root, 'gradle.properties'), 'org.gradle.jvmargs=-Xmx4g\norg.gradle.java.home=relative/jdk\n'); + assert.deepEqual(await settingsFor(root, { GRADLE_USER_HOME: home }), { + settings: { 'java.import.gradle.user.home': home, 'java.import.gradle.jvmArguments': '-Xmx4g' } + }); + assert.deepEqual(await settingsFor(root, { GRADLE_USER_HOME: 'relative' }), { settings: { 'java.import.gradle.jvmArguments': '-Xmx4g' } }); +}); + +test('the function answers only for roots inside an open workspace folder', async (t) => { + const workspace = await scratch(t), outside = await scratch(t); + await mkdir(join(workspace, 'app')); + await symlink(outside, join(workspace, 'escape')); + await writeFile(join(workspace, 'app', 'gradle.properties'), 'org.gradle.jvmargs=-Xmx3g\n'); + const call = handlerFor([{ rootID: 'r', name: 'w', path: workspace }], { GRADLE_USER_HOME: '/nonexistent-lithe-home' }); + assert.deepEqual(await call({ workspaceRoot: join(workspace, 'app') }), { + settings: { 'java.import.gradle.user.home': '/nonexistent-lithe-home', 'java.import.gradle.jvmArguments': '-Xmx3g' } + }); + for (const workspaceRoot of [outside, join(workspace, 'escape'), 'relative', undefined]) { + await assert.rejects(call({ workspaceRoot }), { code: 'gradle.invalidRoot' }); + } + await assert.rejects(call({ workspaceRoot: workspace }, { workspaceContext: null }), { code: 'gradle.noWorkspaceContext' }); +}); + +test('the vendored SDK matches sdk.lock.json', async () => { + const { createHash } = await import('node:crypto'); + const { readFile } = await import('node:fs/promises'); + const lock = JSON.parse(await readFile(new URL('../sdk.lock.json', import.meta.url), 'utf8')); + assert.ok(lock.files.length > 0); + for (const file of lock.files) { + const bytes = await readFile(new URL(`../${file.path}`, import.meta.url)); + assert.equal(createHash('sha256').update(bytes).digest('hex'), file.sha256, file.path); + } +}); From 956f16e24df5ffa7ac899f303d76c5f641089731 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 9 Nov 2026 23:08:43 -0800 Subject: [PATCH 2/2] =?UTF-8?q?refactor(backend):=20Gradle=20=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E5=90=8E=E7=AB=AF=E6=94=B9=E7=94=A8=20Java=EF=BC=8C?= =?UTF-8?q?=E4=B8=8E=20Maven=20=E6=8F=92=E4=BB=B6=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E4=B8=80=E8=87=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 不再要求用户安装 Node。后端、固定版本的官方 Java SDK、打包脚本和后端测试对齐 Maven 插件。 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 4 +- .gitignore | 1 + NOTICE | 7 +- README.md | 10 +- .../gradle/backend/GradleBackend.java | 23 + .../gradle/backend/LanguageImport.java | 113 ++ .../backend/main.mjs | 7 - .../backend/settings.mjs | 85 - .../vendor/lithe-plugin-sdk/backend.mjs | 1085 ------------- .../vendor/lithe-plugin-sdk/diagnostics.mjs | 34 - .../vendor/lithe-plugin-sdk/errors.mjs | 101 -- .../vendor/lithe-plugin-sdk/framing.mjs | 74 - .../backend/vendor/lithe-plugin-sdk/host.mjs | 447 ------ .../vendor/lithe-plugin-sdk/index.d.ts | 714 --------- .../backend/vendor/lithe-plugin-sdk/index.mjs | 8 - .../vendor/lithe-plugin-sdk/process.mjs | 188 --- .../vendor/lithe-plugin-sdk/protocol.mjs | 293 ---- .../backend/vendor/lithe-plugin-sdk/state.mjs | 148 -- io.github.lithe-idea.gradle-build/plugin.json | 2 +- scripts/backend-client.mjs | 153 ++ scripts/package.mjs | 30 +- scripts/sdk/verify-sdk.mjs | 42 + scripts/test-backend.mjs | 74 + sdk.lock.json | 105 +- test/settings.test.mjs | 62 - .../lithe-plugin-sdk => vendor}/LICENSE | 0 .../github/litheidea/plugin/sdk/Backend.java | 1417 +++++++++++++++++ .../litheidea/plugin/sdk/CallContext.java | 119 ++ .../litheidea/plugin/sdk/Cancellation.java | 112 ++ .../plugin/sdk/CancelledException.java | 14 + .../litheidea/plugin/sdk/Diagnostics.java | 71 + .../github/litheidea/plugin/sdk/Framing.java | 138 ++ .../io/github/litheidea/plugin/sdk/Host.java | 520 ++++++ .../litheidea/plugin/sdk/HostChannel.java | 504 ++++++ .../litheidea/plugin/sdk/HostError.java | 96 ++ .../io/github/litheidea/plugin/sdk/Json.java | 426 +++++ .../litheidea/plugin/sdk/PluginError.java | 38 + .../litheidea/plugin/sdk/PluginSdkError.java | 32 + .../litheidea/plugin/sdk/Processes.java | 629 ++++++++ .../github/litheidea/plugin/sdk/Protocol.java | 230 +++ .../litheidea/plugin/sdk/StateStore.java | 198 +++ 41 files changed, 5063 insertions(+), 3291 deletions(-) create mode 100644 backend/src/main/java/io/github/litheidea/gradle/backend/GradleBackend.java create mode 100644 backend/src/main/java/io/github/litheidea/gradle/backend/LanguageImport.java delete mode 100644 io.github.lithe-idea.gradle-build/backend/main.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/settings.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs delete mode 100644 io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs create mode 100644 scripts/backend-client.mjs create mode 100644 scripts/sdk/verify-sdk.mjs create mode 100644 scripts/test-backend.mjs delete mode 100644 test/settings.test.mjs rename {io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk => vendor}/LICENSE (100%) create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b090e0..9c6bfc2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,10 +26,12 @@ jobs: with: distribution: temurin java-version: 17 + - name: Verify vendored Java SDK sources + run: node scripts/sdk/verify-sdk.mjs - name: Check manifest and build the archive run: node scripts/package.mjs - name: Test the settings backend - run: node --test test/settings.test.mjs + run: node scripts/test-backend.mjs - name: Download Gradle ${{ matrix.gradle }} env: VERSION: ${{ matrix.gradle }} diff --git a/.gitignore b/.gitignore index aaf4bbd..89f36d5 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ dist/ .gradle/ build/ .DS_Store +backend/target/ diff --git a/NOTICE b/NOTICE index 7731bc5..b89a079 100644 --- a/NOTICE +++ b/NOTICE @@ -12,9 +12,10 @@ Version 2.0, at revision 158b854d47ac9af2bbd99c0d7c354a5875cb6f81: Copyright 2000-2023 JetBrains s.r.o. and contributors. -The official Node.js SDK in io.github.lithe-idea.gradle-build/backend/vendor/ -lithe-plugin-sdk/ comes from Lithe-IDEA/lithe-plugin-docs at the revision pinned -in sdk.lock.json, licensed under the Apache License, Version 2.0. +The official Java SDK sources in vendor/lithe-plugin-sdk-java/ come from +Lithe-IDEA/lithe-plugin-docs at the revision pinned in sdk.lock.json (some with +local changes recorded there), licensed under the Apache License, Version 2.0. +They are compiled into lib/lithe-gradle-backend.jar. Gradle is a trademark of Gradle, Inc. This plugin is not affiliated with or endorsed by Gradle, Inc. diff --git a/README.md b/README.md index 79f3b2a..fa01caf 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ IntelliJ IDEA 一样按项目列出任务分组和依赖配置,运行任务、应用和测试。 这是一个**社区插件**,用 Lithe 的声明式构建系统接口(插件 API 3 的 `buildSystems`)实现, 只带一个 Gradle 初始化脚本,没有任何宿主代码。工具窗口由 macOS 宿主用 SwiftUI 原生渲染,插件不提供 Web 入口; -插件另带一个很小的 Node 后端,向 Java Support 提供 Gradle 的导入设置(见下文“Java 语言服务器的导入设置”)。 +插件另带一个很小的 Java 后端,向 Java Support 提供 Gradle 的导入设置(见下文“Java 语言服务器的导入设置”)。 > English: Gradle support for Lithe through the declarative `buildSystems` plugin API — projects with their tasks by > group, JavaExec tasks as run entries, test runs with JUnit reports, compiler diagnostics and per-configuration @@ -47,7 +47,7 @@ IntelliJ IDEA 一样按项目列出任务分组和依赖配置,运行任务、 `gradle.properties` 先读 Gradle User Home 里的,再读项目根的,项目根优先。`workspaceRoot` 必须落在已打开的本地工作区文件夹内, 否则函数拒绝(`gradle.invalidRoot`)。工具栏的 Offline 与 Gradle User Home 选项只保存在宿主里,插件后端读不到, -所以它们不再传给 JDT LS,需要宿主把已存选项交给插件函数后才能恢复。后端需要 Node.js 20.3 或更新版本。 +所以它们不再传给 JDT LS,需要宿主把已存选项交给插件函数后才能恢复。后端用 Lithe 找到的 Java(8 或更新版本)运行,Gradle 本身也需要它,所以不增加新的运行时要求。 ## 依赖的程序 @@ -88,17 +88,19 @@ Lithe 已预置 Lithe Store 社区插件源;如果你之前移除了它,先 ```text io.github.lithe-idea.gradle-build/plugin.json # 插件描述,目录名必须等于插件 id io.github.lithe-idea.gradle-build/lithe.init.gradle # 初始化脚本,导出模型和依赖树 -io.github.lithe-idea.gradle-build/backend/ # languageImport.settings 后端(Node)和固定版本的官方 SDK(sdk.lock.json) +backend/ # languageImport.settings 后端(Java),打包成 lib/lithe-gradle-backend.jar +vendor/lithe-plugin-sdk-java/ # 固定版本的官方 Java SDK 源码(sdk.lock.json 逐文件校验,编译进后端 jar) io.github.lithe-idea.gradle-build/icons/ # 工具窗口和工具栏图标(来源见 NOTICE) io.github.lithe-idea.gradle-build/templates/java/ # New Project 的 Gradle Java 项目模板(Kotlin/Groovy DSL、示例代码) test/fixtures/multi/ # 两个子项目的示例构建,供集成测试使用 scripts/package.mjs # 打包成 dist/gradle-build-<版本>-darwin.zip scripts/test.mjs # 用真实 Gradle 运行清单里的命令并检查输出 +scripts/test-backend.mjs # 经 stdio 驱动后端 jar,测试 languageImport.settings(不需要 Gradle) .github/workflows/ci.yml # PR 时打包、用 Gradle 7.6 和 9.6.1 测试,并用 Lithe Store 的规则检查 .github/workflows/release.yml # 推送 v<版本> 标签时发布 GitHub Release ``` -本地需要 Node.js 22+、JDK 17+ 和 Gradle(还需要 `zip`): +本地需要 Node.js 22+(只运行脚本)、JDK 17+ 和 Gradle(还需要 `zip`);打包用 JDK 自带的 `javac` 和 `jar` 编译后端,不需要 Maven: ```bash node scripts/package.mjs diff --git a/backend/src/main/java/io/github/litheidea/gradle/backend/GradleBackend.java b/backend/src/main/java/io/github/litheidea/gradle/backend/GradleBackend.java new file mode 100644 index 0000000..1f85928 --- /dev/null +++ b/backend/src/main/java/io/github/litheidea/gradle/backend/GradleBackend.java @@ -0,0 +1,23 @@ +package io.github.litheidea.gradle.backend; + +import io.github.litheidea.plugin.sdk.Backend; + +/** + * The plugin backend of the Gradle plugin. It only exports plugin functions to + * other plugins ({@code languageImport.settings}, see {@link LanguageImport}); + * Gradle itself is run by the host from the commands in plugin.json. + */ +public final class GradleBackend { + private GradleBackend() {} + + public static void main(String[] arguments) { + Backend backend = Backend.create("lithe-gradle-backend", version()); + backend.function(LanguageImport.FUNCTION, (params, context) -> LanguageImport.handle(params, context, System.getenv())); + backend.listen(); + } + + private static String version() { + String version = GradleBackend.class.getPackage().getImplementationVersion(); + return version == null ? "development" : version; + } +} diff --git a/backend/src/main/java/io/github/litheidea/gradle/backend/LanguageImport.java b/backend/src/main/java/io/github/litheidea/gradle/backend/LanguageImport.java new file mode 100644 index 0000000..47927be --- /dev/null +++ b/backend/src/main/java/io/github/litheidea/gradle/backend/LanguageImport.java @@ -0,0 +1,113 @@ +package io.github.litheidea.gradle.backend; + +import io.github.litheidea.plugin.sdk.CallContext; +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +/** + * The plugin function {@code languageImport.settings} (version 1) that Java + * Support calls before it starts JDT LS: the import settings Gradle's own + * configuration files imply. Nothing here runs Gradle or writes a file; the + * workspace root it is asked about must lie inside an open local workspace + * folder. {@code gradle.properties} of the project wins over the one in the + * Gradle user home, as in Gradle itself. + * + *

{@code GRADLE_USER_HOME} (absolute) becomes {@code java.import.gradle.user.home}, + * {@code org.gradle.java.home} (absolute) {@code java.import.gradle.java.home} and + * {@code org.gradle.jvmargs} {@code java.import.gradle.jvmArguments}. + */ +final class LanguageImport { + static final String FUNCTION = "languageImport.settings"; + private static final long MAX_PROPERTIES_BYTES = 256 * 1024; + + private LanguageImport() {} + + /** The function handler. */ + static Object handle(Map params, CallContext context, Map environment) throws Exception { + String requested = Json.string(params, "workspaceRoot"); + if (requested == null || !Paths.get(requested).isAbsolute()) { + throw new PluginError("gradle.invalidRoot", "workspaceRoot must be an absolute path."); + } + Map workspace = context.workspaceContext(); + if (workspace == null) { + throw new PluginError("gradle.noWorkspaceContext", "The call carries no workspace context."); + } + Path root = Paths.get(requested).toRealPath(); + Map answer = context.host().workspace().getFolders(workspace).get(10, TimeUnit.SECONDS); + if (!insideFolder(root, answer.get("folders"))) { + throw new PluginError("gradle.invalidRoot", "workspaceRoot is not inside an open workspace folder."); + } + context.throwIfCancelled(); + return settings(root, environment); + } + + private static boolean insideFolder(Path root, Object folders) throws IOException { + if (!(folders instanceof List)) { + return false; + } + for (Object folder : (List) folders) { + Object path = folder instanceof Map ? ((Map) folder).get("path") : null; + if (path instanceof String && root.startsWith(Paths.get((String) path).toRealPath())) { + return true; + } + } + return false; + } + + /** The Gradle user home as Gradle resolves it without a command line. */ + static Path userHome(Map environment) { + String value = environment.get("GRADLE_USER_HOME"); + if (value != null && !value.isEmpty() && Paths.get(value).isAbsolute()) { + return Paths.get(value); + } + return Paths.get(System.getProperty("user.home"), ".gradle"); + } + + /** {@code { settings }} for the Gradle build at {@code root}. */ + static Map settings(Path root, Map environment) { + Path home = userHome(environment); + Properties merged = new Properties(); + load(merged, home.resolve("gradle.properties")); + load(merged, root.resolve("gradle.properties")); + Map settings = new LinkedHashMap<>(); + String explicitHome = environment.get("GRADLE_USER_HOME"); + if (explicitHome != null && !explicitHome.isEmpty() && Paths.get(explicitHome).isAbsolute()) { + settings.put("java.import.gradle.user.home", home.toString()); + } + String javaHome = merged.getProperty("org.gradle.java.home"); + if (javaHome != null && !javaHome.isEmpty() && Paths.get(javaHome).isAbsolute()) { + settings.put("java.import.gradle.java.home", javaHome); + } + String jvmArguments = merged.getProperty("org.gradle.jvmargs"); + if (jvmArguments != null && !jvmArguments.isEmpty()) { + settings.put("java.import.gradle.jvmArguments", jvmArguments); + } + Map result = new LinkedHashMap<>(); + result.put("settings", settings); + return result; + } + + /** Adds the entries of a properties file; a missing, unreadable or oversized file adds nothing. */ + private static void load(Properties target, Path file) { + try { + if (!Files.isRegularFile(file) || Files.size(file) > MAX_PROPERTIES_BYTES) { + return; + } + try (InputStream input = Files.newInputStream(file)) { + target.load(input); + } + } catch (IOException | IllegalArgumentException ignored) { + // The file contributes nothing; JDT LS then imports with its defaults. + } + } +} diff --git a/io.github.lithe-idea.gradle-build/backend/main.mjs b/io.github.lithe-idea.gradle-build/backend/main.mjs deleted file mode 100644 index 4edf8ed..0000000 --- a/io.github.lithe-idea.gradle-build/backend/main.mjs +++ /dev/null @@ -1,7 +0,0 @@ -// Gradle plugin backend: serves `languageImport.settings` to the Java plugin. -import { createBackend, PluginError } from './vendor/lithe-plugin-sdk/index.mjs'; -import { registerSettingsFunction } from './settings.mjs'; - -const backend = createBackend({ name: 'gradle-build', version: '0.1.2' }); -registerSettingsFunction(backend, PluginError); -await backend.listen(); diff --git a/io.github.lithe-idea.gradle-build/backend/settings.mjs b/io.github.lithe-idea.gradle-build/backend/settings.mjs deleted file mode 100644 index 5a837ca..0000000 --- a/io.github.lithe-idea.gradle-build/backend/settings.mjs +++ /dev/null @@ -1,85 +0,0 @@ -// `languageImport.settings` of the Gradle plugin: the JDT LS import settings -// that Gradle's own configuration files imply. Nothing here runs Gradle, -// writes a file or reads a path outside the workspace and the user's Gradle -// home. Ownership and lifecycle: README.md ("Java 语言服务器的导入设置"). -import { readFile, realpath } from 'node:fs/promises'; -import { homedir } from 'node:os'; -import { isAbsolute, join, relative, resolve, sep } from 'node:path'; - -const MAX_PROPERTIES_BYTES = 256 * 1024; - -const inside = (root, path) => { - const value = relative(root, path); - return value === '' || (!isAbsolute(value) && value !== '..' && !value.startsWith(`..${sep}`)); -}; - -/** Reads `key=value` pairs of a Java properties file; later lines win. */ -export function parseProperties(text) { - const result = {}; - for (const raw of text.replace(/\\\r?\n\s*/g, '').split(/\r?\n/)) { - const line = raw.trimStart(); - if (line === '' || line.startsWith('#') || line.startsWith('!')) continue; - const match = /^((?:\\.|[^\s:=\\])+)\s*[:=]?\s*(.*)$/.exec(line); - if (!match) continue; - const unescape = (value) => value.replace(/\\(.)/g, '$1'); - result[unescape(match[1])] = unescape(match[2].trimEnd()); - } - return result; -} - -async function properties(path) { - try { - const text = await readFile(path, 'utf8'); - return text.length > MAX_PROPERTIES_BYTES ? {} : parseProperties(text); - } catch { - return {}; - } -} - -/** The Gradle user home as Gradle resolves it without a command line. */ -export function gradleUserHome(environment) { - const value = environment.GRADLE_USER_HOME; - return typeof value === 'string' && isAbsolute(value) ? value : join(homedir(), '.gradle'); -} - -/** - * Settings for the Gradle build at `root`. `gradle.properties` of the project - * wins over the one in the Gradle user home, as in Gradle itself. - */ -export async function settingsFor(root, environment = process.env) { - const home = gradleUserHome(environment); - const merged = { ...(await properties(join(home, 'gradle.properties'))), ...(await properties(join(root, 'gradle.properties'))) }; - const settings = {}; - if (typeof environment.GRADLE_USER_HOME === 'string' && isAbsolute(environment.GRADLE_USER_HOME)) { - settings['java.import.gradle.user.home'] = home; - } - const javaHome = merged['org.gradle.java.home']; - if (javaHome && isAbsolute(javaHome)) settings['java.import.gradle.java.home'] = javaHome; - const jvmArguments = merged['org.gradle.jvmargs']; - if (jvmArguments) settings['java.import.gradle.jvmArguments'] = jvmArguments; - return { settings }; -} - -/** The function handler: only roots inside an open local workspace are read. */ -export function registerSettingsFunction(backend, PluginError, environment = process.env) { - backend.function('languageImport.settings', async (params, context) => { - context.throwIfCancelled(); - const requested = params?.workspaceRoot; - if (typeof requested !== 'string' || !isAbsolute(requested)) { - throw new PluginError('gradle.invalidRoot', 'workspaceRoot must be an absolute path.'); - } - if (!context.workspaceContext) throw new PluginError('gradle.noWorkspaceContext', 'The call carries no workspace context.'); - let root; - try { - root = await realpath(resolve(requested)); - const { folders = [] } = await context.host.workspace.getFolders(context.workspaceContext); - const allowed = []; - for (const folder of folders) if (typeof folder.path === 'string') allowed.push(await realpath(folder.path).catch(() => null)); - if (!allowed.some((folder) => folder && inside(folder, root))) throw new Error('outside'); - } catch { - throw new PluginError('gradle.invalidRoot', 'workspaceRoot is not inside an open workspace folder.'); - } - context.throwIfCancelled(); - return settingsFor(root, environment); - }); -} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs deleted file mode 100644 index 2bf9490..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs +++ /dev/null @@ -1,1085 +0,0 @@ -// The plugin backend session: one process the host starts from the plugin's -// manifest and talks to over stdio with the LSP base protocol. The SDK owns -// everything Lithe manages uniformly -- the lifecycle, protocol negotiation, -// cancellation, error codes, and the `lithe/*` namespace -- and leaves the -// plugin free to decide what its handlers do. -// -// Contracts: contract/v1/README.md ("Build providers", "Plugin functions", -// "Host services" and "VCS providers"), and Lithe's -// shared/contracts/vcs-provider-v1.md. - -import { format } from 'node:util'; -import { performance } from 'node:perf_hooks'; -import { diagnostics, KNOWN_OPERATIONS, requestOperationId } from './diagnostics.mjs'; -import { encodeFrame, FrameDecoder, FramingError, MALFORMED } from './framing.mjs'; -import { HostError, PluginError, PluginSdkError, toResponseError } from './errors.mjs'; -import { createHost, HostChannel } from './host.mjs'; -import { killAllProcesses, runProcess } from './process.mjs'; -import { - BUILD_VERSION, - BUILD_METHOD_VERSIONS, - boundedText, - ERROR_CODES, - FUNCTIONS_VERSION, - HOST_NOTIFICATIONS, - isContextReference, - isFunctionId, - isReservedMethod, - isVcsId, - LIMITS, - METHODS, - RELAY_VERSION, - VCS_OPERATIONS, - VCS_REQUIRED_OPERATIONS, - VCS_VERSION, -} from './protocol.mjs'; - -/** Canonical result format of each typed build request. */ -const BUILD_FORMATS = Object.freeze({ - [METHODS.buildModel]: 'litheBuildModel', - [METHODS.buildDependencies]: 'litheDependencies', - [METHODS.buildDiscoverTests]: 'litheTestDiscovery', -}); - -/** Host notifications the SDK routes itself; see `onCommand`, `onContextsChanged`, and `host.subscribe`. */ -const ROUTED_NOTIFICATIONS = Object.freeze(Object.values(HOST_NOTIFICATIONS)); - -/** VCS capabilities that describe the VCS rather than a request it answers. */ -const VCS_TRAITS = Object.freeze(['push', 'staging']); - -/** - * Creates a backend. Declare handlers, then call `listen()`. - * - * @param {object} [options] - * @param {string} [options.name] Reported as `serverInfo.name` and used as the log prefix. - * @param {string} [options.version] Reported as `serverInfo.version`. - * @param {object} [options.capabilities] Standard LSP server capabilities, for a - * backend that is also a language server. `experimental.litheBuild`, - * `experimental.litheFunctions`, `experimental.litheVcs`, and `experimental.litheKeymapImport` are negotiated by - * the SDK and cannot be set here. - */ -export function createBackend(options = {}) { - return new Backend(options); -} - -class Backend { - #logging = false; - #loggingReady = false; - #earlyDiagnostics = []; - #quietSuccess = new Set(); - #name; - #version; - #capabilities; - #functions = new Map(); - #keymapProviders = new Map(); - #selectedKeymapProviders = new Set(); - #buildHandlers = new Map(); - #buildVersion = null; - #functionsVersion = null; - /** The declared VCS provider: `{ id, handlers: Map, capabilities }`. */ - #vcs = null; - #requestHandlers = new Map(); - #notificationHandlers = new Map(); - #commandHandlers = new Map(); - #contextsHandler = null; - #hostNotificationHandlers = new Map(); - #channel; - #initializeHooks = []; - #shutdownHooks = []; - /** `idle` → `listening` → `initializing` → `ready` → `shuttingDown` → `exited`. */ - #phase = 'idle'; - #negotiated = Object.freeze({ functions: false, build: false, vcs: false }); - #initializeParams = null; - /** Host requests being handled, by JSON-RPC ID. */ - #incoming = new Map(); - /** Requests this backend sent to the host, by JSON-RPC ID. */ - #outgoing = new Map(); - #nextRequestId = 1; - /** Serializes register/unregister so the host sees them in call order. */ - #registrations = Promise.resolve(); - #output = null; - #errorOutput = process.stderr; - #finish = null; - - /** Typed build-provider handlers (`lithe/build/*`). */ - build; - - /** - * Host services (`lithe/host/*`) of plugin-function protocols 2 to 4, - * usable once the session is ready. A handler's `context.host` is the - * same object bound to its call. - */ - host; - - constructor({ name = 'lithe-plugin-backend', version, capabilities = {} } = {}) { - const experimental = capabilities.experimental ?? {}; - if ('litheLogging' in experimental || 'litheBuild' in experimental || 'litheFunctions' in experimental || 'litheVcs' in experimental || 'litheKeymapImport' in experimental) { - throw new PluginSdkError( - 'sdk.capabilities.reserved', - 'litheLogging, litheBuild, litheFunctions, litheVcs, and litheKeymapImport are negotiated by the SDK; declare handlers instead.', - ); - } - this.#name = String(name); - this.#version = version === undefined ? undefined : String(version); - this.#capabilities = capabilities; - this.build = Object.freeze({ - /** Answers `lithe/build/model` with a `litheBuildModel` document. */ - model: (handler) => this.#declareBuild(METHODS.buildModel, handler), - /** Answers `lithe/build/dependencies` with a `litheDependencies` document. */ - dependencies: (handler) => this.#declareBuild(METHODS.buildDependencies, handler), - /** Runs a bounded task in the provider; the host owns its operation. */ - execute: (handler) => this.#declareBuild(METHODS.buildExecute, handler), - test: (handler) => this.#declareBuild(METHODS.buildTest, handler), - discoverTests: (handler) => this.#declareBuild(METHODS.buildDiscoverTests, handler), - /** Prepares a plan; the application itself belongs to the host. */ - prepareRun: (handler) => this.#declareBuild(METHODS.buildPrepareRun, handler), - prepareDebug: (handler) => this.#declareBuild(METHODS.buildPrepareDebug, handler), - }); - this.#channel = new HostChannel({ - version: () => this.#functionsVersion ?? 0, - ready: () => this.#phase === 'ready', - send: (method, params) => this.#send(method, params), - notify: (method, params) => this.#write({ jsonrpc: '2.0', method, params }), - log: () => this.#diagnostics().degraded('notification', 'event_handler_failed'), - }); - this.host = createHost(this.#channel); - } - - /** Protocols the host agreed to in `initialize`; all false before it. */ - get negotiated() { - return this.#negotiated; - } - - /** Selected build protocol version, or null when unavailable. */ - get buildVersion() { return this.#buildVersion; } - - /** Selected plugin-function protocol version (1-4), or null when unavailable. */ - get functionsVersion() { return this.#functionsVersion; } - - /** The host's `initialize` params, or null before it arrives. */ - get initializeParams() { - return this.#initializeParams; - } - - /** IDs of the functions this backend currently serves, sorted. */ - get functionIDs() { - return [...this.#functions.keys()].sort(); - } - - /** - * Declares a plugin function offered from the start, in the `initialize` - * answer. To add one later, use `registerFunction`. - * - * @param {string} id Dot-separated lowerCamelCase segments, such as `snapshot.refresh`. - * @param {(params: object, context: object) => unknown} handler - */ - function(id, handler) { - if (!this.#beforeAnswer()) { - throw new PluginSdkError('sdk.function.lateDeclaration', 'After initialize, add functions with registerFunction().'); - } - this.#checkNewFunction(id, handler); - this.#functions.set(id, handler); - return this; - } - - /** Declares an independent typed shortcut import provider. */ - keymapImportProvider(id, handler) { - if (!this.#beforeAnswer() || !validKeymapProvider(id) || typeof handler !== 'function' - || this.#keymapProviders.has(id) || this.#keymapProviders.size >= 8) { - throw new PluginSdkError('sdk.keymap.invalidRegistration', 'Invalid or duplicate shortcut import provider.'); - } - this.#keymapProviders.set(id, handler); - return this; - } - - /** - * Declares the VCS this backend provides and the operations it answers, - * before `listen()`. Each handler gets the operation's arguments plus - * `root: { path }` and `tool: { executable } | null`, and returns the reply - * object of shared/contracts/vcs-provider-v1.md. Declaring a handler - * negotiates its capability; `status`, `baseContent`, `checkin`, and - * `rollback` are required. - * - * @param {string} id The VCS ID of the manifest's `vcsProviders` entry, such as `svn`. - * @param {Record} handlers Keyed by operation name. - * @param {object} [traits] - * @param {boolean} [traits.push] Check-in is local and publishing is a separate step. - * @param {boolean} [traits.staging] Changes carry a staged/unstaged dimension. - */ - vcs(id, handlers, traits = {}) { - if (this.#phase !== 'idle') { - throw new PluginSdkError('sdk.vcs.lateDeclaration', 'Declare the VCS provider before listen().'); - } - if (this.#vcs) throw new PluginSdkError('sdk.vcs.duplicate', 'A backend provides one VCS.'); - if (!isVcsId(id)) { - throw new PluginSdkError( - 'sdk.vcs.invalidID', - `VCS ID ${JSON.stringify(id)} must be lowercase letters, digits, and "-", start with a letter, and be at most ${LIMITS.maxVcsIdBytes} bytes.`, - ); - } - if (id === 'git') throw new PluginSdkError('sdk.vcs.reserved', 'git is provided by Lithe.'); - const methods = new Map(); - const capabilities = {}; - for (const [operation, handler] of Object.entries(handlers ?? {})) { - const declared = VCS_OPERATIONS[operation]; - if (!declared) throw new PluginSdkError('sdk.vcs.unknownOperation', `${operation} is not a VCS operation.`); - if (typeof handler !== 'function') throw new TypeError(`The ${operation} handler must be a function.`); - methods.set(declared.method, handler); - capabilities[declared.capability] = VCS_VERSION; - } - const missing = VCS_REQUIRED_OPERATIONS.filter((operation) => !methods.has(VCS_OPERATIONS[operation].method)); - if (missing.length > 0) { - throw new PluginSdkError('sdk.vcs.missingOperation', `A VCS provider must answer ${missing.join(', ')}.`); - } - for (const [trait, enabled] of Object.entries(traits)) { - if (!VCS_TRAITS.includes(trait)) throw new PluginSdkError('sdk.vcs.unknownTrait', `${trait} is not a VCS trait.`); - if (enabled) capabilities[trait] = VCS_VERSION; - } - this.#vcs = { id, methods, capabilities: sortedKeys(capabilities) }; - return this; - } - - /** Handles a standard LSP request, for a backend that is also a language server. */ - onRequest(method, handler) { - this.#declareHandler(this.#requestHandlers, method, handler); - return this; - } - - /** Handles a standard LSP notification. */ - onNotification(method, handler) { - this.#declareHandler(this.#notificationHandlers, method, handler); - return this; - } - - /** - * Handles `lithe/host/commands/didRun` for one of the plugin's commands - * (protocol 3). The handler gets `{ commandID, workspaceContext }`, the - * context of the window it ran in or null. It is an event: the host waits - * for no result. - */ - onCommand(commandID, handler) { - if (typeof commandID !== 'string' || !/^[a-z0-9.-]{1,128}$/.test(commandID)) { - throw new PluginSdkError('sdk.command.invalidID', `Command ID ${JSON.stringify(commandID)} must be 1-128 of [a-z0-9.-].`); - } - if (typeof handler !== 'function') throw new TypeError('A command handler must be a function.'); - this.#commandHandlers.set(commandID, handler); - return this; - } - - /** - * Handles `lithe/host/workspace/didChangeContexts` (protocol 3) with - * `{ revision }`; call `host.workspace.listContexts()` for the contexts. - */ - onContextsChanged(handler) { - if (typeof handler !== 'function') throw new TypeError('A handler must be a function.'); - this.#contextsHandler = handler; - return this; - } - - /** - * Handles a `lithe/host/*` notification a later host adds. Commands, - * context changes, and subscription events have their own APIs. - */ - onHostNotification(method, handler) { - if (typeof method !== 'string' || !method.startsWith('lithe/host/')) { - throw new PluginSdkError('sdk.method.invalid', `${method} is not a host notification.`); - } - if (ROUTED_NOTIFICATIONS.includes(method)) { - throw new PluginSdkError('sdk.method.reserved', `${method} is routed by the SDK; use onCommand, onContextsChanged, or host.subscribe.`); - } - if (typeof handler !== 'function') throw new TypeError('A handler must be a function.'); - this.#hostNotificationHandlers.set(method, handler); - return this; - } - - /** Runs before the `initialize` answer, with `{ params, negotiated }`. */ - onInitialize(hook) { - this.#initializeHooks.push(hook); - return this; - } - - /** Runs on `shutdown`, after running calls were cancelled. */ - onShutdown(hook) { - this.#shutdownHooks.push(hook); - return this; - } - - /** - * Adds a function. Before the `initialize` answer (including from an - * `onInitialize` hook) it joins the initial list; afterwards the host must - * accept it first. - */ - registerFunction(id, handler) { - if (this.#beforeAnswer()) { - return settle(() => { - this.#checkNewFunction(id, handler); - this.#functions.set(id, handler); - }); - } - return this.#queueRegistration(async () => { - this.#requireFunctions(); - this.#checkNewFunction(id, handler); - // Installed before the request: the host may invoke it as soon as its - // registry changed, before this backend reads the reply. - this.#functions.set(id, handler); - try { - await this.#request(METHODS.functionRegister, { functions: [{ id }] }); - } catch (error) { - this.#functions.delete(id); - this.#quietSuccess.delete(id); - throw error; - } - }); - } - - /** Withdraws a function. The host ends its running calls as revoked. */ - unregisterFunction(id) { - if (this.#beforeAnswer()) { - return settle(() => { - if (!this.#functions.delete(id)) { - throw new PluginSdkError('sdk.function.unknown', `Function ${id} is not registered.`); - } - this.#quietSuccess.delete(id); - }); - } - return this.#queueRegistration(async () => { - this.#requireFunctions(); - if (!this.#functions.has(id)) { - throw new PluginSdkError('sdk.function.unknown', `Function ${id} is not registered.`); - } - await this.#request(METHODS.functionUnregister, { ids: [id] }); - this.#functions.delete(id); - this.#quietSuccess.delete(id); - for (const call of this.#incoming.values()) { - if (call.functionID === id) call.controller.abort(); - } - }); - } - - /** Sends a standard LSP request to the host. `lithe/*` methods are reserved. */ - sendRequest(method, params) { - this.#checkOutgoing(method); - return this.#request(method, params); - } - - /** Sends a standard LSP notification to the host. `lithe/*` methods are reserved. */ - sendNotification(method, params) { - this.#checkOutgoing(method); - this.#write({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) }); - } - - get diagnostics() { return this.#diagnostics(); } - - suppressSuccessDiagnostics(operation) { - if (!KNOWN_OPERATIONS.has(operation) && !this.#functions.has(operation)) throw new PluginSdkError('sdk.logging.invalidOperation', 'Suppress a registered operation.'); - this.#quietSuccess.add(operation); - return this; - } - - #diagnostics(operationId) { - return diagnostics((params) => { - if (!this.#logging) return; - if (!this.#loggingReady) { if (this.#earlyDiagnostics.length < 8) this.#earlyDiagnostics.push(params); return; } - this.#write({ jsonrpc: '2.0', method: 'lithe/log', params }); - }, (id) => this.#functions.has(id), operationId); - } - - /** - * Serves the host until it sends `exit` or closes the input stream, and - * resolves with the process exit code. With the default `exit`, the process - * then exits with that code. - * - * @param {object} [io] - * @param {NodeJS.ReadableStream} [io.input] Defaults to stdin. - * @param {NodeJS.WritableStream} [io.output] Defaults to stdout. - * @param {NodeJS.WritableStream} [io.errorOutput] Defaults to stderr. - * @param {((code: number) => void) | null} [io.exit] Defaults to `process.exit`; null only resolves. - */ - listen({ input = process.stdin, output = process.stdout, errorOutput = process.stderr, exit = (code) => process.exit(code) } = {}) { - if (this.#phase !== 'idle') { - throw new PluginSdkError('sdk.listen.repeated', 'A backend listens once.'); - } - this.#phase = 'listening'; - this.#output = output; - this.#errorOutput = errorOutput; - if (output === process.stdout) redirectConsole(errorOutput); - - return new Promise((resolve) => { - this.#finish = (code) => { - if (this.#phase === 'exited') return; - this.#phase = 'exited'; - this.#abortAll(); - killAllProcesses(); - // Before the pending requests fail, so a freed slot starts nothing. - this.#channel.close(); - for (const pending of this.#outgoing.values()) { - pending.reject(new PluginSdkError('sdk.session.closed', 'The session ended.')); - } - this.#outgoing.clear(); - input.off?.('data', onData); - resolve(code); - exit?.(code); - }; - const decoder = new FrameDecoder(); - const onData = (chunk) => { - let messages; - try { - messages = decoder.push(chunk); - } catch (error) { - if (!(error instanceof FramingError)) throw error; - this.#diagnostics().terminal('notification', {code:'framing_error'}, 0); - this.#finish(1); - return; - } - for (const message of messages) this.#dispatch(message); - }; - input.on('data', onData); - input.once('end', () => this.#finish(this.#phase === 'shuttingDown' ? 0 : 1)); - input.once('error', () => this.#finish(1)); - }); - } - - #dispatch(message) { - if (message === MALFORMED) { - this.#respond(null, undefined, { code: ERROR_CODES.parseError, message: 'The message is not valid JSON.' }); - return; - } - // Valid JSON that is not a message object, such as `null` or a batch. - if (typeof message !== 'object' || message === null || Array.isArray(message)) { - this.#respond(null, undefined, { code: ERROR_CODES.invalidRequest, message: 'The message is not a JSON-RPC object.' }); - return; - } - const hasID = message.id !== undefined && message.id !== null; - if (typeof message.method !== 'string') { - if (hasID) this.#settleOutgoing(message); - return; - } - if (hasID) { - this.#handleRequest(message); - } else { - this.#handleNotification(message); - } - } - - #handleRequest({ id, method, params }) { - if (method === METHODS.initialize) { - void this.#initialize(id, params ?? {}); - return; - } - if (method === METHODS.shutdown) { - void this.#shutdown(id); - return; - } - if (this.#phase === 'listening' || this.#phase === 'initializing') { - this.#respond(id, undefined, { code: ERROR_CODES.serverNotInitialized, message: 'The backend is not initialized.' }); - return; - } - if (this.#phase !== 'ready') { - this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'The backend is shutting down.' }); - return; - } - if (method === METHODS.functionInvoke) { - this.#invokeFunction(id, params ?? {}); - return; - } - if (method === 'lithe/keymap/import') { - this.#invokeKeymap(id, params); - return; - } - const build = this.#buildHandlers.get(method); - if (build && this.#buildVersion >= BUILD_METHOD_VERSIONS[method]) { - this.#invokeBuild(id, method, params ?? {}, build); - return; - } - const vcs = this.#negotiated.vcs ? this.#vcs.methods.get(method) : undefined; - if (vcs) { - this.#run(id, null, (context) => vcs(params ?? {}, this.#vcsContext(context)), (result) => vcsResult(method, result), undefined, method, params?.operationID); - return; - } - const handler = this.#requestHandlers.get(method); - if (handler) { - this.#run(id, null, (context) => handler(params, context), (result) => result ?? null); - return; - } - this.#respond(id, undefined, { code: ERROR_CODES.methodNotFound, message: `Unsupported method: ${method}` }); - } - - #handleNotification({ method, params }) { - if (method === METHODS.exit) { - this.#finish(this.#phase === 'shuttingDown' ? 0 : 1); - return; - } - if (method === METHODS.cancelRequest) { - this.#incoming.get(requestKey(params?.id))?.controller.abort(); - return; - } - if (this.#phase !== 'ready' || method === METHODS.initialized) return; - if (typeof method === 'string' && method.startsWith('lithe/host/')) { - this.#hostNotification(method, params); - return; - } - const handler = this.#notificationHandlers.get(method); - if (!handler) return; - Promise.resolve() - .then(() => handler(params)) - .catch((error) => this.#diagnostics().terminal('notification', { code: failureKind(error) }, 0)); - } - - /** - * Routes a host notification. Core checked its shape and the session's - * grant; one this SDK does not know is ignored, as the contract asks. - */ - #hostNotification(method, params) { - if ((this.#functionsVersion ?? 0) < 3 || !isObject(params)) return; - if (method === HOST_NOTIFICATIONS.subscriptionNotify) { - this.#channel.deliver(params); - return; - } - let handler; - let event = params; - if (method === HOST_NOTIFICATIONS.commandDidRun) { - handler = this.#commandHandlers.get(params.commandID); - event = { commandID: params.commandID, workspaceContext: isContextReference(params.context) ? params.context : null }; - if (!handler) { - this.#diagnostics().degraded('notification', 'command_unhandled'); - return; - } - } else if (method === HOST_NOTIFICATIONS.didChangeContexts) { - handler = this.#contextsHandler; - } else { - handler = this.#hostNotificationHandlers.get(method); - } - if (!handler) return; - Promise.resolve() - .then(() => handler(event)) - .catch((error) => this.#diagnostics().terminal('notification', { code: failureKind(error) }, 0)); - } - - async #initialize(id, params) { - if (this.#phase !== 'listening') { - this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'initialize was already received.' }); - return; - } - this.#phase = 'initializing'; - this.#initializeParams = params; - const offered = params.capabilities?.experimental ?? {}; - this.#loggingReady = false; - this.#earlyDiagnostics = []; - this.#logging = offered.litheLogging?.versions?.includes(1) === true; - if (!this.#logging) { - this.#phase = 'listening'; - this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'The backend requires litheLogging version 1.' }); - return; - } - const offers = (entry, version) => Array.isArray(entry?.versions) && entry.versions.includes(version); - const highest = (entry, latest) => Array.from({ length: latest }, (_, index) => latest - index) - .find((version) => offers(entry, version)) ?? null; - this.#buildVersion = this.#buildHandlers.size > 0 ? highest(offered.litheBuild, BUILD_VERSION) : null; - this.#functionsVersion = highest(offered.litheFunctions, FUNCTIONS_VERSION); - this.#negotiated = Object.freeze({ - functions: this.#functionsVersion !== null, - build: this.#buildVersion !== null, - vcs: this.#vcs !== null && offers(offered.litheVcs, VCS_VERSION), - }); - try { - for (const hook of this.#initializeHooks) { - await hook({ params, negotiated: this.#negotiated }); - } - } catch (error) { - if (this.#phase === 'initializing') this.#phase = 'listening'; - this.#respond(id, undefined, toResponseError(error)); - return; - } - // A shutdown or exit that arrived while a hook ran ended the session; - // finishing initialize must not reopen it. - if (this.#phase !== 'initializing') { - this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'The session ended during initialize.' }); - return; - } - if (!this.#negotiated.functions && this.#functions.size > 0) { - this.#diagnostics().degraded('initialize', 'functions_unavailable'); - } - const experimental = { ...(this.#capabilities.experimental ?? {}), litheLogging: { version: 1 } }; - if (offers(offered.litheKeymapImport, 1) && Array.isArray(offered.litheKeymapImport?.providers) - && offered.litheKeymapImport.providers.length <= 8) { - this.#selectedKeymapProviders = new Set(offered.litheKeymapImport.providers.filter((id) => this.#keymapProviders.has(id))); - if (this.#selectedKeymapProviders.size) { - experimental.litheKeymapImport = { version: 1, providers: [...this.#selectedKeymapProviders].sort() }; - } - } - if (this.#negotiated.build) experimental.litheBuild = { version: this.#buildVersion }; - if (this.#negotiated.vcs) { - experimental.litheVcs = { version: VCS_VERSION, vcs: this.#vcs.id, capabilities: this.#vcs.capabilities }; - } else if (this.#vcs) { - this.#diagnostics().degraded('initialize', 'vcs_unavailable'); - } - if (this.#negotiated.functions) { - experimental.litheFunctions = { - version: this.#functionsVersion, - functions: this.functionIDs.map((functionID) => ({ id: functionID })), - }; - } - this.#phase = 'ready'; - this.#respond(id, { - capabilities: { ...this.#capabilities, experimental }, - serverInfo: { name: this.#name, ...(this.#version ? { version: this.#version } : {}) }, - }); - this.#loggingReady = true; - for (const params of this.#earlyDiagnostics.splice(0)) this.#write({ jsonrpc: '2.0', method: 'lithe/log', params }); - } - - async #shutdown(id) { - if (this.#phase !== 'ready' && this.#phase !== 'listening' && this.#phase !== 'initializing') { - this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'shutdown was already received.' }); - return; - } - this.#phase = 'shuttingDown'; - this.#abortAll(); - for (const hook of this.#shutdownHooks) { - try { - await hook(); - } catch (error) { - this.#diagnostics().terminal('shutdown', { code: failureKind(error) }, 0); - } - } - killAllProcesses(); - this.#respond(id, null); - } - - #invokeBuild(id, method, params, handler) { - if (Object.hasOwn(params ?? {}, 'modelInputs') && this.#buildVersion < 6) { - this.#respond(id, undefined, { code: ERROR_CODES.invalidParams, message: 'Model inputs require build protocol 6.' }); - return; - } - const progressing = [METHODS.buildExecute, METHODS.buildTest, METHODS.buildPrepareRun, METHODS.buildPrepareDebug].includes(method); - if (!params || typeof params !== 'object' || Array.isArray(params) - || (progressing && typeof params.operationID !== 'string')) { - this.#respond(id, undefined, { code: ERROR_CODES.invalidParams, message: 'A build request needs object params and its wire operationID.' }); - return; - } - const operationID = params.operationID; - let reporting = true; - this.#run(id, null, (context) => handler(params, progressing ? { - ...context, - operationID, - progress: ({ message, percentage, output } = {}) => { - if (!reporting || context.signal.aborted) return; - const report = { operationID }; - if (message !== undefined) report.message = boundedText(message, LIMITS.maxBuildMessageBytes); - if (output !== undefined) report.output = boundedText(output, LIMITS.maxBuildOutputBytes); - if (Number.isFinite(percentage)) report.percentage = Math.min(100, Math.max(0, Math.round(percentage))); - this.#write({ jsonrpc: '2.0', method: METHODS.buildProgress, params: report }); - }, - } : context), (result) => buildResult(method, result), () => { reporting = false; }, method, operationID); - } - - #invokeKeymap(id, params) { - if (!isObject(params) || Object.keys(params).length !== 2 || !validKeymapProvider(params.providerID) - || !validSnapshotToken(params.snapshotID) || !this.#selectedKeymapProviders.has(params.providerID)) { - this.#respond(id, undefined, { code: ERROR_CODES.invalidParams, message: 'Invalid shortcut import request.' }); - return; - } - const handler = this.#keymapProviders.get(params.providerID); - this.#run(id, null, (context) => handler(keymapSnapshot(params, context.host), context), functionResult, undefined, 'lithe/keymap/import'); - } - - #invokeFunction(id, { functionID, operationID, params, context: workspaceContext, caller }) { - const handler = this.#negotiated.functions ? this.#functions.get(functionID) : undefined; - if (!handler) { - this.#respond(id, undefined, { code: ERROR_CODES.invalidParams, message: `Function ${functionID} is not registered.` }); - return; - } - let reporting = true; - const progress = ({ message, percentage } = {}) => { - if (!reporting) return; - const report = { operationID }; - if (message !== undefined) report.message = boundedText(message); - if (Number.isFinite(percentage)) report.percentage = Math.min(100, Math.max(0, Math.round(percentage))); - this.#write({ jsonrpc: '2.0', method: METHODS.functionProgress, params: report }); - }; - // Calls this handler makes through the relay belong to this call. Core - // needs a string of 1-128 bytes; without one the calls carry no parent. - const parentOperationId = typeof operationID === 'string' && operationID.length > 0 - && Buffer.byteLength(operationID) <= LIMITS.maxParentOperationIdBytes ? operationID : undefined; - this.#run( - id, - functionID, - (context) => handler(params ?? {}, { - ...context, - functionID, - operationID, - // The page's window, from protocol 3; null for a call without one. - workspaceContext: isContextReference(workspaceContext) ? workspaceContext : null, - // The calling plugin, from protocol 4 and only for a relayed call; null otherwise. - caller: (this.#functionsVersion ?? 0) >= RELAY_VERSION ? callerReference(caller) : null, - host: createHost(this.#channel, context.signal, parentOperationId), - progress, - }), - functionResult, - () => { - reporting = false; - }, - functionID, - operationID, - ); - } - - /** Runs one handler with its own cancellation and answers exactly once. */ - #run(id, functionID, invoke, shape, onSettled, operation = functionID ?? 'function-call', operationId) { - const started = performance.now(); - const diagnostic = this.#diagnostics(requestOperationId(operationId, id)); - let quietSuccess = false; - const controller = new AbortController(); - const key = requestKey(id); - this.#incoming.set(key, { controller, functionID }); - const { signal } = controller; - const context = { - signal, - diagnostics: diagnostic, - suppressSuccessDiagnostics: () => { quietSuccess = true; }, - throwIfCancelled: () => signal.throwIfAborted(), - run: (command, args, options = {}) => { - const running = runProcess(command, args, { - ...options, - signal: options.signal ? AbortSignal.any([signal, options.signal]) : signal, - }); - // A tool the handler did not await is stopped when the call ends; its - // rejection then must not end the backend as an unhandled rejection. - running.catch(() => {}); - return running; - }, - host: createHost(this.#channel, signal), - }; - Promise.resolve() - .then(() => invoke(context)) - .then( - (value) => { - signal.throwIfAborted(); - return { result: shape(value) }; - }, - (error) => { - return { error: toResponseError(error, signal) }; - }, - ) - .catch((error) => { - // Shaping the result failed, for example a build result in another format. - return { error: toResponseError(error, signal) }; - }) - .then(({ result, error }) => { - if (!signal.aborted && (error || (!quietSuccess && !this.#quietSuccess.has(operation)))) diagnostic.terminal(operation, error ? { code: error.data?.code ?? 'internal_error' } : null, performance.now() - started); - onSettled?.(); - this.#incoming.delete(key); - // Work belongs to its call: tools still running when the handler - // settled, such as the siblings of a failed `Promise.all`, end now. - // Other calls have their own controllers and keep running. - controller.abort(new PluginSdkError('sdk.call.ended', 'The call ended.')); - this.#respond(id, result, error); - }); - } - - /** - * The request context of a VCS handler. Its `run` reports every finished - * command to the host as `lithe/vcs/execution`, for the project console, - * unless the call passes `report: false`. Arguments are reported as given, - * so they must never carry a credential. - */ - #vcsContext(context) { - const report = (command, args, started, outcome) => { - const params = { - command: [String(command), ...args.map(String)], - exitCode: outcome.exitCode ?? null, - durationMilliseconds: Math.max(0, Math.round(performance.now() - started)), - stderr: boundedText(outcome.stderr ?? '', LIMITS.maxExecutionErrorOutputBytes), - }; - this.#write({ jsonrpc: '2.0', method: METHODS.vcsExecution, params }); - }; - return { - ...context, - run: (command, args = [], { report: reporting = true, ...options } = {}) => { - const started = performance.now(); - const running = context.run(command, args, options); - if (!reporting) return running; - const reported = running.then( - (result) => { - report(command, args, started, result); - return result; - }, - (error) => { - if (!context.signal.aborted) report(command, args, started, { exitCode: null, stderr: error?.message }); - throw error; - }, - ); - reported.catch(() => {}); - return reported; - }, - }; - } - - #declareBuild(method, handler) { - if (this.#phase !== 'idle') { - throw new PluginSdkError('sdk.build.lateDeclaration', 'Declare build handlers before listen().'); - } - if (typeof handler !== 'function') throw new TypeError('A build handler must be a function.'); - this.#buildHandlers.set(method, handler); - return this; - } - - #declareHandler(handlers, method, handler) { - if (typeof method !== 'string' || isReservedMethod(method)) { - throw new PluginSdkError('sdk.method.reserved', `${method} is managed by the SDK and Lithe.`); - } - if (typeof handler !== 'function') throw new TypeError('A handler must be a function.'); - handlers.set(method, handler); - } - - #checkNewFunction(id, handler) { - if (!isFunctionId(id)) { - throw new PluginSdkError( - 'sdk.function.invalidID', - `Function ID ${JSON.stringify(id)} must be dot-separated lowerCamelCase segments of at most 128 bytes.`, - ); - } - if (typeof handler !== 'function') throw new TypeError('A function handler must be a function.'); - if (this.#functions.has(id)) { - throw new PluginSdkError('sdk.function.duplicate', `Function ${id} is already declared.`); - } - if (this.#functions.size >= LIMITS.maxFunctions) { - throw new PluginSdkError('sdk.function.limit', `A backend serves at most ${LIMITS.maxFunctions} functions.`); - } - } - - /** True until the `initialize` answer fixes the initial function list. */ - #beforeAnswer() { - return this.#phase === 'idle' || this.#phase === 'listening' || this.#phase === 'initializing'; - } - - #requireFunctions() { - if (this.#phase !== 'ready' || !this.#negotiated.functions) { - throw new PluginSdkError('sdk.functions.unavailable', 'The host has not negotiated plugin functions.'); - } - } - - #queueRegistration(change) { - const next = this.#registrations.then(change); - this.#registrations = next.catch(() => {}); - return next; - } - - #checkOutgoing(method) { - if (typeof method !== 'string' || isReservedMethod(method)) { - throw new PluginSdkError( - 'sdk.method.reserved', - `${method} is reserved. A backend never asks the host to run a domain operation or a function.`, - ); - } - if (this.#phase !== 'ready') { - throw new PluginSdkError('sdk.session.notReady', 'The session is not initialized.'); - } - } - - #request(method, params) { - return this.#send(method, params).response; - } - - /** Writes a request to the host; `response` settles with its answer. */ - #send(method, params) { - const id = `sdk-${this.#nextRequestId++}`; - const response = new Promise((resolve, reject) => { - this.#outgoing.set(id, { resolve, reject, method }); - this.#write({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }); - }); - return { id, response }; - } - - #settleOutgoing({ id, result, error }) { - const pending = this.#outgoing.get(id); - if (!pending) return; - this.#outgoing.delete(id); - if (error) { - pending.reject(HostError.fromResponse(pending.method, error)); - } else { - pending.resolve(result ?? null); - } - } - - #abortAll() { - for (const call of this.#incoming.values()) call.controller.abort(); - } - - #respond(id, result, error) { - if (this.#phase === 'exited') return; - try { - this.#write(error ? { jsonrpc: '2.0', id, error } : { jsonrpc: '2.0', id, result: result ?? null }); - } catch (failure) { - // A result JSON cannot encode, such as a BigInt or a cycle, must not - // become an unhandled rejection that ends the whole session. - this.#diagnostics().terminal('result-encoding', { code: 'result_encoding_failed' }, 0); - this.#write({ jsonrpc: '2.0', id, error: toResponseError(failure) }); - } - } - - #write(message) { - if (!this.#output || this.#phase === 'exited') return; - this.#output.write(encodeFrame(message)); - } -} - -// Errors can include request bodies, credentials and paths. Only the category -// crosses the diagnostic boundary; the response keeps its existing error contract. -function failureKind(error) { - return error instanceof PluginError ? 'plugin_error' : 'internal_error'; -} - -/** Runs `change` now and reports its outcome as a promise. */ -function settle(change) { - try { - change(); - return Promise.resolve(); - } catch (error) { - return Promise.reject(error); - } -} - -/** The JSON-RPC ID as a map key; numbers and strings never collide. */ -function requestKey(id) { - return `${typeof id}:${id}`; -} - -/** - * Stamps the canonical format on a build result, so a handler can return the - * plain document. A result in another format is a backend bug: Core would - * refuse it as `plugin.build.invalidOutput`, so it fails here with a clear log. - */ -function buildResult(method, result) { - const expected = BUILD_FORMATS[method]; - if (!isObject(result)) { - throw new PluginSdkError('sdk.build.invalidResult', `${method} must return a reply object.`); - } - let document = result; - if (expected) { - if (result.format !== undefined && result.format !== expected) { - throw new PluginSdkError('sdk.build.invalidResult', `${method} returned format ${result.format}, not ${expected}.`); - } - if (result.version !== undefined && result.version !== 1) { - throw new PluginSdkError('sdk.build.invalidResult', `${method} returned version ${result.version}, not 1.`); - } - document = { ...result, format: expected, version: 1 }; - } - if ([METHODS.buildExecute, METHODS.buildTest].includes(method) - && (!Number.isInteger(result.exitCode) || result.exitCode < -2147483648 || result.exitCode > 2147483647 - || typeof result.output !== 'string' || Buffer.byteLength(result.output) > LIMITS.maxBuildResultBytes)) { - throw new PluginSdkError('sdk.build.invalidResult', `${method} needs an int32 exitCode and bounded output.`); - } - if (method === METHODS.buildPrepareRun - && (!isObject(result.executable) || !['toolchain', 'command'].includes(result.executable.kind) - || typeof result.executable.value !== 'string' || typeof result.workingDirectory !== 'string' - || !Array.isArray(result.arguments) || !result.arguments.every((value) => typeof value === 'string') - || !isObject(result.environment) || !Object.values(result.environment).every((value) => typeof value === 'string'))) { - throw new PluginSdkError('sdk.build.invalidResult', `${method} needs a portable launch plan.`); - } - if (method === METHODS.buildPrepareDebug - && (typeof result.program !== 'string' || typeof result.workingDirectory !== 'string' - || !Array.isArray(result.arguments) || !result.arguments.every((value) => typeof value === 'string') - || !isObject(result.environment) || !Object.values(result.environment).every((value) => typeof value === 'string') - || Object.keys(result).some((key) => !['program', 'arguments', 'workingDirectory', 'environment'].includes(key)))) { - throw new PluginSdkError('sdk.build.invalidResult', `${method} needs native debug target facts, without an adapter or DAP arguments.`); - } - // Workspace containment and domain facts remain Core/provider responsibilities. - if (Buffer.byteLength(JSON.stringify(document)) > LIMITS.maxBuildResultBytes) { - throw new PluginSdkError('sdk.build.invalidResult', `${method} exceeds the build-result size limit.`); - } - return document; -} - -function isObject(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value); -} - -/** `{ pluginID }` for the exact top-level `caller` Core writes into a relayed call, else null. */ -function callerReference(value) { - if (!isObject(value) || Object.keys(value).length !== 1) return null; - return typeof value.pluginID === 'string' && value.pluginID.length > 0 - ? Object.freeze({ pluginID: value.pluginID }) - : null; -} - -function validKeymapProvider(id) { - return typeof id === 'string' && /^[a-z][a-z0-9-]{0,63}$/.test(id); -} - -function validSnapshotToken(id) { - return typeof id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(id); -} - -function keymapSnapshot({ providerID, snapshotID }, host) { - const scope = { providerID, snapshotID }; - const invalid = () => new PluginSdkError('sdk.keymap.invalidResponse', 'Invalid shortcut source response.'); - return Object.freeze({ - providerID, snapshotID, - async listInputs() { - const result = await host.request('lithe/host/keymapImport/listInputs', scope); - if (!Array.isArray(result?.files) || result.files.length > 128 || result.files.some((file) => - !validSnapshotToken(file?.id) || typeof file.path !== 'string' || !file.path || Buffer.byteLength(file.path) > 4096 - || !Number.isSafeInteger(file.byteCount) || file.byteCount < 0 || file.byteCount > 1048576)) throw invalid(); - return result.files.map(({ id, path, byteCount }) => ({ id, path, byteCount })); - }, - async readChunk(fileID, offset, maximumBytes) { - if (!validSnapshotToken(fileID) || !Number.isSafeInteger(offset) || offset < 0 || offset > 1048576 - || !Number.isInteger(maximumBytes) || maximumBytes < 1 || maximumBytes > 131072) throw invalid(); - const result = await host.request('lithe/host/keymapImport/readChunk', { ...scope, fileID, offset, maximumBytes }); - if (typeof result?.data !== 'string' || result.data.length > 174764) throw invalid(); - const bytes = Buffer.from(result.data, 'base64'); - if (bytes.length > maximumBytes || bytes.toString('base64') !== result.data) throw invalid(); - return bytes; - }, - }); -} - -/** - * A VCS reply must be a JSON object; Core validates its fields and refuses - * anything else as `plugin.vcs.invalidOutput`, so it fails here with a log. - */ -function vcsResult(method, result) { - if (result === undefined) return {}; - if (result === null || typeof result !== 'object' || Array.isArray(result)) { - throw new PluginSdkError('sdk.vcs.invalidResult', `${method} must return a reply object.`); - } - return result; -} - -/** A copy of `object` with its keys sorted, for a stable `initialize` answer. */ -function sortedKeys(object) { - return Object.fromEntries(Object.entries(object).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))); -} - -/** - * A function result as the JSON value Core accepts. A value JSON cannot - * encode, or one over Core's 1 MiB limit, fails here as a backend bug with a - * log line, instead of breaking the response frame or being refused by Core. - */ -function functionResult(result) { - let encoded; - try { - encoded = JSON.stringify(result ?? null); - } catch (error) { - throw new PluginSdkError('sdk.function.invalidResult', `The result is not JSON: ${error.message}`); - } - if (encoded === undefined) { - throw new PluginSdkError('sdk.function.invalidResult', 'The result is not a JSON value.'); - } - if (Buffer.byteLength(encoded) > LIMITS.maxResultBytes) { - throw new PluginSdkError('sdk.function.invalidResult', `The result exceeds ${LIMITS.maxResultBytes} bytes.`); - } - return result ?? null; -} - -/** - * Sends `console.log`, `info`, and `debug` to stderr. Stdout carries the - * protocol; a stray line there would corrupt the stream and end the session. - */ -function redirectConsole(errorOutput) { - const write = (...parts) => errorOutput.write(`${format(...parts)}\n`); - console.log = write; - console.info = write; - console.debug = write; -} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs deleted file mode 100644 index 8fcdc99..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs +++ /dev/null @@ -1,34 +0,0 @@ -// Typed plugin diagnostics use the host's catalog and writer. No payload text crosses this API. -import { PluginSdkError } from './errors.mjs'; - -export const KNOWN_OPERATIONS = new Set([ - 'initialize', 'shutdown', 'notification', 'function-call', 'result-encoding', - ...['model', 'dependencies', 'execute', 'test', 'discoverTests', 'prepareRun', 'prepareDebug'].map((name) => `lithe/build/${name}`), - ...['status', 'baseContent', 'history', 'fileHistory', 'annotate', 'checkin', 'rollback', 'update', 'fileOperation', 'resolve', 'cleanup'].map((name) => `lithe/vcs/${name}`), - 'lithe/keymap/import', -]); -const token = (value, maximum) => typeof value === 'string' && value.length > 0 && value.length <= maximum && /^[A-Za-z0-9._:/\-$]+$/.test(value); -export function requestOperationId(operationId, requestId) { - if (token(operationId, 128)) return operationId; - const fallback = typeof requestId === 'string' ? requestId : Number.isSafeInteger(requestId) ? String(requestId) : undefined; - return token(fallback, 128) ? fallback : undefined; -} -export function diagnostics(send, registered, operationId) { - const record = (kind, operation, code, count, durationMs) => { - if (!KNOWN_OPERATIONS.has(operation) && !registered(operation)) throw new PluginSdkError('sdk.logging.invalidOperation', 'Diagnostics need a registered operation.'); - if (code !== undefined && !token(code, 64)) throw new PluginSdkError('sdk.logging.invalidCode', 'Diagnostics need a controlled code.'); - if (count !== undefined && (!Number.isSafeInteger(count) || count < 0)) throw new PluginSdkError('sdk.logging.invalidCount', 'Diagnostics need a nonnegative safe count.'); - const params = { kind, operation: operation.length <= 64 ? operation : 'function-call' }; - if (code !== undefined) params.code = code; - if (count !== undefined) params.count = count; - if (durationMs !== undefined) params.durationMs = Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.floor(durationMs))); - if (token(operationId, 128)) params.operationId = operationId; - send(params); - }; - return Object.freeze({ - degraded: (operation, code, count) => record('degraded', operation, code, count), - recovered: (operation, code, count) => record('recovered', operation, code, count), - terminal: (operation, error, durationMs = 0) => record(error ? 'operationFailed' : 'operationFinished', operation, - error ? (token(error.code, 64) ? error.code : 'internal_error') : undefined, undefined, durationMs), - }); -} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs deleted file mode 100644 index 048cae0..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs +++ /dev/null @@ -1,101 +0,0 @@ -import { boundedText, ERROR_CODES, HOST_ERRORS, isPluginErrorCode } from './protocol.mjs'; - -/** - * A failure a handler reports on purpose. Core ends the call with the stable - * `plugin.function.failed` code and forwards `code` as `pluginErrorCode`, so - * the plugin's own UI can tell its failures apart. Lithe never branches on it. - */ -export class PluginError extends Error { - /** - * @param {string} code Identifier of at most 64 bytes, such as `maven.snapshotLocked`. - * @param {string} message User-facing text; Core keeps the first 1024 bytes. - * @param {object} [options] `{ cause }`, retained in memory and omitted from automatic diagnostics. - */ - constructor(code, message, options) { - super(message, options); - if (!isPluginErrorCode(code)) { - throw new TypeError( - `Plugin error code ${JSON.stringify(code)} must start with a letter, use letters, digits, ".", "_" or "-", and be at most 64 bytes.`, - ); - } - this.name = 'PluginError'; - this.code = code; - } -} - -/** An SDK usage error, raised synchronously to the plugin author. */ -export class PluginSdkError extends Error { - constructor(code, message) { - super(message); - this.name = 'PluginSdkError'; - this.code = code; - } -} - -const HOST_CODES = new Map(Object.entries(HOST_ERRORS).map(([code, rpcCode]) => [rpcCode, code])); - -/** - * The host refused or failed a request this backend sent. `code` is the - * stable `error.data.code`, such as `plugin.host.contextExpired`; `rpcCode` - * the JSON-RPC number; `details` the object a version 3 host may add, such - * as `{ option }` or `{ retryAfterMilliseconds }`. - */ -export class HostError extends PluginSdkError { - constructor(code, message, { rpcCode, details, method } = {}) { - super(code, message); - this.name = 'HostError'; - this.rpcCode = rpcCode; - this.details = details; - this.method = method; - } - - /** - * The failure for a JSON-RPC error answer. A host method without a known - * code is a host failure: from version 3 a number names one code, and an - * unknown number is `plugin.host.failed`. - */ - static fromResponse(method, error) { - const data = error?.data; - const isHost = method.startsWith('lithe/host/'); - const code = typeof data?.code === 'string' - ? data.code - : isHost - ? HOST_CODES.get(error?.code) ?? 'plugin.host.failed' - : 'sdk.host.error'; - const details = data?.details !== null && typeof data?.details === 'object' && !Array.isArray(data.details) - ? data.details - : undefined; - return new HostError(code, typeof error?.message === 'string' ? error.message : `${method} failed.`, { - rpcCode: error?.code, - details, - method, - }); - } -} - -/** True for the rejection an aborted `AbortSignal` produces. */ -export function isAbort(error, signal) { - return Boolean(signal?.aborted) && (error === signal.reason || error?.name === 'AbortError'); -} - -/** - * The JSON-RPC error object for a handler failure. Only `PluginError` carries - * a plugin code; any other exception becomes a generic internal error so that - * stack traces and machine paths never reach the host's UI. A `PluginError` - * message is shown to the user as written, so it must not contain them either. - */ -export function toResponseError(error, signal) { - if (isAbort(error, signal)) { - return { code: ERROR_CODES.requestCancelled, message: 'The request was cancelled.' }; - } - if (error instanceof PluginError) { - return { - code: ERROR_CODES.requestFailed, - message: boundedText(error.message), - data: { code: error.code }, - }; - } - // Unexpected exceptions often embed absolute paths (ENOENT) or internals; - // the caller logs only a fixed failure category to stderr. - return { code: ERROR_CODES.internalError, message: 'The plugin backend failed unexpectedly.' }; -} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs deleted file mode 100644 index ccfe774..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs +++ /dev/null @@ -1,74 +0,0 @@ -// LSP base-protocol framing: `Content-Length` headers followed by a UTF-8 -// JSON body. Lithe talks to every plugin backend this way, so the SDK owns -// the framing and plugin code never writes to stdout itself. - -const HEADER_END = Buffer.from('\r\n\r\n', 'ascii'); - -/** Largest header block accepted from the host. */ -const MAX_HEADER_BYTES = 8192; - -/** Largest body accepted from the host. Larger frames end the session. */ -export const MAX_FRAME_BYTES = 64 * 1024 * 1024; - -/** Stands for a body that is not JSON; compared by identity, so no host message can mimic it. */ -export const MALFORMED = Object.freeze({ malformed: true }); - -/** A framing error the session cannot recover from. */ -export class FramingError extends Error {} - -/** Incrementally splits a byte stream into decoded JSON-RPC messages. */ -export class FrameDecoder { - #buffer = Buffer.alloc(0); - - /** - * Appends `chunk` and returns every complete message it finished. A body - * that is not JSON is returned as `MALFORMED` so the caller can - * report it without losing the framing position. - */ - push(chunk) { - this.#buffer = this.#buffer.length === 0 ? Buffer.from(chunk) : Buffer.concat([this.#buffer, chunk]); - const messages = []; - for (;;) { - const headerEnd = this.#buffer.indexOf(HEADER_END); - // The same bound whether the header arrived whole or in pieces. - if (headerEnd > MAX_HEADER_BYTES || (headerEnd < 0 && this.#buffer.length > MAX_HEADER_BYTES)) { - throw new FramingError('The message header is too long.'); - } - if (headerEnd < 0) return messages; - const length = contentLength(this.#buffer.subarray(0, headerEnd).toString('ascii')); - const bodyStart = headerEnd + HEADER_END.length; - if (this.#buffer.length < bodyStart + length) { - return messages; - } - const body = this.#buffer.subarray(bodyStart, bodyStart + length).toString('utf8'); - this.#buffer = this.#buffer.subarray(bodyStart + length); - try { - messages.push(JSON.parse(body)); - } catch { - messages.push(MALFORMED); - } - } - } -} - -function contentLength(header) { - for (const line of header.split('\r\n')) { - const separator = line.indexOf(':'); - if (separator < 0) continue; - if (line.slice(0, separator).trim().toLowerCase() !== 'content-length') continue; - const value = line.slice(separator + 1).trim(); - if (!/^\d+$/.test(value)) break; - const length = Number(value); - if (length > MAX_FRAME_BYTES) { - throw new FramingError(`A message of ${length} bytes exceeds the ${MAX_FRAME_BYTES}-byte limit.`); - } - return length; - } - throw new FramingError('A message has no valid Content-Length header.'); -} - -/** Encodes one JSON-RPC message as a complete frame. */ -export function encodeFrame(message) { - const body = Buffer.from(JSON.stringify(message), 'utf8'); - return Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, 'ascii'), body]); -} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs deleted file mode 100644 index fb0fff1..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs +++ /dev/null @@ -1,447 +0,0 @@ -// Host services of plugin-function protocols 2 to 4: the `lithe/host/*` -// requests a backend sends to Lithe, the subscriptions some of them create, -// and the `host` object handlers use. The backend owns the wire; this module -// owns what Core expects of a well-behaved client -- at most 16 unanswered -// host requests, cancellation through `$/cancelRequest` from version 3, -// subscription events routed by ID, and the relay methods only from version 4. -// -// Contract: contract/v1/README.md, "Host services (protocol version 2)" and -// the version 3 and 4 sections after it. - -import { HostError, PluginSdkError } from './errors.mjs'; -import { - CONTEXT_VERSION, - HOST_METHODS, - HOST_SERVICES_VERSION, - isContextReference, - isCredentialKey, - isFunctionId, - isRelayMethod, - LIMITS, - METHODS, - RELAY_VERSION, -} from './protocol.mjs'; - -/** Events kept for a subscription whose creating request is still unanswered. */ -const MAX_EARLY_EVENTS = 128; - -const CREDENTIAL_METHODS = Object.freeze([ - HOST_METHODS.credentialsGet, - HOST_METHODS.credentialsSet, - HOST_METHODS.credentialsDelete, -]); - -/** - * The session's host-request state. `transport` is the backend's wire: - * `{ version(), ready(), send(method, params) -> { id, response }, notify(method, params), log(...) }`. - */ -export class HostChannel { - #transport; - #inFlight = 0; - /** Requests waiting for a free slot, in call order: `{ start, fail }`. */ - #queue = []; - /** Live subscriptions by ID: `{ onEvent, lastSequence }`. */ - #subscriptions = new Map(); - /** Subscribing requests not yet answered; early events wait only while there are some. */ - #subscribing = 0; - #early = []; - #capabilities = null; - #closed = false; - - constructor(transport) { - this.#transport = transport; - } - - /** The negotiated plugin-function version, or 0 before or without one. */ - get version() { - return this.#transport.version(); - } - - request(method, params, { signal } = {}) { - if (typeof method !== 'string' || !method.startsWith('lithe/host/')) { - return Promise.reject(new PluginSdkError('sdk.host.method', `${method} is not a host method; host requests are lithe/host/*.`)); - } - if (this.#closed || !this.#transport.ready()) { - return Promise.reject(new PluginSdkError('sdk.session.notReady', 'The session is not initialized.')); - } - if (this.version < HOST_SERVICES_VERSION) { - // The answer Core would give, without the round trip. - return Promise.reject(new HostError( - 'plugin.host.unavailable', - 'The host did not negotiate plugin-function protocol 2 or later, which offers host services.', - { rpcCode: -32601, method }, - )); - } - if (isRelayMethod(method) && this.version < RELAY_VERSION) { - // Unlike other methods added after version 3, these two are bound to a - // version: Core answers a version 3 backend -32601, so no frame is sent. - return Promise.reject(new HostError( - 'plugin.host.unavailable', - 'The relay needs plugin-function protocol 4.', - { rpcCode: -32601, method }, - )); - } - if (signal?.aborted) return Promise.reject(signal.reason); - return new Promise((resolve, reject) => { - // `queued` → `sent` → `done`; a request settles for its caller once. - let state = 'queued'; - let id; - const done = () => { - state = 'done'; - signal?.removeEventListener('abort', onAbort); - }; - const entry = { - start: () => { - state = 'sent'; - this.#inFlight += 1; - const sent = this.#transport.send(method, params); - id = sent.id; - sent.response - .then( - (result) => { - if (state === 'done') return; - done(); - resolve(result); - }, - (error) => { - if (state === 'done') return; - done(); - reject(error); - }, - ) - .finally(() => { - // The slot frees when Core answers, also after a cancellation: - // from version 3 Core answers it at once, before version 3 the - // host still finishes the request. - this.#inFlight -= 1; - this.#drain(); - }); - }, - fail: (error) => { - if (state === 'done') return; - done(); - reject(error); - }, - }; - const onAbort = () => { - if (state === 'done') return; - if (state === 'queued') { - this.#queue.splice(this.#queue.indexOf(entry), 1); - } else if (this.version >= CONTEXT_VERSION) { - this.#transport.notify(METHODS.cancelRequest, { id }); - } - // A cancelled mutation may already have taken effect; it is never - // sent again. - done(); - reject(signal.reason); - }; - signal?.addEventListener('abort', onAbort, { once: true }); - this.#queue.push(entry); - this.#drain(); - }); - } - - /** - * Sends a request whose result is `{ subscriptionID }` and routes that - * subscription's events to `onEvent(event, { subscriptionID, sequence, gap })`. - */ - async subscribe(method, params, onEvent, options) { - if (onEvent !== undefined && typeof onEvent !== 'function') { - throw new TypeError('A subscription event handler must be a function.'); - } - this.#subscribing += 1; - try { - const result = await this.request(method, params, options); - const subscriptionID = result?.subscriptionID; - if (!isCredentialKey(subscriptionID)) { - throw new PluginSdkError('sdk.host.invalidResult', `${method} answered without a subscriptionID.`); - } - const subscription = { onEvent: onEvent ?? (() => {}), lastSequence: 0, live: true }; - this.#subscriptions.set(subscriptionID, subscription); - // Events the host sent before this answer was read. - const early = this.#early.filter((event) => event.subscriptionID === subscriptionID); - this.#early = this.#early.filter((event) => event.subscriptionID !== subscriptionID); - for (const event of early) this.#emit(subscriptionID, subscription, event); - return Object.freeze({ - subscriptionID, - get disposed() { - return !subscription.live; - }, - dispose: () => this.dispose(subscriptionID), - }); - } finally { - this.#subscribing -= 1; - if (this.#subscribing === 0) this.#early = []; - } - } - - /** Stops routing a subscription's events at once and asks the host to dispose it. */ - async dispose(subscriptionID) { - const subscription = this.#subscriptions.get(subscriptionID); - if (subscription) subscription.live = false; - this.#subscriptions.delete(subscriptionID); - if (this.#closed || !this.#transport.ready()) return; - await this.request(HOST_METHODS.subscriptionsDispose, { subscriptionID }); - } - - /** Routes one `lithe/host/subscriptions/notify`. */ - deliver({ subscriptionID, sequence, event }) { - const subscription = this.#subscriptions.get(subscriptionID); - if (subscription) { - this.#emit(subscriptionID, subscription, { sequence, event }); - } else if (this.#subscribing > 0) { - if (this.#early.length < MAX_EARLY_EVENTS) { - this.#early.push({ subscriptionID, sequence, event }); - } else { - this.#transport.log('Dropped an early subscription event: queue_full'); - } - } - // Otherwise the subscription was disposed; nothing follows a disposal. - } - - /** The cached `getCapabilities` answer; Core answers it itself, from version 3. */ - capabilities() { - if (this.version < CONTEXT_VERSION) { - return Promise.reject(new HostError( - 'plugin.host.unavailable', - 'Capability discovery needs plugin-function protocol 3.', - { rpcCode: -32601, method: HOST_METHODS.getCapabilities }, - )); - } - this.#capabilities ??= this.request(HOST_METHODS.getCapabilities).catch((error) => { - this.#capabilities = null; - throw error; - }); - return this.#capabilities; - } - - /** - * Whether this session may call `method`. From version 3 the answer comes - * from `getCapabilities`; version 2 has no discovery, so it reports the - * methods version 2 defines, and a missing grant still fails the request. - */ - async supports(method) { - if (this.version >= CONTEXT_VERSION) { - const { services } = await this.capabilities(); - return Object.values(services ?? {}).some((service) => Array.isArray(service?.methods) && service.methods.includes(method)); - } - return this.version >= HOST_SERVICES_VERSION && CREDENTIAL_METHODS.includes(method); - } - - /** Ends the channel with the session: queued requests fail, subscriptions end. */ - close() { - this.#closed = true; - for (const entry of this.#queue.splice(0)) { - entry.fail(new PluginSdkError('sdk.session.closed', 'The session ended.')); - } - for (const subscription of this.#subscriptions.values()) subscription.live = false; - this.#subscriptions.clear(); - this.#early = []; - this.#capabilities = null; - } - - #emit(subscriptionID, subscription, { sequence, event }) { - const gap = sequence !== subscription.lastSequence + 1; - subscription.lastSequence = sequence; - Promise.resolve() - .then(() => subscription.onEvent(event, { subscriptionID, sequence, gap })) - .catch(() => this.#transport.log('A subscription listener failed: internal_error')); - } - - #drain() { - while (!this.#closed && this.#inFlight < LIMITS.maxPendingHostRequests && this.#queue.length > 0) { - this.#queue.shift().start(); - } - } -} - -/** - * The `host` object: typed host services over `channel`. A handler's - * `context.host` passes the call's signal, so its unanswered host requests - * are cancelled when the call ends. It also passes the `operationID` of the - * `lithe/function/invoke` being served as `parentOperationId`, which - * `functions.invoke` sends as the new call's parent unless the caller names - * another. A host object without them (`backend.host`) has no default parent. - */ -export function createHost(channel, callSignal, parentOperationId) { - const withSignal = (options = {}) => { - if (!callSignal) return options; - return { ...options, signal: options.signal ? AbortSignal.any([callSignal, options.signal]) : callSignal }; - }; - const request = (method, params, options) => channel.request(method, params, withSignal(options)); - const subscribe = (method, params, onEvent, options) => channel.subscribe(method, params, onEvent, withSignal(options)); - /** A method whose params name a workspace context. */ - const scoped = (method) => async (context, params = {}, options) => - request(method, { ...params, context: contextReference(context) }, options); - - return Object.freeze({ - get version() { - return channel.version; - }, - request: async (method, params, options) => request(method, params, options), - subscribe: async (method, params, onEvent, options) => subscribe(method, params, onEvent, options), - capabilities: () => channel.capabilities(), - supports: (method) => channel.supports(method), - credentials: Object.freeze({ - async get(key, options) { - checkCredentialKey(key); - const result = await request(HOST_METHODS.credentialsGet, { key }, options); - if (result === null) return null; - if (typeof result?.secret !== 'string') { - throw new PluginSdkError('sdk.host.invalidResult', 'The host answered credentials/get without a secret.'); - } - return result.secret; - }, - async set(key, secret, options) { - checkCredentialKey(key); - if (typeof secret !== 'string' || Buffer.byteLength(secret) > LIMITS.maxCredentialSecretBytes) { - throw new PluginSdkError('sdk.credentials.invalidSecret', 'A secret is a string of at most 16 KiB.'); - } - await request(HOST_METHODS.credentialsSet, { key, secret }, options); - }, - async delete(key, options) { - checkCredentialKey(key); - await request(HOST_METHODS.credentialsDelete, { key }, options); - }, - }), - subscriptions: Object.freeze({ - dispose: async (subscriptionID) => channel.dispose(subscriptionID), - }), - workspace: Object.freeze({ - listContexts: async (options) => request(HOST_METHODS.workspaceListContexts, {}, options), - getContext: async (context, options) => - request(HOST_METHODS.workspaceGetContext, { context: contextReference(context) }, options), - getFolders: async (context, options) => - request(HOST_METHODS.workspaceGetFolders, { context: contextReference(context) }, options), - readDirectory: scoped(HOST_METHODS.workspaceReadDirectory), - stat: scoped(HOST_METHODS.workspaceStat), - readFile: scoped(HOST_METHODS.workspaceReadFile), - watch: async (context, params, onEvent, options) => - subscribe(HOST_METHODS.workspaceWatch, { ...params, context: contextReference(context) }, onEvent, options), - findFiles: scoped(HOST_METHODS.workspaceFindFiles), - findText: scoped(HOST_METHODS.workspaceFindText), - }), - functions: Object.freeze({ - providers: async (functionID, options) => { - checkRelayFunctionId(functionID); - return request(HOST_METHODS.functionsProviders, { functionID }, options); - }, - invoke: async (context, call, options) => - request(HOST_METHODS.functionsInvoke, relayInvokeParams(context, call, parentOperationId), options), - }), - documents: Object.freeze({ - list: scoped(HOST_METHODS.documentsList), - getSnapshot: scoped(HOST_METHODS.documentsGetSnapshot), - }), - editor: Object.freeze({ - getActive: scoped(HOST_METHODS.editorGetActive), - getSelections: scoped(HOST_METHODS.editorGetSelections), - applyEdits: scoped(HOST_METHODS.editorApplyEdits), - replaceSelections: scoped(HOST_METHODS.editorReplaceSelections), - insertText: scoped(HOST_METHODS.editorInsertText), - open: scoped(HOST_METHODS.editorOpen), - reveal: scoped(HOST_METHODS.editorReveal), - registerActions: async (context, params, options) => - subscribe(HOST_METHODS.editorRegisterActions, { ...params, context: contextReference(context) }, undefined, options), - }), - preview: Object.freeze({ - openHTML: scoped(HOST_METHODS.previewOpenHTML), - }), - browser: Object.freeze({ - openExternal: scoped(HOST_METHODS.browserOpenExternal), - }), - terminal: Object.freeze({ - create: scoped(HOST_METHODS.terminalCreate), - show: scoped(HOST_METHODS.terminalShow), - close: scoped(HOST_METHODS.terminalClose), - reopen: scoped(HOST_METHODS.terminalReopen), - dispose: scoped(HOST_METHODS.terminalDispose), - onExit: async (context, terminalID, onEvent, options) => - subscribe(HOST_METHODS.terminalOnExit, { context: contextReference(context), terminalID }, onEvent, options), - }), - window: Object.freeze({ - showInformation: scoped(HOST_METHODS.windowShowInformation), - showWarning: scoped(HOST_METHODS.windowShowWarning), - showError: scoped(HOST_METHODS.windowShowError), - }), - }); -} - -/** - * `{ contextID, generation }` of a context reference or of a full context - * from `listContexts` or `getContext`, so either can be passed on. - */ -export function contextReference(value) { - const reference = { contextID: value?.contextID, generation: value?.generation }; - if (!isContextReference(reference)) { - throw new PluginSdkError( - 'sdk.host.invalidContext', - 'A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, ".", "_", ":" or "-", and a positive generation.', - ); - } - return reference; -} - -function checkCredentialKey(key) { - if (!isCredentialKey(key)) { - throw new PluginSdkError( - 'sdk.credentials.invalidKey', - 'A credential key is 1-128 ASCII letters, digits, ".", "_", ":" or "-".', - ); - } -} - -function invalidRelayCall(message) { - return new PluginSdkError('sdk.functions.invalidCall', message); -} - -function checkRelayFunctionId(functionID) { - if (!isFunctionId(functionID)) { - throw invalidRelayCall('A function ID is dot-separated lowerCamelCase segments of at most 128 bytes, such as "project.describe".'); - } -} - -function isParentOperationId(value) { - return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= LIMITS.maxParentOperationIdBytes; -} - -/** - * The params of one `lithe/host/functions/invoke`, built from the whitelisted - * fields of `call` only, so a caller cannot add a field of its own (Core - * refuses `caller` and writes it itself). Checks what Core checks first; a - * mistake throws before any frame is written. `params` stays absent unless - * given. The parent is the call's own `parentOperationID`, else the operation - * being served (`defaultParent`), else absent. - */ -function relayInvokeParams(context, call, defaultParent) { - if (call === null || typeof call !== 'object' || Array.isArray(call)) { - throw invalidRelayCall('A relayed call is { pluginID, functionID, params?, timeoutMilliseconds?, parentOperationID? }.'); - } - const { pluginID, functionID, params, timeoutMilliseconds, parentOperationID } = call; - if (typeof pluginID !== 'string' || pluginID.length === 0) { - throw invalidRelayCall('pluginID is the ID of the plugin that provides the function, a non-empty string.'); - } - checkRelayFunctionId(functionID); - const wire = { pluginID, functionID, context: contextReference(context) }; - if (params !== undefined) { - if (params === null || typeof params !== 'object' || Array.isArray(params)) { - throw invalidRelayCall('params are a JSON object.'); - } - wire.params = params; - } - if (timeoutMilliseconds !== undefined) { - if (!Number.isSafeInteger(timeoutMilliseconds) || timeoutMilliseconds < 1) { - throw invalidRelayCall('timeoutMilliseconds is a positive integer.'); - } - wire.timeoutMilliseconds = timeoutMilliseconds; - } - if (parentOperationID !== undefined) { - if (!isParentOperationId(parentOperationID)) { - throw invalidRelayCall('parentOperationID is a string of 1-128 bytes.'); - } - wire.parentOperationID = parentOperationID; - } else if (defaultParent !== undefined) { - wire.parentOperationID = defaultParent; - } - return wire; -} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts deleted file mode 100644 index 3217197..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts +++ /dev/null @@ -1,714 +0,0 @@ -// Type declarations for the Lithe plugin backend SDK. Keep in sync with the -// `.mjs` sources; `sdk/node/test/support.test.mjs` checks the exported names. - -/** Any value JSON can carry. */ -export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }; -export type JsonObject = { [key: string]: JsonValue }; - -export interface RunProcessOptions { - cwd?: string; - /** Replaces the environment when given; Lithe's process markers are carried over regardless. */ - env?: Record; - /** Aborting it ends the whole process tree and rejects with its reason. */ - signal?: AbortSignal; - /** Captured bytes per stream; default 1 MiB. */ - maxOutputBytes?: number; - onStdout?: (chunk: string) => void; - onStderr?: (chunk: string) => void; - /** Delay between the polite and forced stop; default 2000. */ - killGraceMilliseconds?: number; -} - -export interface ProcessResult { - exitCode: number | null; - signal: string | null; - stdout: string; - stderr: string; - truncated: boolean; -} - -/** Typed facts for the host-owned litheLogging 1 event catalog. */ -export interface Diagnostics { - degraded(operation: string, code: string, count?: number): void; - recovered(operation: string, code: string, count?: number): void; -} - -/** Shared by every handler. */ -export interface RequestContext { - /** Aborted when the host cancels the call, the call times out, the session ends, or the call has settled. */ - signal: AbortSignal; - throwIfCancelled(): void; - /** `runProcess` bound to this call: its tree ends when the call is cancelled or settles. */ - run(command: string, args?: string[], options?: RunProcessOptions): Promise; - /** Fixed facts, correlated with the host operation; never accepts payload text. */ - readonly diagnostics: Diagnostics; - /** Omits only this call's successful fact; failures remain visible. */ - suppressSuccessDiagnostics(): void; - /** `backend.host` bound to this call: its unanswered host requests are cancelled when the call ends. */ - host: Host; -} - -/** `{ contextID, generation }`: one generation of one workspace context (protocol 3). */ -export interface ContextReference { - contextID: string; - generation: number; -} - -export interface WorkspaceFolder { - /** Stable per plugin and location; reveals nothing about the path. */ - rootID: string; - name: string; - /** Present only for a local authority. */ - path?: string; -} - -/** One open workspace in one window. */ -export interface WorkspaceContext extends ContextReference { - name: string; - authority: { kind: 'local' | 'remote'; id?: string }; - folders: WorkspaceFolder[]; - /** Private to the plugin and the workspace; only `getContext` returns, and creates, it. */ - stateDirectory?: string; - [key: string]: unknown; -} - -export interface HostCapabilities { - protocolVersion: number; - backendAuthority: 'local'; - /** Each service this session may use, with the requests it may send and the notifications it may receive. */ - services: Record; - limits: { - pendingHostRequests: number; - functionResultBytes: number; - hostRequestBytes: number; - hostResultBytes: number; - errorMessageBytes: number; - errorDetailsBytes: number; - notificationBytes: number; - [key: string]: number; - }; - [key: string]: unknown; -} - -export interface HostRequestOptions { - /** Aborting it rejects with its reason; from protocol 3 the host is also told to stop. Never retried. */ - signal?: AbortSignal; -} - -export interface SubscriptionEventInfo { - subscriptionID: string; - sequence: number; - /** True when `sequence` does not follow the previous event: events were missed. */ - gap: boolean; -} - -export type SubscriptionHandler = (event: JsonObject, info: SubscriptionEventInfo) => unknown; - -export interface Subscription { - readonly subscriptionID: string; - readonly disposed: boolean; - /** Stops routing events at once and asks the host to dispose the subscription. */ - dispose(): Promise; -} - -/** A file or folder under a root of `getFolders`; `path` uses `/` and is relative to the root. */ -export interface WorkspaceResource { - rootID: string; - path: string; -} - -/** One-based UTF-16 position. */ -export interface TextPosition { - line: number; - column: number; -} - -/** Half-open range. */ -export interface TextRange { - start: TextPosition; - end: TextPosition; -} - -export interface TextSelection { - anchor: TextPosition; - active: TextPosition; -} - -export interface DocumentSummary { - documentID: string; - version: number; - /** Workspace-relative, or null outside the root. */ - path: string | null; - languageID: string | null; - isReadOnly: boolean; - isDirty: boolean; - encoding: string; - lineEnding: string; - [key: string]: unknown; -} - -export interface EditResult { - documentID: string; - version: number; - applied: boolean; - [key: string]: unknown; -} - -export interface OpenParams { - resource: WorkspaceResource; - activation?: 'select' | 'background'; - range?: TextRange; - tab?: 'regular'; -} - -export interface FindPage { - matches: T[]; - nextCursor: string | null; - isTruncated: boolean; - source: 'disk'; - [key: string]: unknown; -} - -type Scoped = (context: ContextReference, params: P, options?: HostRequestOptions) => Promise; -type ScopedOptional = (context: ContextReference, params?: P, options?: HostRequestOptions) => Promise; - -/** One enabled plugin that exports a function, from `host.functions.providers`. */ -export interface FunctionProvider { - pluginID: string; - /** The contract version of the exported function. */ - version: number; -} - -export interface FunctionProvidersResult { - /** Enabled plugins other than the caller, sorted by plugin ID. */ - providers: FunctionProvider[]; -} - -/** One cross-plugin call, the argument of `host.functions.invoke`. */ -export interface FunctionCall { - /** The providing plugin, one of `providers(functionID)`. */ - pluginID: string; - functionID: string; - /** A JSON object; not sent when omitted, which Core reads as `{}`. */ - params?: JsonObject; - /** A positive integer. Core defaults it to 60000 and caps it at 600000. */ - timeoutMilliseconds?: number; - /** - * The `operationID` of the call this one belongs to, a string of 1-128 bytes. - * Inside a function handler `context.host` fills it with the call being - * served; `backend.host` has no default. - */ - parentOperationID?: string; -} - -export interface FunctionInvokeResult { - /** The provider's result; `null` is a result. */ - value: JsonValue; -} - -/** - * Host services of plugin-function protocols 2 to 4. Every method rejects - * with `HostError` when the host refuses; from protocol 3 check - * `supports(method)` instead of assuming a method from the version. - * A full `WorkspaceContext` may be passed wherever a reference is expected. - */ -export interface Host { - /** The negotiated plugin-function version, or 0 before or without one. */ - readonly version: number; - /** Sends any `lithe/host/*` request, including ones a later host adds. */ - request(method: string, params?: JsonObject, options?: HostRequestOptions): Promise; - /** Sends a request answering `{ subscriptionID }` and routes that subscription's events. */ - subscribe(method: string, params: JsonObject, onEvent?: SubscriptionHandler, options?: HostRequestOptions): Promise; - /** The session's capabilities; protocol 3, cached. */ - capabilities(): Promise; - /** Whether this session may call `method`. Under protocol 2, which has no discovery, the methods it defines. */ - supports(method: string): Promise; - /** Protocol 2; permission `credentials.store`. Kept in the platform's secret store, per plugin. */ - readonly credentials: { - /** The stored secret, or null. */ - get(key: string, options?: HostRequestOptions): Promise; - set(key: string, secret: string, options?: HostRequestOptions): Promise; - delete(key: string, options?: HostRequestOptions): Promise; - }; - readonly subscriptions: { - dispose(subscriptionID: string): Promise; - }; - readonly workspace: { - /** Permission `workspace.metadata`. Entries carry no `stateDirectory`. */ - listContexts(options?: HostRequestOptions): Promise<{ revision: number; contexts: WorkspaceContext[] }>; - getContext(context: ContextReference, options?: HostRequestOptions): Promise; - getFolders(context: ContextReference, options?: HostRequestOptions): Promise<{ folders: WorkspaceFolder[] }>; - /** Permission `workspace.files.read`. */ - readDirectory: Scoped<{ resource: WorkspaceResource; cursor?: string; limit?: number }, { - entries: { name: string; resource: WorkspaceResource; kind: string }[]; - nextCursor: string | null; - }>; - stat: Scoped<{ resource: WorkspaceResource }, { resource: WorkspaceResource; kind: string; size: number; modifiedMilliseconds: number }>; - readFile: Scoped<{ resource: WorkspaceResource; maximumBytes?: number }, { - resource: WorkspaceResource; - source: 'disk'; - byteCount: number; - isTruncated: boolean; - identity: JsonValue; - text?: string; - encoding?: string; - base64?: string; - }>; - /** Permission `workspace.files.watch`. Events carry `{ rootID, changedPaths, requiresRescan }`. */ - watch( - context: ContextReference, - params: { resource: WorkspaceResource; recursive?: boolean }, - onEvent: SubscriptionHandler, - options?: HostRequestOptions, - ): Promise; - /** Permission `workspace.search`; `resource` names the root (`path: ""`). */ - findFiles: Scoped<{ resource: WorkspaceResource; query: string; fileMask?: string; cursor?: string; limit?: number }, FindPage>; - findText: Scoped<{ - resource: WorkspaceResource; - pattern: string; - fileMask?: string; - caseSensitive?: boolean; - wholeWords?: boolean; - regularExpression?: boolean; - cursor?: string; - limit?: number; - }, FindPage<{ resource: WorkspaceResource; line: number; preview: string; range: TextRange | null }>>; - }; - /** Permission `documents.read`. */ - readonly documents: { - list: ScopedOptional; - getSnapshot: Scoped<{ documentID: string }, { document: DocumentSummary; text: string }>; - }; - readonly editor: { - getActive: ScopedOptional; - getSelections: Scoped<{ documentID: string }, { documentID: string; version: number; selections: TextSelection[]; primaryIndex: number }>; - /** Permission `editor.edit`. Not replayed on cancellation or timeout: the edit may have committed. */ - applyEdits: Scoped<{ documentID: string; expectedVersion: number; edits: { range: TextRange; text: string }[] }, EditResult>; - replaceSelections: Scoped<{ documentID: string; expectedVersion: number; selections: TextSelection[]; replacements: string[] }, EditResult>; - insertText: Scoped<{ documentID: string; expectedVersion: number; at: TextPosition; text: string }, EditResult>; - /** Permission `editor.open`. */ - open: Scoped; - reveal: Scoped; - /** Permission `editor.actions`; the host later calls `function` to collect actions. */ - registerActions( - context: ContextReference, - params: { id: string; function: string; selector: { fileExtensions?: string[]; fileNames?: string[] } }, - options?: HostRequestOptions, - ): Promise; - }; - /** Permission `preview.open`. */ - readonly preview: { - openHTML: Scoped<{ resource: WorkspaceResource; presentation?: 'editorAndPreview' | 'previewOnly'; range?: TextRange }, JsonObject>; - }; - /** Permission `browser.open`; exactly one of `url` or `resource`. */ - readonly browser: { - openExternal: Scoped< - { url: string } | { resource: WorkspaceResource; unsaved?: 'openSavedFile' | 'requireSaved' }, - { opened: true; source: 'web' | 'disk'; hasUnsavedChanges?: boolean } - >; - }; - /** - * Protocol 4; the manifest's `pluginFunctions.calls`. Calls between plugins, - * relayed through Core. Under protocol 3 or earlier both reject at once with - * `HostError` `plugin.host.unavailable`, and nothing is sent. Argument - * mistakes reject with `PluginSdkError` `sdk.functions.invalidCall`, or - * `sdk.host.invalidContext` for the context, before anything is sent. - */ - readonly functions: { - /** The enabled plugins other than this one that export `functionID`. */ - providers(functionID: string, options?: HostRequestOptions): Promise; - /** Calls one provider's function in a workspace context. A provider's own failure is `plugin.function.failed`. */ - invoke(context: ContextReference, call: FunctionCall, options?: HostRequestOptions): Promise; - }; - /** Permission `terminal.create`; only terminals owned by this backend session and context. */ - readonly terminal: { - create: Scoped<{ executable: string; arguments?: string[]; title?: string; cwd?: WorkspaceResource; - environment?: Record; show?: boolean; retainedContextBytes?: number }, { terminalID: string; generation: number }>; - show: Scoped<{ terminalID: string }, null>; - close: Scoped<{ terminalID: string; retainedContextBytes?: number }, { retainedContextBytes: number }>; - reopen: Scoped<{ terminalID: string; show?: boolean }, { terminalID: string; generation: number; restoredContextBytes: number }>; - dispose: Scoped<{ terminalID: string }, null>; - onExit(context: ContextReference, terminalID: string, - onEvent: (event: { type: 'exit'; terminalID: string; exitCode: number | null; reason: 'exited' | 'closed'; generation: number }, metadata: SubscriptionEventInfo) => void, - options?: HostRequestOptions): Promise; - }; - /** Permission `window.messages`. `selectedIndex` is zero-based, or null on dismissal. */ - readonly window: { - showInformation: Scoped<{ text: string; actions?: string[] }, { selectedIndex: number | null }>; - showWarning: Scoped<{ text: string; actions?: string[] }, { selectedIndex: number | null }>; - showError: Scoped<{ text: string; actions?: string[] }, { selectedIndex: number | null }>; - }; -} - -export interface CommandEvent { - commandID: string; - /** The context of the window the command ran in, or null. */ - workspaceContext: ContextReference | null; -} - -export interface ProgressReport { - /** Cut to 1024 bytes. */ - message?: string; - /** Rounded and clamped to 0-100. */ - percentage?: number; -} - -export interface FunctionContext extends RequestContext { - functionID: string; - /** Opaque per-call ID chosen by Lithe. */ - operationID: string; - /** The context of the page's window (protocol 3), or null. */ - workspaceContext: ContextReference | null; - /** - * The plugin that called this function through the relay (protocol 4), or - * null: the host started the call, or the session negotiated less than 4. - * Decide by this field, never by a plugin ID inside `params`. - */ - readonly caller: { readonly pluginID: string } | null; - /** Reports progress; ignored once the call has ended. */ - progress(report: ProgressReport): void; -} - -export type FunctionHandler = (params: JsonObject, context: FunctionContext) => unknown | Promise; -export type BuildHandler = (params: BuildRequestParams, context: RequestContext) => JsonObject | Promise; - -/** A file captured under the selected shortcut source. `path` is a relative label. */ -export interface KeymapSourceFile { id: string; path: string; byteCount: number } -export interface KeymapImportSnapshot { - readonly providerID: string; - readonly snapshotID: string; - listInputs(): Promise; - readChunk(fileID: string, offset: number, maximumBytes: number): Promise; -} -export interface KeymapImportBinding { - commandID: string; - keys: Array<{ key: string; modifiers: Array<'control' | 'alt' | 'shift' | 'meta'> }>; -} -export type KeymapImportHandler = (snapshot: KeymapImportSnapshot, context: RequestContext) => - { bindings: KeymapImportBinding[] } | Promise<{ bindings: KeymapImportBinding[] }>; - -/** Params of `lithe/build/model` and `lithe/build/dependencies`. */ -export interface BuildRequestParams { - /** Read-only host snapshot; missing producers remain unavailable. Requires protocol 6. */ - modelInputs?: BuildModelInputs; - buildSystemID: string; - root: string; - options: JsonObject; - optionArguments: string[]; - environment: Record; - /** Dependencies only: the selected project, or null for the workspace. */ - project?: { name: string; path: string } | null; - /** True when the user or a sync-file change asked to reload; skip any snapshot. */ - refresh?: boolean; - /** The build tool the host resolved; absent when it could not, so look it up yourself. */ - tool?: { executable: string }; - [key: string]: unknown; -} - -/** Public normalized facts. Tasks, run plans, settings and optionValues never cross this boundary. */ -export interface BuildSharedModel { - projects: { id: string; name: string; path: string; displayName?: string; parentID?: string; properties: Record }[]; - targets: { id: string; projectID: string; name: string; path: string; tags: string[]; properties: Record }[]; - contentRoots: { projectID: string; path: string; kind: string }[]; -} -export type BuildModelInputInstance = - | { root: string; state: 'ready'; model: BuildSharedModel; configurationFingerprint: string; options: JsonObject } - | { root: string; state: 'loading' | 'stale' | 'failed' }; -export interface BuildModelInputs { - version: 1; - /** Opaque workspace-activation revision; discard cached work after it changes. */ - revision: number; - inputs: { pluginID: string; buildSystemID: string; state: 'available' | 'unavailable'; instances: BuildModelInputInstance[] }[]; -} - -/** Current upstream model selection, preserved as data rather than shell text. */ -export interface BuildSelection { - name: string; - path: string; - tags?: string[]; - properties?: JsonObject; -} - -export interface BuildExecutionParams extends BuildRequestParams { - task: string; - project?: BuildSelection | null; - target?: BuildSelection | null; - userArguments: string[]; - operationID: string; -} - -export interface BuildTestParams extends BuildRequestParams { - project?: BuildSelection | null; - target?: BuildSelection | null; - suite?: string; - case?: string; - userArguments: string[]; - operationID: string; -} - -export interface BuildRunParams extends BuildRequestParams { - run: string; - project: BuildSelection; - target: BuildSelection; - userArguments: string[]; - operationID: string; -} - -export interface BuildProgressReport extends ProgressReport { - /** Cut to 64 KiB of UTF-8 per notification. Build messages are cut to 4096 bytes. */ - output?: string; -} - -export interface BuildContext extends RequestContext { - /** The Core-assigned wire identity, never a plugin-selected value. */ - operationID: string; - /** Dropped after cancellation or completion. */ - progress(report: BuildProgressReport): void; -} - -export interface BuildExecutionResult { exitCode: number; output: string; } -export interface BuildTestDiscovery { - format?: 'litheTestDiscovery'; - version?: 1; - tests: { suite: string; case: string; project?: BuildSelection; target?: BuildSelection }[]; -} -export interface BuildRunPreparation { - executable: { kind: 'toolchain' | 'command'; value: string }; - arguments: string[]; - workingDirectory: string; - environment: Record; -} -export type BuildExecutionHandler = (params: BuildExecutionParams, context: BuildContext) => BuildExecutionResult | Promise; -export type BuildTestHandler = (params: BuildTestParams, context: BuildContext) => BuildExecutionResult | Promise; -export type BuildDiscoveryHandler = (params: BuildRequestParams, context: RequestContext) => BuildTestDiscovery | Promise; -export interface BuildDebugPreparation { - program: string; - arguments: string[]; - workingDirectory: string; - environment: Record; -} -export type BuildDebugHandler = (params: BuildRunParams, context: BuildContext) => BuildDebugPreparation | Promise; -export type BuildRunHandler = (params: BuildRunParams, context: BuildContext) => BuildRunPreparation | Promise; - -/** Params every VCS handler receives, on top of its operation's arguments. */ -export interface VcsRequestParams { - root: { path: string }; - /** The VCS client the host resolved; null when it could not, so report `vcs.tool.unavailable`. */ - tool: { executable: string } | null; - [key: string]: unknown; -} - -export interface VcsRunOptions extends RunProcessOptions { - /** Report the finished command as `lithe/vcs/execution`; default true. */ - report?: boolean; -} - -export interface VcsContext extends RequestContext { - /** `RequestContext.run` that also reports each finished command to the host's console. */ - run(command: string, args?: string[], options?: VcsRunOptions): Promise; -} - -export type VcsHandler = (params: VcsRequestParams, context: VcsContext) => JsonObject | void | Promise; - -/** Handlers keyed by operation; see shared/contracts/vcs-provider-v1.md for each reply. */ -export interface VcsHandlers { - status: VcsHandler; - baseContent: VcsHandler; - checkin: VcsHandler; - rollback: VcsHandler; - history?: VcsHandler; - fileHistory?: VcsHandler; - annotate?: VcsHandler; - update?: VcsHandler; - fileOperation?: VcsHandler; - resolve?: VcsHandler; - cleanup?: VcsHandler; -} - -export interface VcsTraits { - /** Check-in is local and publishing is a separate step. */ - push?: boolean; - /** Changes carry a staged/unstaged dimension. */ - staging?: boolean; -} - -export interface Negotiated { - functions: boolean; - build: boolean; - vcs: boolean; -} - -export interface BackendOptions { - name?: string; - version?: string; - /** Standard LSP server capabilities; the SDK negotiates its experimental protocols. */ - capabilities?: JsonObject; -} - -export interface ListenOptions { - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - errorOutput?: NodeJS.WritableStream; - /** Defaults to `process.exit`; null only resolves the returned promise. */ - exit?: ((code: number) => void) | null; -} - -export interface Backend { - readonly negotiated: Negotiated; - readonly initializeParams: JsonObject | null; - /** Highest common version (1-6), or null before/without negotiation. */ - readonly buildVersion: number | null; - /** Highest common plugin-function version (1-4), or null before/without negotiation. */ - readonly functionsVersion: number | null; - readonly functionIDs: string[]; - /** Host services; usable once the session is ready. */ - readonly host: Host; - readonly build: { - model(handler: BuildHandler): Backend; - dependencies(handler: BuildHandler): Backend; - execute(handler: BuildExecutionHandler): Backend; - test(handler: BuildTestHandler): Backend; - discoverTests(handler: BuildDiscoveryHandler): Backend; - prepareRun(handler: BuildRunHandler): Backend; - prepareDebug(handler: BuildDebugHandler): Backend; - }; - vcs(id: string, handlers: VcsHandlers, traits?: VcsTraits): Backend; - function(id: string, handler: FunctionHandler): Backend; - /** Declares an independent shortcut import provider before initialize. */ - keymapImportProvider(id: string, handler: KeymapImportHandler): Backend; - registerFunction(id: string, handler: FunctionHandler): Promise; - unregisterFunction(id: string): Promise; - onRequest(method: string, handler: (params: unknown, context: RequestContext) => unknown): Backend; - onNotification(method: string, handler: (params: unknown) => unknown): Backend; - /** Handles `lithe/host/commands/didRun` for one of the plugin's commands (protocol 3). */ - onCommand(commandID: string, handler: (event: CommandEvent) => unknown): Backend; - /** Handles `lithe/host/workspace/didChangeContexts` (protocol 3). */ - onContextsChanged(handler: (event: { revision: number }) => unknown): Backend; - /** Handles a `lithe/host/*` notification a later host adds. */ - onHostNotification(method: string, handler: (params: JsonObject) => unknown): Backend; - onInitialize(hook: (event: { params: JsonObject; negotiated: Negotiated }) => unknown): Backend; - onShutdown(hook: () => unknown): Backend; - sendRequest(method: string, params?: unknown): Promise; - sendNotification(method: string, params?: unknown): void; - readonly diagnostics: Diagnostics; - suppressSuccessDiagnostics(operation: string): this; - listen(options?: ListenOptions): Promise; -} - -export function createBackend(options?: BackendOptions): Backend; - -export class PluginError extends Error { - constructor(code: string, message: string, options?: { cause?: unknown }); - readonly code: string; -} - -export class PluginSdkError extends Error { - readonly code: string; -} - -/** The host refused or failed a request this backend sent. */ -export class HostError extends PluginSdkError { - /** `error.data.code`, such as `plugin.host.contextExpired`. */ - readonly code: string; - /** The JSON-RPC error number. */ - readonly rpcCode: number | undefined; - /** Protocol 3 details, such as `{ option }` or `{ retryAfterMilliseconds }`. */ - readonly details: JsonObject | undefined; - readonly method: string | undefined; -} - -export function runProcess(command: string, args?: string[], options?: RunProcessOptions): Promise; - -export interface StateStore { - readonly directory: string; - read(key: string, fallback?: T): T | undefined; - write(key: string, value: JsonValue): void; - delete(key: string): void; -} - -export function openStateStore(directory: string, options?: { packageDirectory?: string | null }): StateStore; - -export function isFunctionId(value: unknown): boolean; - -/** - * Host failure codes and the JSON-RPC number each has from protocol 3. The - * `plugin.function.*` codes belong to the relay (protocol 4). - */ -export const HOST_ERRORS: Readonly<{ - 'plugin.host.unavailable': -32601; - 'plugin.host.invalidParams': -32602; - 'plugin.host.failed': -32603; - 'plugin.host.cancelled': -32800; - 'plugin.host.permissionDenied': -32010; - 'plugin.host.contextExpired': -32011; - 'plugin.host.authorityUnsupported': -32012; - 'plugin.host.versionConflict': -32013; - 'plugin.host.limitExceeded': -32014; - 'plugin.host.timeout': -32015; - 'plugin.host.notFound': -32016; - 'plugin.host.readOnly': -32017; - 'plugin.host.unsupportedOption': -32018; - 'plugin.host.preconditionFailed': -32019; - 'plugin.host.busy': -32020; - 'plugin.host.rateLimited': -32021; - 'plugin.host.languageServerUnavailable': -32022; - 'plugin.host.languageServerError': -32023; - 'plugin.host.methodNotDeclared': -32024; - 'plugin.host.toolUnresolved': -32025; - 'plugin.host.foreignContribution': -32026; - 'plugin.function.notDeclared': -32027; - 'plugin.function.notExported': -32028; - 'plugin.function.providerDisabled': -32029; - 'plugin.function.versionMismatch': -32030; - 'plugin.function.callCycle': -32065; - 'plugin.function.depthExceeded': -32066; - 'plugin.function.tooManyCalls': -32067; - 'plugin.function.payloadTooLarge': -32068; - 'plugin.function.providerUnavailable': -32069; - 'plugin.function.failed': -32070; - 'plugin.function.invalidResult': -32071; -}>; - -/** Host request method names of protocols 2 to 4. */ -export const HOST_METHODS: Readonly>; - -export function isVcsId(value: unknown): boolean; - -/** Provider error codes Core passes on; use them as `PluginError` codes. */ -export const VCS_ERRORS: Readonly<{ - authenticationFailed: 'vcs.authentication.failed'; - conflict: 'vcs.conflict'; - outOfDate: 'vcs.outOfDate'; - toolUnavailable: 'vcs.tool.unavailable'; - workingCopyLocked: 'vcs.workingCopy.locked'; - workingCopyUnsupported: 'vcs.workingCopy.unsupported'; -}>; - -export const LIMITS: Readonly<{ - maxFunctions: number; - maxFunctionIdBytes: number; - maxPluginErrorCodeBytes: number; - maxMessageBytes: number; - maxResultBytes: number; - maxBuildResultBytes: number; - maxBuildMessageBytes: number; - maxBuildOutputBytes: number; - maxVcsIdBytes: number; - maxExecutionErrorOutputBytes: number; - maxCredentialKeyBytes: number; - maxCredentialSecretBytes: number; - maxPendingHostRequests: number; - relayDefaultTimeoutMilliseconds: number; - relayMaxTimeoutMilliseconds: number; - maxParentOperationIdBytes: number; -}>; diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs deleted file mode 100644 index 6c1d1dd..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs +++ /dev/null @@ -1,8 +0,0 @@ -// Official Node.js SDK for Lithe plugin backends. -// Guide: sdk/node/README.md. Wire contract: contract/v1/README.md. - -export { createBackend } from './backend.mjs'; -export { HostError, PluginError, PluginSdkError } from './errors.mjs'; -export { runProcess } from './process.mjs'; -export { openStateStore } from './state.mjs'; -export { HOST_ERRORS, HOST_METHODS, isFunctionId, isVcsId, LIMITS, VCS_ERRORS } from './protocol.mjs'; diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs deleted file mode 100644 index 03f59df..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs +++ /dev/null @@ -1,188 +0,0 @@ -// Child processes a backend starts for one call. Lithe's host offers no -// process capability in protocol version 1, so a backend runs its tools -// itself; this helper makes sure that the call ending, cancelling it, or the -// backend shutting down also ends the whole process tree it started. When the -// backend itself is killed no JavaScript runs; the host then ends what is left -// through its own process lifecycle, which owns that boundary. - -import { spawn } from 'node:child_process'; -import { StringDecoder } from 'node:string_decoder'; - -const isWindows = process.platform === 'win32'; - -/** Every process tree started through `runProcess` that has not exited. */ -const running = new Set(); - -/** - * Variables Lithe sets on the backend so it can find and end every process - * the backend started, even one that left its process group. A tool always - * inherits them, also when the plugin replaces the environment. - */ -const HOST_MARKERS = ['LITHE_PROCESS_SCOPE', 'LITHE_PLUGIN_BACKEND_SCOPE']; - -function withHostMarkers(env) { - const result = { ...env }; - for (const name of HOST_MARKERS) { - if (process.env[name] === undefined) delete result[name]; - else result[name] = process.env[name]; - } - return result; -} - -/** - * Runs `command` without a shell and resolves with its exit status and - * captured output. Aborting `signal` ends the process tree and rejects with - * the signal's reason. A non-zero exit resolves; the caller decides what it - * means for its tool. - * - * @param {string} command Executable path or name. - * @param {string[]} [args] - * @param {object} [options] - * @param {string} [options.cwd] - * @param {Record} [options.env] Replaces the environment when given; the - * host's process markers are carried over regardless. - * @param {AbortSignal} [options.signal] - * @param {number} [options.maxOutputBytes] Captured bytes per stream; default 1 MiB. - * @param {(chunk: string) => void} [options.onStdout] - * @param {(chunk: string) => void} [options.onStderr] - * @param {number} [options.killGraceMilliseconds] Delay between the polite and forced stop; default 2000. - */ -export function runProcess(command, args = [], options = {}) { - const { cwd, env, signal, onStdout, onStderr } = options; - const maxOutputBytes = options.maxOutputBytes ?? 1 << 20; - const killGraceMilliseconds = options.killGraceMilliseconds ?? 2000; - if (signal?.aborted) return Promise.reject(signal.reason); - - return new Promise((resolve, reject) => { - const child = spawn(command, args, { - cwd, - env: env && withHostMarkers(env), - shell: false, - windowsHide: true, - // Its own process group on POSIX, so a stop reaches grandchildren too. - detached: !isWindows, - stdio: ['ignore', 'pipe', 'pipe'], - }); - const entry = { child, stopping: false, forceTimer: null }; - running.add(entry); - const stdout = capture(maxOutputBytes, onStdout); - const stderr = capture(maxOutputBytes, onStderr); - child.stdout.on('data', stdout.push); - child.stderr.on('data', stderr.push); - - const onAbort = () => stopTree(entry, killGraceMilliseconds); - signal?.addEventListener('abort', onAbort, { once: true }); - - let settled = false; - const finish = (outcome) => { - if (settled) return; - settled = true; - // A stopped tree stays registered until its forced stop: the leader - // can exit on SIGTERM while a grandchild in its group ignores it. - if (!entry.stopping) { - // The leader ended on its own; members it left behind in its group, - // such as a background worker, end with it. - signalTree(child, 'SIGKILL', { evenAfterExit: true }); - running.delete(entry); - } - signal?.removeEventListener('abort', onAbort); - stdout.end(); - stderr.end(); - outcome(); - }; - child.once('error', (error) => finish(() => reject(error))); - child.once('close', (exitCode, exitSignal) => - finish(() => { - if (signal?.aborted) { - reject(signal.reason); - return; - } - resolve({ - exitCode, - signal: exitSignal, - stdout: stdout.text(), - stderr: stderr.text(), - truncated: stdout.truncated() || stderr.truncated(), - }); - }), - ); - }); -} - -/** - * Forcibly ends every process tree still running. The backend calls it on - * shutdown, on `exit`, and when the host closes stdin, so no tool outlives - * the session that started it. - */ -export function killAllProcesses() { - for (const entry of running) { - clearTimeout(entry.forceTimer); - signalTree(entry.child, 'SIGKILL', { evenAfterExit: true }); - } - running.clear(); -} - -/** Number of process trees still running or being stopped, for tests and diagnostics. */ -export function runningProcessCount() { - return running.size; -} - -function stopTree(entry, graceMilliseconds) { - if (entry.stopping) return; - entry.stopping = true; - signalTree(entry.child, 'SIGTERM'); - entry.forceTimer = setTimeout(() => { - running.delete(entry); - signalTree(entry.child, 'SIGKILL', { evenAfterExit: true }); - }, graceMilliseconds); - entry.forceTimer.unref?.(); -} - -/** - * Signals the child's whole tree. `evenAfterExit` still signals the POSIX - * process group after its leader exited, which reaches members that survived - * the polite stop. While any member lives the group ID cannot be reused; - * once all exited the signal fails with ESRCH, which is ignored. - */ -function signalTree(child, signalName, { evenAfterExit = false } = {}) { - if (child.pid === undefined) return; - const exited = child.exitCode !== null || child.signalCode !== null; - if (exited && (isWindows || !evenAfterExit)) return; - try { - if (isWindows) { - // taskkill /T is the only stock way to end a Windows process tree. - spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); - } else { - process.kill(-child.pid, signalName); - } - } catch { - // The group already exited between the check and the signal. - } -} - -function capture(limit, listener) { - const chunks = []; - // Keeps a multi-byte character split across chunks whole in `listener`. - const decoder = new StringDecoder('utf8'); - let size = 0; - let truncated = false; - const deliver = (text) => { - if (text) listener?.(text); - }; - return { - push(chunk) { - deliver(decoder.write(chunk)); - if (size >= limit) { - truncated = true; - return; - } - const kept = chunk.subarray(0, limit - size); - truncated ||= kept.length < chunk.length; - chunks.push(kept); - size += kept.length; - }, - end: () => deliver(decoder.end()), - text: () => Buffer.concat(chunks).toString('utf8'), - truncated: () => truncated, - }; -} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs deleted file mode 100644 index f96cad3..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs +++ /dev/null @@ -1,293 +0,0 @@ -// Wire constants and validation shared with Lithe's Rust Core -// (rust/lithe-core/src/lsp/interface/plugin_function.rs and -// rust/lithe-core/src/vcs/ in the Lithe repository). The SDK checks the -// same rules locally so a plugin author sees a mistake when registering a -// handler instead of as a refused session at runtime. - -/** Protocol versions this SDK can answer: the highest of each. */ -export const FUNCTIONS_VERSION = 4; -export const BUILD_VERSION = 6; -export const VCS_VERSION = 1; - -/** First plugin-function version with host services (credentials). */ -export const HOST_SERVICES_VERSION = 2; -/** First plugin-function version with workspace contexts, discovery, and host notifications. */ -export const CONTEXT_VERSION = 3; -/** First plugin-function version with cross-plugin calls relayed through Core and the callee's `caller`. */ -export const RELAY_VERSION = 4; - -export const METHODS = Object.freeze({ - initialize: 'initialize', - initialized: 'initialized', - shutdown: 'shutdown', - exit: 'exit', - cancelRequest: '$/cancelRequest', - functionInvoke: 'lithe/function/invoke', - functionRegister: 'lithe/function/register', - functionUnregister: 'lithe/function/unregister', - functionProgress: 'lithe/function/progress', - buildModel: 'lithe/build/model', - buildDependencies: 'lithe/build/dependencies', - buildExecute: 'lithe/build/execute', - buildTest: 'lithe/build/test', - buildDiscoverTests: 'lithe/build/discoverTests', - buildPrepareRun: 'lithe/build/prepareRun', - buildPrepareDebug: 'lithe/build/prepareDebug', - buildProgress: 'lithe/build/progress', - vcsExecution: 'lithe/vcs/execution', -}); - -/** - * Backend-to-host requests of plugin-function protocols 2 to 4. From - * version 3 the host adds methods without a new version; `host.request` - * sends any `lithe/host/*` method, and `getCapabilities` says which ones - * this session may call. The two `functions` methods are the exception: - * they need version 4. - */ -export const HOST_METHODS = Object.freeze({ - credentialsGet: 'lithe/host/credentials/get', - credentialsSet: 'lithe/host/credentials/set', - credentialsDelete: 'lithe/host/credentials/delete', - getCapabilities: 'lithe/host/getCapabilities', - subscriptionsDispose: 'lithe/host/subscriptions/dispose', - workspaceListContexts: 'lithe/host/workspace/listContexts', - workspaceGetContext: 'lithe/host/workspace/getContext', - workspaceGetFolders: 'lithe/host/workspace/getFolders', - workspaceReadDirectory: 'lithe/host/workspace/readDirectory', - workspaceStat: 'lithe/host/workspace/stat', - workspaceReadFile: 'lithe/host/workspace/readFile', - workspaceWatch: 'lithe/host/workspace/watch', - workspaceFindFiles: 'lithe/host/workspace/findFiles', - workspaceFindText: 'lithe/host/workspace/findText', - documentsList: 'lithe/host/documents/list', - documentsGetSnapshot: 'lithe/host/documents/getSnapshot', - editorRegisterActions: 'lithe/host/editor/registerActions', - editorGetActive: 'lithe/host/editor/getActive', - editorGetSelections: 'lithe/host/editor/getSelections', - editorApplyEdits: 'lithe/host/editor/applyEdits', - editorReplaceSelections: 'lithe/host/editor/replaceSelections', - editorInsertText: 'lithe/host/editor/insertText', - editorOpen: 'lithe/host/editor/open', - editorReveal: 'lithe/host/editor/reveal', - previewOpenHTML: 'lithe/host/preview/openHTML', - browserOpenExternal: 'lithe/host/browser/openExternal', - windowShowInformation: 'lithe/host/window/showInformation', - windowShowWarning: 'lithe/host/window/showWarning', - windowShowError: 'lithe/host/window/showError', - terminalCreate: 'lithe/host/terminal/create', - terminalShow: 'lithe/host/terminal/show', - terminalClose: 'lithe/host/terminal/close', - terminalReopen: 'lithe/host/terminal/reopen', - terminalDispose: 'lithe/host/terminal/dispose', - terminalOnExit: 'lithe/host/terminal/onExit', - functionsProviders: 'lithe/host/functions/providers', - functionsInvoke: 'lithe/host/functions/invoke', -}); - -/** Host-to-backend notifications of protocol 3. */ -export const HOST_NOTIFICATIONS = Object.freeze({ - didChangeContexts: 'lithe/host/workspace/didChangeContexts', - subscriptionNotify: 'lithe/host/subscriptions/notify', - commandDidRun: 'lithe/host/commands/didRun', -}); - -/** - * Host failure codes (`error.data.code`) and the JSON-RPC number Core sends - * with each to a version 3 or 4 backend. A number never changes meaning; a - * later host adds codes after the last one listed here. The - * `plugin.function.*` codes are the relay's own (protocol 4). - */ -export const HOST_ERRORS = Object.freeze({ - 'plugin.host.unavailable': -32601, - 'plugin.host.invalidParams': -32602, - 'plugin.host.failed': -32603, - 'plugin.host.cancelled': -32800, - 'plugin.host.permissionDenied': -32010, - 'plugin.host.contextExpired': -32011, - 'plugin.host.authorityUnsupported': -32012, - 'plugin.host.versionConflict': -32013, - 'plugin.host.limitExceeded': -32014, - 'plugin.host.timeout': -32015, - 'plugin.host.notFound': -32016, - 'plugin.host.readOnly': -32017, - 'plugin.host.unsupportedOption': -32018, - 'plugin.host.preconditionFailed': -32019, - 'plugin.host.busy': -32020, - 'plugin.host.rateLimited': -32021, - 'plugin.host.languageServerUnavailable': -32022, - 'plugin.host.languageServerError': -32023, - 'plugin.host.methodNotDeclared': -32024, - 'plugin.host.toolUnresolved': -32025, - 'plugin.host.foreignContribution': -32026, - 'plugin.function.notDeclared': -32027, - 'plugin.function.notExported': -32028, - 'plugin.function.providerDisabled': -32029, - 'plugin.function.versionMismatch': -32030, - 'plugin.function.callCycle': -32065, - 'plugin.function.depthExceeded': -32066, - 'plugin.function.tooManyCalls': -32067, - 'plugin.function.payloadTooLarge': -32068, - 'plugin.function.providerUnavailable': -32069, - 'plugin.function.failed': -32070, - 'plugin.function.invalidResult': -32071, -}); - -/** Minimum negotiated version of each typed build operation. */ -export const BUILD_METHOD_VERSIONS = Object.freeze({ - [METHODS.buildModel]: 1, - [METHODS.buildDependencies]: 1, - [METHODS.buildExecute]: 2, - [METHODS.buildTest]: 3, - [METHODS.buildDiscoverTests]: 3, - [METHODS.buildPrepareRun]: 4, - [METHODS.buildPrepareDebug]: 5, -}); - -/** - * VCS-provider operations: the handler name a plugin declares, the request - * Core sends for it, and the capability declaring the handler negotiates. - * Contract: shared/contracts/vcs-provider-v1.md. - */ -export const VCS_OPERATIONS = Object.freeze({ - status: Object.freeze({ method: 'lithe/vcs/status', capability: 'status' }), - baseContent: Object.freeze({ method: 'lithe/vcs/baseContent', capability: 'baseContent' }), - history: Object.freeze({ method: 'lithe/vcs/history', capability: 'history' }), - fileHistory: Object.freeze({ method: 'lithe/vcs/fileHistory', capability: 'fileHistory' }), - annotate: Object.freeze({ method: 'lithe/vcs/annotate', capability: 'annotate' }), - checkin: Object.freeze({ method: 'lithe/vcs/checkin', capability: 'checkin' }), - rollback: Object.freeze({ method: 'lithe/vcs/rollback', capability: 'rollback' }), - update: Object.freeze({ method: 'lithe/vcs/update', capability: 'update' }), - fileOperation: Object.freeze({ method: 'lithe/vcs/fileOperation', capability: 'fileOperations' }), - resolve: Object.freeze({ method: 'lithe/vcs/resolve', capability: 'conflicts' }), - cleanup: Object.freeze({ method: 'lithe/vcs/cleanup', capability: 'cleanup' }), -}); - -/** Handlers every VCS provider must declare; Core refuses a provider without them. */ -export const VCS_REQUIRED_OPERATIONS = Object.freeze(['status', 'baseContent', 'checkin', 'rollback']); - -/** - * The provider error codes Core passes on (`error.data.code`). Throw a - * `PluginError` with one of them; any other code reaches the host as - * `vcs.provider.failed`. - */ -export const VCS_ERRORS = Object.freeze({ - authenticationFailed: 'vcs.authentication.failed', - conflict: 'vcs.conflict', - outOfDate: 'vcs.outOfDate', - toolUnavailable: 'vcs.tool.unavailable', - workingCopyLocked: 'vcs.workingCopy.locked', - workingCopyUnsupported: 'vcs.workingCopy.unsupported', -}); - -/** JSON-RPC and LSP error codes the SDK answers with. */ -export const ERROR_CODES = Object.freeze({ - parseError: -32700, - invalidRequest: -32600, - methodNotFound: -32601, - invalidParams: -32602, - internalError: -32603, - serverNotInitialized: -32002, - requestFailed: -32000, - requestCancelled: -32800, -}); - -export const LIMITS = Object.freeze({ - maxFunctions: 256, - maxFunctionIdBytes: 128, - maxPluginErrorCodeBytes: 64, - maxMessageBytes: 1024, - maxResultBytes: 1 << 20, - maxBuildResultBytes: 32 * 1024 * 1024, - maxBuildMessageBytes: 4096, - maxBuildOutputBytes: 65536, - maxVcsIdBytes: 32, - maxExecutionErrorOutputBytes: 16 * 1024, - maxCredentialKeyBytes: 128, - maxCredentialSecretBytes: 16 * 1024, - maxPendingHostRequests: 16, - // The relay's bounds are Core's to enforce; the SDK only names them. - relayDefaultTimeoutMilliseconds: 60000, - relayMaxTimeoutMilliseconds: 600000, - maxParentOperationIdBytes: 128, -}); - -/** True for the two host methods that need plugin-function protocol 4. */ -export function isRelayMethod(method) { - return method === HOST_METHODS.functionsProviders || method === HOST_METHODS.functionsInvoke; -} - -/** Dot-separated lowerCamelCase segments, for example `snapshot.refresh`. */ -export function isFunctionId(value) { - return ( - typeof value === 'string' && - value.length > 0 && - Buffer.byteLength(value) <= LIMITS.maxFunctionIdBytes && - value.split('.').every((segment) => /^[a-z][A-Za-z0-9]*$/.test(segment)) - ); -} - -/** A VCS ID: lowercase ASCII letters, digits, and `-`, starting with a letter, such as `svn`. */ -export function isVcsId(value) { - return typeof value === 'string' && value.length <= LIMITS.maxVcsIdBytes && /^[a-z][a-z0-9-]*$/.test(value); -} - -/** - * The key alphabet of protocols 2 to 4: 1-128 ASCII letters, digits, `.`, - * `_`, `:`, or `-`. Credential keys, context IDs, and subscription IDs use it. - */ -export function isCredentialKey(value) { - return typeof value === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(value); -} - -/** `{ contextID, generation }`, exactly, naming one generation of one workspace context. */ -export function isContextReference(value) { - return ( - value !== null && - typeof value === 'object' && - !Array.isArray(value) && - Object.keys(value).length === 2 && - isCredentialKey(value.contextID) && - Number.isSafeInteger(value.generation) && - value.generation >= 1 - ); -} - -/** The plugin error code alphabet Core forwards as `pluginErrorCode`. */ -export function isPluginErrorCode(value) { - return ( - typeof value === 'string' && - Buffer.byteLength(value) <= LIMITS.maxPluginErrorCodeBytes && - /^[A-Za-z][A-Za-z0-9._-]*$/.test(value) - ); -} - -/** Cuts `value` to `limit` UTF-8 bytes without splitting a character. */ -export function boundedText(value, limit = LIMITS.maxMessageBytes) { - const text = String(value ?? ''); - if (Buffer.byteLength(text) <= limit) return text; - let used = 0; - let end = 0; - for (const character of text) { - const size = Buffer.byteLength(character); - if (used + size > limit) break; - used += size; - end += character.length; - } - return text.slice(0, end); -} - -/** - * Methods reserved for the SDK. A plugin cannot install its own handler for - * these, or send them to the host: the lifecycle belongs to the host's - * session management, and `lithe/*` belongs to Lithe's typed contracts. - */ -export function isReservedMethod(method) { - return ( - method === METHODS.initialize || - method === METHODS.initialized || - method === METHODS.shutdown || - method === METHODS.exit || - method === METHODS.cancelRequest || - method.startsWith('lithe/') - ); -} diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs b/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs deleted file mode 100644 index f648bb3..0000000 --- a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs +++ /dev/null @@ -1,148 +0,0 @@ -// Durable plugin state. The host gives every backend writable directories -// through the `${stateDir}` and `${workspaceStateDir}` launch variables; the -// installed package and the host's installation are read-only, because -// signatures and delta updates are computed over their exact bytes. - -import { - closeSync, - existsSync, - fsyncSync, - mkdirSync, - openSync, - readFileSync, - realpathSync, - renameSync, - rmSync, - writeFileSync, -} from 'node:fs'; -import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; -import { randomBytes } from 'node:crypto'; -import { PluginSdkError } from './errors.mjs'; - -/** Version of the envelope each value is stored in. */ -const STORE_FORMAT = 1; -const KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; - -/** - * Opens a key-value store in `directory`, creating the directory. Values are - * JSON; each key is one file replaced atomically, so a crash leaves either the - * old or the new value, never half of one. - * - * @param {string} directory Absolute path, normally the value of `${workspaceStateDir}`. - * @param {object} [options] - * @param {string | null} [options.packageDirectory] The installed plugin package, - * which the store refuses to write into. Defaults to the nearest directory - * containing `plugin.json` above the running entry script. - */ -export function openStateStore(directory, options = {}) { - if (typeof directory !== 'string' || !isAbsolute(directory)) { - throw new PluginSdkError('sdk.state.invalidDirectory', 'The state directory must be an absolute path passed by the host.'); - } - const packageDirectory = options.packageDirectory === undefined ? findPackageDirectory() : options.packageDirectory; - // Checked before creating anything, so a refused path leaves the package untouched. - const root = canonical(directory); - if (packageDirectory && isInside(root, canonical(packageDirectory))) { - throw new PluginSdkError( - 'sdk.state.readOnlyPackage', - 'The state directory is inside the plugin package, which is read-only. Use ${stateDir} or ${workspaceStateDir}.', - ); - } - mkdirSync(root, { recursive: true }); - return new StateStore(root); -} - -class StateStore { - #root; - - constructor(root) { - this.#root = root; - } - - /** The resolved directory, for a backend that keeps its own files next to the store. */ - get directory() { - return this.#root; - } - - /** The stored value, or `fallback` when the key is missing or unreadable. */ - read(key, fallback = undefined) { - const path = this.#path(key); - if (!existsSync(path)) return fallback; - try { - const envelope = JSON.parse(readFileSync(path, 'utf8')); - if (envelope?.litheStateStore !== STORE_FORMAT || !('value' in envelope)) return fallback; - return envelope.value; - } catch { - return fallback; - } - } - - /** Stores `value`, which must be JSON-serializable, replacing the previous one. */ - write(key, value) { - const path = this.#path(key); - // `undefined`, a function, or a symbol would vanish from the envelope and - // silently replace the stored value with nothing; refuse it and keep the file. - if (JSON.stringify(value) === undefined) { - throw new PluginSdkError('sdk.state.invalidValue', `The value for ${key} is not JSON-serializable.`); - } - const body = JSON.stringify({ litheStateStore: STORE_FORMAT, value }); - const temporary = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`; - try { - writeFileSync(temporary, body, { encoding: 'utf8', mode: 0o600 }); - const handle = openSync(temporary, 'r'); - try { - fsyncSync(handle); - } finally { - closeSync(handle); - } - renameSync(temporary, path); - } catch (error) { - rmSync(temporary, { force: true }); - throw error; - } - } - - /** Removes the key; a missing key is not an error. */ - delete(key) { - rmSync(this.#path(key), { force: true }); - } - - #path(key) { - if (typeof key !== 'string' || !KEY.test(key) || key.endsWith('.tmp')) { - throw new PluginSdkError( - 'sdk.state.invalidKey', - `State key ${JSON.stringify(key)} must be 1-128 letters, digits, ".", "_" or "-", start with a letter or digit, and not end with ".tmp".`, - ); - } - return join(this.#root, `${key}.json`); - } -} - -function isInside(path, parent) { - const difference = relative(parent, path); - return difference === '' || (!difference.startsWith(`..${sep}`) && difference !== '..' && !isAbsolute(difference)); -} - -/** Resolves symbolic links of the longest existing prefix of `path`. */ -function canonical(path) { - const missing = []; - let current = resolve(path); - while (!existsSync(current)) { - const parent = dirname(current); - if (parent === current) break; - missing.unshift(basename(current)); - current = parent; - } - return join(realpathSync(current), ...missing); -} - -function findPackageDirectory() { - const entry = process.argv[1]; - if (!entry) return null; - let current = dirname(resolve(entry)); - for (;;) { - if (existsSync(join(current, 'plugin.json'))) return current; - const parent = dirname(current); - if (parent === current) return null; - current = parent; - } -} diff --git a/io.github.lithe-idea.gradle-build/plugin.json b/io.github.lithe-idea.gradle-build/plugin.json index e8816bf..175c041 100644 --- a/io.github.lithe-idea.gradle-build/plugin.json +++ b/io.github.lithe-idea.gradle-build/plugin.json @@ -14,7 +14,7 @@ "activationEvents": ["onBuildSystem:gradle"], "languages": [], "backend": { - "launch": { "kind": "runtime", "tool": "node", "minimumVersion": "20.3", "entry": "backend/main.mjs" } + "launch": { "kind": "runtime", "tool": "java", "minimumVersion": "8", "entry": "lib/lithe-gradle-backend.jar" } }, "pluginFunctions": { "exports": [{ "id": "languageImport.settings", "version": 1, "context": "workspace" }] diff --git a/scripts/backend-client.mjs b/scripts/backend-client.mjs new file mode 100644 index 0000000..1cf5288 --- /dev/null +++ b/scripts/backend-client.mjs @@ -0,0 +1,153 @@ +// Talks to lib/lithe-maven-backend.jar the way Lithe does: LSP base-protocol +// frames over the process's stdio, `initialize` offering litheBuild 1, then +// lithe/build/* requests. Every wait is bounded, and the backend runs in its +// own process group so a test can always end whatever it left behind. +import { spawn } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +export const WAIT_MS = 20_000; + +export class BackendClient { + #buffer = Buffer.alloc(0); + #pending = new Map(); + #nextId = 1; + stderr = ""; + diagnostics = []; + + /** Starts `java -jar --state ` (or `args`); `javaOptions` go before `-jar`. */ + constructor({ java = "java", jar, state, env = process.env, javaOptions = [], timeoutMs = WAIT_MS, args, hostRequests = {} }) { + this.timeoutMs = timeoutMs; + // Answers to requests the backend sends to the host, keyed by method. + this.hostRequests = hostRequests; + this.child = spawn(java, [...javaOptions, "-jar", jar, ...(args ?? ["--state", state])], { + env, stdio: ["pipe", "pipe", "pipe"], detached: true, + }); + this.exited = new Promise((resolve) => this.child.once("exit", (code, signal) => { + this.#fail(`the backend exited with ${signal ?? `status ${code}`}`); + resolve(signal ?? code); + })); + this.child.once("error", (error) => this.#fail(`cannot start the backend: ${error.message}`)); + this.child.stdout.on("data", (chunk) => this.#read(chunk)); + this.child.stderr.on("data", (chunk) => { this.stderr += chunk; }); + this.child.stdin.on("error", () => {}); + } + + /** Sends a request; `response` settles with the whole response message. */ + send(method, params) { + const id = this.#nextId++; + const response = new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.#pending.delete(id); + reject(new Error(`no response to ${method} #${id} within ${this.timeoutMs} ms\nbackend stderr:\n${this.stderr}`)); + }, this.timeoutMs); + this.#pending.set(id, (message) => { + clearTimeout(timer); + if (message instanceof Error) reject(message); + else resolve(message); + }); + }); + this.#write({ jsonrpc: "2.0", id, method, params }); + return { id, response }; + } + + /** Sends a request and resolves with its result, or rejects with its error. */ + async request(method, params) { + const message = await this.send(method, params).response; + if (message.error) { + const error = new Error(`${method} failed: ${message.error.message}`); + error.response = message.error; + throw error; + } + return message.result; + } + + notify(method, params) { + this.#write({ jsonrpc: "2.0", method, params }); + } + + cancel(id) { + this.notify("$/cancelRequest", { id }); + } + + async initialize(root, { functions = false } = {}) { + const result = await this.request("initialize", { + processId: process.pid, + rootUri: pathToFileURL(root).href, + capabilities: { experimental: { + ...(functions ? { litheFunctions: { versions: [1, 2, 3] } } : { litheBuild: { versions: [1] } }), + litheLogging: { versions: [1] }, + } }, + }); + this.notify("initialized", {}); + return result; + } + + /** `shutdown` and `exit`; resolves with the exit code. */ + async close() { + if (this.child.exitCode === null && this.child.signalCode === null) { + await this.request("shutdown", null); + this.notify("exit", null); + this.child.stdin.end(); + } + return bounded(this.exited, "the backend to exit"); + } + + /** Ends the backend's whole process group, for teardown after a failure. */ + kill() { + if (!this.child.pid) return; + // macOS answers EPERM for a group whose members already exited but are not reaped yet. + try { process.kill(-this.child.pid, "SIGKILL"); } + catch (error) { if (error.code !== "ESRCH" && error.code !== "EPERM") throw error; } + } + + #write(message) { + const body = Buffer.from(JSON.stringify(message), "utf8"); + this.child.stdin.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, "ascii"), body])); + } + + /** Rejects every waiting request; nothing more will answer them. */ + #fail(reason) { + const error = new Error(`${reason}\nbackend stderr:\n${this.stderr}`); + for (const settle of this.#pending.values()) settle(error); + this.#pending.clear(); + } + + #read(chunk) { + this.#buffer = Buffer.concat([this.#buffer, chunk]); + for (;;) { + const headerEnd = this.#buffer.indexOf("\r\n\r\n"); + if (headerEnd < 0) return; + const length = Number(/Content-Length: *(\d+)/i.exec(this.#buffer.subarray(0, headerEnd).toString("ascii"))?.[1]); + if (!Number.isSafeInteger(length)) return this.#broken("a frame without Content-Length"); + if (this.#buffer.length < headerEnd + 4 + length) return; + let message; + try { message = JSON.parse(this.#buffer.subarray(headerEnd + 4, headerEnd + 4 + length).toString("utf8")); } + catch { return this.#broken("a frame that is not JSON"); } + this.#buffer = this.#buffer.subarray(headerEnd + 4 + length); + if (message.method === "lithe/log") { + this.diagnostics.push(message.params); + } else if (message.id !== undefined && message.method !== undefined) { + const answer = this.hostRequests[message.method]; + this.#write(answer === undefined + ? { jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "unsupported" } } + : { jsonrpc: "2.0", id: message.id, result: answer(message.params) }); + } else if (message.id !== undefined && message.method === undefined) { + this.#pending.get(message.id)?.(message); + this.#pending.delete(message.id); + } + } + } + + #broken(what) { + this.#fail(`the backend wrote ${what}`); + this.kill(); + } +} + +export function bounded(promise, description, timeoutMs = WAIT_MS) { + let timer; + return Promise.race([ + promise, + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out waiting for ${description}`)), timeoutMs); }), + ]).finally(() => clearTimeout(timer)); +} diff --git a/scripts/package.mjs b/scripts/package.mjs index 5a3f35e..434bdc3 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -3,16 +3,17 @@ // Lithe Store's release tracker recognizes (docs/publishing.md there). // // The package is plain data: plugin.json, icons, New Project templates, and -// the init script that runs inside the user's own Gradle, so one archive -// serves every Mac. The +// the init script that runs inside the user's own Gradle, and the Java backend +// jar (lib/lithe-gradle-backend.jar), so one archive serves every Mac. The // unpacked package stays in dist/package/ for installing a local // development copy into Lithe. // // Usage: node scripts/package.mjs [--expect-tag ] import { execFileSync } from "node:child_process"; +import { verifySdk } from "./sdk/verify-sdk.mjs"; import { createHash } from "node:crypto"; -import { cpSync, lstatSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs"; +import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; const PACKAGE_DIR = "io.github.lithe-idea.gradle-build"; @@ -79,9 +80,32 @@ function assertNoLinks(directory) { } } +// The backend (backend/) and the vendored official Java SDK (vendor/, pinned by +// sdk.lock.json) are compiled together for Java 8 with the JDK's own javac and +// jar, so building needs no Maven. A fixed timestamp makes the jar reproducible. +await verifySdk(); +const BACKEND_BUILD = join("backend", "target"); +const BACKEND_JAR = join(BACKEND_BUILD, "lithe-gradle-backend.jar"); +function sourcesUnder(directory) { + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const path = join(directory, entry.name); + return entry.isDirectory() ? sourcesUnder(path) : entry.name.endsWith(".java") ? [path] : []; + }); +} +rmSync(BACKEND_BUILD, { recursive: true, force: true }); +mkdirSync(join(BACKEND_BUILD, "classes"), { recursive: true }); +const javaSources = [...sourcesUnder("backend/src/main/java"), ...sourcesUnder("vendor/lithe-plugin-sdk-java/src/main/java")]; +execFileSync("javac", ["-encoding", "UTF-8", "--release", "8", "-Xlint:-options", "-d", join(BACKEND_BUILD, "classes"), ...javaSources], { stdio: "inherit", timeout: 120_000 }); +writeFileSync(join(BACKEND_BUILD, "MANIFEST.MF"), `Main-Class: io.github.litheidea.gradle.backend.GradleBackend\nImplementation-Version: ${manifest.version}\n`); +execFileSync("jar", ["--create", "--file", BACKEND_JAR, "--manifest", join(BACKEND_BUILD, "MANIFEST.MF"), "--date", "2026-10-20T00:00:00Z", "-C", join(BACKEND_BUILD, "classes"), "."], { stdio: "inherit", timeout: 60_000 }); +if (!existsSync(BACKEND_JAR)) throw new Error(`${BACKEND_JAR} was not built`); + rmSync("dist", { recursive: true, force: true }); const packageRoot = join(PACKAGE_ROOT, PACKAGE_DIR); cpSync(PACKAGE_DIR, packageRoot, { recursive: true }); +mkdirSync(join(packageRoot, "lib"), { recursive: true }); +cpSync(BACKEND_JAR, join(packageRoot, "lib", "lithe-gradle-backend.jar")); +cpSync("vendor/LICENSE", join(packageRoot, "SDK-LICENSE")); cpSync("LICENSE", join(packageRoot, "LICENSE")); cpSync("NOTICE", join(packageRoot, "NOTICE")); assertNoLinks(packageRoot); diff --git a/scripts/sdk/verify-sdk.mjs b/scripts/sdk/verify-sdk.mjs new file mode 100644 index 0000000..b352bb4 --- /dev/null +++ b/scripts/sdk/verify-sdk.mjs @@ -0,0 +1,42 @@ +import { createHash } from 'node:crypto'; +import { lstat, readFile, readdir } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const repository = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); + +/** Verify every vendored production source before building the backend. */ +export async function verifySdk(root = repository) { + const lock = JSON.parse(await readFile(join(root, 'sdk.lock.json'), 'utf8')); + if (lock.schemaVersion !== 1 || !/^[0-9a-f]{40}$/.test(lock.source?.revision) || !Array.isArray(lock.files) || lock.source.repository !== 'https://github.com/Lithe-IDEA/lithe-plugin-docs') { + throw new Error('The SDK lock must identify its upstream base and every source hash.'); + } + const expected = new Set(); + for (const entry of lock.files) { + if (!entry.path?.startsWith('vendor/') || entry.path.includes('\\') + || entry.path.split('/').some((part) => !part || part === '.' || part === '..') + || !/^[0-9a-f]{64}$/.test(entry.sha256) || expected.has(entry.path) + || (entry.localChanges === true && (!Object.hasOwn(entry, 'upstreamSha256') || (entry.upstreamSha256 !== null && !/^[0-9a-f]{64}$/.test(entry.upstreamSha256))))) { + throw new Error('Invalid or duplicate SDK source lock entry.'); + } + const file = join(root, entry.path); + if (!(await lstat(file)).isFile()) throw new Error(`SDK input is not a regular file: ${entry.path}`); + const digest = createHash('sha256').update(await readFile(file)).digest('hex'); + if (digest !== entry.sha256) throw new Error(`SDK SHA-256 mismatch: ${entry.path}`); + expected.add(entry.path); + } + async function walk(directory, prefix) { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const name = `${prefix}/${entry.name}`; + if (entry.isDirectory()) await walk(join(directory, entry.name), name); + else if (!expected.delete(name)) throw new Error(`Unpinned SDK input: ${name}`); + } + } + await walk(join(root, 'vendor'), 'vendor'); + if (expected.size) throw new Error('A pinned SDK source is missing.'); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await verifySdk(); + console.log('Vendored Java SDK source hashes verified.'); +} diff --git a/scripts/test-backend.mjs b/scripts/test-backend.mjs new file mode 100644 index 0000000..8913b0f --- /dev/null +++ b/scripts/test-backend.mjs @@ -0,0 +1,74 @@ +#!/usr/bin/env node +// Drives lib/lithe-gradle-backend.jar from dist/package over its stdio, as +// Lithe does: `languageImport.settings` for roots inside and outside an open +// workspace folder. No Gradle or network is needed. +// +// Run scripts/package.mjs first. LITHE_TEST_JAVA selects the Java that runs the +// backend (default `java`), so CI also checks Java 8. +// +// Usage: node scripts/test-backend.mjs + +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { BackendClient, bounded } from "./backend-client.mjs"; + +const jar = resolve("dist", "package", "io.github.lithe-idea.gradle-build", "lib", "lithe-gradle-backend.jar"); +if (!existsSync(jar)) { + console.error("✗ dist/package is missing the backend; run node scripts/package.mjs first"); + process.exit(1); +} +const java = process.env.LITHE_TEST_JAVA ?? "java"; +const scratch = realpathSync(mkdtempSync(join(tmpdir(), "lithe-gradle-backend-test-"))); +const workspace = join(scratch, "workspace"); +const outside = join(scratch, "outside"); +const gradleHome = join(scratch, "gradle-home"); +const home = join(scratch, "home"); +for (const directory of [join(workspace, "app"), outside, gradleHome, home]) mkdirSync(directory, { recursive: true }); +writeFileSync(join(gradleHome, "gradle.properties"), "org.gradle.jvmargs=-Xmx1g\norg.gradle.java.home=/jdk/home\norg.gradle.parallel=true\n"); +writeFileSync(join(workspace, "app", "gradle.properties"), "org.gradle.jvmargs=-Xmx4g \\\n -Dfile.encoding=UTF-8\norg.gradle.java.home=relative/jdk\n"); +symlinkSync(outside, join(workspace, "escape")); + +let client; +let failed = false; +const step = async (name, body) => { + try { await body(); console.log(`✓ ${name}`); } + catch (error) { failed = true; console.error(`✗ ${name}\n${error.stack}`); } +}; +try { + client = new BackendClient({ + java, jar, args: [], javaOptions: [`-Duser.home=${home}`], + env: { ...process.env, GRADLE_USER_HOME: gradleHome }, + hostRequests: { "lithe/host/workspace/getFolders": () => ({ folders: [{ rootID: "r", name: "w", path: workspace }] }) }, + }); + const initialized = await client.initialize(workspace, { functions: true }); + assert.deepEqual(initialized.capabilities.experimental.litheFunctions.functions, [{ id: "languageImport.settings" }]); + const invoke = (workspaceRoot, context = { contextID: "ctx", generation: 1 }) => client.send("lithe/function/invoke", { + functionID: "languageImport.settings", operationID: `op-${Math.random()}`, params: { workspaceRoot }, ...(context ? { context } : {}), + }).response; + + await step("the project's gradle.properties overrides the Gradle user home and only known keys are exported", async () => { + assert.deepEqual((await invoke(join(workspace, "app"))).result, { settings: { + "java.import.gradle.user.home": gradleHome, + "java.import.gradle.jvmArguments": "-Xmx4g -Dfile.encoding=UTF-8", + } }); + }); + await step("a root outside the open workspace folders, through a link, relative or without a context is refused", async () => { + for (const root of [outside, join(workspace, "escape"), "relative"]) { + assert.equal((await invoke(root)).error?.data?.code, "gradle.invalidRoot", root); + } + assert.equal((await invoke(workspace, null)).error?.data?.code, "gradle.noWorkspaceContext"); + }); + await step("the backend exits on shutdown", async () => { + assert.equal(await client.close(), 0, `the backend exits cleanly\n${client.stderr}`); + client = undefined; + }); +} finally { + if (client) { + client.kill(); + await bounded(client.exited, "the backend to be killed").catch(() => {}); + } + rmSync(scratch, { recursive: true, force: true }); +} +process.exitCode = failed ? 1 : 0; diff --git a/sdk.lock.json b/sdk.lock.json index 80f08b6..453b59b 100644 --- a/sdk.lock.json +++ b/sdk.lock.json @@ -2,64 +2,103 @@ "schemaVersion": 1, "source": { "repository": "https://github.com/Lithe-IDEA/lithe-plugin-docs", - "revision": "db17c719bad755b420600c897615c67ed8cab67c", - "sdkVersion": "0.4.0" + "revision": "29b245c0e1d77c761d9032a3144a301d1818bfc7", + "localChanges": "Structured logging lithe/log implementation from the accompanying SDK working tree. Per-file hashes identify these reviewed inputs; no published release is claimed." }, "files": [ { "upstream": "LICENSE", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/LICENSE", + "path": "vendor/LICENSE", "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21" }, { - "upstream": "sdk/node/src/backend.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/backend.mjs", - "sha256": "e5a6419c7ec8a8367c9f602ac0e8478f51ee7f1756e3bc0188c50ca1a1a677e5" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java", + "sha256": "c5430ea55f5ee73a88b8c6c3517cf6bc2237827b009ae1844c105254b7f48a24", + "localChanges": true, + "upstreamSha256": "c1943d63121ce20dfadf24dfcac50581da4371356fb5f7ee30962b41b2fd04a2" }, { - "upstream": "sdk/node/src/diagnostics.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/diagnostics.mjs", - "sha256": "2735350b0e9658729311d18e9632cb38f93a01576ed0de61c66eefc8dd89e73f" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java", + "sha256": "c41fcc2cbc6533215ee9034409292ddeb6237d6c3defdd65b2cdfb8fb848dde8", + "localChanges": true, + "upstreamSha256": "8157d980a585b85ed31b96ad974fe980e167b6c0b7701b2636328ba84c0b62af" }, { - "upstream": "sdk/node/src/errors.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/errors.mjs", - "sha256": "e756aa0a88f1807ffdc985f3aed307f283c2a59902a287e22dd408dae5179bd2" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java", + "sha256": "826c246360a607eb40ce950202db0988a465718082dc22be539f045139671db3", + "localChanges": true, + "upstreamSha256": "87eb1a9b673f59774ac1688393f62f8aa5379ead1ed2464b50ab64a0d6ad80d9" }, { - "upstream": "sdk/node/src/framing.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/framing.mjs", - "sha256": "ec745be1ecf4cf24d521c5aa3108da2bbbfb9156f2197fcb5158de1f1bc9cfd1" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java", + "sha256": "699c054b1857a0518fd244ff193bc87445495ae40cbf7cc34436ac92ba42973e" }, { - "upstream": "sdk/node/src/host.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/host.mjs", - "sha256": "4f4feaa8e3fdfa7f765e48b9ca53365126b0f57c5857d0b46208fccaa82e9e4e" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java", + "sha256": "e6b70f167f1b030509fccf399745bc7693023eabeff1201696e866340d546ec9", + "localChanges": true, + "upstreamSha256": null }, { - "upstream": "sdk/node/src/index.d.ts", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.d.ts", - "sha256": "d229e44b7cec125f1a1f388312aabe64cb0ac089e13c0a2cb91ff88a019f50c2" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Framing.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java", + "sha256": "510a82f0c29e634d4235326ed9abccc2c618f795e9aca6c354d516c7dce278db" }, { - "upstream": "sdk/node/src/index.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/index.mjs", - "sha256": "79042db2ac6e0ac896ff0a1643ee540217b7b84fab4d1b1b82ad4246263d16af" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java", + "sha256": "ff2cc8830645722173a257aec66adec94cfae7d5a91501b1024e2843954dc8f1" }, { - "upstream": "sdk/node/src/process.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/process.mjs", - "sha256": "a72f78cbfbb8d98b2d44ebea7f869038a3e34ebe7ee000f63cdd36fb2aaece66" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java", + "sha256": "79e337d8fc495c1c993d33205f70d79a0baa5fe49c054ef7032f02ce500f147c", + "localChanges": true, + "upstreamSha256": "1830ac36651759f3b4f77bda5fb23fd4b478a2c153671fc01920af38faefd09f" }, { - "upstream": "sdk/node/src/protocol.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/protocol.mjs", - "sha256": "f145f8c156c8831dc3f3b8076553d677484b59e63da7c1d8ceea16b5fa24b68f" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java", + "sha256": "8072d652209042f578c3eaf49600f8797ed19662b8119581772f60a3b972fa96" }, { - "upstream": "sdk/node/src/state.mjs", - "path": "io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/state.mjs", - "sha256": "946618214fbcb736c76ee85c87e0b969fe853fbab215f7c192990f2edf2035a4" + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Json.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java", + "sha256": "7ff4a54ab5003cd86046db3b35110b4906b97fc56b8d934f33e6f51eb96dd5ed" + }, + { + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java", + "sha256": "882485659c7e77833ebb383dd8175b7eede292596696f63678fbcd868c029806", + "localChanges": true, + "upstreamSha256": "33dec00015fc1611084bd99063e90dbce3c306e99b83faed1cd6a2f8cab24de7" + }, + { + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java", + "sha256": "ced28c084e0f0d1d5c42d29d1c85b6528e065b9a933f7a6ab0a4eae1bcd6a520" + }, + { + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Processes.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java", + "sha256": "86b50e196fb23ccd28e576b524a8da2d8928ac3113bbcd105180ceaef9981319", + "localChanges": true, + "upstreamSha256": "e1a499d9fc526179c624be1084188e2a394e46f5d5c512cc5c3e3b3d39661aeb" + }, + { + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java", + "sha256": "b491ba1a55f869bf29ba337684fe0a1c42c00b9ae8887dac508cc508748d419d" + }, + { + "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java", + "sha256": "c56519730a9243d5ce9e8333025456bd934890bd7ad134de3b8e8fb9fd28bfe4" } ] } diff --git a/test/settings.test.mjs b/test/settings.test.mjs deleted file mode 100644 index 4059042..0000000 --- a/test/settings.test.mjs +++ /dev/null @@ -1,62 +0,0 @@ -import assert from 'node:assert/strict'; -import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import test from 'node:test'; -import { parseProperties, registerSettingsFunction, settingsFor } from '../io.github.lithe-idea.gradle-build/backend/settings.mjs'; - -class PluginError extends Error { constructor(code, message) { super(message); this.code = code; } } - -async function scratch(t) { - const directory = await realpath(await mkdtemp(join(tmpdir(), 'lithe-gradle-settings-'))); - t.after(() => rm(directory, { recursive: true, force: true })); - return directory; -} - -function handlerFor(folders, environment = {}) { - let handler; - registerSettingsFunction({ function: (id, fn) => { assert.equal(id, 'languageImport.settings'); handler = fn; } }, PluginError, environment); - const context = { throwIfCancelled() {}, workspaceContext: { contextID: 'c', generation: 1 }, host: { workspace: { getFolders: async () => ({ folders }) } } }; - return (params, overrides = {}) => handler(params, { ...context, ...overrides }); -} - -test('properties parser keeps escapes and ignores comments', () => { - assert.deepEqual(parseProperties('# c\n! c\norg.gradle.jvmargs=-Xmx2g \\\n -Dfile.encoding=UTF-8\nkey : v\\:x\n'), - { 'org.gradle.jvmargs': '-Xmx2g -Dfile.encoding=UTF-8', key: 'v:x' }); -}); - -test('project gradle.properties overrides the user home and only known keys are exported', async (t) => { - const root = await scratch(t), home = await scratch(t); - await writeFile(join(home, 'gradle.properties'), 'org.gradle.jvmargs=-Xmx1g\norg.gradle.java.home=/jdk/home\norg.gradle.parallel=true\n'); - await writeFile(join(root, 'gradle.properties'), 'org.gradle.jvmargs=-Xmx4g\norg.gradle.java.home=relative/jdk\n'); - assert.deepEqual(await settingsFor(root, { GRADLE_USER_HOME: home }), { - settings: { 'java.import.gradle.user.home': home, 'java.import.gradle.jvmArguments': '-Xmx4g' } - }); - assert.deepEqual(await settingsFor(root, { GRADLE_USER_HOME: 'relative' }), { settings: { 'java.import.gradle.jvmArguments': '-Xmx4g' } }); -}); - -test('the function answers only for roots inside an open workspace folder', async (t) => { - const workspace = await scratch(t), outside = await scratch(t); - await mkdir(join(workspace, 'app')); - await symlink(outside, join(workspace, 'escape')); - await writeFile(join(workspace, 'app', 'gradle.properties'), 'org.gradle.jvmargs=-Xmx3g\n'); - const call = handlerFor([{ rootID: 'r', name: 'w', path: workspace }], { GRADLE_USER_HOME: '/nonexistent-lithe-home' }); - assert.deepEqual(await call({ workspaceRoot: join(workspace, 'app') }), { - settings: { 'java.import.gradle.user.home': '/nonexistent-lithe-home', 'java.import.gradle.jvmArguments': '-Xmx3g' } - }); - for (const workspaceRoot of [outside, join(workspace, 'escape'), 'relative', undefined]) { - await assert.rejects(call({ workspaceRoot }), { code: 'gradle.invalidRoot' }); - } - await assert.rejects(call({ workspaceRoot: workspace }, { workspaceContext: null }), { code: 'gradle.noWorkspaceContext' }); -}); - -test('the vendored SDK matches sdk.lock.json', async () => { - const { createHash } = await import('node:crypto'); - const { readFile } = await import('node:fs/promises'); - const lock = JSON.parse(await readFile(new URL('../sdk.lock.json', import.meta.url), 'utf8')); - assert.ok(lock.files.length > 0); - for (const file of lock.files) { - const bytes = await readFile(new URL(`../${file.path}`, import.meta.url)); - assert.equal(createHash('sha256').update(bytes).digest('hex'), file.sha256, file.path); - } -}); diff --git a/io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/LICENSE b/vendor/LICENSE similarity index 100% rename from io.github.lithe-idea.gradle-build/backend/vendor/lithe-plugin-sdk/LICENSE rename to vendor/LICENSE diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java new file mode 100644 index 0000000..b71b683 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java @@ -0,0 +1,1417 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.FileDescriptor; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +/** + * The plugin backend session: one process the host starts from the plugin's + * manifest and talks to over stdio with the LSP base protocol. + * + *

The SDK owns everything Lithe manages uniformly -- the lifecycle, protocol + * negotiation, cancellation, error codes, and the {@code lithe/*} namespace -- + * and leaves the plugin free to decide what its handlers do. Declare handlers, + * then call {@link #listen()}. Handlers run on their own threads, so several + * calls can be in flight at once; shared plugin state needs its own locking. + * + *

Host services ({@code lithe/host/*}) of plugin-function protocols 2 and 3 + * are in {@link #host()}, or a handler's {@link CallContext#host()}. + * + *

Contract: {@code contract/v1/README.md} ("Build providers" + * and "Plugin functions"). Behaviour and error codes match the Node.js SDK. + */ +public final class Backend { + /** Answers a typed build request or a plugin function. */ + @FunctionalInterface + public interface Handler { + Object handle(Map params, CallContext context) throws Exception; + } + + /** Answers a standard LSP request, for a backend that is also a language server. */ + @FunctionalInterface + public interface RequestHandler { + Object handle(Object params, CallContext context) throws Exception; + } + + /** Handles a standard LSP notification. */ + @FunctionalInterface + public interface NotificationHandler { + void handle(Object params) throws Exception; + } + + /** + * Handles {@code lithe/host/commands/didRun} for one of the plugin's + * commands. {@code workspaceContext} is the {@code { contextID, generation }} + * of the window the command ran in, or null. + */ + @FunctionalInterface + public interface CommandHandler { + void handle(String commandId, Map workspaceContext) throws Exception; + } + + /** Runs before the {@code initialize} answer. */ + @FunctionalInterface + public interface InitializeHook { + void run(Map params, Negotiated negotiated) throws Exception; + } + + /** Runs on {@code shutdown}, after running calls were cancelled. */ + @FunctionalInterface + public interface ShutdownHook { + void run() throws Exception; + } + + /** Protocols the host agreed to in {@code initialize}. */ + public static final class Negotiated { + static final Negotiated NONE = new Negotiated(0, 0); + + private final int functionsVersion; + private final int buildVersion; + + Negotiated(int functionsVersion, int buildVersion) { + this.functionsVersion = functionsVersion; + this.buildVersion = buildVersion; + } + + /** Whether the host negotiated plugin functions ({@code litheFunctions}). */ + public boolean functions() { + return functionsVersion > 0; + } + + /** + * Selected plugin-function version (1-3), or zero when unavailable. + * Version 2 adds host credentials; version 3 workspace contexts, the + * other host services, and host notifications. + */ + public int functionsVersion() { + return functionsVersion; + } + + /** Whether the host negotiated typed build requests. */ + public boolean build() { + return buildVersion > 0; + } + + /** Selected build protocol version, or zero when unavailable. */ + public int buildVersion() { + return buildVersion; + } + } + + private enum Phase { IDLE, LISTENING, INITIALIZING, READY, SHUTTING_DOWN, EXITED } + + /** Canonical result format of each typed build request. */ + private static final Map BUILD_FORMATS; + + static { + Map formats = new HashMap<>(); + formats.put(Protocol.BUILD_MODEL, "litheBuildModel"); + formats.put(Protocol.BUILD_DEPENDENCIES, "litheDependencies"); + formats.put(Protocol.BUILD_DISCOVER_TESTS, "litheTestDiscovery"); + BUILD_FORMATS = Collections.unmodifiableMap(formats); + } + + private volatile boolean logging; + private boolean loggingReady; + private final List> earlyDiagnostics = new ArrayList<>(); + private final java.util.Set quietSuccess = new java.util.HashSet<>(); + private final String name; + private final String version; + private final Map capabilities; + private final Object lock = new Object(); + private final Object writeLock = new Object(); + private final Map functions = new HashMap<>(); + private final Map buildHandlers = new HashMap<>(); + private final Map requestHandlers = new HashMap<>(); + private final Map notificationHandlers = new HashMap<>(); + private final Map commandHandlers = new HashMap<>(); + private final Map hostNotificationHandlers = new HashMap<>(); + private NotificationHandler contextsHandler; + private final List initializeHooks = new ArrayList<>(); + private final List shutdownHooks = new ArrayList<>(); + /** Host requests being handled, by JSON-RPC ID. */ + private final Map incoming = new HashMap<>(); + /** Requests this backend sent to the host, by JSON-RPC ID. */ + private final Map outgoing = new HashMap<>(); + private final AtomicInteger nextRequestId = new AtomicInteger(1); + private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadNamer()); + private final HostChannel channel = new HostChannel(new Wire()); + private final Host host = new Host(channel, Collections.emptyList()); + /** Serializes register/unregister so the host sees them in call order. */ + private CompletableFuture registrations = CompletableFuture.completedFuture(null); + private volatile Phase phase = Phase.IDLE; + private volatile Negotiated negotiated = Negotiated.NONE; + private volatile Map initializeParams; + private volatile OutputStream output; + private volatile PrintStream errorOutput = System.err; + private int exitCode = 1; + + private Backend(String name, String version, Map capabilities) { + Object experimental = capabilities.get("experimental"); + if (experimental instanceof Map + && (((Map) experimental).containsKey("litheBuild") + || ((Map) experimental).containsKey("litheFunctions") + || ((Map) experimental).containsKey("litheLogging"))) { + throw new PluginSdkError("sdk.capabilities.reserved", + "litheBuild and litheFunctions are negotiated by the SDK; declare handlers instead."); + } + this.name = name == null ? "lithe-plugin-backend" : name; + this.version = version; + this.capabilities = new LinkedHashMap<>(capabilities); + } + + /** + * Creates a backend. + * + * @param name reported as {@code serverInfo.name} and used as the log prefix + * @param version reported as {@code serverInfo.version}; may be null + */ + public static Backend create(String name, String version) { + return new Backend(name, version, Collections.emptyMap()); + } + + /** + * Creates a backend that also declares standard LSP server capabilities. + * {@code experimental.litheBuild} and {@code experimental.litheFunctions} + * are negotiated by the SDK and cannot be set here. + */ + public static Backend create(String name, String version, Map capabilities) { + return new Backend(name, version, capabilities == null ? Collections.emptyMap() : capabilities); + } + + /** Protocols the host agreed to in {@code initialize}; both false before it. */ + public Negotiated negotiated() { + return negotiated; + } + + /** + * Host services of plugin-function protocols 2 and 3, usable once the + * session is ready. Prefer a handler's {@link CallContext#host()}, whose + * requests end with the call. + */ + public Host host() { + return host; + } + + /** The host's {@code initialize} params, or null before it arrives. */ + public Map initializeParams() { + return initializeParams; + } + + /** IDs of the functions this backend currently serves, sorted. */ + public List functionIds() { + synchronized (lock) { + List ids = new ArrayList<>(functions.keySet()); + Collections.sort(ids); + return ids; + } + } + + /** Answers {@code lithe/build/model} with a {@code litheBuildModel} document. */ + public Backend onModel(Handler handler) { + return declareBuild(Protocol.BUILD_MODEL, handler); + } + + /** Answers {@code lithe/build/dependencies} with a {@code litheDependencies} document. */ + public Backend onDependencies(Handler handler) { + return declareBuild(Protocol.BUILD_DEPENDENCIES, handler); + } + + /** Executes a bounded provider task; requires build protocol 2 or newer. */ + public Backend onExecute(Handler handler) { + return declareBuild(Protocol.BUILD_EXECUTE, handler); + } + + /** Runs exact test selectors; requires build protocol 3 or newer. */ + public Backend onTest(Handler handler) { + return declareBuild(Protocol.BUILD_TEST, handler); + } + + /** Returns the upstream engine's runnable test selectors, with the format stamped. */ + public Backend onDiscoverTests(Handler handler) { + return declareBuild(Protocol.BUILD_DISCOVER_TESTS, handler); + } + + /** Prepares native executable target facts; requires build protocol 5. */ + public Backend onPrepareDebug(Handler handler) { + return declareBuild(Protocol.BUILD_PREPARE_DEBUG, handler); + } + + /** Prepares a portable application launch with build protocol 4 or newer. */ + public Backend onPrepareRun(Handler handler) { + return declareBuild(Protocol.BUILD_PREPARE_RUN, handler); + } + + /** + * Declares a plugin function offered from the start, in the {@code initialize} + * answer. To add one later, use {@link #registerFunction}. + * + * @param id dot-separated lowerCamelCase segments, such as {@code snapshot.refresh} + */ + public Backend function(String id, Handler handler) { + synchronized (lock) { + if (!beforeAnswer()) { + throw new PluginSdkError("sdk.function.lateDeclaration", + "After initialize, add functions with registerFunction()."); + } + checkNewFunction(id, handler); + functions.put(id, handler); + } + return this; + } + + /** Handles a standard LSP request, for a backend that is also a language server. */ + public Backend onRequest(String method, RequestHandler handler) { + checkDeclared(method, handler); + synchronized (lock) { + requestHandlers.put(method, handler); + } + return this; + } + + /** Handles a standard LSP notification. */ + public Backend onNotification(String method, NotificationHandler handler) { + checkDeclared(method, handler); + synchronized (lock) { + notificationHandlers.put(method, handler); + } + return this; + } + + /** + * Handles {@code lithe/host/commands/didRun} for one of the plugin's + * commands (protocol 3). It is an event: the host waits for no result. + * + * @param commandId the command's ID from the manifest, 1-128 of {@code [a-z0-9.-]} + */ + public Backend onCommand(String commandId, CommandHandler handler) { + if (!Protocol.isCommandId(commandId)) { + throw new PluginSdkError("sdk.command.invalidID", "Command ID \"" + commandId + "\" must be 1-128 of [a-z0-9.-]."); + } + if (handler == null) { + throw new IllegalArgumentException("A command handler must not be null."); + } + synchronized (lock) { + commandHandlers.put(commandId, handler); + } + return this; + } + + /** + * Handles {@code lithe/host/workspace/didChangeContexts} (protocol 3) with + * {@code { revision }}; call {@code host().workspace().listContexts()} for + * the contexts. + */ + public Backend onContextsChanged(NotificationHandler handler) { + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + synchronized (lock) { + contextsHandler = handler; + } + return this; + } + + /** + * Handles a {@code lithe/host/*} notification a later host adds. Commands, + * context changes, and subscription events have their own APIs. + */ + public Backend onHostNotification(String method, NotificationHandler handler) { + if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { + throw new PluginSdkError("sdk.method.invalid", method + " is not a host notification."); + } + if (method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) || method.equals(Protocol.HOST_SUBSCRIPTION_NOTIFY) + || method.equals(Protocol.HOST_COMMAND_DID_RUN)) { + throw new PluginSdkError("sdk.method.reserved", + method + " is routed by the SDK; use onCommand, onContextsChanged, or Host.subscribe."); + } + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + synchronized (lock) { + hostNotificationHandlers.put(method, handler); + } + return this; + } + + /** Runs before the {@code initialize} answer, with the host's params and the negotiation. */ + public Backend onInitialize(InitializeHook hook) { + synchronized (lock) { + initializeHooks.add(hook); + } + return this; + } + + /** Runs on {@code shutdown}, after running calls were cancelled. */ + public Backend onShutdown(ShutdownHook hook) { + synchronized (lock) { + shutdownHooks.add(hook); + } + return this; + } + + /** + * Adds a function. Before the {@code initialize} answer (including from an + * {@link #onInitialize} hook) it joins the initial list; afterwards the host + * must accept it first. The future completes once the function is served. + */ + public CompletableFuture registerFunction(String id, Handler handler) { + synchronized (lock) { + if (beforeAnswer()) { + try { + checkNewFunction(id, handler); + functions.put(id, handler); + return CompletableFuture.completedFuture(null); + } catch (RuntimeException error) { + return failed(error); + } + } + } + return queueRegistration(() -> { + synchronized (lock) { + requireFunctions(); + checkNewFunction(id, handler); + // Installed before the request: the host may invoke it as soon as + // its registry changed, before this backend reads the reply. + functions.put(id, handler); + } + Map entry = new LinkedHashMap<>(); + entry.put("id", id); + Map params = new LinkedHashMap<>(); + params.put("functions", Collections.singletonList(entry)); + return request(Protocol.FUNCTION_REGISTER, params).handle((result, error) -> { + if (error != null) { + synchronized (lock) { + functions.remove(id); + quietSuccess.remove(id); + } + throw new CompletionException(unwrap(error)); + } + return null; + }); + }); + } + + /** Withdraws a function. The host ends its running calls as revoked. */ + public CompletableFuture unregisterFunction(String id) { + synchronized (lock) { + if (beforeAnswer()) { + if (functions.remove(id) == null) { + return failed(unknownFunction(id)); + } + quietSuccess.remove(id); + return CompletableFuture.completedFuture(null); + } + } + return queueRegistration(() -> { + synchronized (lock) { + requireFunctions(); + if (!functions.containsKey(id)) { + throw unknownFunction(id); + } + } + Map params = new LinkedHashMap<>(); + params.put("ids", Collections.singletonList(id)); + return request(Protocol.FUNCTION_UNREGISTER, params).thenApply(result -> { + List running = new ArrayList<>(); + synchronized (lock) { + functions.remove(id); + quietSuccess.remove(id); + for (Call call : incoming.values()) { + if (id.equals(call.functionId)) { + running.add(call); + } + } + } + for (Call call : running) { + call.cancellation.cancel("The function was withdrawn."); + } + return null; + }); + }); + } + + /** Sends a standard LSP request to the host. {@code lithe/*} methods are reserved. */ + public CompletableFuture sendRequest(String method, Object params) { + checkOutgoing(method); + return request(method, params); + } + + /** Sends a standard LSP notification to the host. {@code lithe/*} methods are reserved. */ + public void sendNotification(String method, Object params) { + checkOutgoing(method); + Map message = message(null, method); + if (params != null) { + message.put("params", params); + } + write(message); + } + + public Diagnostics diagnostics() { return new Diagnostics(this, null); } + + public Backend suppressSuccessDiagnostics(String operation) { + if (!loggingOperation(operation)) throw new PluginSdkError("sdk.logging.invalidOperation", "Suppress a registered operation."); + synchronized (lock) { quietSuccess.add(operation); } + return this; + } + + boolean loggingOperation(String operation) { + synchronized (lock) { return Diagnostics.OPERATIONS.contains(operation) || functions.containsKey(operation); } + } + + void logFact(Map params) { + synchronized (lock) { + if (!logging) return; + if (!loggingReady) { if (earlyDiagnostics.size() < 8) earlyDiagnostics.add(params); return; } + } + Map notification = message(null, "lithe/log"); + notification.put("params", params); + write(notification); + } + + /** + * Serves the host over stdio until it sends {@code exit} or closes stdin, + * then exits the process with the session's exit code: 0 after a + * {@code shutdown}, 1 otherwise. {@code System.out} is redirected to stderr + * first, because stdout carries the protocol and a stray line there would + * end the session. + */ + public void listen() { + OutputStream protocol = new FileOutputStream(FileDescriptor.out); + System.setOut(System.err); + int code = listen(System.in, protocol, System.err); + System.exit(code); + } + + /** + * Serves the host over the given streams and returns the exit code once the + * session ended, without exiting the process. Blocks the calling thread. + */ + public int listen(InputStream input, OutputStream output, PrintStream errorOutput) { + synchronized (lock) { + if (phase != Phase.IDLE) { + throw new PluginSdkError("sdk.listen.repeated", "A backend listens once."); + } + phase = Phase.LISTENING; + this.output = output; + this.errorOutput = errorOutput; + } + Framing.Decoder decoder = new Framing.Decoder(); + byte[] chunk = new byte[64 * 1024]; + try { + while (phase != Phase.EXITED) { + int count = input.read(chunk); + if (count < 0) { + finish(phase == Phase.SHUTTING_DOWN ? 0 : 1); + break; + } + List messages; + try { + messages = decoder.push(chunk, 0, count); + } catch (Framing.FramingException error) { + diagnostics().terminal("notification", new IllegalStateException(), System.nanoTime()); + finish(1); + break; + } + for (Object message : messages) { + if (phase == Phase.EXITED) { + break; + } + dispatch(message); + } + } + } catch (IOException error) { + finish(1); + } + synchronized (lock) { + return exitCode; + } + } + + private void dispatch(Object message) { + if (message == Framing.MALFORMED) { + respond(null, null, error(Protocol.PARSE_ERROR, "The message is not valid JSON.")); + return; + } + // Valid JSON that is not a message object, such as `null` or a batch. + if (!(message instanceof Map)) { + respond(null, null, error(Protocol.INVALID_REQUEST, "The message is not a JSON-RPC object.")); + return; + } + Map object = Json.object(message); + Object id = object.get("id"); + Object method = object.get("method"); + if (!(method instanceof String)) { + if (id != null) { + settleOutgoing(object); + } + return; + } + if (id != null) { + handleRequest(id, (String) method, object.get("params")); + } else { + handleNotification((String) method, object.get("params")); + } + } + + private void handleRequest(Object id, String method, Object params) { + if (method.equals(Protocol.INITIALIZE)) { + initialize(id, params instanceof Map ? Json.object(params) : new LinkedHashMap<>()); + return; + } + if (method.equals(Protocol.SHUTDOWN)) { + shutdown(id); + return; + } + Phase current = phase; + if (current == Phase.LISTENING || current == Phase.INITIALIZING) { + respond(id, null, error(Protocol.SERVER_NOT_INITIALIZED, "The backend is not initialized.")); + return; + } + if (current != Phase.READY) { + respond(id, null, error(Protocol.INVALID_REQUEST, "The backend is shutting down.")); + return; + } + if (method.equals(Protocol.FUNCTION_INVOKE)) { + invokeFunction(id, params); + return; + } + Handler build; + RequestHandler handler; + synchronized (lock) { + build = negotiated.buildVersion() >= Protocol.buildMethodVersion(method) ? buildHandlers.get(method) : null; + handler = requestHandlers.get(method); + } + if (build != null) { + if (params != null && !(params instanceof Map)) { + respond(id, null, error(Protocol.INVALID_PARAMS, method + " params must be an object.")); + return; + } + Map arguments = Json.object(params); + invokeBuild(id, method, arguments, build); + return; + } + if (handler != null) { + run(id, null, null, context -> handler.handle(params, context), result -> result, null); + return; + } + respond(id, null, error(Protocol.METHOD_NOT_FOUND, "Unsupported method: " + method)); + } + + private void handleNotification(String method, Object params) { + if (method.equals(Protocol.EXIT)) { + finish(phase == Phase.SHUTTING_DOWN ? 0 : 1); + return; + } + if (method.equals(Protocol.CANCEL_REQUEST)) { + Object id = params instanceof Map ? ((Map) params).get("id") : null; + Call call; + synchronized (lock) { + call = incoming.get(requestKey(id)); + } + if (call != null) { + call.cancellation.cancel("The request was cancelled."); + } + return; + } + if (phase != Phase.READY || method.equals(Protocol.INITIALIZED)) { + return; + } + if (method.startsWith(Protocol.HOST_PREFIX)) { + hostNotification(method, params); + return; + } + NotificationHandler handler; + synchronized (lock) { + handler = notificationHandlers.get(method); + } + if (handler == null) { + return; + } + notifyHandler(method, () -> handler.handle(params)); + } + + /** + * Routes a host notification. Core checked its shape and the session's + * grant; one this SDK does not know is ignored, as the contract asks. + */ + private void hostNotification(String method, Object raw) { + if (negotiated.functionsVersion() < Protocol.CONTEXT_VERSION || !(raw instanceof Map)) { + return; + } + Map params = Json.object(raw); + if (method.equals(Protocol.HOST_SUBSCRIPTION_NOTIFY)) { + channel.deliver(params); + return; + } + if (method.equals(Protocol.HOST_COMMAND_DID_RUN)) { + Object commandId = params.get("commandID"); + CommandHandler handler; + synchronized (lock) { + handler = commandId instanceof String ? commandHandlers.get(commandId) : null; + } + if (handler == null) { + diagnostics().degraded("notification", "command_unhandled"); + return; + } + Map context = workspaceContext(params.get("context")); + notifyHandler(method, () -> handler.handle((String) commandId, context)); + return; + } + NotificationHandler handler; + synchronized (lock) { + handler = method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) ? contextsHandler : hostNotificationHandlers.get(method); + } + if (handler != null) { + notifyHandler(method, () -> handler.handle(params)); + } + } + + private interface Notified { + void run() throws Exception; + } + + /** Runs a notification handler off the reader thread; a failure is logged. */ + private void notifyHandler(String method, Notified handler) { + executor.execute(() -> { + try { + handler.run(); + } catch (Throwable error) { + diagnostics().terminal("notification", error, System.nanoTime()); + } + }); + } + + private void initialize(Object id, Map params) { + Negotiated agreed; + List hooks; + synchronized (lock) { + if (phase != Phase.LISTENING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "initialize was already received.")); + return; + } + phase = Phase.INITIALIZING; + initializeParams = params; + Map offered = experimental(params.get("capabilities")); + loggingReady = false; + earlyDiagnostics.clear(); + logging = offers(offered.get("litheLogging"), 1); + if (!logging) { + phase = Phase.LISTENING; + respond(id, null, error(Protocol.INVALID_REQUEST, "The backend requires litheLogging version 1.")); + return; + } + int buildVersion = 0; + if (!buildHandlers.isEmpty()) { + for (int version = Protocol.BUILD_VERSION; version > 0; version--) { + if (offers(offered.get("litheBuild"), version)) { + buildVersion = version; + break; + } + } + } + int functionsVersion = 0; + for (int version = Protocol.FUNCTIONS_VERSION; version > 0; version--) { + if (offers(offered.get("litheFunctions"), version)) { + functionsVersion = version; + break; + } + } + agreed = new Negotiated(functionsVersion, buildVersion); + negotiated = agreed; + hooks = new ArrayList<>(initializeHooks); + } + executor.execute(() -> { + try { + for (InitializeHook hook : hooks) { + hook.run(params, agreed); + } + } catch (Throwable failure) { + synchronized (lock) { + if (phase == Phase.INITIALIZING) { + phase = Phase.LISTENING; + } + } + respond(id, null, toResponseError(failure, null)); + return; + } + synchronized (lock) { + // A shutdown or exit that arrived while a hook ran ended the + // session; finishing initialize must not reopen it. + if (phase != Phase.INITIALIZING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "The session ended during initialize.")); + return; + } + if (!agreed.functions() && !functions.isEmpty()) { + diagnostics().degraded("initialize", "functions_unavailable"); + } + Map experimental = new LinkedHashMap<>(experimental(capabilities)); + experimental.put("litheLogging", singleton("version", 1)); + if (agreed.build()) { + experimental.put("litheBuild", singleton("version", agreed.buildVersion())); + } + if (agreed.functions()) { + List offered = new ArrayList<>(); + for (String functionId : functionIds()) { + offered.add(singleton("id", functionId)); + } + Map entry = singleton("version", agreed.functionsVersion()); + entry.put("functions", offered); + experimental.put("litheFunctions", entry); + } + Map answered = new LinkedHashMap<>(capabilities); + answered.put("experimental", experimental); + Map serverInfo = singleton("name", name); + if (version != null) { + serverInfo.put("version", version); + } + Map result = singleton("capabilities", answered); + result.put("serverInfo", serverInfo); + phase = Phase.READY; + respond(id, result, null); + loggingReady = true; + List> early = new ArrayList<>(earlyDiagnostics); + earlyDiagnostics.clear(); + for (Map fact : early) logFact(fact); + } + }); + } + + private void shutdown(Object id) { + List hooks; + synchronized (lock) { + if (phase != Phase.READY && phase != Phase.LISTENING && phase != Phase.INITIALIZING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "shutdown was already received.")); + return; + } + phase = Phase.SHUTTING_DOWN; + hooks = new ArrayList<>(shutdownHooks); + } + cancelAll("The backend is shutting down."); + executor.execute(() -> { + for (ShutdownHook hook : hooks) { + try { + hook.run(); + } catch (Throwable error) { + diagnostics().terminal("shutdown", error, System.nanoTime()); + } + } + Processes.killAll(); + respond(id, null, null); + }); + } + + private void invokeFunction(Object id, Object raw) { + Map invocation = raw instanceof Map ? Json.object(raw) : new LinkedHashMap<>(); + Object functionId = invocation.get("functionID"); + Object operationId = invocation.get("operationID"); + Object params = invocation.get("params"); + Map workspaceContext = workspaceContext(invocation.get("context")); + Handler handler; + synchronized (lock) { + handler = negotiated.functions() && functionId instanceof String ? functions.get(functionId) : null; + } + if (handler == null) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Function " + functionId + " is not registered.")); + return; + } + if (params != null && !(params instanceof Map)) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Function " + functionId + " params must be an object.")); + return; + } + String function = (String) functionId; + String operation = operationId instanceof String ? (String) operationId : null; + Map arguments = Json.object(params); + AtomicBoolean reporting = new AtomicBoolean(true); + CallContext.ProgressSink progress = (message, percentage) -> { + if (!reporting.get()) { + return; + } + Map report = new LinkedHashMap<>(); + report.put("operationID", operationId); + if (message != null) { + report.put("message", Protocol.boundedText(message)); + } + if (percentage != null && !percentage.isNaN() && !percentage.isInfinite()) { + report.put("percentage", Math.min(100L, Math.max(0L, Math.round(percentage)))); + } + Map notification = message(null, Protocol.FUNCTION_PROGRESS); + notification.put("params", report); + write(notification); + }; + run(id, function, operation, workspaceContext, context -> handler.handle(arguments, context), + Backend::functionResult, () -> reporting.set(false), progress); + } + + private void invokeBuild(Object id, String method, Map arguments, Handler handler) { + if (arguments.containsKey("modelInputs") && negotiated.buildVersion() < 6) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Model inputs require build protocol 6.")); + return; + } + if (!Protocol.buildProgress(method)) { + run(id, null, null, null, context -> handler.handle(arguments, context), result -> buildResult(method, result), null, null, method); + return; + } + Object wireId = arguments.get("operationID"); + if (!(wireId instanceof String)) { + respond(id, null, error(Protocol.INVALID_PARAMS, "A build request needs its wire operationID.")); + return; + } + AtomicBoolean reporting = new AtomicBoolean(true); + CallContext.ProgressSink progress = new CallContext.ProgressSink() { + @Override + public void report(String message, Double percentage) { report(message, percentage, null); } + @Override + public void report(String text, Double percentage, String output) { + if (!reporting.get()) return; + Map report = singleton("operationID", wireId); + if (text != null) report.put("message", Protocol.boundedText(text, Protocol.MAX_BUILD_MESSAGE_BYTES)); + if (output != null) report.put("output", Protocol.boundedText(output, Protocol.MAX_BUILD_OUTPUT_BYTES)); + if (percentage != null && !percentage.isNaN() && !percentage.isInfinite()) { + report.put("percentage", Math.min(100L, Math.max(0L, Math.round(percentage)))); + } + Map notification = message(null, Protocol.BUILD_PROGRESS); + notification.put("params", report); + write(notification); + } + }; + run(id, null, (String) wireId, null, context -> handler.handle(arguments, context), + result -> buildResult(method, result), () -> reporting.set(false), progress, method); + } + + private interface Invocation { + Object invoke(CallContext context) throws Exception; + } + + private interface Shape { + Object apply(Object result); + } + + private void run(Object id, String functionId, String operationId, Invocation invoke, Shape shape, Runnable onSettled) { + run(id, functionId, operationId, null, invoke, shape, onSettled, null); + } + + /** Runs one handler with its own cancellation and answers exactly once. */ + private void run(Object id, String functionId, String operationId, Map workspaceContext, + Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress) { + run(id, functionId, operationId, workspaceContext, invoke, shape, onSettled, progress, functionId == null ? "function-call" : functionId); + } + + private void run(Object id, String functionId, String operationId, Map workspaceContext, + Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress, String diagnosticOperation) { + long started = System.nanoTime(); + String diagnosticOperationId = Diagnostics.requestOperationId(operationId, id); + Cancellation cancellation = new Cancellation(() -> diagnostics().degraded("notification", "cancellation_listener_failed")); + String key = requestKey(id); + synchronized (lock) { + incoming.put(key, new Call(cancellation, functionId)); + } + CallContext context = new CallContext(cancellation, this, functionId, diagnosticOperationId, progress, + new Host(channel, Collections.singletonList(cancellation)), workspaceContext); + executor.execute(() -> { + Object result = null; + Map error = null; + try { + Object value = invoke.invoke(context); + cancellation.throwIfCancelled(); + result = shape.apply(value); + } catch (Throwable failure) { + if (!cancellation.isCancelled()) { + new Diagnostics(this, diagnosticOperationId).terminal(diagnosticOperation, failure, started); + } + error = toResponseError(failure, cancellation); + } + if (error == null && !cancellation.isCancelled()) { + boolean quiet; + synchronized (lock) { quiet = context.quietSuccess() || quietSuccess.contains(diagnosticOperation); } + if (!quiet) new Diagnostics(this, diagnosticOperationId).terminal(diagnosticOperation, null, started); + } + try { + if (onSettled != null) { + onSettled.run(); + } + } finally { + synchronized (lock) { + incoming.remove(key); + } + // Work belongs to its call: tools still running when the handler + // returned end now. Other calls have their own cancellation. + cancellation.cancel("The call ended."); + // Answered whatever the clean-up did, so Lithe never waits for + // its timeout. + respond(id, result, error); + } + }); + } + + private Backend declareBuild(String method, Handler handler) { + if (handler == null) { + throw new IllegalArgumentException("A build handler must not be null."); + } + synchronized (lock) { + if (phase != Phase.IDLE) { + throw new PluginSdkError("sdk.build.lateDeclaration", "Declare build handlers before listen()."); + } + buildHandlers.put(method, handler); + } + return this; + } + + private static void checkDeclared(String method, Object handler) { + if (method == null || Protocol.isReservedMethod(method)) { + throw new PluginSdkError("sdk.method.reserved", method + " is managed by the SDK and Lithe."); + } + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + } + + private void checkNewFunction(String id, Handler handler) { + if (!Protocol.isFunctionId(id)) { + throw new PluginSdkError("sdk.function.invalidID", "Function ID \"" + id + + "\" must be dot-separated lowerCamelCase segments of at most 128 bytes."); + } + if (handler == null) { + throw new IllegalArgumentException("A function handler must not be null."); + } + if (functions.containsKey(id)) { + throw new PluginSdkError("sdk.function.duplicate", "Function " + id + " is already declared."); + } + if (functions.size() >= Protocol.MAX_FUNCTIONS) { + throw new PluginSdkError("sdk.function.limit", + "A backend serves at most " + Protocol.MAX_FUNCTIONS + " functions."); + } + } + + /** True until the {@code initialize} answer fixes the initial function list. */ + private boolean beforeAnswer() { + return phase == Phase.IDLE || phase == Phase.LISTENING || phase == Phase.INITIALIZING; + } + + private void requireFunctions() { + if (phase != Phase.READY || !negotiated.functions()) { + throw new PluginSdkError("sdk.functions.unavailable", "The host has not negotiated plugin functions."); + } + } + + private static PluginSdkError unknownFunction(String id) { + return new PluginSdkError("sdk.function.unknown", "Function " + id + " is not registered."); + } + + private CompletableFuture queueRegistration(Supplier> change) { + synchronized (lock) { + CompletableFuture next = registrations.thenComposeAsync(ignored -> { + try { + return change.get(); + } catch (RuntimeException error) { + return failed(error); + } + }, executor); + registrations = next.handle((result, error) -> null); + return next; + } + } + + private void checkOutgoing(String method) { + if (method == null || Protocol.isReservedMethod(method)) { + throw new PluginSdkError("sdk.method.reserved", method + + " is reserved. A backend never asks the host to run a domain operation or a function."); + } + if (phase != Phase.READY) { + throw new PluginSdkError("sdk.session.notReady", "The session is not initialized."); + } + } + + private CompletableFuture request(String method, Object params) { + return send(method, params).response; + } + + /** Writes a request; params JSON cannot encode throw before anything is registered. */ + private HostChannel.Sent send(String method, Object params) { + String id = "sdk-" + nextRequestId.getAndIncrement(); + CompletableFuture future = new CompletableFuture<>(); + Map message = message(id, method); + if (params != null) { + message.put("params", params); + } + byte[] frame = Framing.encode(message); + synchronized (lock) { + if (phase == Phase.EXITED) { + future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); + return new HostChannel.Sent(id, future); + } + outgoing.put(id, new Pending(future, method)); + } + writeEncoded(frame); + return new HostChannel.Sent(id, future); + } + + private void settleOutgoing(Map message) { + Object id = message.get("id"); + Pending pending; + synchronized (lock) { + pending = id instanceof String ? outgoing.remove(id) : null; + } + if (pending == null) { + return; + } + Object error = message.get("error"); + // Completed on a handler thread: the reader thread never runs plugin code. + if (error instanceof Map) { + HostError rejection = HostError.fromResponse(pending.method, Json.object(error)); + executor.execute(() -> pending.future.completeExceptionally(rejection)); + } else { + Object result = message.get("result"); + executor.execute(() -> pending.future.complete(result)); + } + } + + private void cancelAll(String reason) { + List calls; + synchronized (lock) { + calls = new ArrayList<>(incoming.values()); + } + for (Call call : calls) { + call.cancellation.cancel(reason); + } + } + + private void finish(int code) { + List pending; + synchronized (lock) { + if (phase == Phase.EXITED) { + return; + } + phase = Phase.EXITED; + exitCode = code; + pending = new ArrayList<>(outgoing.values()); + outgoing.clear(); + } + channel.close(); + cancelAll("The session ended."); + Processes.killAll(); + for (Pending request : pending) { + request.future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); + } + // Running handlers finish on their own threads; nothing new starts. + executor.shutdown(); + } + + private void respond(Object id, Object result, Map error) { + if (phase == Phase.EXITED) { + return; + } + Map message = message(id, null); + if (error != null) { + message.put("error", error); + } else { + message.put("result", result); + } + try { + writeEncoded(Framing.encode(message)); + } catch (Json.JsonException failure) { + // A result JSON cannot encode must not end the session. + diagnostics().terminal("result-encoding", failure, System.nanoTime()); + Map fallback = message(id, null); + fallback.put("error", toResponseError(failure, null)); + write(fallback); + } + } + + private void write(Map message) { + writeEncoded(Framing.encode(message)); + } + + private void writeEncoded(byte[] frame) { + synchronized (writeLock) { + OutputStream stream = output; + if (stream == null || phase == Phase.EXITED) { + return; + } + try { + stream.write(frame); + stream.flush(); + } catch (IOException error) { + // The host closed the pipe; the input side ends the session. + // The closed protocol pipe leaves the host owning the terminal process fact. + } + } + } + + /** + * The JSON-RPC error object for a handler failure. Only {@link PluginError} + * carries a plugin code; any other exception becomes a generic internal + * error so that stack traces and machine paths never reach the host's UI. + */ + static Map toResponseError(Throwable failure, Cancellation cancellation) { + Throwable error = unwrap(failure); + if (cancellation != null && cancellation.isCancelled() && error instanceof CancelledException) { + return error(Protocol.REQUEST_CANCELLED, "The request was cancelled."); + } + if (error instanceof PluginError) { + Map response = error(Protocol.REQUEST_FAILED, Protocol.boundedText(error.getMessage())); + response.put("data", singleton("code", ((PluginError) error).code())); + return response; + } + // Unexpected exceptions often embed absolute paths or internals; the + // caller logs only a fixed failure category to stderr. + return error(Protocol.INTERNAL_ERROR, "The plugin backend failed unexpectedly."); + } + + /** + * Stamps the canonical format on a build result, so a handler can return the + * plain document. A result in another format is a backend bug: Core would + * refuse it as {@code plugin.build.invalidOutput}, so it fails here with a log. + */ + static Object buildResult(String method, Object result) { + String expected = BUILD_FORMATS.get(method); + if (!(result instanceof Map)) { + throw new PluginSdkError("sdk.build.invalidResult", method + " must return a reply object."); + } + Map document = new LinkedHashMap<>(Json.object(result)); + if (expected != null) { + Object format = document.get("format"); + if (format != null && !expected.equals(format)) { + throw new PluginSdkError("sdk.build.invalidResult", method + " returned another format."); + } + Object version = document.get("version"); + if (version != null && !(version instanceof Number && ((Number) version).doubleValue() == 1)) { + throw new PluginSdkError("sdk.build.invalidResult", method + " returned a version other than 1."); + } + document.put("format", expected); + document.put("version", 1); + } + if (Protocol.BUILD_EXECUTE.equals(method) || Protocol.BUILD_TEST.equals(method)) { + Object exit = document.get("exitCode"); + Object output = document.get("output"); + if (!(exit instanceof Number) || ((Number) exit).doubleValue() < Integer.MIN_VALUE + || ((Number) exit).doubleValue() > Integer.MAX_VALUE + || ((Number) exit).doubleValue() != ((Number) exit).longValue() + || !(output instanceof String) || Protocol.utf8Length((String) output) > Protocol.MAX_BUILD_RESULT_BYTES) { + throw new PluginSdkError("sdk.build.invalidResult", method + " needs an int32 exitCode and bounded output."); + } + document.put("exitCode", ((Number) exit).longValue()); + } + if (Protocol.BUILD_PREPARE_DEBUG.equals(method)) { + if (!(document.get("program") instanceof String) || !(document.get("workingDirectory") instanceof String) + || !stringList(document.get("arguments")) || !stringMap(document.get("environment")) + || document.size() != 4) { + throw new PluginSdkError("sdk.build.invalidResult", "Native debug preparation needs program, arguments, workingDirectory and environment only."); + } + } + if (Protocol.BUILD_PREPARE_RUN.equals(method)) { + Map executable = Json.object(document.get("executable")); + if (!("toolchain".equals(executable.get("kind")) || "command".equals(executable.get("kind"))) + || !(executable.get("value") instanceof String) || !(document.get("workingDirectory") instanceof String) + || !stringList(document.get("arguments")) || !stringMap(document.get("environment"))) { + throw new PluginSdkError("sdk.build.invalidResult", method + " needs a portable launch plan."); + } + } + // Workspace containment and domain facts remain Core/provider responsibilities. + if (Protocol.utf8Length(Json.stringify(document)) > Protocol.MAX_BUILD_RESULT_BYTES) { + throw new PluginSdkError("sdk.build.invalidResult", method + " exceeds the build-result size limit."); + } + return document; + } + + private static boolean stringList(Object value) { + if (!(value instanceof List)) return false; + for (Object item : (List) value) if (!(item instanceof String)) return false; + return true; + } + + private static boolean stringMap(Object value) { + if (!(value instanceof Map)) return false; + for (Map.Entry item : ((Map) value).entrySet()) { + if (!(item.getKey() instanceof String) || !(item.getValue() instanceof String)) return false; + } + return true; + } + + /** + * A function result as the JSON value Core accepts. A value JSON cannot + * encode, or one over Core's 1 MiB limit, fails here as a backend bug with a + * log line, instead of breaking the response frame or being refused by Core. + */ + static Object functionResult(Object result) { + String encoded; + try { + encoded = Json.stringify(result); + } catch (Json.JsonException error) { + throw new PluginSdkError("sdk.function.invalidResult", "The result is not JSON: " + error.getMessage()); + } + if (encoded.getBytes(StandardCharsets.UTF_8).length > Protocol.MAX_RESULT_BYTES) { + throw new PluginSdkError("sdk.function.invalidResult", + "The result exceeds " + Protocol.MAX_RESULT_BYTES + " bytes."); + } + return result; + } + + private static boolean offers(Object entry, int version) { + if (!(entry instanceof Map)) { + return false; + } + Object versions = ((Map) entry).get("versions"); + if (!(versions instanceof List)) { + return false; + } + for (Object offered : (List) versions) { + if (offered instanceof Number && ((Number) offered).doubleValue() == version) { + return true; + } + } + return false; + } + + /** {@code capabilities.experimental}, or an empty map. */ + private static Map experimental(Object capabilities) { + Object experimental = capabilities instanceof Map ? ((Map) capabilities).get("experimental") : null; + return experimental instanceof Map ? Json.object(experimental) : Collections.emptyMap(); + } + + /** The JSON-RPC ID as a map key; numbers and strings never collide. */ + private static String requestKey(Object id) { + if (id instanceof Number) { + Number number = (Number) id; + return "number:" + (number.doubleValue() == number.longValue() ? Long.toString(number.longValue()) : number); + } + return (id instanceof String ? "string:" : "other:") + id; + } + + private static Map message(Object id, String method) { + Map message = new LinkedHashMap<>(); + message.put("jsonrpc", "2.0"); + if (id != null || method == null) { + message.put("id", id); + } + if (method != null) { + message.put("method", method); + } + return message; + } + + private static Map error(int code, String text) { + Map error = new LinkedHashMap<>(); + error.put("code", code); + error.put("message", text); + return error; + } + + private static Map singleton(String key, Object value) { + Map map = new LinkedHashMap<>(); + map.put(key, value); + return map; + } + + /** The failure inside {@code CompletableFuture}'s wrappers, from {@code join()} or {@code get()}. */ + static Throwable unwrap(Throwable error) { + Throwable current = error; + while ((current instanceof CompletionException || current instanceof ExecutionException) && current.getCause() != null) { + current = current.getCause(); + } + return current; + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } + + /** The {@code { contextID, generation }} the host sent, or null. */ + private static Map workspaceContext(Object value) { + return Protocol.isContextReference(value) ? Host.contextReference(Json.object(value)) : null; + } + + /** The session's wire, for host services. */ + private final class Wire implements HostChannel.Transport { + @Override + public int version() { + return negotiated.functionsVersion(); + } + + @Override + public boolean ready() { + return phase == Phase.READY; + } + + @Override + public HostChannel.Sent send(String method, Object params) { + return Backend.this.send(method, params); + } + + @Override + public void notify(String method, Object params) { + Map notification = message(null, method); + notification.put("params", params); + write(notification); + } + + @Override + public void log(String message) { + Backend.this.diagnostics().degraded("notification", "subscription_queue_full"); + } + + @Override + public void log(String message, Throwable error) { + Backend.this.diagnostics().terminal("notification", error, System.nanoTime()); + } + + @Override + public void execute(Runnable task) { + executor.execute(task); + } + } + + /** One host request being handled. */ + private static final class Call { + final Cancellation cancellation; + final String functionId; + + Call(Cancellation cancellation, String functionId) { + this.cancellation = cancellation; + this.functionId = functionId; + } + } + + /** One request this backend sent to the host. */ + private static final class Pending { + final CompletableFuture future; + final String method; + + Pending(CompletableFuture future, String method) { + this.future = future; + this.method = method; + } + } + + /** Daemon threads, so a handler still running never keeps the process alive after exit. */ + private static final class ThreadNamer implements java.util.concurrent.ThreadFactory { + private final AtomicInteger next = new AtomicInteger(1); + + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "lithe-sdk-call-" + next.getAndIncrement()); + thread.setDaemon(true); + return thread; + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java new file mode 100644 index 0000000..ceffda4 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java @@ -0,0 +1,119 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * What a handler gets besides its params: the call's cancellation, tools and + * host requests that end with the call, the backend's log, and progress for + * plugin functions or bounded build operations. + */ +public final class CallContext { + /** Sends one progress report; absent for model, dependency and discovery requests. */ + interface ProgressSink { + void report(String message, Double percentage); + default void report(String message, Double percentage, String output) { report(message, percentage); } + } + + private final java.util.concurrent.atomic.AtomicBoolean quietSuccess = new java.util.concurrent.atomic.AtomicBoolean(); + private final Cancellation cancellation; + private final Backend backend; + private final String functionId; + private final String operationId; + private final ProgressSink progress; + private final Host host; + private final Map workspaceContext; + + CallContext(Cancellation cancellation, Backend backend, String functionId, String operationId, ProgressSink progress, + Host host, Map workspaceContext) { + this.cancellation = cancellation; + this.backend = backend; + this.functionId = functionId; + this.operationId = operationId; + this.progress = progress; + this.host = host; + this.workspaceContext = workspaceContext; + } + + /** + * Cancelled when the host cancels the call, the backend shuts down, or the + * call ends; work a handler leaves running after it returned is stopped. + */ + public Cancellation cancellation() { + return cancellation; + } + + public boolean isCancelled() { + return cancellation.isCancelled(); + } + + /** Throws {@link CancelledException} once the call was cancelled. */ + public void throwIfCancelled() { + cancellation.throwIfCancelled(); + } + + /** + * Runs a tool that belongs to this call: cancelling the call or ending it + * stops the tool, and the backend shutting down ends it. + */ + public Processes.Result run(List command, Processes.Options options) throws IOException { + Processes.Options settings = options == null ? new Processes.Options() : options.copy(); + settings.listenerFailure(() -> diagnostics().degraded("notification", "output_listener_failed")); + Cancellation own = settings.cancellation(); + settings.cancellation(own == null ? cancellation : cancellation.combinedWith(own)); + return Processes.run(command, settings); + } + + /** Runs a tool that belongs to this call with default options. */ + public Processes.Result run(List command) throws IOException { + return run(command, null); + } + + public void suppressSuccessDiagnostics() { quietSuccess.set(true); } + boolean quietSuccess() { return quietSuccess.get(); } + + public Diagnostics diagnostics() { return new Diagnostics(backend, operationId); } + + /** + * Reports progress of a function or bounded build call. Function messages + * are cut to 1024 bytes, build messages to 4096; percentages are rounded to + * 0-100. Reports after cancellation or completion are dropped. + */ + public void progress(String message, Double percentage) { progress(message, percentage, null); } + + /** Build calls may additionally stream up to 64 KiB of output per report. */ + public void progress(String message, Double percentage, String output) { + if (progress != null && !cancellation.isCancelled()) progress.report(message, percentage, output); + } + + /** The function this call runs, or null for a build or LSP request. */ + public String functionId() { + return functionId; + } + + /** The wire operation ID of a function or bounded build call, otherwise null. */ + public String operationId() { + return operationId; + } + + /** + * Host services that belong to this call: requests still unanswered when + * the call is cancelled or ends fail with {@link CancelledException} and, + * from protocol 3, are cancelled on the wire. A subscription created here + * outlives the call until it is disposed. + */ + public Host host() { + return host; + } + + /** + * The {@code { contextID, generation }} of the workspace a function was + * invoked for (protocol 3), or null: for other calls, before protocol 3, + * and for an invocation outside a workspace. Pass it to the + * {@link Host} methods that name a context. + */ + public Map workspaceContext() { + return workspaceContext; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java new file mode 100644 index 0000000..d80cd7d --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java @@ -0,0 +1,112 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayList; +import java.util.List; + +/** + * Cancellation of one call, or of work a plugin manages itself. Listeners run + * once, on the thread that cancels; a listener added after cancellation runs + * immediately. A listener that throws is logged to stderr and does not keep + * the others, or the thread that cancelled, from running on. Cancelling never interrupts threads, because an interrupt + * closes NIO channels a handler may be writing state through; long work checks + * {@link #isCancelled()} or {@link #throwIfCancelled()} instead. + */ +public final class Cancellation { + private final Object lock = new Object(); + private final List listeners = new ArrayList<>(); + private String reason; + private final Runnable listenerFailure; + public Cancellation() { this(() -> {}); } + Cancellation(Runnable listenerFailure) { this.listenerFailure = listenerFailure; } + + /** Cancels with {@code reason}; later calls have no effect. */ + public void cancel(String reason) { + List pending; + synchronized (lock) { + if (this.reason != null) { + return; + } + this.reason = reason == null ? "The request was cancelled." : reason; + pending = new ArrayList<>(listeners); + listeners.clear(); + } + for (Runnable listener : pending) { + runIsolated(listener); + } + } + + public boolean isCancelled() { + synchronized (lock) { + return reason != null; + } + } + + /** Throws {@link CancelledException} once cancelled. */ + public void throwIfCancelled() { + String current; + synchronized (lock) { + current = reason; + } + if (current != null) { + throw new CancelledException(current); + } + } + + /** + * Runs {@code listener} on cancellation. The returned handle removes it, + * for work that finished first. + */ + public Registration onCancel(Runnable listener) { + synchronized (lock) { + if (reason == null) { + listeners.add(listener); + return () -> { + synchronized (lock) { + listeners.remove(listener); + } + }; + } + } + runIsolated(listener); + return () -> {}; + } + + /** + * A token cancelled when either this one or {@code other} is; for work that + * a plugin may also stop for its own reasons. + */ + public Cancellation combinedWith(Cancellation other) { + Cancellation combined = new Cancellation(listenerFailure); + Registration first = onCancel(() -> combined.cancel(reasonOrDefault())); + Registration second = other.onCancel(() -> combined.cancel(other.reasonOrDefault())); + combined.onCancel(() -> { + first.remove(); + second.remove(); + }); + return combined; + } + + private void runIsolated(Runnable listener) { + try { + listener.run(); + } catch (RuntimeException error) { + listenerFailure.run(); + } + } + + /** The reason it was cancelled with, or the default text before that. */ + String reason() { + return reasonOrDefault(); + } + + private String reasonOrDefault() { + synchronized (lock) { + return reason == null ? "The request was cancelled." : reason; + } + } + + /** Removes a cancellation listener. */ + public interface Registration { + void remove(); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java new file mode 100644 index 0000000..dd01676 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java @@ -0,0 +1,14 @@ +package io.github.litheidea.plugin.sdk; + +/** + * Thrown when the call a piece of work belongs to was cancelled or ended. + * A handler normally lets it propagate; the SDK then answers the host with + * {@code RequestCancelled}. + */ +public class CancelledException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public CancelledException(String message) { + super(message); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java new file mode 100644 index 0000000..6912594 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java @@ -0,0 +1,71 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** Typed facts for the host's litheLogging 1 catalog; never accepts message or payload text. */ +public final class Diagnostics { + static final long MAX_INTEGER = 9007199254740991L; + static final Set OPERATIONS = new HashSet<>(Arrays.asList( + "initialize", "shutdown", "notification", "function-call", "result-encoding", + "lithe/build/model", "lithe/build/dependencies", "lithe/build/execute", "lithe/build/test", + "lithe/build/discoverTests", "lithe/build/prepareRun", "lithe/build/prepareDebug", + "lithe/vcs/status", "lithe/vcs/baseContent", "lithe/vcs/history", "lithe/vcs/fileHistory", + "lithe/vcs/annotate", "lithe/vcs/checkin", "lithe/vcs/rollback", "lithe/vcs/update", + "lithe/vcs/fileOperation", "lithe/vcs/resolve", "lithe/vcs/cleanup")); + private final Backend backend; + private final String operationId; + + Diagnostics(Backend backend, String operationId) { + this.backend = backend; + this.operationId = operationId; + } + + public void degraded(String operation, String code, Long count) { record("degraded", operation, code, count, null); } + public void recovered(String operation, String code, Long count) { record("recovered", operation, code, count, null); } + public void degraded(String operation, String code) { degraded(operation, code, null); } + public void recovered(String operation, String code) { recovered(operation, code, null); } + + static boolean token(String value, int maximum) { + return value != null && value.length() > 0 && value.length() <= maximum && value.matches("[A-Za-z0-9._:/\\-$]+"); + } + + static String requestOperationId(String operationId, Object requestId) { + if (token(operationId, 128)) return operationId; + String fallback = requestId instanceof String ? (String) requestId : null; + if (requestId instanceof Number) { + double number = ((Number) requestId).doubleValue(); + if (Double.isFinite(number) && Math.abs(number) <= MAX_INTEGER && number == Math.rint(number)) { + fallback = Long.toString(((Number) requestId).longValue()); + } + } + return token(fallback, 128) ? fallback : null; + } + + void terminal(String operation, Throwable failure, long started) { + String code = null; + if (failure != null) { + Throwable error = Backend.unwrap(failure); + code = error instanceof PluginError ? ((PluginError) error).code() : "internal_error"; + } + record(failure == null ? "operationFinished" : "operationFailed", operation, code, null, + Math.min(MAX_INTEGER, Math.max(0, (System.nanoTime() - started) / 1000000))); + } + + private void record(String kind, String operation, String code, Long count, Long duration) { + if (!backend.loggingOperation(operation)) throw new PluginSdkError("sdk.logging.invalidOperation", "Diagnostics need a registered operation."); + if (code != null && !token(code, 64)) throw new PluginSdkError("sdk.logging.invalidCode", "Diagnostics need a controlled code."); + if (count != null && (count < 0 || count > MAX_INTEGER)) throw new PluginSdkError("sdk.logging.invalidCount", "Diagnostics need a nonnegative safe count."); + Map params = new LinkedHashMap<>(); + params.put("kind", kind); + params.put("operation", operation.length() <= 64 ? operation : "function-call"); + if (code != null) params.put("code", code); + if (count != null) params.put("count", count); + if (duration != null) params.put("durationMs", duration); + if (token(operationId, 128)) params.put("operationId", operationId); + backend.logFact(params); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java new file mode 100644 index 0000000..36f76f6 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java @@ -0,0 +1,138 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * LSP base-protocol framing: {@code Content-Length} headers followed by a UTF-8 + * JSON body. Lithe talks to every plugin backend this way, so the SDK owns the + * framing and plugin code never writes to stdout itself. + */ +public final class Framing { + /** Largest header block accepted from the host. */ + static final int MAX_HEADER_BYTES = 8192; + + /** Largest body accepted from the host. Larger frames end the session. */ + public static final int MAX_FRAME_BYTES = 64 * 1024 * 1024; + + /** Stands for a body that is not JSON; compared by identity, so no host message can mimic it. */ + public static final Object MALFORMED = new Object() { + @Override + public String toString() { + return "MALFORMED"; + } + }; + + private static final byte[] HEADER_END = {'\r', '\n', '\r', '\n'}; + + private Framing() {} + + /** A framing error the session cannot recover from. */ + public static final class FramingException extends RuntimeException { + private static final long serialVersionUID = 1L; + + FramingException(String message) { + super(message); + } + } + + /** Encodes one JSON-RPC message as a complete frame. */ + public static byte[] encode(Object message) { + byte[] body = Json.stringify(message).getBytes(StandardCharsets.UTF_8); + byte[] header = ("Content-Length: " + body.length + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII); + byte[] frame = Arrays.copyOf(header, header.length + body.length); + System.arraycopy(body, 0, frame, header.length, body.length); + return frame; + } + + /** Incrementally splits a byte stream into decoded JSON-RPC messages. */ + public static final class Decoder { + private byte[] buffer = new byte[8192]; + private int length; + + /** + * Appends {@code count} bytes of {@code chunk} and returns every complete + * message they finished. A body that is not JSON is returned as + * {@link #MALFORMED} so the caller can report it without losing the + * framing position. + */ + public List push(byte[] chunk, int offset, int count) { + ensureCapacity(length + count); + System.arraycopy(chunk, offset, buffer, length, count); + length += count; + List messages = new ArrayList<>(); + int start = 0; + for (;;) { + int headerEnd = indexOfHeaderEnd(start); + int available = length - start; + // The same bound whether the header arrived whole or in pieces. + if ((headerEnd >= 0 && headerEnd - start > MAX_HEADER_BYTES) + || (headerEnd < 0 && available > MAX_HEADER_BYTES)) { + throw new FramingException("The message header is too long."); + } + if (headerEnd < 0) { + break; + } + int bodyLength = contentLength(new String(buffer, start, headerEnd - start, StandardCharsets.US_ASCII)); + int bodyStart = headerEnd + HEADER_END.length; + if ((long) length < (long) bodyStart + bodyLength) { + break; + } + String body = new String(buffer, bodyStart, bodyLength, StandardCharsets.UTF_8); + start = bodyStart + bodyLength; + try { + messages.add(Json.parse(body)); + } catch (Json.JsonException error) { + messages.add(MALFORMED); + } + } + if (start > 0) { + System.arraycopy(buffer, start, buffer, 0, length - start); + length -= start; + } + return messages; + } + + private int indexOfHeaderEnd(int from) { + for (int index = from; index + HEADER_END.length <= length; index++) { + if (buffer[index] == '\r' && buffer[index + 1] == '\n' + && buffer[index + 2] == '\r' && buffer[index + 3] == '\n') { + return index; + } + } + return -1; + } + + private void ensureCapacity(int required) { + if (required > buffer.length) { + buffer = Arrays.copyOf(buffer, Math.max(required, buffer.length * 2)); + } + } + } + + private static int contentLength(String header) { + for (String line : header.split("\r\n")) { + int separator = line.indexOf(':'); + if (separator < 0) { + continue; + } + if (!line.substring(0, separator).trim().equalsIgnoreCase("content-length")) { + continue; + } + String value = line.substring(separator + 1).trim(); + if (!value.matches("[0-9]+")) { + break; + } + // More than ten digits exceeds the limit whatever they are. + long length = value.length() > 10 ? Long.MAX_VALUE : Long.parseLong(value); + if (length > MAX_FRAME_BYTES) { + throw new FramingException("A message of " + value + " bytes exceeds the " + + MAX_FRAME_BYTES + "-byte limit."); + } + return (int) length; + } + throw new FramingException("A message has no valid Content-Length header."); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java new file mode 100644 index 0000000..5e67d63 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -0,0 +1,520 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.function.BooleanSupplier; + +/** + * Host services ({@code lithe/host/*}) of plugin-function protocols 2 and 3: + * credentials from version 2; workspace contexts, files, documents, the + * editor, previews, the browser, messages, and capability discovery from + * version 3. Every method answers with a future and never blocks; failures + * the host reports arrive as {@link HostError}. + * + *

{@link Backend#host()} is usable once the session is ready. A handler's + * {@link CallContext#host()} belongs to its call: requests still unanswered + * when the call is cancelled or ends fail with {@link CancelledException} and, + * from version 3, are cancelled on the wire. At most 16 requests are on the + * wire at once; the rest wait their turn. + * + *

Contract: {@code contract/v1/README.md}, "Host services". + */ +public final class Host { + /** Receives a subscription's events, one at a time and in order. */ + @FunctionalInterface + public interface Listener { + void onEvent(Event event) throws Exception; + } + + /** One {@code lithe/host/subscriptions/notify}. */ + public static final class Event { + private final String subscriptionId; + private final long sequence; + private final boolean gap; + private final Object event; + + Event(String subscriptionId, long sequence, boolean gap, Object event) { + this.subscriptionId = subscriptionId; + this.sequence = sequence; + this.gap = gap; + this.event = event; + } + + public String subscriptionId() { + return subscriptionId; + } + + /** Starts at 1 and grows by one per event of the subscription. */ + public long sequence() { + return sequence; + } + + /** + * True when events before this one were lost, so state built from + * earlier events should be refreshed, for example by rescanning. + */ + public boolean gap() { + return gap; + } + + /** The event, usually an object. */ + public Object event() { + return event; + } + } + + /** A host subscription, such as a file watch or registered editor actions. */ + public static final class Subscription { + private final String id; + private final BooleanSupplier live; + private final HostChannel channel; + + Subscription(String id, BooleanSupplier live, HostChannel channel) { + this.id = id; + this.live = live; + this.channel = channel; + } + + public String id() { + return id; + } + + /** True once disposed here or the session ended. */ + public boolean isDisposed() { + return !live.getAsBoolean(); + } + + /** Stops routing events at once and asks the host to dispose the subscription. */ + public CompletableFuture dispose() { + return channel.dispose(id); + } + } + + private final HostChannel channel; + private final List scope; + private final Credentials credentials = new Credentials(); + private final Subscriptions subscriptions = new Subscriptions(); + private final Workspace workspace = new Workspace(); + private final Documents documents = new Documents(); + private final Editor editor = new Editor(); + private final Preview preview = new Preview(); + private final Browser browser = new Browser(); + private final Window window = new Window(); + + Host(HostChannel channel, List scope) { + this.channel = channel; + this.scope = Collections.unmodifiableList(new ArrayList<>(scope)); + } + + /** The negotiated plugin-function version, or 0 before or without one. */ + public int version() { + return channel.version(); + } + + /** + * The same services, with requests also cancelled by {@code cancellation}, + * for work a plugin may stop for its own reasons. + */ + public Host withCancellation(Cancellation cancellation) { + if (cancellation == null) { + throw new IllegalArgumentException("A cancellation must not be null."); + } + List combined = new ArrayList<>(scope); + combined.add(cancellation); + return new Host(channel, combined); + } + + /** + * Sends any {@code lithe/host/*} request, including methods a later host + * adds; {@link #supports} says whether the session may call it. + */ + public CompletableFuture request(String method, Object params) { + return channel.request(method, params, scope); + } + + /** + * Sends a request that answers {@code { subscriptionID }} and routes the + * subscription's events to {@code listener}. + */ + public CompletableFuture subscribe(String method, Object params, Listener listener) { + return channel.subscribe(method, params, listener, scope); + } + + /** + * {@code { protocolVersion, backendAuthority, services, limits }}, asked + * once per session; needs protocol 3. + */ + public CompletableFuture> capabilities() { + return channel.capabilities(); + } + + /** + * Whether this session may call {@code method}: from {@link #capabilities} + * on protocol 3, the credential methods on protocol 2. + */ + public CompletableFuture supports(String method) { + return channel.supports(method); + } + + public Credentials credentials() { + return credentials; + } + + public Subscriptions subscriptions() { + return subscriptions; + } + + public Workspace workspace() { + return workspace; + } + + public Documents documents() { + return documents; + } + + public Editor editor() { + return editor; + } + + public Preview preview() { + return preview; + } + + public Browser browser() { + return browser; + } + + public Terminal terminal() { + return new Terminal(); + } + + public Window window() { + return window; + } + + /** + * {@code { contextID, generation }} of a context reference or of a full + * context from {@code listContexts} or {@code getContext}, so either can be + * passed on. + * + * @throws PluginSdkError {@code sdk.host.invalidContext} for anything else + */ + public static Map contextReference(Map context) { + Object id = context == null ? null : context.get("contextID"); + Object generation = context == null ? null : context.get("generation"); + if (!(id instanceof String) || !Protocol.isCredentialKey((String) id) || !Protocol.isGeneration(generation)) { + throw new PluginSdkError("sdk.host.invalidContext", + "A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\", and a positive generation."); + } + Map reference = new LinkedHashMap<>(); + reference.put("contextID", id); + reference.put("generation", ((Number) generation).longValue()); + return Collections.unmodifiableMap(reference); + } + + /** Secrets in the operating system's credential store, scoped to the plugin (protocol 2). */ + public final class Credentials { + private Credentials() {} + + /** The stored secret, or null when nothing is stored under {@code key}. */ + public CompletableFuture get(String key) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + return channel.request(Protocol.HOST_CREDENTIALS_GET, params("key", key), scope).thenApply(result -> { + if (result == null) { + return null; + } + Object secret = result instanceof Map ? ((Map) result).get("secret") : null; + if (!(secret instanceof String)) { + throw new PluginSdkError("sdk.host.invalidResult", "The host answered credentials/get without a secret."); + } + return (String) secret; + }); + } + + public CompletableFuture set(String key, String secret) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length > Protocol.MAX_CREDENTIAL_SECRET_BYTES) { + return failed(new PluginSdkError("sdk.credentials.invalidSecret", "A secret is a string of at most 16 KiB.")); + } + Map params = params("key", key); + params.put("secret", secret); + return channel.request(Protocol.HOST_CREDENTIALS_SET, params, scope).thenApply(result -> null); + } + + /** Deletes the secret; also succeeds when nothing was stored. */ + public CompletableFuture delete(String key) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + return channel.request(Protocol.HOST_CREDENTIALS_DELETE, params("key", key), scope).thenApply(result -> null); + } + } + + public final class Subscriptions { + private Subscriptions() {} + + /** Disposes a subscription by ID; also succeeds for an unknown or disposed one. */ + public CompletableFuture dispose(String subscriptionId) { + return channel.dispose(subscriptionId); + } + } + + /** + * Workspace contexts and files (protocol 3). Every method but + * {@link #listContexts} names a context: a reference from + * {@link CallContext#workspaceContext()}, or a context from + * {@link #listContexts}. + */ + public final class Workspace { + private Workspace() {} + + /** {@code { revision, contexts }}. */ + public CompletableFuture> listContexts() { + return object(Protocol.HOST_WORKSPACE_LIST_CONTEXTS, channel.request( + Protocol.HOST_WORKSPACE_LIST_CONTEXTS, new LinkedHashMap(), scope)); + } + + public CompletableFuture> getContext(Map context) { + return scoped(Protocol.HOST_WORKSPACE_GET_CONTEXT, context, null); + } + + /** {@code { folders }}. */ + public CompletableFuture> getFolders(Map context) { + return scoped(Protocol.HOST_WORKSPACE_GET_FOLDERS, context, null); + } + + /** {@code params}: {@code resource, cursor?, limit?}. */ + public CompletableFuture> readDirectory(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_READ_DIRECTORY, context, params); + } + + /** {@code params}: {@code resource}. */ + public CompletableFuture> stat(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_STAT, context, params); + } + + /** {@code params}: {@code resource, maximumBytes?}. */ + public CompletableFuture> readFile(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_READ_FILE, context, params); + } + + /** + * Watches {@code resource, recursive?}; events are + * {@code { rootID, changedPaths, requiresRescan }}. + */ + public CompletableFuture watch(Map context, Map params, Listener listener) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return channel.subscribe(Protocol.HOST_WORKSPACE_WATCH, message, listener, scope); + } + + /** {@code params}: root {@code resource, query, fileMask?, cursor?, limit?}. */ + public CompletableFuture> findFiles(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_FIND_FILES, context, params); + } + + /** {@code params}: root {@code resource, pattern}, and optional search options. */ + public CompletableFuture> findText(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_FIND_TEXT, context, params); + } + } + + /** Open documents, read from their live buffers (protocol 3). */ + public final class Documents { + private Documents() {} + + /** {@code { documents }}. */ + public CompletableFuture> list(Map context) { + return scoped(Protocol.HOST_DOCUMENTS_LIST, context, null); + } + + /** {@code params}: {@code documentID}; answers {@code { document, text }}. */ + public CompletableFuture> getSnapshot(Map context, Map params) { + return scoped(Protocol.HOST_DOCUMENTS_GET_SNAPSHOT, context, params); + } + } + + /** The text editor (protocol 3). */ + public final class Editor { + private Editor() {} + + /** The foreground text tab's document summary, or null. */ + public CompletableFuture> getActive(Map context) { + return scoped(Protocol.HOST_EDITOR_GET_ACTIVE, context, null); + } + + /** {@code params}: {@code documentID}. */ + public CompletableFuture> getSelections(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_GET_SELECTIONS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, edits}. */ + public CompletableFuture> applyEdits(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_APPLY_EDITS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, selections, replacements}. */ + public CompletableFuture> replaceSelections(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_REPLACE_SELECTIONS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, at, text}. */ + public CompletableFuture> insertText(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_INSERT_TEXT, context, params); + } + + /** {@code params}: {@code resource, activation?, range?, tab?}. */ + public CompletableFuture> open(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_OPEN, context, params); + } + + /** {@code params}: {@code resource, activation?, range?, tab?}. */ + public CompletableFuture> reveal(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_REVEAL, context, params); + } + + /** + * Registers editor actions ({@code id, function, selector}) that invoke + * one of the backend's functions; disposing the subscription removes them. + */ + public CompletableFuture registerActions(Map context, Map params) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return channel.subscribe(Protocol.HOST_EDITOR_REGISTER_ACTIONS, message, null, scope); + } + } + + /** HTML previews (protocol 3). */ + public final class Preview { + private Preview() {} + + /** {@code params}: HTML {@code resource, presentation?, range?}. */ + public CompletableFuture> openHtml(Map context, Map params) { + return scoped(Protocol.HOST_PREVIEW_OPEN_HTML, context, params); + } + } + + /** The system browser (protocol 3). */ + public final class Browser { + private Browser() {} + + /** {@code params}: exactly one of an HTTP(S) {@code url} or an HTML {@code resource}. */ + public CompletableFuture> openExternal(Map context, Map params) { + return scoped(Protocol.HOST_BROWSER_OPEN_EXTERNAL, context, params); + } + } + + /** Native terminals private to the backend session and workspace (protocol 3). */ + public final class Terminal { + private Terminal() {} + /** Params: executable, arguments?, title?, cwd?, environment?, show?. */ + public CompletableFuture> create(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_CREATE, context, params); + } + public CompletableFuture> show(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_SHOW, context, params); + } + public CompletableFuture> close(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_CLOSE, context, params); + } + /** Restarts the saved argv, restoring only the chosen plain display suffix. */ + public CompletableFuture> reopen(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_REOPEN, context, params); + } + /** Forgets the handle and its retained display history. */ + public CompletableFuture> dispose(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_DISPOSE, context, params); + } + /** Params: terminalID; disposing the subscription does not close the terminal. */ + public CompletableFuture onExit(Map context, Map params) { + Map message; + try { message = withContext(context, params); } + catch (PluginSdkError error) { return failed(error); } + return channel.subscribe(Protocol.HOST_TERMINAL_ON_EXIT, message, null, scope); + } + } + + /** + * Messages in the window (protocol 3). {@code params}: {@code text, + * actions?}; answers {@code { selectedIndex }}, null on dismissal. + */ + public final class Window { + private Window() {} + + public CompletableFuture> showInformation(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_INFORMATION, context, params); + } + + public CompletableFuture> showWarning(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_WARNING, context, params); + } + + public CompletableFuture> showError(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_ERROR, context, params); + } + } + + /** A method whose params name a workspace context. */ + private CompletableFuture> scoped(String method, Map context, Map params) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return object(method, channel.request(method, message, scope)); + } + + private static Map withContext(Map context, Map params) { + Map message = params == null ? new LinkedHashMap() : new LinkedHashMap(params); + message.put("context", contextReference(context)); + return message; + } + + /** The result as an object, or null; anything else is a host bug. */ + private static CompletableFuture> object(String method, CompletableFuture response) { + return response.thenApply(result -> { + if (result == null) { + return null; + } + if (!(result instanceof Map)) { + throw new PluginSdkError("sdk.host.invalidResult", method + " answered with something other than an object."); + } + return Json.object(result); + }); + } + + private static Map params(String key, Object value) { + Map params = new LinkedHashMap<>(); + params.put(key, value); + return params; + } + + private static PluginSdkError invalidKey() { + return new PluginSdkError("sdk.credentials.invalidKey", + "A credential key is 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\"."); + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java new file mode 100644 index 0000000..274fbd4 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java @@ -0,0 +1,504 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.RejectedExecutionException; + +/** + * The session's host-request state for plugin-function protocols 2 and 3. The + * backend owns the wire; this class owns what Core expects of a well-behaved + * client -- at most 16 unanswered host requests, cancellation through + * {@code $/cancelRequest} from version 3, and subscription events routed by + * ID, in order, off the reader thread. + * + *

Contract: {@code contract/v1/README.md}, "Host services (protocol + * version 2)" and the version 3 sections after it. + */ +final class HostChannel { + /** Events kept for a subscription whose creating request is still unanswered. */ + static final int MAX_EARLY_EVENTS = 128; + + /** The backend's wire. */ + interface Transport { + /** The negotiated plugin-function version, or 0 before or without one. */ + int version(); + + boolean ready(); + + /** Writes a request; its response settles when the host answers or the session ends. */ + Sent send(String method, Object params); + + void notify(String method, Object params); + + void log(String message); + + void log(String message, Throwable error); + + /** Runs plugin code off the reader thread. */ + void execute(Runnable task); + } + + /** A request on the wire. */ + static final class Sent { + final String id; + final CompletableFuture response; + + Sent(String id, CompletableFuture response) { + this.id = id; + this.response = response; + } + } + + private enum State { QUEUED, SENDING, SENT } + + /** One host request; settles for its caller once. */ + private static final class Entry { + final String method; + final Object params; + final CompletableFuture future = new CompletableFuture<>(); + final List registrations = new ArrayList<>(); + State state = State.QUEUED; + boolean settled; + /** Cancelled while being written: {@code $/cancelRequest} follows the write. */ + boolean cancelAfterWrite; + String id; + + Entry(String method, Object params) { + this.method = method; + this.params = params; + } + } + + /** A live subscription. */ + private static final class Route { + final String id; + final Host.Listener listener; + final ArrayDeque pending = new ArrayDeque<>(); + volatile boolean live = true; + long lastSequence; + boolean draining; + + Route(String id, Host.Listener listener) { + this.id = id; + this.listener = listener; + } + + boolean isLive() { + return live; + } + } + + private static final class Early { + final String subscriptionId; + final long sequence; + final Object event; + + Early(String subscriptionId, long sequence, Object event) { + this.subscriptionId = subscriptionId; + this.sequence = sequence; + this.event = event; + } + } + + private final Transport transport; + private final Object lock = new Object(); + private final ArrayDeque queue = new ArrayDeque<>(); + private final Map routes = new HashMap<>(); + private final List early = new ArrayList<>(); + private int inFlight; + /** Subscribing requests not yet answered; early events wait only while there are some. */ + private int subscribing; + private CompletableFuture> capabilities; + private boolean closed; + + HostChannel(Transport transport) { + this.transport = transport; + } + + int version() { + return transport.version(); + } + + /** + * Sends {@code method} once a slot is free. Cancelling any of + * {@code scope} rejects the caller at once with {@link CancelledException}; + * a request already sent is cancelled on the wire from version 3, and never + * sent again, because a cancelled mutation may already have taken effect. + */ + CompletableFuture request(String method, Object params, List scope) { + if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { + return failed(new PluginSdkError("sdk.host.method", + method + " is not a host method; host requests are lithe/host/*.")); + } + if (!open()) { + return failed(notReady()); + } + if (transport.version() < Protocol.HOST_SERVICES_VERSION) { + // The answer Core would give, without the round trip. + return failed(unavailable(method, + "The host did not negotiate plugin-function protocol 2 or later, which offers host services.")); + } + for (Cancellation cancellation : scope) { + try { + cancellation.throwIfCancelled(); + } catch (CancelledException error) { + return failed(error); + } + } + Entry entry = new Entry(method, params); + synchronized (lock) { + if (closed || !transport.ready()) { + return failed(notReady()); + } + queue.add(entry); + } + for (Cancellation cancellation : scope) { + Cancellation.Registration registration = cancellation.onCancel(() -> cancel(entry, cancellation)); + boolean settled; + synchronized (lock) { + settled = entry.settled; + if (!settled) { + entry.registrations.add(registration); + } + } + if (settled) { + registration.remove(); + } + } + drain(); + return entry.future; + } + + /** + * Sends a request whose result is {@code { subscriptionID }} and routes + * that subscription's events to {@code listener}, one at a time and in the + * order the host sent them. + */ + CompletableFuture subscribe(String method, Object params, Host.Listener listener, + List scope) { + synchronized (lock) { + subscribing++; + } + return request(method, params, scope).handle((result, error) -> { + try { + if (error != null) { + throw new CompletionException(Backend.unwrap(error)); + } + Object id = result instanceof Map ? ((Map) result).get("subscriptionID") : null; + if (!(id instanceof String) || !Protocol.isCredentialKey((String) id)) { + throw new PluginSdkError("sdk.host.invalidResult", method + " answered without a subscriptionID."); + } + String subscriptionId = (String) id; + Route route = new Route(subscriptionId, listener); + synchronized (lock) { + if (closed) { + throw new PluginSdkError("sdk.session.closed", "The session ended."); + } + routes.put(subscriptionId, route); + // Events the host sent before this answer was read. + for (Iterator events = early.iterator(); events.hasNext();) { + Early event = events.next(); + if (event.subscriptionId.equals(subscriptionId)) { + events.remove(); + emit(route, event.sequence, event.event); + } + } + } + return new Host.Subscription(subscriptionId, route::isLive, this); + } finally { + synchronized (lock) { + subscribing--; + if (subscribing == 0) { + early.clear(); + } + } + } + }); + } + + /** Stops routing a subscription's events at once and asks the host to dispose it. */ + CompletableFuture dispose(String subscriptionId) { + synchronized (lock) { + Route route = routes.remove(subscriptionId); + if (route != null) { + route.live = false; + route.pending.clear(); + } + if (closed || !transport.ready()) { + return CompletableFuture.completedFuture(null); + } + } + Map params = new LinkedHashMap<>(); + params.put("subscriptionID", subscriptionId); + return request(Protocol.HOST_SUBSCRIPTIONS_DISPOSE, params, Collections.emptyList()) + .thenApply(result -> null); + } + + /** Routes one {@code lithe/host/subscriptions/notify}. */ + void deliver(Map params) { + Object id = params.get("subscriptionID"); + if (!(id instanceof String)) { + return; + } + Object number = params.get("sequence"); + long sequence = number instanceof Number ? ((Number) number).longValue() : 0; + synchronized (lock) { + Route route = routes.get(id); + if (route != null) { + emit(route, sequence, params.get("event")); + } else if (subscribing > 0) { + if (early.size() < MAX_EARLY_EVENTS) { + early.add(new Early((String) id, sequence, params.get("event"))); + } else { + transport.log("Dropped an early subscription event: queue_full"); + } + } + // Otherwise the subscription was disposed; nothing follows a disposal. + } + } + + /** The cached {@code getCapabilities} answer; Core answers it itself, from version 3. */ + CompletableFuture> capabilities() { + if (transport.version() < Protocol.CONTEXT_VERSION) { + return failed(unavailable(Protocol.HOST_GET_CAPABILITIES, + "Capability discovery needs plugin-function protocol 3.")); + } + CompletableFuture> answer; + synchronized (lock) { + if (capabilities != null) { + return capabilities.thenApply(result -> result); + } + answer = new CompletableFuture<>(); + capabilities = answer; + } + request(Protocol.HOST_GET_CAPABILITIES, null, Collections.emptyList()).whenComplete((result, error) -> { + if (error == null && result instanceof Map) { + answer.complete(Collections.unmodifiableMap(Json.object(result))); + return; + } + synchronized (lock) { + if (capabilities == answer) { + capabilities = null; + } + } + answer.completeExceptionally(error != null ? Backend.unwrap(error) + : new PluginSdkError("sdk.host.invalidResult", "getCapabilities answered without an object.")); + }); + return answer.thenApply(result -> result); + } + + /** + * Whether this session may call {@code method}. From version 3 the answer + * comes from {@code getCapabilities}; version 2 has no discovery, so it + * reports the methods version 2 defines, and a missing grant still fails + * the request. + */ + CompletableFuture supports(String method) { + if (transport.version() >= Protocol.CONTEXT_VERSION) { + return capabilities().thenApply(answer -> { + Object services = answer.get("services"); + if (!(services instanceof Map)) { + return false; + } + for (Object service : ((Map) services).values()) { + Object methods = service instanceof Map ? ((Map) service).get("methods") : null; + if (methods instanceof List && ((List) methods).contains(method)) { + return true; + } + } + return false; + }); + } + return CompletableFuture.completedFuture(transport.version() >= Protocol.HOST_SERVICES_VERSION + && (Protocol.HOST_CREDENTIALS_GET.equals(method) + || Protocol.HOST_CREDENTIALS_SET.equals(method) + || Protocol.HOST_CREDENTIALS_DELETE.equals(method))); + } + + /** Ends the channel with the session: queued requests fail, subscriptions end. */ + void close() { + List queued; + synchronized (lock) { + closed = true; + queued = new ArrayList<>(queue); + queue.clear(); + for (Route route : routes.values()) { + route.live = false; + route.pending.clear(); + } + routes.clear(); + early.clear(); + capabilities = null; + } + for (Entry entry : queued) { + settle(entry, null, new PluginSdkError("sdk.session.closed", "The session ended.")); + } + } + + private void drain() { + List starting = new ArrayList<>(); + synchronized (lock) { + while (!closed && inFlight < Protocol.MAX_PENDING_HOST_REQUESTS && !queue.isEmpty()) { + Entry entry = queue.poll(); + entry.state = State.SENDING; + inFlight++; + starting.add(entry); + } + } + for (Entry entry : starting) { + start(entry); + } + } + + /** Writes outside the lock, so a full pipe never blocks the reader thread's routing. */ + private void start(Entry entry) { + Sent sent; + try { + sent = transport.send(entry.method, entry.params); + } catch (RuntimeException error) { + // Params JSON cannot encode never reached the wire. + synchronized (lock) { + inFlight--; + } + settle(entry, null, error); + drain(); + return; + } + boolean cancelNow; + synchronized (lock) { + entry.id = sent.id; + entry.state = State.SENT; + cancelNow = entry.cancelAfterWrite; + } + if (cancelNow) { + transport.notify(Protocol.CANCEL_REQUEST, Collections.singletonMap("id", sent.id)); + } + sent.response.whenComplete((result, error) -> { + synchronized (lock) { + // The slot frees when Core answers, also after a cancellation: + // from version 3 Core answers it at once, before version 3 the + // host still finishes the request. + inFlight--; + } + settle(entry, result, error == null ? null : Backend.unwrap(error)); + drain(); + }); + } + + private void cancel(Entry entry, Cancellation cancellation) { + String id = null; + synchronized (lock) { + if (entry.settled) { + return; + } + if (entry.state == State.QUEUED) { + queue.remove(entry); + } else if (transport.version() >= Protocol.CONTEXT_VERSION) { + if (entry.state == State.SENDING) { + entry.cancelAfterWrite = true; + } else { + id = entry.id; + } + } + } + if (id != null) { + transport.notify(Protocol.CANCEL_REQUEST, Collections.singletonMap("id", id)); + } + settle(entry, null, new CancelledException(cancellation.reason())); + } + + /** Completes the caller's future once, on a handler thread. */ + private void settle(Entry entry, Object result, Throwable error) { + List registrations; + synchronized (lock) { + if (entry.settled) { + return; + } + entry.settled = true; + registrations = new ArrayList<>(entry.registrations); + entry.registrations.clear(); + } + for (Cancellation.Registration registration : registrations) { + registration.remove(); + } + Runnable complete = () -> { + if (error != null) { + entry.future.completeExceptionally(error); + } else { + entry.future.complete(result); + } + }; + try { + transport.execute(complete); + } catch (RejectedExecutionException ended) { + complete.run(); + } + } + + /** Queues one event; called with the lock held. */ + private void emit(Route route, long sequence, Object event) { + boolean gap = sequence != route.lastSequence + 1; + route.lastSequence = sequence; + route.pending.add(new Host.Event(route.id, sequence, gap, event)); + if (route.draining) { + return; + } + route.draining = true; + try { + transport.execute(() -> run(route)); + } catch (RejectedExecutionException ended) { + route.draining = false; + route.pending.clear(); + } + } + + /** Hands a subscription's events to its listener one at a time. */ + private void run(Route route) { + while (true) { + Host.Event event; + synchronized (lock) { + event = route.live ? route.pending.poll() : null; + if (event == null) { + route.draining = false; + route.pending.clear(); + return; + } + } + try { + if (route.listener != null) { + route.listener.onEvent(event); + } + } catch (Throwable error) { + transport.log("A subscription listener failed:", error); + } + } + } + + private boolean open() { + synchronized (lock) { + return !closed && transport.ready(); + } + } + + private static PluginSdkError notReady() { + return new PluginSdkError("sdk.session.notReady", "The session is not initialized."); + } + + private static HostError unavailable(String method, String message) { + return new HostError("plugin.host.unavailable", message, Protocol.METHOD_NOT_FOUND, null, method); + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java new file mode 100644 index 0000000..dbd452c --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java @@ -0,0 +1,96 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The host refused or failed a request this backend sent. {@link #code()} is + * the stable {@code error.data.code}, such as {@code plugin.host.contextExpired}; + * {@link #rpcCode()} the JSON-RPC number; {@link #details()} the object a + * version 3 host may add, such as {@code { option }} or + * {@code { retryAfterMilliseconds }}. + */ +public final class HostError extends PluginSdkError { + private static final long serialVersionUID = 1L; + + /** + * Stable host failure codes of plugin-function protocol 3 and their + * JSON-RPC numbers. A later host adds codes after {@code -32021}. + */ + public static final Map CODES; + private static final Map BY_RPC_CODE; + + static { + Map codes = new LinkedHashMap<>(); + codes.put("plugin.host.unavailable", -32601); + codes.put("plugin.host.invalidParams", -32602); + codes.put("plugin.host.failed", -32603); + codes.put("plugin.host.cancelled", -32800); + codes.put("plugin.host.permissionDenied", -32010); + codes.put("plugin.host.contextExpired", -32011); + codes.put("plugin.host.authorityUnsupported", -32012); + codes.put("plugin.host.versionConflict", -32013); + codes.put("plugin.host.limitExceeded", -32014); + codes.put("plugin.host.timeout", -32015); + codes.put("plugin.host.notFound", -32016); + codes.put("plugin.host.readOnly", -32017); + codes.put("plugin.host.unsupportedOption", -32018); + codes.put("plugin.host.preconditionFailed", -32019); + codes.put("plugin.host.busy", -32020); + codes.put("plugin.host.rateLimited", -32021); + CODES = Collections.unmodifiableMap(codes); + Map byNumber = new HashMap<>(); + for (Map.Entry entry : codes.entrySet()) { + byNumber.put(entry.getValue(), entry.getKey()); + } + BY_RPC_CODE = Collections.unmodifiableMap(byNumber); + } + + private final transient Map details; + private final String method; + + public HostError(String code, String message, Integer rpcCode, Map details, String method) { + super(code, message, rpcCode); + this.details = details == null ? null : Collections.unmodifiableMap(new LinkedHashMap<>(details)); + this.method = method; + } + + /** The failure's {@code error.data.details}, or null when the host sent none. */ + public Map details() { + return details; + } + + /** The request that failed. */ + public String method() { + return method; + } + + /** + * The failure for a JSON-RPC error answer. A host method without a known + * code is a host failure: from version 3 a number names one code, and an + * unknown number is {@code plugin.host.failed}. + */ + static HostError fromResponse(String method, Map error) { + Object data = error.get("data"); + Map fields = data instanceof Map ? Json.object(data) : Collections.emptyMap(); + Object rpcCode = error.get("code"); + Integer number = rpcCode instanceof Number && ((Number) rpcCode).doubleValue() == ((Number) rpcCode).intValue() + ? ((Number) rpcCode).intValue() + : null; + String code = Json.string(fields, "code"); + if (code == null) { + if (method.startsWith(Protocol.HOST_PREFIX)) { + String known = number == null ? null : BY_RPC_CODE.get(number); + code = known == null ? "plugin.host.failed" : known; + } else { + code = "sdk.host.error"; + } + } + Object details = fields.get("details"); + String text = Json.string(error, "message"); + return new HostError(code, text == null ? method + " failed." : text, number, + details instanceof Map ? Json.object(details) : null, method); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java new file mode 100644 index 0000000..64ff3f5 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java @@ -0,0 +1,426 @@ +package io.github.litheidea.plugin.sdk; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Minimal JSON reader and writer for protocol messages and stored state. + * + *

The SDK carries its own codec so that a plugin can shade it next to any + * JSON library without version conflicts. Values map to plain Java types: + * objects to {@code Map} (insertion-ordered), arrays to + * {@code List}, strings to {@code String}, booleans to + * {@code Boolean}, {@code null} to {@code null}, integers to {@code Long} (or + * {@code BigInteger} beyond its range), and other numbers to {@code Double}. + */ +public final class Json { + /** Deeper input is refused instead of overflowing the reader's stack. */ + private static final int MAX_DEPTH = 512; + + private Json() {} + + /** A value that is not JSON, or one JSON cannot represent. */ + public static final class JsonException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public JsonException(String message) { + super(message); + } + } + + /** Parses one JSON document; trailing content other than whitespace is an error. */ + public static Object parse(String text) { + Reader reader = new Reader(text); + reader.skipWhitespace(); + Object value = reader.value(0); + reader.skipWhitespace(); + if (reader.position != text.length()) { + throw reader.error("Unexpected content after the value"); + } + return value; + } + + /** + * Encodes {@code value}. Maps need string keys; numbers must be finite. + * Arrays of objects and any {@link Collection} encode as JSON arrays. + */ + public static String stringify(Object value) { + StringBuilder output = new StringBuilder(); + write(output, value, 0); + return output.toString(); + } + + /** {@code value} as an object, or an empty map when it is {@code null}. */ + @SuppressWarnings("unchecked") + public static Map object(Object value) { + if (value == null) { + return new LinkedHashMap<>(); + } + if (value instanceof Map) { + return (Map) value; + } + throw new JsonException("Expected a JSON object."); + } + + /** The string at {@code key}, or {@code null} when it is missing or not a string. */ + public static String string(Map object, String key) { + Object value = object.get(key); + return value instanceof String ? (String) value : null; + } + + private static void write(StringBuilder output, Object value, int depth) { + if (depth > MAX_DEPTH) { + throw new JsonException("The value is nested too deeply, or contains itself."); + } + if (value == null) { + output.append("null"); + } else if (value instanceof String || value instanceof Character) { + quote(output, value.toString()); + } else if (value instanceof Boolean) { + output.append(value.toString()); + } else if (value instanceof Double || value instanceof Float) { + output.append(decimal(((Number) value).doubleValue())); + } else if (value instanceof Long || value instanceof Integer || value instanceof Short + || value instanceof Byte || value instanceof BigInteger) { + output.append(value.toString()); + } else if (value instanceof BigDecimal) { + output.append(((BigDecimal) value).toString()); + } else if (value instanceof Map) { + output.append('{'); + boolean first = true; + for (Map.Entry entry : ((Map) value).entrySet()) { + if (!(entry.getKey() instanceof String)) { + throw new JsonException("Object keys must be strings."); + } + if (!first) { + output.append(','); + } + first = false; + quote(output, (String) entry.getKey()); + output.append(':'); + write(output, entry.getValue(), depth + 1); + } + output.append('}'); + } else if (value instanceof Collection) { + writeArray(output, ((Collection) value).toArray(), depth); + } else if (value instanceof Object[]) { + writeArray(output, (Object[]) value, depth); + } else { + throw new JsonException("A " + value.getClass().getName() + " is not a JSON value."); + } + } + + private static void writeArray(StringBuilder output, Object[] values, int depth) { + output.append('['); + for (int index = 0; index < values.length; index++) { + if (index > 0) { + output.append(','); + } + write(output, values[index], depth + 1); + } + output.append(']'); + } + + private static String decimal(double value) { + if (Double.isNaN(value) || Double.isInfinite(value)) { + throw new JsonException("JSON has no representation for " + value + "."); + } + // Integral values print without a fraction, as JavaScript prints them. + if (value == Math.rint(value) && Math.abs(value) < 1e15) { + return Long.toString((long) value); + } + return Double.toString(value); + } + + private static void quote(StringBuilder output, String text) { + output.append('"'); + for (int index = 0; index < text.length(); index++) { + char character = text.charAt(index); + switch (character) { + case '"': + output.append("\\\""); + break; + case '\\': + output.append("\\\\"); + break; + case '\n': + output.append("\\n"); + break; + case '\r': + output.append("\\r"); + break; + case '\t': + output.append("\\t"); + break; + case '\b': + output.append("\\b"); + break; + case '\f': + output.append("\\f"); + break; + default: + if (character < 0x20 || isLoneSurrogate(text, index)) { + // A lone surrogate has no UTF-8 encoding; escaping it + // keeps the frame valid, as JSON.stringify does. + output.append(String.format("\\u%04x", (int) character)); + } else { + output.append(character); + } + } + } + output.append('"'); + } + + private static boolean isLoneSurrogate(String text, int index) { + char character = text.charAt(index); + if (Character.isHighSurrogate(character)) { + return index + 1 >= text.length() || !Character.isLowSurrogate(text.charAt(index + 1)); + } + if (Character.isLowSurrogate(character)) { + return index == 0 || !Character.isHighSurrogate(text.charAt(index - 1)); + } + return false; + } + + private static final class Reader { + private final String text; + private int position; + + Reader(String text) { + this.text = text; + } + + Object value(int depth) { + if (depth > MAX_DEPTH) { + throw error("The document is nested too deeply"); + } + if (position >= text.length()) { + throw error("Unexpected end of input"); + } + char character = text.charAt(position); + switch (character) { + case '{': + return object(depth); + case '[': + return array(depth); + case '"': + return string(); + case 't': + return literal("true", Boolean.TRUE); + case 'f': + return literal("false", Boolean.FALSE); + case 'n': + return literal("null", null); + default: + if (character == '-' || (character >= '0' && character <= '9')) { + return number(); + } + throw error("Unexpected character"); + } + } + + private Map object(int depth) { + Map result = new LinkedHashMap<>(); + position++; + skipWhitespace(); + if (peek() == '}') { + position++; + return result; + } + for (;;) { + skipWhitespace(); + if (peek() != '"') { + throw error("Expected a property name"); + } + String key = string(); + skipWhitespace(); + expect(':'); + skipWhitespace(); + result.put(key, value(depth + 1)); + skipWhitespace(); + char next = peek(); + position++; + if (next == '}') { + return result; + } + if (next != ',') { + throw error("Expected ',' or '}'"); + } + } + } + + private List array(int depth) { + List result = new ArrayList<>(); + position++; + skipWhitespace(); + if (peek() == ']') { + position++; + return result; + } + for (;;) { + skipWhitespace(); + result.add(value(depth + 1)); + skipWhitespace(); + char next = peek(); + position++; + if (next == ']') { + return result; + } + if (next != ',') { + throw error("Expected ',' or ']'"); + } + } + } + + private String string() { + position++; + StringBuilder result = new StringBuilder(); + for (;;) { + if (position >= text.length()) { + throw error("Unterminated string"); + } + char character = text.charAt(position++); + if (character == '"') { + return result.toString(); + } + if (character < 0x20) { + throw error("Control character in string"); + } + if (character != '\\') { + result.append(character); + continue; + } + if (position >= text.length()) { + throw error("Unterminated escape"); + } + char escape = text.charAt(position++); + switch (escape) { + case '"': + case '\\': + case '/': + result.append(escape); + break; + case 'b': + result.append('\b'); + break; + case 'f': + result.append('\f'); + break; + case 'n': + result.append('\n'); + break; + case 'r': + result.append('\r'); + break; + case 't': + result.append('\t'); + break; + case 'u': + if (position + 4 > text.length()) { + throw error("Incomplete unicode escape"); + } + int code = 0; + for (int index = 0; index < 4; index++) { + int digit = Character.digit(text.charAt(position++), 16); + if (digit < 0) { + throw error("Invalid unicode escape"); + } + code = code * 16 + digit; + } + result.append((char) code); + break; + default: + throw error("Invalid escape"); + } + } + } + + private Object number() { + int start = position; + if (peek() == '-') { + position++; + } + if (peek() == '0') { + position++; + } else if (isDigit(peek())) { + digits(); + } else { + throw error("Invalid number"); + } + boolean integral = true; + if (peek() == '.') { + integral = false; + position++; + if (!isDigit(peek())) { + throw error("Invalid number"); + } + digits(); + } + if (peek() == 'e' || peek() == 'E') { + integral = false; + position++; + if (peek() == '+' || peek() == '-') { + position++; + } + if (!isDigit(peek())) { + throw error("Invalid number"); + } + digits(); + } + String literal = text.substring(start, position); + if (integral) { + BigInteger value = new BigInteger(literal); + return value.bitLength() < 64 ? (Object) value.longValue() : value; + } + return Double.parseDouble(literal); + } + + private void digits() { + while (isDigit(peek())) { + position++; + } + } + + private Object literal(String word, Object value) { + if (!text.startsWith(word, position)) { + throw error("Unexpected literal"); + } + position += word.length(); + return value; + } + + private void expect(char character) { + if (peek() != character) { + throw error("Expected '" + character + "'"); + } + position++; + } + + private char peek() { + return position < text.length() ? text.charAt(position) : '\0'; + } + + void skipWhitespace() { + while (position < text.length()) { + char character = text.charAt(position); + if (character != ' ' && character != '\t' && character != '\n' && character != '\r') { + return; + } + position++; + } + } + + JsonException error(String message) { + return new JsonException(message + " at offset " + position + "."); + } + + private static boolean isDigit(char character) { + return character >= '0' && character <= '9'; + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java new file mode 100644 index 0000000..c7e83b3 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java @@ -0,0 +1,38 @@ +package io.github.litheidea.plugin.sdk; + +/** + * A failure a handler reports on purpose. Core ends the call with the stable + * {@code plugin.function.failed} code and forwards {@link #code()} as + * {@code pluginErrorCode}, so the plugin's own UI can tell its failures apart. + * Lithe never branches on it. + * + *

The message is shown to the user as written (Core keeps its first 1024 + * bytes), so it must not contain stack traces or machine paths. + */ +public class PluginError extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + + /** + * @param code identifier of at most 64 bytes, such as {@code maven.snapshotLocked} + * @param message user-facing text + */ + public PluginError(String code, String message) { + this(code, message, null); + } + + /** As {@link #PluginError(String, String)}; {@code cause} stays in memory, outside automatic diagnostics. */ + public PluginError(String code, String message, Throwable cause) { + super(message, cause); + if (!Protocol.isPluginErrorCode(code)) { + throw new IllegalArgumentException("Plugin error code \"" + code + + "\" must start with a letter, use letters, digits, \".\", \"_\" or \"-\", and be at most 64 bytes."); + } + this.code = code; + } + + public String code() { + return code; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java new file mode 100644 index 0000000..043ba52 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java @@ -0,0 +1,32 @@ +package io.github.litheidea.plugin.sdk; + +/** + * An SDK usage error raised to the plugin author, or a failure the host + * reported for a request this backend sent. {@link #rpcCode()} carries the + * host's JSON-RPC error code in the latter case. + */ +public class PluginSdkError extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + private final Integer rpcCode; + + public PluginSdkError(String code, String message) { + this(code, message, null); + } + + public PluginSdkError(String code, String message, Integer rpcCode) { + super(message); + this.code = code; + this.rpcCode = rpcCode; + } + + public String code() { + return code; + } + + /** The host's JSON-RPC error code, or {@code null} for a local usage error. */ + public Integer rpcCode() { + return rpcCode; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java new file mode 100644 index 0000000..6764cca --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java @@ -0,0 +1,629 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Child processes a backend starts for one call. + * + *

Lithe's host offers no process capability in protocol version 1, so a + * backend runs its tools itself; this helper makes sure that the call ending, + * cancelling it, or the backend shutting down also ends the tools it started. + * + *

Process trees: on macOS and Linux every tool leads its own process group, + * as in the Node SDK, on every Java version. Java has no API for that, so the + * tool starts through the system {@code perl}, which calls {@code setpgrp} and + * then replaces itself with the tool, keeping its PID. A stop signals the whole + * group, and once the tool exits on its own the members it left behind, such + * as a background worker, are killed too; descendants that leave the group + * with {@code setsid} are out of reach. Windows, and a system without + * {@code perl}, fall back to {@code ProcessHandle} on Java 9 and newer, found + * by reflection so the SDK still loads on Java 8; it reaches only the + * descendants still attached to the tool. Lithe starts every backend inside + * its own process scope ({@code LITHE_PLUGIN_BACKEND_SCOPE}) and ends whatever + * is left of it when the session ends; that remains the final boundary. + */ +public final class Processes { + /** + * Variables Lithe sets on the backend so it can find and end every process + * the backend started, even one that left its parent. A tool always + * inherits them, also when the plugin replaces the environment. + */ + static final String[] HOST_MARKERS = {"LITHE_PROCESS_SCOPE", "LITHE_PLUGIN_BACKEND_SCOPE"}; + + /** Every tool started through {@link #run} that has not exited or been stopped. */ + private static final Set RUNNING = Collections.newSetFromMap(new ConcurrentHashMap<>()); + + private static final ScheduledExecutorService TIMERS = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, "lithe-sdk-process-timer"); + thread.setDaemon(true); + return thread; + }); + + private static final ProcessTree TREE = ProcessTree.load(); + + private static final ProcessGroups GROUPS = ProcessGroups.load(); + + private Processes() {} + + /** Options of one {@link #run}; every setter returns this object. */ + public static final class Options { + private Path directory; + private Map environment; + private Cancellation cancellation; + private int maxOutputBytes = 1 << 20; + private long killGraceMillis = 2000; + private Consumer onStdout; + private Consumer onStderr; + private Runnable listenerFailure = () -> {}; + + /** Working directory; defaults to the backend's. */ + public Options directory(Path value) { + directory = value; + return this; + } + + /** Replaces the environment; the host's process markers are carried over regardless. */ + public Options environment(Map value) { + environment = value; + return this; + } + + /** Cancelling it stops the tool and makes {@link #run} throw {@link CancelledException}. */ + public Options cancellation(Cancellation value) { + cancellation = value; + return this; + } + + /** Captured bytes per stream; default 1 MiB. Listeners still see everything. */ + public Options maxOutputBytes(int value) { + maxOutputBytes = value; + return this; + } + + /** Delay between the polite and the forced stop; default 2000. */ + public Options killGraceMillis(long value) { + killGraceMillis = value; + return this; + } + + /** Receives stdout as it arrives, decoded as UTF-8 without splitting characters. */ + public Options onStdout(Consumer value) { + onStdout = value; + return this; + } + + /** Receives stderr as it arrives, decoded as UTF-8 without splitting characters. */ + public Options onStderr(Consumer value) { + onStderr = value; + return this; + } + + Options listenerFailure(Runnable value) { listenerFailure = value; return this; } + + Cancellation cancellation() { + return cancellation; + } + + Options copy() { + Options copy = new Options(); + copy.directory = directory; + copy.environment = environment; + copy.cancellation = cancellation; + copy.maxOutputBytes = maxOutputBytes; + copy.killGraceMillis = killGraceMillis; + copy.onStdout = onStdout; + copy.onStderr = onStderr; + copy.listenerFailure = listenerFailure; + return copy; + } + } + + /** Exit status and captured output of a tool. */ + public static final class Result { + private final int exitCode; + private final String stdout; + private final String stderr; + private final boolean truncated; + + Result(int exitCode, String stdout, String stderr, boolean truncated) { + this.exitCode = exitCode; + this.stdout = stdout; + this.stderr = stderr; + this.truncated = truncated; + } + + /** The exit code; on POSIX a tool ended by signal N reports 128 + N. */ + public int exitCode() { + return exitCode; + } + + public String stdout() { + return stdout; + } + + public String stderr() { + return stderr; + } + + /** True when either stream exceeded {@code maxOutputBytes}. */ + public boolean truncated() { + return truncated; + } + } + + /** + * Runs {@code command} without a shell and returns its exit status and + * captured output. A non-zero exit returns normally; the caller decides + * what it means for its tool. Cancellation stops the tool and throws + * {@link CancelledException} once it ended. + */ + public static Result run(List command, Options options) throws IOException { + Options settings = options == null ? new Options() : options; + Cancellation cancellation = settings.cancellation; + if (cancellation != null) { + cancellation.throwIfCancelled(); + } + if (command.isEmpty()) { + throw new IllegalArgumentException("A command needs an executable."); + } + ProcessBuilder builder = new ProcessBuilder(new ArrayList<>(command)); + if (settings.directory != null) { + builder.directory(settings.directory.toFile()); + } + if (settings.environment != null) { + Map environment = builder.environment(); + environment.clear(); + environment.putAll(settings.environment); + for (String name : HOST_MARKERS) { + String value = System.getenv(name); + if (value == null) { + environment.remove(name); + } else { + environment.put(name, value); + } + } + } + boolean grouped = GROUPS.available(); + if (grouped) { + builder.command(GROUPS.launcher(command, builder.environment())); + } + Process process = builder.start(); + // Tools get no input; an open pipe would let one wait on it forever. + process.getOutputStream().close(); + Running entry = new Running(process, grouped ? GROUPS.leader(process) : 0); + RUNNING.add(entry); + Capture stdout = new Capture(process.getInputStream(), settings.maxOutputBytes, settings.onStdout, "stdout", settings.listenerFailure); + Capture stderr = new Capture(process.getErrorStream(), settings.maxOutputBytes, settings.onStderr, "stderr", settings.listenerFailure); + Cancellation.Registration registration = cancellation == null + ? () -> {} + : cancellation.onCancel(() -> entry.stop(settings.killGraceMillis)); + int exitCode; + try { + exitCode = waitFor(process, entry); + registration.remove(); + // The tool ended on its own; what it left running, such as a + // background worker, ends with it. A stopped tool stays registered + // until its forced stop, which reaches the same members. + entry.endLeftovers(); + // A descendant out of reach can keep the inherited pipes open after + // the tool exited; the output then ends at the grace period. + stdout.join(settings.killGraceMillis); + stderr.join(settings.killGraceMillis); + } finally { + registration.remove(); + if (!entry.stopping()) { + RUNNING.remove(entry); + } + } + if (cancellation != null) { + cancellation.throwIfCancelled(); + } + String errors = stderr.text(); + if (grouped && exitCode == ProcessGroups.EXEC_FAILED && errors.startsWith(ProcessGroups.EXEC_FAILURE)) { + // The launcher could not start the tool; report it as ProcessBuilder would. + throw new IOException("Cannot run program \"" + command.get(0) + "\": " + + errors.substring(ProcessGroups.EXEC_FAILURE.length()).trim()); + } + return new Result(exitCode, stdout.text(), errors, stdout.truncated() || stderr.truncated()); + } + + /** Runs {@code command} with default options. */ + public static Result run(List command) throws IOException { + return run(command, null); + } + + /** + * Forcibly ends every tool still running. The backend calls it on shutdown, + * on {@code exit}, and when the host closes stdin, so no tool outlives the + * session that started it. + */ + public static void killAll() { + for (Running entry : new ArrayList<>(RUNNING)) { + entry.forceStop(); + } + RUNNING.clear(); + } + + /** Number of tools still running or being stopped, for tests and diagnostics. */ + public static int runningCount() { + return RUNNING.size(); + } + + private static int waitFor(Process process, Running entry) { + boolean interrupted = false; + try { + for (;;) { + try { + return process.waitFor(); + } catch (InterruptedException error) { + // The tool still belongs to this call; end it before giving + // the interrupt back to the caller. + interrupted = true; + entry.forceStop(); + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + /** One started tool and its stop state. */ + private static final class Running { + private final Process process; + /** The tool's process group, or 0 when it has none of its own. */ + private final long group; + private final Object lock = new Object(); + private boolean stopping; + private List tree = Collections.emptyList(); + private ScheduledFuture forceTimer; + + Running(Process process, long group) { + this.process = process; + this.group = group; + } + + /** Kills what the tool left after exiting on its own, unless a stop owns that. */ + void endLeftovers() { + synchronized (lock) { + if (stopping) { + return; + } + } + if (group > 0) { + // While any member lives the group ID cannot be reused, so this + // reaches only what this tool started; an empty group is ignored. + GROUPS.signal(group, true); + } else { + // Windows keeps the parent link of an exited tool, so its + // descendants are still found there. + TREE.destroy(TREE.descendants(process), true); + } + } + + boolean stopping() { + synchronized (lock) { + return stopping; + } + } + + /** Asks the tree to stop, then forces it after {@code graceMillis}. */ + void stop(long graceMillis) { + synchronized (lock) { + if (stopping) { + return; + } + stopping = true; + if (group > 0) { + GROUPS.signal(group, false); + } else { + // Descendants are listed before the tool is signalled: once + // it exits they are reparented and no longer reachable from it. + tree = TREE.descendants(process); + TREE.destroy(tree, false); + } + // Also covers a tool that has not formed its group yet. + process.destroy(); + forceTimer = TIMERS.schedule(this::forceStop, graceMillis, TimeUnit.MILLISECONDS); + } + } + + void forceStop() { + List known; + synchronized (lock) { + stopping = true; + if (forceTimer != null) { + forceTimer.cancel(false); + } + known = new ArrayList<>(tree); + if (group <= 0) { + known.addAll(TREE.descendants(process)); + } + } + if (group > 0) { + GROUPS.signal(group, true); + } + TREE.destroy(known, true); + process.destroyForcibly(); + RUNNING.remove(this); + } + } + + /** Reads one output stream on its own thread, keeping at most {@code limit} bytes. */ + private static final class Capture { + private final ByteArrayOutputStream kept = new ByteArrayOutputStream(); + private final InputStream input; + private final int limit; + private final Consumer listener; + private final Runnable listenerFailure; + private final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE); + private final Thread thread; + private volatile boolean truncated; + + Capture(InputStream input, int limit, Consumer listener, String name, Runnable listenerFailure) { + this.listenerFailure = listenerFailure; + this.input = input; + this.limit = limit; + this.listener = listener; + thread = new Thread(this::read, "lithe-sdk-" + name); + thread.setDaemon(true); + thread.start(); + } + + private void read() { + byte[] chunk = new byte[8192]; + // Holds a multi-byte character split across reads until it is whole. + ByteBuffer pending = ByteBuffer.allocate(chunk.length + 8); + try { + int count; + while ((count = input.read(chunk)) >= 0) { + synchronized (kept) { + int room = Math.max(0, limit - kept.size()); + kept.write(chunk, 0, Math.min(room, count)); + if (count > room) { + truncated = true; + } + } + if (listener != null) { + pending.put(chunk, 0, count); + pending.flip(); + deliver(pending, false); + pending.compact(); + } + } + if (listener != null) { + pending.flip(); + deliver(pending, true); + } + } catch (IOException error) { + // The stream was closed after the grace period; what was read is kept. + } + } + + private void deliver(ByteBuffer bytes, boolean end) { + CharBuffer characters = CharBuffer.allocate(bytes.remaining() + 1); + decoder.decode(bytes, characters, end); + if (end) { + decoder.flush(characters); + } + characters.flip(); + if (characters.hasRemaining()) { + try { + listener.accept(characters.toString()); + } catch (RuntimeException error) { + listenerFailure.run(); + } + } + } + + void join(long millis) { + try { + thread.join(Math.max(1, millis)); + if (thread.isAlive()) { + input.close(); + thread.join(millis); + } + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } catch (IOException error) { + // Closing an output pipe that already failed changes nothing. + } + } + + String text() { + synchronized (kept) { + return new String(kept.toByteArray(), StandardCharsets.UTF_8); + } + } + + boolean truncated() { + return truncated; + } + } + + /** + * A process group per tool on macOS and Linux. The launcher is + * {@code perl -e SCRIPT -- command...}: it calls + * {@code setpgrp(0, 0)} and replaces itself with the tool, so the PID Java + * reports is the tool's and also its group ID. {@code PERL5OPT} would make + * perl load modules before the script runs, so it is withheld from perl and + * handed back to the tool. Signals go through {@code /bin/kill}, which + * Java 8 needs for a negative PID. + */ + private static final class ProcessGroups { + /** Exit code and stderr prefix of a launcher that could not start the tool. */ + static final int EXEC_FAILED = 127; + static final String EXEC_FAILURE = "lithe-sdk-exec-failed: "; + + private static final String SCRIPT = "my $has = shift; my $opt = shift;" + + " $ENV{PERL5OPT} = $opt if $has;" + + " setpgrp(0, 0);" + + " exec { $ARGV[0] } @ARGV;" + + " print STDERR '" + EXEC_FAILURE + "', \"$!\\n\"; exit " + EXEC_FAILED + ";"; + + /** A signal that has not run after this long is abandoned; the host scope remains. */ + private static final long SIGNAL_TIMEOUT_MILLIS = 2000; + + private final String perl; + private final String kill; + private final Method pid; + + private ProcessGroups(String perl, String kill, Method pid) { + this.perl = perl; + this.kill = kill; + this.pid = pid; + } + + static ProcessGroups load() { + if (System.getProperty("os.name", "").startsWith("Windows")) { + return new ProcessGroups(null, null, null); + } + Method pid; + try { + pid = Process.class.getMethod("pid"); + } catch (NoSuchMethodException error) { + // Java 8 keeps the PID in a private field of UNIXProcess. + pid = null; + } + return new ProcessGroups(executable("/usr/bin/perl", "/bin/perl"), + executable("/bin/kill", "/usr/bin/kill"), pid); + } + + private static String executable(String... candidates) { + for (String candidate : candidates) { + if (new File(candidate).canExecute()) { + return candidate; + } + } + return null; + } + + boolean available() { + return perl != null && kill != null; + } + + List launcher(List command, Map environment) { + String option = environment.remove("PERL5OPT"); + List launcher = new ArrayList<>(Arrays.asList(perl, "-e", SCRIPT, "--", + option == null ? "0" : "1", option == null ? "" : option)); + launcher.addAll(command); + return launcher; + } + + /** The tool's PID, which is its group ID; 0 when it cannot be read. */ + long leader(Process process) { + try { + if (pid != null) { + return ((Number) pid.invoke(process)).longValue(); + } + Field field = process.getClass().getDeclaredField("pid"); + field.setAccessible(true); + return field.getInt(process); + } catch (ReflectiveOperationException | RuntimeException error) { + return 0; + } + } + + /** Signals every member of {@code group}; an empty group is ignored. */ + void signal(long group, boolean forcibly) { + ProcessBuilder builder = new ProcessBuilder(kill, "-s", forcibly ? "KILL" : "TERM", "--", "-" + group); + File discard = new File("/dev/null"); + builder.redirectOutput(discard).redirectError(discard); + try { + Process signal = builder.start(); + signal.getOutputStream().close(); + if (!signal.waitFor(SIGNAL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { + signal.destroyForcibly(); + } + } catch (IOException error) { + // The host's process scope ends what this could not reach. + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } + } + } + + /** + * {@code ProcessHandle} through reflection: present from Java 9, absent on + * Java 8, where only the direct child can be stopped. + */ + private static final class ProcessTree { + private final Method descendants; + private final Method destroy; + private final Method destroyForcibly; + + private ProcessTree(Method descendants, Method destroy, Method destroyForcibly) { + this.descendants = descendants; + this.destroy = destroy; + this.destroyForcibly = destroyForcibly; + } + + static ProcessTree load() { + try { + Class handle = Class.forName("java.lang.ProcessHandle"); + return new ProcessTree( + Process.class.getMethod("descendants"), + handle.getMethod("destroy"), + handle.getMethod("destroyForcibly")); + } catch (ReflectiveOperationException error) { + return new ProcessTree(null, null, null); + } + } + + List descendants(Process process) { + if (descendants == null) { + return Collections.emptyList(); + } + try { + @SuppressWarnings("unchecked") + Stream stream = (Stream) descendants.invoke(process); + return stream.collect(Collectors.toList()); + } catch (ReflectiveOperationException | RuntimeException error) { + return Collections.emptyList(); + } + } + + void destroy(List handles, boolean forcibly) { + Method method = forcibly ? destroyForcibly : destroy; + if (method == null) { + return; + } + for (Object handle : handles) { + try { + method.invoke(handle); + } catch (ReflectiveOperationException | RuntimeException error) { + // The process already exited, or the platform refused; the + // host's process scope ends what is left. + } + } + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java new file mode 100644 index 0000000..c4e2ff8 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -0,0 +1,230 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Wire constants and validation shared with Lithe's Rust Core + * ({@code rust/lithe-core/src/lsp/interface/plugin_function.rs} in the Lithe + * repository) and the Node.js + * SDK. The SDK checks the same rules locally so a plugin author sees a mistake + * when registering a handler instead of as a refused session at runtime. + */ +public final class Protocol { + /** Protocol versions this SDK can answer: the highest of each. */ + public static final int FUNCTIONS_VERSION = 3; + public static final int BUILD_VERSION = 6; + + /** First plugin-function version with host services (credentials). */ + public static final int HOST_SERVICES_VERSION = 2; + /** First plugin-function version with workspace contexts, discovery, and host notifications. */ + public static final int CONTEXT_VERSION = 3; + + public static final String INITIALIZE = "initialize"; + public static final String INITIALIZED = "initialized"; + public static final String SHUTDOWN = "shutdown"; + public static final String EXIT = "exit"; + public static final String CANCEL_REQUEST = "$/cancelRequest"; + public static final String FUNCTION_INVOKE = "lithe/function/invoke"; + public static final String FUNCTION_REGISTER = "lithe/function/register"; + public static final String FUNCTION_UNREGISTER = "lithe/function/unregister"; + public static final String FUNCTION_PROGRESS = "lithe/function/progress"; + public static final String BUILD_MODEL = "lithe/build/model"; + public static final String BUILD_DEPENDENCIES = "lithe/build/dependencies"; + public static final String BUILD_EXECUTE = "lithe/build/execute"; + public static final String BUILD_TEST = "lithe/build/test"; + public static final String BUILD_DISCOVER_TESTS = "lithe/build/discoverTests"; + public static final String BUILD_PREPARE_DEBUG = "lithe/build/prepareDebug"; + public static final String BUILD_PREPARE_RUN = "lithe/build/prepareRun"; + public static final String BUILD_PROGRESS = "lithe/build/progress"; + + /** + * Backend-to-host requests of plugin-function protocols 2 and 3. From + * version 3 the host adds methods without a new version; + * {@link Host#request} sends any {@code lithe/host/*} method, and + * {@code getCapabilities} says which ones the session may call. + */ + public static final String HOST_TERMINAL_CREATE = "lithe/host/terminal/create"; + public static final String HOST_TERMINAL_SHOW = "lithe/host/terminal/show"; + public static final String HOST_TERMINAL_CLOSE = "lithe/host/terminal/close"; + public static final String HOST_TERMINAL_REOPEN = "lithe/host/terminal/reopen"; + public static final String HOST_TERMINAL_DISPOSE = "lithe/host/terminal/dispose"; + public static final String HOST_TERMINAL_ON_EXIT = "lithe/host/terminal/onExit"; + public static final String HOST_PREFIX = "lithe/host/"; + public static final String HOST_CREDENTIALS_GET = "lithe/host/credentials/get"; + public static final String HOST_CREDENTIALS_SET = "lithe/host/credentials/set"; + public static final String HOST_CREDENTIALS_DELETE = "lithe/host/credentials/delete"; + public static final String HOST_GET_CAPABILITIES = "lithe/host/getCapabilities"; + public static final String HOST_SUBSCRIPTIONS_DISPOSE = "lithe/host/subscriptions/dispose"; + public static final String HOST_WORKSPACE_LIST_CONTEXTS = "lithe/host/workspace/listContexts"; + public static final String HOST_WORKSPACE_GET_CONTEXT = "lithe/host/workspace/getContext"; + public static final String HOST_WORKSPACE_GET_FOLDERS = "lithe/host/workspace/getFolders"; + public static final String HOST_WORKSPACE_READ_DIRECTORY = "lithe/host/workspace/readDirectory"; + public static final String HOST_WORKSPACE_STAT = "lithe/host/workspace/stat"; + public static final String HOST_WORKSPACE_READ_FILE = "lithe/host/workspace/readFile"; + public static final String HOST_WORKSPACE_WATCH = "lithe/host/workspace/watch"; + public static final String HOST_WORKSPACE_FIND_FILES = "lithe/host/workspace/findFiles"; + public static final String HOST_WORKSPACE_FIND_TEXT = "lithe/host/workspace/findText"; + public static final String HOST_DOCUMENTS_LIST = "lithe/host/documents/list"; + public static final String HOST_DOCUMENTS_GET_SNAPSHOT = "lithe/host/documents/getSnapshot"; + public static final String HOST_EDITOR_REGISTER_ACTIONS = "lithe/host/editor/registerActions"; + public static final String HOST_EDITOR_GET_ACTIVE = "lithe/host/editor/getActive"; + public static final String HOST_EDITOR_GET_SELECTIONS = "lithe/host/editor/getSelections"; + public static final String HOST_EDITOR_APPLY_EDITS = "lithe/host/editor/applyEdits"; + public static final String HOST_EDITOR_REPLACE_SELECTIONS = "lithe/host/editor/replaceSelections"; + public static final String HOST_EDITOR_INSERT_TEXT = "lithe/host/editor/insertText"; + public static final String HOST_EDITOR_OPEN = "lithe/host/editor/open"; + public static final String HOST_EDITOR_REVEAL = "lithe/host/editor/reveal"; + public static final String HOST_PREVIEW_OPEN_HTML = "lithe/host/preview/openHTML"; + public static final String HOST_BROWSER_OPEN_EXTERNAL = "lithe/host/browser/openExternal"; + public static final String HOST_WINDOW_SHOW_INFORMATION = "lithe/host/window/showInformation"; + public static final String HOST_WINDOW_SHOW_WARNING = "lithe/host/window/showWarning"; + public static final String HOST_WINDOW_SHOW_ERROR = "lithe/host/window/showError"; + + /** Host-to-backend notifications of plugin-function protocol 3. */ + public static final String HOST_DID_CHANGE_CONTEXTS = "lithe/host/workspace/didChangeContexts"; + public static final String HOST_SUBSCRIPTION_NOTIFY = "lithe/host/subscriptions/notify"; + public static final String HOST_COMMAND_DID_RUN = "lithe/host/commands/didRun"; + + /** JSON-RPC and LSP error codes the SDK answers with. */ + public static final int PARSE_ERROR = -32700; + public static final int INVALID_REQUEST = -32600; + public static final int METHOD_NOT_FOUND = -32601; + public static final int INVALID_PARAMS = -32602; + public static final int INTERNAL_ERROR = -32603; + public static final int SERVER_NOT_INITIALIZED = -32002; + public static final int REQUEST_FAILED = -32000; + public static final int REQUEST_CANCELLED = -32800; + + public static final int MAX_FUNCTIONS = 256; + public static final int MAX_FUNCTION_ID_BYTES = 128; + public static final int MAX_PLUGIN_ERROR_CODE_BYTES = 64; + public static final int MAX_MESSAGE_BYTES = 1024; + public static final int MAX_RESULT_BYTES = 1 << 20; + public static final int MAX_BUILD_RESULT_BYTES = 32 * 1024 * 1024; + public static final int MAX_BUILD_MESSAGE_BYTES = 4096; + public static final int MAX_BUILD_OUTPUT_BYTES = 65536; + /** Unanswered host requests Core allows a session; the SDK queues the rest. */ + public static final int MAX_PENDING_HOST_REQUESTS = 16; + public static final int MAX_CREDENTIAL_SECRET_BYTES = 16 * 1024; + + /** Minimum negotiated version; unknown methods can never pass admission. */ + static int buildMethodVersion(String method) { + if (BUILD_MODEL.equals(method) || BUILD_DEPENDENCIES.equals(method)) return 1; + if (BUILD_EXECUTE.equals(method)) return 2; + if (BUILD_TEST.equals(method) || BUILD_DISCOVER_TESTS.equals(method)) return 3; + if (BUILD_PREPARE_DEBUG.equals(method)) return 5; + if (BUILD_PREPARE_RUN.equals(method)) return 4; + return Integer.MAX_VALUE; + } + + static boolean buildProgress(String method) { + return BUILD_EXECUTE.equals(method) || BUILD_TEST.equals(method) || BUILD_PREPARE_RUN.equals(method) || BUILD_PREPARE_DEBUG.equals(method); + } + + private static final Pattern FUNCTION_SEGMENT = Pattern.compile("[a-z][A-Za-z0-9]*"); + private static final Pattern PLUGIN_ERROR_CODE = Pattern.compile("[A-Za-z][A-Za-z0-9._-]*"); + private static final Pattern KEY = Pattern.compile("[A-Za-z0-9._:-]{1,128}"); + private static final Pattern COMMAND_ID = Pattern.compile("[a-z0-9.-]{1,128}"); + private static final long MAX_SAFE_INTEGER = 9007199254740991L; + + private Protocol() {} + + /** Dot-separated lowerCamelCase segments, for example {@code snapshot.refresh}. */ + public static boolean isFunctionId(String value) { + if (value == null || value.isEmpty() || utf8Length(value) > MAX_FUNCTION_ID_BYTES) { + return false; + } + for (String segment : value.split("\\.", -1)) { + if (!FUNCTION_SEGMENT.matcher(segment).matches()) { + return false; + } + } + return true; + } + + /** The plugin error code alphabet Core forwards as {@code pluginErrorCode}. */ + public static boolean isPluginErrorCode(String value) { + return value != null + && utf8Length(value) <= MAX_PLUGIN_ERROR_CODE_BYTES + && PLUGIN_ERROR_CODE.matcher(value).matches(); + } + + /** + * The key alphabet of protocols 2 and 3: 1-128 ASCII letters, digits, + * {@code .}, {@code _}, {@code :}, or {@code -}. Credential keys, context + * IDs, and subscription IDs use it. + */ + public static boolean isCredentialKey(String value) { + return value != null && KEY.matcher(value).matches(); + } + + /** {@code { contextID, generation }}, exactly, naming one generation of one workspace context. */ + public static boolean isContextReference(Object value) { + if (!(value instanceof Map) || ((Map) value).size() != 2) { + return false; + } + Map reference = (Map) value; + Object id = reference.get("contextID"); + return id instanceof String && isCredentialKey((String) id) && isGeneration(reference.get("generation")); + } + + /** A command ID from the plugin's manifest: 1-128 of {@code [a-z0-9.-]}. */ + public static boolean isCommandId(String value) { + return value != null && COMMAND_ID.matcher(value).matches(); + } + + /** A positive integer JSON can carry exactly. */ + static boolean isGeneration(Object value) { + if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) { + long number = ((Number) value).longValue(); + return number >= 1 && number <= MAX_SAFE_INTEGER; + } + if (value instanceof Double || value instanceof Float) { + double number = ((Number) value).doubleValue(); + return number >= 1 && number <= MAX_SAFE_INTEGER && number == Math.rint(number); + } + return false; + } + + /** Cuts {@code value} to {@link #MAX_MESSAGE_BYTES} UTF-8 bytes without splitting a character. */ + public static String boundedText(String value) { + return boundedText(value, MAX_MESSAGE_BYTES); + } + + /** Cuts {@code value} to {@code limit} UTF-8 bytes without splitting a character. */ + public static String boundedText(String value, int limit) { + String text = value == null ? "" : value; + int used = 0; + int index = 0; + while (index < text.length()) { + int codePoint = text.codePointAt(index); + int size = codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4; + if (used + size > limit) { + return text.substring(0, index); + } + used += size; + index += Character.charCount(codePoint); + } + return text; + } + + /** + * Methods reserved for the SDK. A plugin cannot install its own handler for + * these, or send them to the host: the lifecycle belongs to the host's + * session management, and {@code lithe/*} belongs to Lithe's typed contracts. + */ + public static boolean isReservedMethod(String method) { + return method.equals(INITIALIZE) + || method.equals(INITIALIZED) + || method.equals(SHUTDOWN) + || method.equals(EXIT) + || method.equals(CANCEL_REQUEST) + || method.startsWith("lithe/"); + } + + static int utf8Length(String value) { + return value.getBytes(StandardCharsets.UTF_8).length; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java new file mode 100644 index 0000000..24761e2 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java @@ -0,0 +1,198 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.CodeSource; +import java.security.SecureRandom; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Durable plugin state, in a directory the host gives the backend. + * + *

The host passes writable directories through the {@code ${stateDir}} and + * {@code ${workspaceStateDir}} launch variables; the installed package and the + * host's installation are read-only, because signatures and delta updates are + * computed over their exact bytes. Values are JSON; each key is one file + * replaced atomically, so a crash leaves either the old or the new value, + * never half of one. The envelope matches the Node.js SDK's, so either SDK + * reads what the other wrote. + */ +public final class StateStore { + /** Version of the envelope each value is stored in. */ + private static final int STORE_FORMAT = 1; + private static final Pattern KEY = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,127}"); + private static final SecureRandom RANDOM = new SecureRandom(); + + private final Path root; + + private StateStore(Path root) { + this.root = root; + } + + /** + * Opens a store in {@code directory}, creating the directory. Refuses a + * directory inside the plugin package, found as the nearest directory with + * a {@code plugin.json} above the JAR this class was loaded from. + * + * @param directory absolute path, normally the value of {@code ${workspaceStateDir}} + */ + public static StateStore open(Path directory) throws IOException { + return open(directory, findPackageDirectory()); + } + + /** + * Opens a store in {@code directory}, refusing one inside + * {@code packageDirectory}; null skips that check. + */ + public static StateStore open(Path directory, Path packageDirectory) throws IOException { + if (directory == null || !directory.isAbsolute()) { + throw new PluginSdkError("sdk.state.invalidDirectory", + "The state directory must be an absolute path passed by the host."); + } + // Checked before creating anything, so a refused path leaves the package untouched. + Path resolved = canonical(directory); + if (packageDirectory != null && resolved.startsWith(canonical(packageDirectory))) { + throw new PluginSdkError("sdk.state.readOnlyPackage", + "The state directory is inside the plugin package, which is read-only. Use ${stateDir} or ${workspaceStateDir}."); + } + Files.createDirectories(resolved); + return new StateStore(resolved); + } + + /** The resolved directory, for a backend that keeps its own files next to the store. */ + public Path directory() { + return root; + } + + /** The stored value, or {@code fallback} when the key is missing or unreadable. */ + public Object read(String key, Object fallback) { + Path path = path(key); + if (!Files.isRegularFile(path)) { + return fallback; + } + try { + Object envelope = Json.parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); + if (!(envelope instanceof Map)) { + return fallback; + } + Map fields = (Map) envelope; + Object format = fields.get("litheStateStore"); + if (!(format instanceof Number) || ((Number) format).doubleValue() != STORE_FORMAT + || !fields.containsKey("value")) { + return fallback; + } + return fields.get("value"); + } catch (IOException | RuntimeException error) { + return fallback; + } + } + + /** Stores {@code value}, which must be JSON-encodable, replacing the previous one. */ + public void write(String key, Object value) throws IOException { + Path path = path(key); + Map envelope = new LinkedHashMap<>(); + envelope.put("litheStateStore", STORE_FORMAT); + envelope.put("value", value); + byte[] body; + try { + body = Json.stringify(envelope).getBytes(StandardCharsets.UTF_8); + } catch (Json.JsonException error) { + // Refused before touching the file, so the stored value stays. + throw new PluginSdkError("sdk.state.invalidValue", "The value for " + key + " is not JSON-encodable."); + } + Path temporary = root.resolve(key + ".json." + Long.toHexString(RANDOM.nextLong()) + ".tmp"); + try { + createPrivate(temporary); + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + ByteBuffer buffer = ByteBuffer.wrap(body); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); + } + try { + Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException error) { + Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException | RuntimeException error) { + Files.deleteIfExists(temporary); + throw error; + } + } + + /** Removes the key; a missing key is not an error. */ + public void delete(String key) throws IOException { + Files.deleteIfExists(path(key)); + } + + private Path path(String key) { + if (key == null || !KEY.matcher(key).matches() || key.endsWith(".tmp")) { + throw new PluginSdkError("sdk.state.invalidKey", "State key \"" + key + + "\" must be 1-128 letters, digits, \".\", \"_\" or \"-\", start with a letter or digit, and not end with \".tmp\"."); + } + return root.resolve(key + ".json"); + } + + /** Creates an empty file only the user can read, where the platform supports it. */ + private static void createPrivate(Path file) throws IOException { + try { + Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + } catch (UnsupportedOperationException error) { + Files.createFile(file); + } catch (FileAlreadyExistsException error) { + throw new IOException("A temporary state file already exists: " + file.getFileName(), error); + } + } + + /** Resolves symbolic links of the longest existing prefix of {@code path}. */ + static Path canonical(Path path) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + Path existing = absolute; + while (existing != null && !Files.exists(existing)) { + existing = existing.getParent(); + } + if (existing == null) { + return absolute; + } + return existing.toRealPath().resolve(existing.relativize(absolute)); + } + + /** The nearest directory with a {@code plugin.json} above the JAR this class came from. */ + static Path findPackageDirectory() { + try { + CodeSource source = StateStore.class.getProtectionDomain().getCodeSource(); + URL location = source == null ? null : source.getLocation(); + if (location == null) { + return null; + } + Path current = Paths.get(location.toURI()).toAbsolutePath(); + if (Files.isRegularFile(current)) { + current = current.getParent(); + } + while (current != null) { + if (Files.isRegularFile(current.resolve("plugin.json"))) { + return current; + } + current = current.getParent(); + } + return null; + } catch (URISyntaxException | RuntimeException error) { + return null; + } + } +}