dsh-gufa-code 1.3.118 → 1.3.173
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 +2 -2
- package/client.js +826 -108
- 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 +76 -0
- package/docs/RELEASE.md +14 -5
- package/host/code.js +41 -0
- package/host/fs.js +35 -0
- package/host/lint.js +152 -2
- package/host/ts-definition.js +212 -0
- package/package.json +2 -1
- package/scripts/selftest-host.mjs +54 -2
- package/scripts/test-editor.mjs +3 -3
- package/src/client/00-core.js +13 -0
- package/src/client/20-editor.js +383 -86
- package/src/client/30-terminal.js +10 -1
- package/src/client/55-backdrop.js +51 -0
- package/src/client/60-dock.js +199 -6
- package/src/client/90-app.js +169 -14
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
<key>CFBundleDisplayName</key><string>古法编程悬浮层</string>
|
|
8
8
|
<key>CFBundleExecutable</key><string>gufa-float</string>
|
|
9
9
|
<key>CFBundlePackageType</key><string>APPL</string>
|
|
10
|
-
<key>CFBundleShortVersionString</key><string>1.3.
|
|
11
|
-
<key>CFBundleVersion</key><string>1.3.
|
|
10
|
+
<key>CFBundleShortVersionString</key><string>1.3.173</string>
|
|
11
|
+
<key>CFBundleVersion</key><string>1.3.173</string>
|
|
12
12
|
<key>LSUIElement</key><true/>
|
|
13
13
|
<key>NSHighResolutionCapable</key><true/>
|
|
14
14
|
<key>NSPrincipalClass</key><string>NSApplication</string>
|
|
Binary file
|
package/docs/KNOWN-PITFALLS.md
CHANGED
|
@@ -90,6 +90,82 @@
|
|
|
90
90
|
- 策略:语法诊断(`getSyntacticDiagnostics`)全保留;语义诊断白名单 `2304/2552/2448/2454`(Cannot find name / Block-scoped variable before declaration 等),其余(2339、2306、模块解析类)不展示。
|
|
91
91
|
- 实测 `baiducomp/taskks.js` 从 4 条误报 → 0 条;回归测试覆盖“属性不存在不报”。
|
|
92
92
|
|
|
93
|
+
## 0.16 分割条拖拽不能每帧 setState(1.3.119)
|
|
94
|
+
|
|
95
|
+
- 现象:拖动左栏/聊天栏/终端高度拖沓。原因:`useSplitter` 的 mousemove 每帧 `setSize`,导致 `GufaApp` 整棵树(含 Monaco 容器、DSH ChatDock)反复 re-render,且聊天栏里的 DSH 原生浮层还要等下一次轮询才重定位。
|
|
96
|
+
- 方案:拖拽中只写根节点 CSS 变量(`--gufa-w-explorer / --gufa-w-chat / --gufa-h-terminal`),用 rAF 合帧、不触发 React;松手时才 `setSize` 一次并写 localStorage。终端/Monaco 靠自己的 ResizeObserver 自适应;ChatDock 监听 `layout:resize` 事件逐帧重定位原生浮层。
|
|
97
|
+
- 组件尺寸统一走 `var(--gufa-*, 数值px)`,`useLayoutEffect` 在首帧前同步变量,避免恢复持久化宽度时闪一下。
|
|
98
|
+
|
|
99
|
+
## 0.17 Cmd+点击跳转定义改回 Monaco 原生链路(1.3.120)
|
|
100
|
+
|
|
101
|
+
- 旧实现:自定义 DOM mousedown → 先 setPosition 再 `instance.getAction('editor.action.revealDefinition').run()`,但**没有先把光标移到点击位置**,native action 在旧光标处解析;失败后再走 Host 搜索兜底,导致“有时跳错、有时没反应、hover 还要等项目级搜索”。
|
|
102
|
+
- 新实现:
|
|
103
|
+
- 用 `monaco.languages.registerDefinitionProvider` 给 JS/TS/Python 注册 provider;JS/TS 后端改用 **TypeScript LanguageService 的 `getDefinitionAtPosition`**(`host/ts-definition.js` / `code.tsDefinition`),不再用正则项目搜索(正则会出现同名函数跳到别的文件);Python 用 pyright `lsp.definition`;
|
|
104
|
+
- 用 `monaco.editor.registerEditorOpener` 把 Monaco 打开的 `file://` 位置转成 App 的 `editor:open-at`;
|
|
105
|
+
- Cmd+点击只做「focus + setPosition(点击位置) + 触发原生 revealDefinition」,F12 同样走原生;多结果由 Monaco 原生 peek 处理;
|
|
106
|
+
- 同时用 `setModeConfiguration({...mode, definitions:false})` 关掉 Monaco TS worker 自带的 definition provider,避免它和 Host 结果合并/跳错;
|
|
107
|
+
- Cmd 悬停不再跑 Host 搜索,按住 Cmd 立即给当前单词下划线/手型,真正解析只在点击时发生。
|
|
108
|
+
- 注意:`gufaRegisterDefinitionInfrastructure` 全局只注册一次(`G.__gufaDefinitionInfra`),provider 内动态读 `G.projectRoot`,HMR/多窗口都复用。
|
|
109
|
+
|
|
110
|
+
## 0.18 ⌘+点击内置 API 跳到 TS lib(1.3.126)
|
|
111
|
+
|
|
112
|
+
- `parseInt` 这类系统 API 的定义在 `node_modules/typescript/lib/*.d.ts`,不在项目根内。旧 `code.tsDefinition` 把 root 外的定义全过滤掉,客户端拿不到结果;而旧兜底 `code.definition` 是正则项目搜索,会把 `parseInt` 当成普通单词,跳到项目里别的使用处(用户看到的“乱跳”)。
|
|
113
|
+
- 现在:`tsDefinition` 允许返回 TypeScript lib 内的定义(`external: true, absolutePath`);Cmd+点击不再经过 Monaco 原生动作/正则兜底,直接调 `code.tsDefinition`:
|
|
114
|
+
- 项目内定义 → `editor:open-at`;
|
|
115
|
+
- 系统 lib → `editor:open-external`,App 调 `code.readTsLib` 以只读标签打开(`~typescript/lib.es5.d.ts`),编辑器 `readOnly=true`,保存/自动保存跳过。
|
|
116
|
+
- `code.readTsLib` 只允许读 `typescript/lib` 下的 `.d.ts/.ts/.js`,不是任意路径读取。
|
|
117
|
+
|
|
118
|
+
## 0.19 Monaco 原生功能审计(1.3.127)
|
|
119
|
+
|
|
120
|
+
用户质问「本项目外定义全过滤」后,逐项核对我们对 Monaco 原生行为的覆盖:
|
|
121
|
+
|
|
122
|
+
| 能力 | 状态 |
|
|
123
|
+
| --- | --- |
|
|
124
|
+
| JS/TS **F12 Go to Definition** | 1.3.121 曾用 `setModeConfiguration({definitions:false})` 关掉原生 TS DefinitionProvider,属于误伤;**1.3.127 已恢复**,F12 重新走 Monaco 原生 TS worker;系统 lib(parseInt 等)由 `registerEditorOpener` 转成只读 `~typescript/lib*.d.ts` 标签 |
|
|
125
|
+
| JS/TS **Cmd+点击** | Monaco standalone **本来就没有** VS Code 层的定义链接(tsMode 只注册 DefinitionProvider/Hover,不注册 LinkProvider);所以必须自定义手势。现在 Cmd+点击直接走 Host TypeScript LanguageService(`code.tsDefinition`),不再经过原生动作/旧正则兜底,内置 API 也能跳 lib |
|
|
126
|
+
| JS/TS **diagnostics** | 1.3.117 起关闭 Monaco TS worker 诊断(`noSemanticValidation/noSyntaxValidation=true`),改用 Host tsc + 白名单语义错误(2304/2552/2448/2454)。这是**有意替换**:worker 诊断在 dsh-app 下不稳定,且动态 JS 项目全量语义诊断误报多(2339/2306)。若要恢复原生诊断,需同时接受这些误报 |
|
|
127
|
+
| AI Tab 补全 | 从来是自研(不是 Monaco 内置),用户要求移除,已删 |
|
|
128
|
+
| `automaticLayout` | 只在拖拽分割条期间临时关闭,松手恢复并 layout 一次(性能优化,不是功能删除) |
|
|
129
|
+
| 项目根白名单 | `ProjectRegistry` / `fs.read` 只允许项目内路径,这是文件读写安全限制;系统 TS lib 通过只读 `code.readTsLib` 单独放行 |
|
|
130
|
+
| minimap / overview ruler | 初始设计就关闭(视觉取舍),未改过 |
|
|
131
|
+
|
|
132
|
+
结论:真正误伤原生功能的是「TS DefinitionProvider 被禁用」和「项目外定义被过滤」,1.3.126/1.3.127 已修正;diagnostics 是有意替换,若要原生诊断需要接受误报或用更细的过滤。
|
|
133
|
+
|
|
134
|
+
## 0.20 Cmd+点击与 F12 统一(1.3.128)
|
|
135
|
+
|
|
136
|
+
- Monaco 的 F12 是内置 action:`editor.action.revealDefinition` → 查询所有 `registerDefinitionProvider` → 通过 `ICodeEditorService` + `registerEditorOpener` 打开。Cmd+点击不是 action,Monaco standalone 没有鼠标手势;`tsMode.js` 只注册 DefinitionProvider/Hover,不注册 LinkProvider(VS Code 的 Cmd+点击是 workbench 层另做的),所以鼠标事件必须自定义。
|
|
137
|
+
- 之前为了绕开不稳定的 TS worker,Cmd+点击走了 Host LanguageService 另一套解析,导致 F12 和 Cmd+点击行为不一致;1.3.123 恢复原生 TS DefinitionProvider 后,1.3.128 把 Cmd+点击改成:
|
|
138
|
+
1. `focus()` + `setPosition(点击位置)`;
|
|
139
|
+
2. 直接 `instance.getAction('editor.action.revealDefinition').run()`;
|
|
140
|
+
3. 同一个 `registerEditorOpener` 打开项目文件或只读 `~typescript/lib*.d.ts`。
|
|
141
|
+
- 也就是说 Cmd+点击现在和 F12 **完全同一条代码路径**,不再有自己的解析/兜底。唯一的自定义只是「把鼠标事件翻译成这个 action」这一层。
|
|
142
|
+
|
|
143
|
+
## 0.21 诊断改用 ESLint(1.3.138)
|
|
144
|
+
|
|
145
|
+
- 之前 Host tsc 单文件 Program 不认识项目里自定义的全局变量,把业务里的 global 变量全报成未定义;Monaco 原生 worker 在桌面壳又不稳定。
|
|
146
|
+
- 现在 JS/JSX/MJS/CJS 用 ESLint:
|
|
147
|
+
- 优先用项目自己的 ESLint(存在 `eslint.config.js` 时从项目 node_modules 加载);
|
|
148
|
+
- 否则用插件内置 ESLint 8 + `useEslintrc`,自动读取 `.eslintrc.*` / package.json `eslintConfig`;没有配置时用内置 `no-undef` 规则 + node/browser globals;
|
|
149
|
+
- `.eslintrc` 里的 `globals` / `rules` / 插件会生效,自定义全局变量不再误报;
|
|
150
|
+
- TS/TSX 仍走 Host tsc(ESLint 默认 parser 不解析 TS 语法)。
|
|
151
|
+
- Monaco 原生 worker 诊断关闭,避免同一错误双份 marker;Host lint 仍 debounce 650ms 更新。
|
|
152
|
+
- 项目示例 `.eslintrc.json`:
|
|
153
|
+
```json
|
|
154
|
+
{ "env": { "node": true, "browser": true, "es2022": true },
|
|
155
|
+
"globals": { "myGlobal": "readonly" },
|
|
156
|
+
"rules": { "no-undef": "error" } }
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## 0.22 会话文件引用跳古法编辑器(1.3.139)
|
|
160
|
+
|
|
161
|
+
- DSH 对话里的文件引用(MarkdownText 的 `fileMention`/`fileLink` 按钮、用户引用 chip)原生 onClick 调用的是 ChatView 的 `openFile`,它打开 `ctx.sidebarRight` 资源面板;在古法 IDE 覆盖层下这个面板被挡住,所以点了“没反应”。
|
|
162
|
+
- 修复:ChatDock 停靠成功后,在**官方会话根节点**上挂 capture click 监听:
|
|
163
|
+
- 命中 `button.fileMention / .fileLink / [data-ref-chip]`;
|
|
164
|
+
- 从 `title`(完整路径)+ 文本(`xxx.js:165` / `#L165`)解析 path/line;
|
|
165
|
+
- 调 Host `code.resolvePath` 把 basename/相对路径解析成项目内路径(优先当前目录、层级更浅);
|
|
166
|
+
- `editor:open-at` 打开古法编辑器并定位,同时 preventDefault/stopPropagation 阻止 DSH 侧边栏打开;
|
|
167
|
+
- `undock()`/根节点变化时移除监听。
|
|
168
|
+
|
|
93
169
|
## 1. 弹窗/菜单层级:只有一个正确做法(反复踩过多次,最终定案)
|
|
94
170
|
|
|
95
171
|
**现象**:弹窗被右侧「古法 AI」聊天栏压住、只显示一半、关闭按钮点不到;或者反过来把官方设置/会话弹窗盖住。
|
package/docs/RELEASE.md
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
# 发布流程(维护者)
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## ⚠️ 发布规则(用户明确要求)
|
|
4
|
+
|
|
5
|
+
- **只有用户明确说「发布 / 发版」时才发布 npm**。日常改 bug、跑测试、构建本地 client/helper 都不发布。
|
|
6
|
+
- 创建 GitHub Release **不再自动触发 npm 发布**(`publish.yml` 只保留 `workflow_dispatch`)。
|
|
7
|
+
- 用户未要求发布时:本地 commit / push main 可以(只会跑 test,不会发 npm),但**不要**打新 tag、不要 `gh release create`。
|
|
8
|
+
- 用户要求发布时:按下面流程 bump/tag/release,然后手动触发 `publish.yml`。
|
|
9
|
+
|
|
10
|
+
## 发布流程:打 tag + 建 GitHub Release + 手动触发 npm
|
|
4
11
|
|
|
5
12
|
1. 确认 `package.json` 版本号已更新(`npm version patch --no-git-tag-version` 或手改);
|
|
6
13
|
2. 提交并推送 tag:
|
|
@@ -11,10 +18,12 @@
|
|
|
11
18
|
```bash
|
|
12
19
|
gh release create v1.3.x --title "..." --notes "..."
|
|
13
20
|
```
|
|
14
|
-
4.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
21
|
+
4. Release 会触发 `.github/workflows/build-float.yml`(三平台编译 helper + 严格冒烟,二进制作为 release assets);
|
|
22
|
+
5. **用户明确要求发布时**,手动触发 npm(trusted publishing / OIDC provenance,不需要本地 token):
|
|
23
|
+
```bash
|
|
24
|
+
gh workflow run publish.yml --repo liujiannanchenjbguo/dsh-gufa-code
|
|
25
|
+
```
|
|
26
|
+
6. 验证:`npm view dsh-gufa-code version`、Release 页面 assets。
|
|
18
27
|
|
|
19
28
|
## 本地发布(不推荐,需要 npm 2FA)
|
|
20
29
|
|
package/host/code.js
CHANGED
|
@@ -371,6 +371,47 @@ export async function definition(body, env) {
|
|
|
371
371
|
}
|
|
372
372
|
}
|
|
373
373
|
|
|
374
|
+
function insideProject(root, target) {
|
|
375
|
+
const rel = relative(root, target)
|
|
376
|
+
return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* 会话里的文件引用(`tasks.js:165`、`engine/x/service.js`)解析成项目内相对路径。
|
|
381
|
+
* 支持完整相对路径、以 / 结尾的部分路径、纯 basename;多个同名时优先当前文件同目录、层级更浅的。
|
|
382
|
+
*/
|
|
383
|
+
export async function resolvePath(body, env) {
|
|
384
|
+
const project = env.projects.ensure(typeof body.root === 'string' ? body.root : '')
|
|
385
|
+
const root = project.root
|
|
386
|
+
let hint = String(body.path ?? '').replace(/\\/g, '/').trim()
|
|
387
|
+
if (hint === '') return { path: null, matches: [] }
|
|
388
|
+
hint = hint.replace(/^file:\/\//, '').replace(/^\.\//, '')
|
|
389
|
+
if (isAbsolute(hint)) {
|
|
390
|
+
const absolute = resolve(hint)
|
|
391
|
+
if (!insideProject(root, absolute)) return { path: null, matches: [] }
|
|
392
|
+
hint = relative(root, absolute).split(sep).join('/')
|
|
393
|
+
}
|
|
394
|
+
hint = hint.replace(/^\/+/, '')
|
|
395
|
+
if (hint === '' || hint.includes('..')) return { path: null, matches: [] }
|
|
396
|
+
const candidates = await listCandidates(root, null)
|
|
397
|
+
const activePath = String(body.activePath ?? '').replace(/\\/g, '/').replace(/^\/+/, '')
|
|
398
|
+
const activeDir = activePath.includes('/') ? activePath.slice(0, activePath.lastIndexOf('/')) : ''
|
|
399
|
+
let pool = candidates.filter((candidate) => candidate === hint)
|
|
400
|
+
if (pool.length === 0) pool = candidates.filter((candidate) => candidate.endsWith(`/${hint}`) || candidate.split('/').pop() === hint)
|
|
401
|
+
pool = [...new Set(pool)]
|
|
402
|
+
pool.sort((a, b) => {
|
|
403
|
+
const aNear = activeDir !== '' && a.startsWith(`${activeDir}/`) ? 0 : 1
|
|
404
|
+
const bNear = activeDir !== '' && b.startsWith(`${activeDir}/`) ? 0 : 1
|
|
405
|
+
if (aNear !== bNear) return aNear - bNear
|
|
406
|
+
const depthDiff = a.split('/').length - b.split('/').length
|
|
407
|
+
if (depthDiff !== 0) return depthDiff
|
|
408
|
+
return a.localeCompare(b)
|
|
409
|
+
})
|
|
410
|
+
if (pool.length === 0) return { path: null, matches: [] }
|
|
411
|
+
return { path: pool[0], matches: pool.slice(0, 10) }
|
|
412
|
+
}
|
|
413
|
+
|
|
374
414
|
export function register(router, env) {
|
|
375
415
|
router.method('code.definition', (body) => definition(body, env))
|
|
416
|
+
router.method('code.resolvePath', (body) => resolvePath(body, env))
|
|
376
417
|
}
|
package/host/fs.js
CHANGED
|
@@ -285,6 +285,30 @@ export function register(router, env) {
|
|
|
285
285
|
/* Python 语言服务(LSP/pyright):/lsp/definition API;Cmd+点击与悬停由客户端调用 */
|
|
286
286
|
registerLsp(router, env)
|
|
287
287
|
|
|
288
|
+
/* JS/TS 定义解析(Monaco DefinitionProvider 用):LanguageService 比正则项目搜索准确 */
|
|
289
|
+
router.method('code.tsDefinition', async (body) => {
|
|
290
|
+
let stamp = '0'
|
|
291
|
+
try {
|
|
292
|
+
stamp = String(statSync(new URL('./ts-definition.js', import.meta.url)).mtimeMs)
|
|
293
|
+
} catch {
|
|
294
|
+
stamp = '0'
|
|
295
|
+
}
|
|
296
|
+
const module = await import(new URL(`./ts-definition.js?gufa-tsdef=${stamp}`, import.meta.url).href)
|
|
297
|
+
return module.tsDefinition(body, env)
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
/* 只读读取 TypeScript 内置 lib(parseInt/Promise 等系统 API 定义) */
|
|
301
|
+
router.method('code.readTsLib', async (body) => {
|
|
302
|
+
let stamp = '0'
|
|
303
|
+
try {
|
|
304
|
+
stamp = String(statSync(new URL('./ts-definition.js', import.meta.url)).mtimeMs)
|
|
305
|
+
} catch {
|
|
306
|
+
stamp = '0'
|
|
307
|
+
}
|
|
308
|
+
const module = await import(new URL(`./ts-definition.js?gufa-tsdef=${stamp}`, import.meta.url).href)
|
|
309
|
+
return module.readTsLib(body)
|
|
310
|
+
})
|
|
311
|
+
|
|
288
312
|
/* JS/TS 诊断:TypeScript 编译器在 Host 侧跑,返回 Monaco marker 需要的位置 */
|
|
289
313
|
router.method('lint.javascript', async (body) => {
|
|
290
314
|
let stamp = '0'
|
|
@@ -312,6 +336,17 @@ export function register(router, env) {
|
|
|
312
336
|
|
|
313
337
|
/* 代码导航(Cmd+点击跳定义):实现放在 code.js,但 Host 热重载只按 host/*.js 的 mtime
|
|
314
338
|
触发,因此这里用带 mtime 的 query 动态 import,code.js 改动后下一次请求就能热生效。 */
|
|
339
|
+
router.method('code.resolvePath', async (body) => {
|
|
340
|
+
let stamp = '0'
|
|
341
|
+
try {
|
|
342
|
+
stamp = String(statSync(new URL('./code.js', import.meta.url)).mtimeMs)
|
|
343
|
+
} catch {
|
|
344
|
+
stamp = '0'
|
|
345
|
+
}
|
|
346
|
+
const module = await import(new URL(`./code.js?gufa-code-resolve=${stamp}`, import.meta.url).href)
|
|
347
|
+
return module.resolvePath(body, env)
|
|
348
|
+
})
|
|
349
|
+
|
|
315
350
|
router.method('code.definition', async (body) => {
|
|
316
351
|
let stamp = '0'
|
|
317
352
|
try {
|
package/host/lint.js
CHANGED
|
@@ -6,9 +6,12 @@
|
|
|
6
6
|
* importScripts 自定义协议资源会失败,导致语法/语义诊断时有时无;Host 侧
|
|
7
7
|
* 编译结果稳定,且可以随插件依赖(typescript)一起分发。
|
|
8
8
|
*/
|
|
9
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
9
10
|
import { readFile } from 'node:fs/promises'
|
|
10
|
-
import {
|
|
11
|
+
import { createRequire } from 'node:module'
|
|
12
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
11
13
|
|
|
14
|
+
import { ESLint } from 'eslint'
|
|
12
15
|
import ts from 'typescript'
|
|
13
16
|
|
|
14
17
|
import { ApiError, badRequest } from './context.js'
|
|
@@ -60,7 +63,7 @@ function severityOf(category) {
|
|
|
60
63
|
return 2
|
|
61
64
|
}
|
|
62
65
|
|
|
63
|
-
|
|
66
|
+
async function diagnoseWithTsc(body, env) {
|
|
64
67
|
if (typeof body.root !== 'string' || body.root === '') throw badRequest('root is required')
|
|
65
68
|
const project = env.projects.ensure(body.root)
|
|
66
69
|
const root = project.root
|
|
@@ -196,6 +199,153 @@ export async function diagnose(body, env) {
|
|
|
196
199
|
return { diagnostics }
|
|
197
200
|
}
|
|
198
201
|
|
|
202
|
+
const FLAT_CONFIG_FILES = ['eslint.config.js', 'eslint.config.cjs', 'eslint.config.mjs']
|
|
203
|
+
const LEGACY_CONFIG_FILES = ['.eslintrc', '.eslintrc.js', '.eslintrc.cjs', '.eslintrc.json', '.eslintrc.yml', '.eslintrc.yaml']
|
|
204
|
+
const eslintCache = new Map()
|
|
205
|
+
|
|
206
|
+
function configSignature(root) {
|
|
207
|
+
const parts = []
|
|
208
|
+
for (const name of [...FLAT_CONFIG_FILES, ...LEGACY_CONFIG_FILES, 'package.json']) {
|
|
209
|
+
const file = join(root, name)
|
|
210
|
+
try {
|
|
211
|
+
parts.push(`${name}:${statSync(file).mtimeMs}`)
|
|
212
|
+
} catch {
|
|
213
|
+
/* ignore */
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return parts.join('|')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function hasLegacyRegexConfig(root) {
|
|
220
|
+
for (const name of LEGACY_CONFIG_FILES) {
|
|
221
|
+
if (existsSync(join(root, name))) return true
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|
225
|
+
return pkg !== null && typeof pkg === 'object' && pkg.eslintConfig !== undefined
|
|
226
|
+
} catch {
|
|
227
|
+
return false
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function fallbackEslintConfig() {
|
|
232
|
+
return {
|
|
233
|
+
env: { browser: true, node: true, es2022: true },
|
|
234
|
+
parserOptions: { ecmaVersion: 'latest', sourceType: 'module', ecmaFeatures: { jsx: true } },
|
|
235
|
+
rules: {
|
|
236
|
+
'no-undef': 'error',
|
|
237
|
+
'no-unused-vars': 'off',
|
|
238
|
+
},
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** 优先用项目自己的 eslint(支持 eslint.config.js / 自定义规则),否则用插件内置 ESLint。 */
|
|
243
|
+
async function getEslint(root) {
|
|
244
|
+
const signature = configSignature(root)
|
|
245
|
+
const cached = eslintCache.get(root)
|
|
246
|
+
if (cached !== undefined && cached.signature === signature) return cached.instance
|
|
247
|
+
let instance = null
|
|
248
|
+
const flatConfig = FLAT_CONFIG_FILES.find((name) => existsSync(join(root, name)))
|
|
249
|
+
if (flatConfig !== undefined) {
|
|
250
|
+
try {
|
|
251
|
+
const projectRequire = createRequire(join(root, 'package.json'))
|
|
252
|
+
const projectModule = projectRequire('eslint')
|
|
253
|
+
const ProjectESLint = projectModule?.ESLint
|
|
254
|
+
if (typeof ProjectESLint === 'function') {
|
|
255
|
+
instance = new ProjectESLint({ cwd: root, errorOnUnmatchedPattern: false })
|
|
256
|
+
}
|
|
257
|
+
} catch {
|
|
258
|
+
instance = null
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (instance === null) {
|
|
262
|
+
try {
|
|
263
|
+
const legacy = hasLegacyRegexConfig(root) || flatConfig !== undefined
|
|
264
|
+
instance = new ESLint({
|
|
265
|
+
cwd: root,
|
|
266
|
+
useEslintrc: true,
|
|
267
|
+
errorOnUnmatchedPattern: false,
|
|
268
|
+
resolvePluginsRelativeTo: root,
|
|
269
|
+
...(legacy ? {} : { overrideConfig: fallbackEslintConfig() }),
|
|
270
|
+
})
|
|
271
|
+
} catch {
|
|
272
|
+
instance = null
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
eslintCache.set(root, { signature, instance })
|
|
276
|
+
return instance
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function eslintDiagnostics(root, absolute, content) {
|
|
280
|
+
const eslint = await getEslint(root)
|
|
281
|
+
if (eslint === null || eslint === undefined) return null
|
|
282
|
+
let results = []
|
|
283
|
+
try {
|
|
284
|
+
results = await eslint.lintText(content, { filePath: absolute, warnIgnored: false })
|
|
285
|
+
} catch {
|
|
286
|
+
return null
|
|
287
|
+
}
|
|
288
|
+
const result = Array.isArray(results) ? results[0] : null
|
|
289
|
+
if (result === null || result === undefined) return []
|
|
290
|
+
const diagnostics = []
|
|
291
|
+
const seen = new Set()
|
|
292
|
+
for (const message of Array.isArray(result.messages) ? result.messages : []) {
|
|
293
|
+
if (message === null || typeof message !== 'object') continue
|
|
294
|
+
if (Number(message.severity) < 1) continue
|
|
295
|
+
const ruleId = typeof message.ruleId === 'string' && message.ruleId !== '' ? message.ruleId : (message.fatal === true ? 'parsing-error' : 'eslint')
|
|
296
|
+
const line = Math.max(1, Math.trunc(Number(message.line) || 1))
|
|
297
|
+
const column = Math.max(1, Math.trunc(Number(message.column) || 1))
|
|
298
|
+
const endLine = Math.max(line, Math.trunc(Number(message.endLine) || line))
|
|
299
|
+
const endColumn = Math.max(column + 1, Math.trunc(Number(message.endColumn) || (column + 1)))
|
|
300
|
+
const text = String(message.message ?? '')
|
|
301
|
+
const key = `${ruleId}:${line}:${column}:${text}`
|
|
302
|
+
if (seen.has(key)) continue
|
|
303
|
+
seen.add(key)
|
|
304
|
+
diagnostics.push({
|
|
305
|
+
severity: Number(message.severity) === 2 ? 1 : 0,
|
|
306
|
+
message: text,
|
|
307
|
+
code: ruleId,
|
|
308
|
+
line,
|
|
309
|
+
column,
|
|
310
|
+
endLine,
|
|
311
|
+
endColumn,
|
|
312
|
+
})
|
|
313
|
+
if (diagnostics.length >= 200) break
|
|
314
|
+
}
|
|
315
|
+
return diagnostics
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export async function diagnose(body, env) {
|
|
319
|
+
if (typeof body.root !== 'string' || body.root === '') throw badRequest('root is required')
|
|
320
|
+
const project = env.projects.ensure(body.root)
|
|
321
|
+
const root = project.root
|
|
322
|
+
const rawPath = typeof body.path === 'string' ? body.path : ''
|
|
323
|
+
if (rawPath === '') throw badRequest('path is required')
|
|
324
|
+
const absolute = resolve(root, rawPath)
|
|
325
|
+
if (!inside(root, absolute)) throw new ApiError('path-outside', '路径超出项目范围', 403)
|
|
326
|
+
const extension = rawPath.split('.').pop()?.toLowerCase() ?? ''
|
|
327
|
+
if (!['js', 'jsx', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts'].includes(extension)) return { diagnostics: [] }
|
|
328
|
+
let content = typeof body.content === 'string' ? body.content : ''
|
|
329
|
+
if (content === '') {
|
|
330
|
+
try {
|
|
331
|
+
content = await readFile(absolute, 'utf8')
|
|
332
|
+
} catch {
|
|
333
|
+
throw new ApiError('not-found', `文件不存在:${rawPath}`, 404)
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
/* JS/JSX 用 ESLint(尊重项目 .eslintrc / eslint.config.js 的 globals、rules、插件);
|
|
337
|
+
TS/TSX 仍用 TypeScript 编译器(ESLint 默认 parser 不解析 TS 语法)。 */
|
|
338
|
+
if (['js', 'jsx', 'mjs', 'cjs'].includes(extension)) {
|
|
339
|
+
try {
|
|
340
|
+
const diagnostics = await eslintDiagnostics(root, absolute, content)
|
|
341
|
+
if (diagnostics !== null) return { diagnostics }
|
|
342
|
+
} catch {
|
|
343
|
+
/* 配置/插件加载失败时回落 tsc,避免完全没诊断 */
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return diagnoseWithTsc(body, env)
|
|
347
|
+
}
|
|
348
|
+
|
|
199
349
|
export function registerLint(router, env) {
|
|
200
350
|
router.method('lint.javascript', (body) => diagnose(body, env))
|
|
201
351
|
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JS/TS 定义解析(供 Monaco 原生 DefinitionProvider / F12 / Cmd+点击使用)。
|
|
3
|
+
*
|
|
4
|
+
* 和 host/lint.js 一样把当前编辑内容 + 本地 import 组成一个 TypeScript Program,
|
|
5
|
+
* 但这里用 LanguageService 的 getDefinitionAtPosition:比原来的正则项目搜索准确,
|
|
6
|
+
* 不会再因为同名函数/变量跳到别的文件。
|
|
7
|
+
*/
|
|
8
|
+
import { readFile } from 'node:fs/promises'
|
|
9
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
|
|
10
|
+
|
|
11
|
+
import ts from 'typescript'
|
|
12
|
+
|
|
13
|
+
import { ApiError, badRequest } from './context.js'
|
|
14
|
+
|
|
15
|
+
const GLOBALS_FILE = '/__gufa_code_tsdef_globals__.d.ts'
|
|
16
|
+
const GLOBALS_TEXT = 'declare var process: any;\ndeclare var require: any;\ndeclare var module: any;\ndeclare var exports: any;\n'
|
|
17
|
+
|
|
18
|
+
function inside(root, target) {
|
|
19
|
+
const rel = relative(root, target)
|
|
20
|
+
return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function compilerOptions(root) {
|
|
24
|
+
return {
|
|
25
|
+
allowJs: true,
|
|
26
|
+
checkJs: true,
|
|
27
|
+
noEmit: true,
|
|
28
|
+
target: ts.ScriptTarget.ES2022,
|
|
29
|
+
module: ts.ModuleKind.ESNext,
|
|
30
|
+
moduleResolution: ts.ModuleResolutionKind.NodeJs,
|
|
31
|
+
jsx: ts.JsxEmit.Preserve,
|
|
32
|
+
esModuleInterop: true,
|
|
33
|
+
allowSyntheticDefaultImports: true,
|
|
34
|
+
resolveJsonModule: true,
|
|
35
|
+
skipLibCheck: true,
|
|
36
|
+
skipDefaultLibCheck: true,
|
|
37
|
+
strict: false,
|
|
38
|
+
noImplicitAny: false,
|
|
39
|
+
types: [],
|
|
40
|
+
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
|
|
41
|
+
allowNonTsExtensions: true,
|
|
42
|
+
baseUrl: root,
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function collectScriptFiles(root, currentAbsolute, currentContent) {
|
|
47
|
+
const virtual = new Map([[currentAbsolute, currentContent], [GLOBALS_FILE, GLOBALS_TEXT]])
|
|
48
|
+
const scriptFiles = [currentAbsolute, GLOBALS_FILE]
|
|
49
|
+
const seen = new Set(scriptFiles)
|
|
50
|
+
const queue = [currentAbsolute]
|
|
51
|
+
while (queue.length > 0 && seen.size <= 40) {
|
|
52
|
+
const file = queue.shift()
|
|
53
|
+
const text = virtual.get(file) ?? ts.sys.readFile(file)
|
|
54
|
+
if (typeof text !== 'string') continue
|
|
55
|
+
let pre = null
|
|
56
|
+
try {
|
|
57
|
+
pre = ts.preProcessFile(text, true, true)
|
|
58
|
+
} catch {
|
|
59
|
+
continue
|
|
60
|
+
}
|
|
61
|
+
const specs = [...(pre.importedFiles ?? []), ...(pre.referencedFiles ?? [])]
|
|
62
|
+
for (const spec of specs) {
|
|
63
|
+
try {
|
|
64
|
+
const resolution = ts.resolveModuleName(spec.fileName, file, compilerOptions(root), {
|
|
65
|
+
fileExists: ts.sys.fileExists,
|
|
66
|
+
readFile: ts.sys.readFile,
|
|
67
|
+
})
|
|
68
|
+
const resolved = resolution.resolvedModule?.resolvedFileName
|
|
69
|
+
if (typeof resolved !== 'string' || resolved === '' || !inside(root, resolved)) continue
|
|
70
|
+
const key = resolve(resolved)
|
|
71
|
+
if (seen.has(key)) continue
|
|
72
|
+
seen.add(key)
|
|
73
|
+
scriptFiles.push(key)
|
|
74
|
+
queue.push(key)
|
|
75
|
+
} catch {
|
|
76
|
+
/* ignore */
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { scriptFiles, virtual }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function tsDefinition(body, env) {
|
|
84
|
+
if (typeof body.root !== 'string' || body.root === '') throw badRequest('root is required')
|
|
85
|
+
const project = env.projects.ensure(body.root)
|
|
86
|
+
const root = project.root
|
|
87
|
+
const rawPath = typeof body.path === 'string' ? body.path : ''
|
|
88
|
+
if (rawPath === '') throw badRequest('path is required')
|
|
89
|
+
const absolute = resolve(root, rawPath)
|
|
90
|
+
if (!inside(root, absolute)) throw new ApiError('path-outside', '路径超出项目范围', 403)
|
|
91
|
+
const extension = rawPath.split('.').pop()?.toLowerCase() ?? ''
|
|
92
|
+
if (!['js', 'jsx', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts'].includes(extension)) return { matches: [] }
|
|
93
|
+
const line = Math.max(1, Math.trunc(Number(body.line) || 1))
|
|
94
|
+
const column = Math.max(1, Math.trunc(Number(body.column) || 1))
|
|
95
|
+
let content = typeof body.content === 'string' ? body.content : ''
|
|
96
|
+
if (content === '') {
|
|
97
|
+
try {
|
|
98
|
+
content = await readFile(absolute, 'utf8')
|
|
99
|
+
} catch {
|
|
100
|
+
throw new ApiError('not-found', `文件不存在:${rawPath}`, 404)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const { scriptFiles, virtual } = collectScriptFiles(root, absolute, content)
|
|
105
|
+
const options = compilerOptions(root)
|
|
106
|
+
const host = {
|
|
107
|
+
getScriptFileNames: () => scriptFiles,
|
|
108
|
+
getScriptVersion: (fileName) => (virtual.has(resolve(fileName)) ? '1' : '0'),
|
|
109
|
+
getScriptSnapshot: (fileName) => {
|
|
110
|
+
const key = resolve(fileName)
|
|
111
|
+
const text = virtual.get(key) ?? ts.sys.readFile(key)
|
|
112
|
+
if (text === undefined) return undefined
|
|
113
|
+
return ts.ScriptSnapshot.fromString(text)
|
|
114
|
+
},
|
|
115
|
+
getCurrentDirectory: () => root,
|
|
116
|
+
getCompilationSettings: () => options,
|
|
117
|
+
getDefaultLibFileName: (compileOptions) => ts.getDefaultLibFilePath(compileOptions),
|
|
118
|
+
fileExists: (fileName) => virtual.has(resolve(fileName)) || ts.sys.fileExists(fileName),
|
|
119
|
+
readFile: (fileName) => virtual.get(resolve(fileName)) ?? ts.sys.readFile(fileName),
|
|
120
|
+
readDirectory: ts.sys.readDirectory,
|
|
121
|
+
directoryExists: ts.sys.directoryExists,
|
|
122
|
+
getDirectories: ts.sys.getDirectories,
|
|
123
|
+
getCanonicalFileName: (fileName) => fileName,
|
|
124
|
+
useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
|
|
125
|
+
getNewLine: () => '\n',
|
|
126
|
+
}
|
|
127
|
+
let languageService = null
|
|
128
|
+
try {
|
|
129
|
+
languageService = ts.createLanguageService(host)
|
|
130
|
+
} catch {
|
|
131
|
+
languageService = null
|
|
132
|
+
}
|
|
133
|
+
if (languageService === null) return { matches: [] }
|
|
134
|
+
let definitions = []
|
|
135
|
+
try {
|
|
136
|
+
const program = languageService.getProgram()
|
|
137
|
+
const sourceFile = program?.getSourceFile(absolute)
|
|
138
|
+
if (sourceFile === undefined || sourceFile === null) return { matches: [] }
|
|
139
|
+
const offset = ts.getPositionOfLineAndCharacter(sourceFile, Math.min(sourceFile.getLineStarts().length - 1, line - 1), column - 1)
|
|
140
|
+
definitions = languageService.getDefinitionAtPosition(absolute, offset) ?? []
|
|
141
|
+
} catch {
|
|
142
|
+
definitions = []
|
|
143
|
+
}
|
|
144
|
+
const libDir = dirname(ts.getDefaultLibFilePath(options))
|
|
145
|
+
const matches = []
|
|
146
|
+
const seen = new Set()
|
|
147
|
+
for (const definition of definitions) {
|
|
148
|
+
if (definition === null || definition === undefined) continue
|
|
149
|
+
const fileName = resolve(definition.fileName)
|
|
150
|
+
const internal = inside(root, fileName)
|
|
151
|
+
/* 项目内定义正常返回;TS 内置 lib(parseInt/Promise 等)也返回,
|
|
152
|
+
客户端会以只读标签打开 node_modules/typescript/lib/*.d.ts。 */
|
|
153
|
+
if (!internal && !inside(libDir, fileName)) continue
|
|
154
|
+
let defSource = null
|
|
155
|
+
try {
|
|
156
|
+
defSource = languageService.getProgram()?.getSourceFile(fileName)
|
|
157
|
+
} catch {
|
|
158
|
+
defSource = null
|
|
159
|
+
}
|
|
160
|
+
if (defSource === undefined || defSource === null) continue
|
|
161
|
+
const start = Math.max(0, Number(definition.textSpan?.start) || 0)
|
|
162
|
+
const position = ts.getLineAndCharacterOfPosition(defSource, start)
|
|
163
|
+
const path = internal ? relative(root, fileName).split(sep).join('/') : relative(libDir, fileName).split(sep).join('/')
|
|
164
|
+
const key = `${internal ? 'in' : 'lib'}:${fileName}:${position.line + 1}:${position.character + 1}`
|
|
165
|
+
if (seen.has(key)) continue
|
|
166
|
+
seen.add(key)
|
|
167
|
+
matches.push({
|
|
168
|
+
path,
|
|
169
|
+
absolutePath: internal ? undefined : fileName,
|
|
170
|
+
external: internal ? undefined : true,
|
|
171
|
+
line: position.line + 1,
|
|
172
|
+
column: position.character + 1,
|
|
173
|
+
kind: internal ? 'lsp' : 'lib',
|
|
174
|
+
preview: internal ? '' : `typescript/lib/${path}`,
|
|
175
|
+
score: internal ? 1000 : 900,
|
|
176
|
+
})
|
|
177
|
+
if (matches.length >= 8) break
|
|
178
|
+
}
|
|
179
|
+
return { matches }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const LIB_EXTENSIONS = new Set(['.d.ts', '.ts', '.js'])
|
|
183
|
+
|
|
184
|
+
/** 只读打开 TypeScript 内置 lib(parseInt/Promise/Array 等定义)用。 */
|
|
185
|
+
export async function readTsLib(body) {
|
|
186
|
+
const libDir = dirname(ts.getDefaultLibFilePath({}))
|
|
187
|
+
const libName = typeof body.libName === 'string' ? body.libName.trim() : ''
|
|
188
|
+
const rawPath = typeof body.absolutePath === 'string' ? body.absolutePath : ''
|
|
189
|
+
let absolute = ''
|
|
190
|
+
if (libName !== '') {
|
|
191
|
+
if (!/^lib\.[A-Za-z0-9._-]+\.d\.ts$/.test(libName)) throw new ApiError('forbidden', '非法的 TypeScript lib 名称', 403)
|
|
192
|
+
absolute = resolve(libDir, libName)
|
|
193
|
+
} else {
|
|
194
|
+
if (rawPath === '') throw new ApiError('bad-request', 'absolutePath is required', 400)
|
|
195
|
+
absolute = resolve(rawPath)
|
|
196
|
+
}
|
|
197
|
+
if (!inside(libDir, absolute)) throw new ApiError('forbidden', '只允许读取 TypeScript 内置 lib 文件', 403)
|
|
198
|
+
const extension = absolute.slice(absolute.lastIndexOf('.')).toLowerCase()
|
|
199
|
+
if (!LIB_EXTENSIONS.has(extension)) throw new ApiError('forbidden', '不允许的文件类型', 403)
|
|
200
|
+
const content = await readFile(absolute, 'utf8')
|
|
201
|
+
return {
|
|
202
|
+
content,
|
|
203
|
+
language: 'typescript',
|
|
204
|
+
absolutePath: absolute,
|
|
205
|
+
name: absolute.slice(absolute.lastIndexOf('/') + 1),
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function registerTsDefinition(router, env) {
|
|
210
|
+
router.method('code.tsDefinition', (body) => tsDefinition(body, env))
|
|
211
|
+
router.method('code.readTsLib', (body) => readTsLib(body))
|
|
212
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-gufa-code",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.173",
|
|
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
|
+
"eslint": "^8.57.1",
|
|
43
44
|
"pyright": "^1.1.414",
|
|
44
45
|
"typescript": "^5.9.3",
|
|
45
46
|
"ws": "^8.22.0"
|