dsh-gufa-code 1.3.82 → 1.3.88
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/client.js +315 -49
- package/desktop/float/bin/gufa-float-macos-arm64 +0 -0
- package/desktop/float/bin/gufa-float-macos-universal +0 -0
- package/desktop/float/bin/gufa-float-macos-x64 +0 -0
- package/desktop/float//345/217/244/346/263/225/347/274/226/347/250/213/346/202/254/346/265/256/345/261/202.app/Contents/Info.plist +2 -2
- package/desktop/float//345/217/244/346/263/225/347/274/226/347/250/213/346/202/254/346/265/256/345/261/202.app/Contents/MacOS/gufa-float +0 -0
- package/docs/KNOWN-PITFALLS.md +15 -0
- package/host/fs.js +4 -0
- package/host/lsp.js +350 -0
- package/package.json +2 -1
- package/src/client/00-core.js +2 -0
- package/src/client/20-editor.js +312 -48
package/host/lsp.js
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 语言服务桥(LSP):给 IDE 的 Cmd/Ctrl+点击、悬停提供真正的语言级定义。
|
|
3
|
+
*
|
|
4
|
+
* 目前接 Pyright(Python):npm 依赖 `pyright`,Host 以子进程方式启动
|
|
5
|
+
* `node node_modules/pyright/langserver.index.js --stdio`,用 JSON-RPC over stdio
|
|
6
|
+
* 管理 initialize / didOpen / didChange / textDocument/definition,返回项目内
|
|
7
|
+
* 定义位置。浏览器侧不直连 LSP,而是通过 `lsp.definition` API 调用,避免在
|
|
8
|
+
* renderer 里再实现一遍 JSON-RPC。
|
|
9
|
+
*/
|
|
10
|
+
import { spawn } from 'node:child_process'
|
|
11
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
12
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
14
|
+
|
|
15
|
+
import { ApiError, badRequest } from './context.js'
|
|
16
|
+
|
|
17
|
+
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
18
|
+
|
|
19
|
+
/** root → session */
|
|
20
|
+
const sessions = new Map()
|
|
21
|
+
let installPromise = null
|
|
22
|
+
|
|
23
|
+
function pyrightEntry() {
|
|
24
|
+
return resolve(packageRoot, 'node_modules', 'pyright', 'langserver.index.js')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function fileExists(file) {
|
|
28
|
+
try {
|
|
29
|
+
await stat(file)
|
|
30
|
+
return true
|
|
31
|
+
} catch {
|
|
32
|
+
return false
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 缺依赖时按用户授权做一次自动安装(npm 依赖 pyright)。 */
|
|
37
|
+
async function ensurePyright() {
|
|
38
|
+
const entry = pyrightEntry()
|
|
39
|
+
if (await fileExists(entry)) return entry
|
|
40
|
+
if (installPromise === null) {
|
|
41
|
+
installPromise = (async () => {
|
|
42
|
+
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'
|
|
43
|
+
await new Promise((resolvePromise, rejectPromise) => {
|
|
44
|
+
const child = spawn(npm, ['install', 'pyright', '--no-audit', '--no-fund'], {
|
|
45
|
+
cwd: packageRoot,
|
|
46
|
+
env: process.env,
|
|
47
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
48
|
+
})
|
|
49
|
+
let stderr = ''
|
|
50
|
+
child.stderr?.on('data', (chunk) => { stderr += String(chunk) })
|
|
51
|
+
const timer = setTimeout(() => {
|
|
52
|
+
try { child.kill('SIGKILL') } catch { /* ignore */ }
|
|
53
|
+
rejectPromise(new Error('安装 pyright 超时(npm install)'))
|
|
54
|
+
}, 180000)
|
|
55
|
+
child.on('error', (error) => {
|
|
56
|
+
clearTimeout(timer)
|
|
57
|
+
rejectPromise(new Error(`无法执行 npm:${error.message}`))
|
|
58
|
+
})
|
|
59
|
+
child.on('exit', (code) => {
|
|
60
|
+
clearTimeout(timer)
|
|
61
|
+
if (code === 0) resolvePromise()
|
|
62
|
+
else rejectPromise(new Error(`npm install pyright 失败(exit ${code}):${stderr.slice(-400)}`))
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
if (!(await fileExists(entry))) throw new Error('pyright 安装完成但找不到 langserver.index.js')
|
|
66
|
+
return entry
|
|
67
|
+
})().finally(() => { installPromise = null })
|
|
68
|
+
}
|
|
69
|
+
return await installPromise
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
class JsonRpcClient {
|
|
73
|
+
constructor(child, root, name) {
|
|
74
|
+
this.child = child
|
|
75
|
+
this.root = root
|
|
76
|
+
this.name = name
|
|
77
|
+
this.buffer = Buffer.alloc(0)
|
|
78
|
+
this.nextId = 1
|
|
79
|
+
this.pending = new Map()
|
|
80
|
+
this.stderr = ''
|
|
81
|
+
this.closed = false
|
|
82
|
+
child.stdout.on('data', (chunk) => this.onData(chunk))
|
|
83
|
+
child.stderr?.on('data', (chunk) => {
|
|
84
|
+
this.stderr += String(chunk)
|
|
85
|
+
if (this.stderr.length > 16000) this.stderr = this.stderr.slice(-8000)
|
|
86
|
+
})
|
|
87
|
+
child.on('exit', (code) => {
|
|
88
|
+
this.closed = true
|
|
89
|
+
const failure = new ApiError('lsp-exited', `语言服务进程已退出(code ${code})${this.stderr.slice(-300)}`, 500)
|
|
90
|
+
for (const entry of this.pending.values()) entry.reject(failure)
|
|
91
|
+
this.pending.clear()
|
|
92
|
+
})
|
|
93
|
+
child.on('error', (error) => {
|
|
94
|
+
this.closed = true
|
|
95
|
+
const failure = new ApiError('lsp-error', `语言服务进程错误:${error.message}`, 500)
|
|
96
|
+
for (const entry of this.pending.values()) entry.reject(failure)
|
|
97
|
+
this.pending.clear()
|
|
98
|
+
})
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
onData(chunk) {
|
|
102
|
+
this.buffer = Buffer.concat([this.buffer, chunk])
|
|
103
|
+
for (;;) {
|
|
104
|
+
const headerEnd = this.buffer.indexOf('\r\n\r\n')
|
|
105
|
+
if (headerEnd < 0) return
|
|
106
|
+
const header = this.buffer.subarray(0, headerEnd).toString('utf8')
|
|
107
|
+
const lengthMatch = /content-length:\s*(\d+)/i.exec(header)
|
|
108
|
+
if (lengthMatch === null) {
|
|
109
|
+
this.buffer = this.buffer.subarray(headerEnd + 4)
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
const length = Number(lengthMatch[1])
|
|
113
|
+
const total = headerEnd + 4 + length
|
|
114
|
+
if (this.buffer.length < total) return
|
|
115
|
+
const body = this.buffer.subarray(headerEnd + 4, total).toString('utf8')
|
|
116
|
+
this.buffer = this.buffer.subarray(total)
|
|
117
|
+
let message = null
|
|
118
|
+
try {
|
|
119
|
+
message = JSON.parse(body)
|
|
120
|
+
} catch {
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
this.dispatch(message)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
dispatch(message) {
|
|
128
|
+
if (message === null || typeof message !== 'object') return
|
|
129
|
+
if (typeof message.id === 'number' && (message.result !== undefined || message.error !== undefined)) {
|
|
130
|
+
const entry = this.pending.get(message.id)
|
|
131
|
+
if (entry === undefined) return
|
|
132
|
+
this.pending.delete(message.id)
|
|
133
|
+
clearTimeout(entry.timer)
|
|
134
|
+
if (message.error !== undefined) entry.reject(new ApiError('lsp-error', String(message.error?.message ?? '语言服务返回错误'), 500))
|
|
135
|
+
else entry.resolve(message.result ?? null)
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
if (typeof message.method === 'string' && message.id !== undefined) {
|
|
139
|
+
/* 服务端 → 客户端请求 */
|
|
140
|
+
let result = null
|
|
141
|
+
if (message.method === 'workspace/configuration') {
|
|
142
|
+
const items = Array.isArray(message.params?.items) ? message.params.items : []
|
|
143
|
+
result = items.map(() => null)
|
|
144
|
+
} else if (message.method === 'workspace/workspaceFolders') {
|
|
145
|
+
result = [{ uri: pathToFileURL(this.root).href, name: this.root.split(sep).filter(Boolean).at(-1) ?? 'workspace' }]
|
|
146
|
+
} else if (message.method === 'client/registerCapability' || message.method === 'window/workDoneProgress/create') {
|
|
147
|
+
result = null
|
|
148
|
+
}
|
|
149
|
+
this.send({ jsonrpc: '2.0', id: message.id, result })
|
|
150
|
+
return
|
|
151
|
+
}
|
|
152
|
+
/* 通知:忽略,但要消费 */
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
send(message) {
|
|
156
|
+
if (this.closed) return
|
|
157
|
+
try {
|
|
158
|
+
const body = JSON.stringify(message)
|
|
159
|
+
this.child.stdin.write(`Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`)
|
|
160
|
+
} catch {
|
|
161
|
+
/* broken pipe */
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
notify(method, params) {
|
|
166
|
+
this.send({ jsonrpc: '2.0', method, params })
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
request(method, params, timeoutMs = 20000) {
|
|
170
|
+
if (this.closed) return Promise.reject(new ApiError('lsp-exited', '语言服务进程已退出', 500))
|
|
171
|
+
const id = this.nextId++
|
|
172
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
173
|
+
const timer = setTimeout(() => {
|
|
174
|
+
this.pending.delete(id)
|
|
175
|
+
rejectPromise(new ApiError('lsp-timeout', `语言服务响应超时(${method})`, 504))
|
|
176
|
+
}, timeoutMs)
|
|
177
|
+
this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer })
|
|
178
|
+
this.send({ jsonrpc: '2.0', id, method, params })
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function inside(root, target) {
|
|
184
|
+
const rel = relative(root, target)
|
|
185
|
+
return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function startSession(root) {
|
|
189
|
+
const entry = await ensurePyright()
|
|
190
|
+
const child = spawn(process.execPath, [entry, '--stdio'], {
|
|
191
|
+
cwd: root,
|
|
192
|
+
env: { ...process.env, PYTHONUNBUFFERED: '1' },
|
|
193
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
194
|
+
})
|
|
195
|
+
const rpc = new JsonRpcClient(child, root, 'pyright')
|
|
196
|
+
const session = { root, child, rpc, ready: null, documents: new Map() }
|
|
197
|
+
session.ready = (async () => {
|
|
198
|
+
const rootUri = pathToFileURL(root).href
|
|
199
|
+
await rpc.request('initialize', {
|
|
200
|
+
processId: process.pid,
|
|
201
|
+
rootPath: root,
|
|
202
|
+
rootUri,
|
|
203
|
+
workspaceFolders: [{ uri: rootUri, name: root.split(sep).filter(Boolean).at(-1) ?? 'workspace' }],
|
|
204
|
+
capabilities: {
|
|
205
|
+
workspace: { workspaceFolders: true, configuration: true },
|
|
206
|
+
textDocument: {
|
|
207
|
+
synchronization: { dynamicRegistration: false, willSave: false, didSave: false },
|
|
208
|
+
definition: { linkSupport: true },
|
|
209
|
+
hover: { contentFormat: ['markdown', 'plaintext'] },
|
|
210
|
+
publishDiagnostics: { relatedInformation: false },
|
|
211
|
+
},
|
|
212
|
+
},
|
|
213
|
+
clientInfo: { name: 'gufa-code', version: '1.0.0' },
|
|
214
|
+
}, 30000)
|
|
215
|
+
rpc.notify('initialized', {})
|
|
216
|
+
return true
|
|
217
|
+
})()
|
|
218
|
+
session.ready.catch(() => {
|
|
219
|
+
try { child.kill('SIGKILL') } catch { /* ignore */ }
|
|
220
|
+
sessions.delete(root)
|
|
221
|
+
})
|
|
222
|
+
return session
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function getSession(root) {
|
|
226
|
+
let session = sessions.get(root)
|
|
227
|
+
if (session !== undefined && session.rpc.closed !== true) {
|
|
228
|
+
await session.ready
|
|
229
|
+
return session
|
|
230
|
+
}
|
|
231
|
+
if (session !== undefined) sessions.delete(root)
|
|
232
|
+
session = await startSession(root)
|
|
233
|
+
sessions.set(root, session)
|
|
234
|
+
await session.ready
|
|
235
|
+
return session
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function syncDocument(session, absolutePath, content) {
|
|
239
|
+
const uri = pathToFileURL(absolutePath).href
|
|
240
|
+
const existing = session.documents.get(uri)
|
|
241
|
+
if (existing === undefined) {
|
|
242
|
+
const document = { uri, version: 1, content }
|
|
243
|
+
session.documents.set(uri, document)
|
|
244
|
+
session.rpc.notify('textDocument/didOpen', {
|
|
245
|
+
textDocument: { uri, languageId: 'python', version: 1, text: content },
|
|
246
|
+
})
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
if (existing.content !== content) {
|
|
250
|
+
existing.version += 1
|
|
251
|
+
existing.content = content
|
|
252
|
+
session.rpc.notify('textDocument/didChange', {
|
|
253
|
+
textDocument: { uri, version: existing.version },
|
|
254
|
+
contentChanges: [{ text: content }],
|
|
255
|
+
})
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function normalizeLocations(root, result) {
|
|
260
|
+
const raw = Array.isArray(result) ? result : (result === null || result === undefined ? [] : [result])
|
|
261
|
+
const matches = []
|
|
262
|
+
const seen = new Set()
|
|
263
|
+
for (const item of raw) {
|
|
264
|
+
if (item === null || typeof item !== 'object') continue
|
|
265
|
+
const uri = typeof item.uri === 'string' ? item.uri : (typeof item.targetUri === 'string' ? item.targetUri : '')
|
|
266
|
+
const range = item.range !== null && typeof item.range === 'object' ? item.range : (item.targetRange ?? null)
|
|
267
|
+
if (uri === '' || range === null || typeof range !== 'object') continue
|
|
268
|
+
let absolute = ''
|
|
269
|
+
try {
|
|
270
|
+
absolute = fileURLToPath(uri)
|
|
271
|
+
} catch {
|
|
272
|
+
continue
|
|
273
|
+
}
|
|
274
|
+
if (!inside(root, absolute)) continue
|
|
275
|
+
const rel = relative(root, absolute).split(sep).join('/')
|
|
276
|
+
const line = Number(range.start?.line)
|
|
277
|
+
const character = Number(range.start?.character)
|
|
278
|
+
if (!Number.isFinite(line) || !Number.isFinite(character)) continue
|
|
279
|
+
const key = `${rel}:${line}:${character}`
|
|
280
|
+
if (seen.has(key)) continue
|
|
281
|
+
seen.add(key)
|
|
282
|
+
matches.push({ path: rel, line: line + 1, column: character + 1, kind: 'lsp', score: 100, preview: '' })
|
|
283
|
+
}
|
|
284
|
+
return matches
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async function definition(body, env) {
|
|
288
|
+
if (typeof body.root !== 'string' || body.root === '') throw badRequest('root is required')
|
|
289
|
+
const project = env.projects.ensure(body.root)
|
|
290
|
+
const root = project.root
|
|
291
|
+
const rawPath = typeof body.path === 'string' ? body.path : ''
|
|
292
|
+
if (rawPath === '') throw badRequest('path is required')
|
|
293
|
+
const line = Number(body.line)
|
|
294
|
+
const column = Number(body.column)
|
|
295
|
+
if (!Number.isInteger(line) || line < 1 || !Number.isInteger(column) || column < 1) throw badRequest('line/column is invalid')
|
|
296
|
+
const absolute = resolve(root, rawPath)
|
|
297
|
+
if (!inside(root, absolute)) throw new ApiError('path-outside', '路径超出项目范围', 403)
|
|
298
|
+
let content = typeof body.content === 'string' ? body.content : ''
|
|
299
|
+
if (content === '') {
|
|
300
|
+
try {
|
|
301
|
+
content = await readFile(absolute, 'utf8')
|
|
302
|
+
} catch {
|
|
303
|
+
throw new ApiError('not-found', `文件不存在:${rawPath}`, 404)
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const session = await getSession(root)
|
|
307
|
+
syncDocument(session, absolute, content)
|
|
308
|
+
const uri = pathToFileURL(absolute).href
|
|
309
|
+
let result = null
|
|
310
|
+
try {
|
|
311
|
+
result = await session.rpc.request('textDocument/definition', {
|
|
312
|
+
textDocument: { uri },
|
|
313
|
+
position: { line: line - 1, character: column - 1 },
|
|
314
|
+
}, 25000)
|
|
315
|
+
} catch (error) {
|
|
316
|
+
if (error instanceof ApiError) throw error
|
|
317
|
+
throw new ApiError('lsp-failed', `语言服务查询失败:${String(error?.message ?? error)}`, 500)
|
|
318
|
+
}
|
|
319
|
+
const matches = normalizeLocations(root, result)
|
|
320
|
+
return { matches, current: { path: relative(root, absolute).split(sep).join('/'), line, column }, language: 'python', server: 'pyright' }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async function status(body, env) {
|
|
324
|
+
const entry = pyrightEntry()
|
|
325
|
+
const available = await fileExists(entry)
|
|
326
|
+
let version = ''
|
|
327
|
+
try {
|
|
328
|
+
const pkg = JSON.parse(await readFile(resolve(packageRoot, 'node_modules', 'pyright', 'package.json'), 'utf8'))
|
|
329
|
+
version = String(pkg.version ?? '')
|
|
330
|
+
} catch {
|
|
331
|
+
version = ''
|
|
332
|
+
}
|
|
333
|
+
void body
|
|
334
|
+
void env
|
|
335
|
+
return {
|
|
336
|
+
available,
|
|
337
|
+
server: 'pyright',
|
|
338
|
+
version,
|
|
339
|
+
languages: available ? ['python'] : [],
|
|
340
|
+
hint: available ? '' : '缺少 pyright 语言服务;重新安装插件或运行 npm install pyright',
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function registerLsp(router, env) {
|
|
345
|
+
router.method('lsp.status', (body) => status(body, env))
|
|
346
|
+
router.method('lsp.definition', (body) => definition(body, env))
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/* 供未来其他 host 模块复用 */
|
|
350
|
+
export { normalizeLocations }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-gufa-code",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.88",
|
|
4
4
|
"description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
|
|
5
5
|
"icon": "icon.svg",
|
|
6
6
|
"keywords": [
|
|
@@ -40,6 +40,7 @@
|
|
|
40
40
|
"desktop"
|
|
41
41
|
],
|
|
42
42
|
"dependencies": {
|
|
43
|
+
"pyright": "^1.1.414",
|
|
43
44
|
"ws": "^8.22.0"
|
|
44
45
|
},
|
|
45
46
|
"dsh": {
|
package/src/client/00-core.js
CHANGED
|
@@ -1677,6 +1677,8 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
|
|
|
1677
1677
|
border-bottom:1px solid var(--gufa-border);overflow:hidden;white-space:nowrap}
|
|
1678
1678
|
.gufa-breadcrumb b{font-weight:500;color:var(--gufa-text)}
|
|
1679
1679
|
.gufa-editor-host{flex:1 1 auto;position:relative;min-height:0;min-width:0;overflow:hidden}
|
|
1680
|
+
.gufa-def-link{text-decoration:underline;text-decoration-color:var(--gufa-accent);text-decoration-thickness:1px;text-underline-offset:2px;cursor:pointer}
|
|
1681
|
+
.monaco-editor.gufa-def-hover .view-lines{cursor:pointer}
|
|
1680
1682
|
.gufa-editor-fallback{position:absolute;inset:0;overflow:auto;margin:0;padding:14px 18px;font:12.5px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre;tab-size:2}
|
|
1681
1683
|
.gufa-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;height:100%;padding:28px;
|
|
1682
1684
|
color:var(--gufa-text-dim);text-align:center}
|