dsh-gufa-code 1.3.78 → 1.3.82

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 CHANGED
@@ -41,7 +41,7 @@ dsh plugin add dsh-gufa-code
41
41
  - Monaco 编辑器(离线随包分发,无需联网下载);
42
42
  - 多标签、按扩展名语法高亮、面包屑、状态栏(分支 / 行列 / 保存状态);
43
43
  - 保存走磁盘版本冲突检测 + 原子写;未保存标记;
44
- - **⌘/Ctrl + 点击跳转定义 / 方法实现**:优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明),单结果直接跳,多结果弹「跳转到定义」列表;
44
+ - **⌘/Ctrl + 点击跳转定义 / 方法实现**:优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明)。兜底会解析 import/require 直接定位来源文件,并跳过压缩产物/大文件;同一个文件里的声明、import 命中的定义、目录距离近的定义直接跳,只有多个真正同名的声明才弹「跳转到定义」列表,点同名属性/变量时不会拿远端无关的 const 来凑数;
45
45
  - **全局搜索 / 替换**(左栏放大镜 / `⌘⇧F`):整个项目的文本搜索,支持区分大小写、正则、包含/排除文件(glob);结果按文件分组、高亮匹配,点击跳转行列;替换栏支持保留大小写(AB)、全部替换(需确认)、按文件替换(悬停文件头铅笔)、按单行匹配替换与忽略(悬停结果行);替换前会自动保存未落盘的编辑器内容;Git 项目用 `git ls-files` 枚举文件(尊重 `.gitignore`、含未跟踪文件),非 Git 项目遍历目录并自动跳过 `node_modules` 等依赖/缓存目录;摸鱼悬浮窗里同样可用;
46
46
  - 资源管理器右键:新建 / 重命名 / 删除 / 复制 / 粘贴 / 打开所在文件夹 / 两文件对比;
47
47
  - **从 Finder 粘贴/拖入文件**:系统剪贴板里复制的文件可直接 ⌘V 粘进资源管理器(写入选中的目录,重名自动加「副本」),也可从 Finder 直接拖进文件树;
package/client.js CHANGED
@@ -16,7 +16,7 @@ const GUFA_NS = 'gufa-code'
16
16
  const G = {}
17
17
  G.NS = GUFA_NS
18
18
  /** 客户端构建标记(排查页面是否加载了新代码时看标题栏) */
19
- G.BUILD = '1.3.78'
19
+ G.BUILD = '1.3.82'
20
20
  G.PANEL_ID = 'gufa-code'
21
21
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
22
22
  G.pendingEntryWorkspace = null
@@ -2747,7 +2747,10 @@ G.FooterAction = function FooterAction(props) {
2747
2747
  if (gufaReadyMonaco() === null) gufaMonacoPromise = null
2748
2748
  }
2749
2749
 
2750
- /* ── model / URI ────────────────────────────────────────────────────── */
2750
+ /** 这些声明类型算「定义级」,多个同名时值得让用户选;普通 const/赋值等弱匹配不轻易弹列表。 */
2751
+ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export'])
2752
+
2753
+ /* ── model / URI ────────────────────────────────────────────────────── */
2751
2754
 
2752
2755
  /**
2753
2756
  * tab → Monaco model URI:file:///<root>/<path>(root 为项目绝对路径)。
@@ -3172,11 +3175,38 @@ G.FooterAction = function FooterAction(props) {
3172
3175
  })
3173
3176
  const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
3174
3177
  if (matches.length === 0) return
3175
- if (matches.length === 1) {
3176
- G.bus.emit('editor:open-at', { path: matches[0].path, line: matches[0].line, column: matches[0].column })
3178
+ const openMatch = (item) => G.bus.emit('editor:open-at', { path: item.path, line: item.line, column: item.column })
3179
+ const currentPath = result.current !== null && result.current !== undefined && typeof result.current.path === 'string' ? result.current.path : null
3180
+ const top = matches[0]
3181
+ const topScore = Number(top.score) || 0
3182
+ /* 当前文件里的声明:直接跳,不打扰 */
3183
+ if (currentPath !== null && top.path === currentPath) {
3184
+ openMatch(top)
3185
+ return
3186
+ }
3187
+ const isStrong = (item) => GUFA_DEFINITION_STRONG_KINDS.has(item.kind)
3188
+ /* 弱匹配(const/赋值等)只有在很近/很确定时才跳,避免点属性名时跳到别的仓库同名变量 */
3189
+ if (!isStrong(top) && topScore < 50) return
3190
+ if (topScore < 30) return
3191
+ const cluster = matches.filter((item) => (Number(item.score) || 0) >= topScore - 8).slice(0, 8)
3192
+ if (cluster.length === 1) {
3193
+ openMatch(cluster[0])
3194
+ return
3195
+ }
3196
+ const declCluster = cluster.filter((item) => isStrong(item))
3197
+ if (declCluster.length === 0) {
3198
+ const secondScore = matches.length > 1 ? Number(matches[1].score) || 0 : 0
3199
+ if (topScore >= 50 && topScore - secondScore >= 10) {
3200
+ openMatch(top)
3201
+ }
3202
+ return
3203
+ }
3204
+ const distinctFiles = new Set(declCluster.map((item) => item.path))
3205
+ if (distinctFiles.size === 1) {
3206
+ openMatch(declCluster[0])
3177
3207
  return
3178
3208
  }
3179
- G.bus.emit('definition:pick', { word: result.word ?? word, matches, x: event.clientX, y: event.clientY })
3209
+ G.bus.emit('definition:pick', { word: result.word ?? word, matches: declCluster, x: event.clientX, y: event.clientY })
3180
3210
  } catch {
3181
3211
  /* ignore */
3182
3212
  }
@@ -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.78</string>
11
- <key>CFBundleVersion</key><string>1.3.78</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.82</string>
11
+ <key>CFBundleVersion</key><string>1.3.82</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
package/host/code.js CHANGED
@@ -14,7 +14,7 @@ import { promisify } from 'node:util'
14
14
  import { ApiError, badRequest } from './context.js'
15
15
 
16
16
  const runCommand = promisify(execFile)
17
- const MAX_FILE_SIZE = 1024 * 1024
17
+ const MAX_FILE_SIZE = 512 * 1024
18
18
  const MAX_SCANNED = 3000
19
19
  const TIME_BUDGET = 7000
20
20
  const MAX_MATCHES = 30
@@ -96,15 +96,100 @@ function definitionPatterns(word) {
96
96
  ]
97
97
  }
98
98
 
99
+ function pathSegments(relPath) {
100
+ if (relPath === '') return []
101
+ const dir = relPath.includes('/') ? relPath.slice(0, relPath.lastIndexOf('/')) : ''
102
+ return dir === '' ? [] : dir.split('/')
103
+ }
104
+
99
105
  function scoreMatch(match, current) {
100
106
  let score = match.weight
101
107
  if (match.path === current.path) score += 120
102
108
  if (extensionOf(match.path) === extensionOf(current.path)) score += 6
103
- if (match.path.startsWith(`${current.dir}/`)) score += 4
109
+ if (current.dir !== '' && match.path.startsWith(`${current.dir}/`)) score += 8
110
+ /* 目录距离:同目录 > 子目录 > 兄弟目录 > 远处目录(项目根是 home 时尤其重要) */
111
+ const currentSegments = pathSegments(current.path)
112
+ const matchSegments = pathSegments(match.path)
113
+ let common = 0
114
+ while (common < currentSegments.length && common < matchSegments.length && currentSegments[common] === matchSegments[common]) common += 1
115
+ const gap = currentSegments.length + matchSegments.length - common * 2
116
+ score += Math.max(0, 20 - gap * 4)
104
117
  if (match.kind === 'method' || match.kind === 'function' || match.kind === 'def' || match.kind === 'func' || match.kind === 'fn') score += 4
118
+ if (match.importBoost === true) score += 220
105
119
  return score
106
120
  }
107
121
 
122
+ /** 压缩/生成的单行超长文件:定义搜索里排除,避免点到包产物里的同名变量。 */
123
+ function isMinifiedText(text) {
124
+ const value = String(text)
125
+ if (value.length < 2000) return false
126
+ const lines = value.split('\n')
127
+ if (lines.length < 12) return true
128
+ let longLines = 0
129
+ const sample = Math.min(lines.length, 200)
130
+ for (let index = 0; index < sample; index += 1) {
131
+ if (lines[index].length > 1200) longLines += 1
132
+ }
133
+ if (longLines >= 1) return true
134
+ return value.length / lines.length > 240
135
+ }
136
+
137
+ /** 解析当前文件的 import/require,得到 标识符 → 模块 spec 的映射。 */
138
+ function parseImportMap(text) {
139
+ const map = new Map()
140
+ const source = String(text)
141
+ try {
142
+ let match
143
+ const es = /import\s+([^'"]+?)\s+from\s+['"]([^'"]+)['"]/g
144
+ while ((match = es.exec(source)) !== null) {
145
+ const clause = match[1]
146
+ const spec = match[2]
147
+ const named = /\{([^}]*)\}/.exec(clause)
148
+ if (named !== null) {
149
+ for (const part of named[1].split(',')) {
150
+ const raw = part.trim()
151
+ if (raw === '') continue
152
+ const alias = raw.split(/\s+as\s+/).pop().trim()
153
+ if (/^[A-Za-z_$][\w$]*$/.test(alias)) map.set(alias, spec)
154
+ }
155
+ }
156
+ const def = clause.replace(/\{[^}]*\}/g, '').replace(/,/g, ' ').trim().split(/\s+/)[0]
157
+ if (def !== undefined && /^[A-Za-z_$][\w$]*$/.test(def)) map.set(def, spec)
158
+ }
159
+ const cjs = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/g
160
+ while ((match = cjs.exec(source)) !== null) map.set(match[1], match[2])
161
+ const cjsNamed = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/g
162
+ while ((match = cjsNamed.exec(source)) !== null) {
163
+ for (const part of match[1].split(',')) {
164
+ const name = part.trim().split(/\s*:\s*/).pop()
165
+ if (/^[A-Za-z_$][\w$]*$/.test(name)) map.set(name, match[2])
166
+ }
167
+ }
168
+ } catch {
169
+ /* ignore */
170
+ }
171
+ return map
172
+ }
173
+
174
+ /** 把相对 import 解析成候选文件路径(不含存在性检查)。 */
175
+ function importTargetPaths(currentPath, spec) {
176
+ if (!spec.startsWith('.')) return []
177
+ const baseDir = currentPath.includes('/') ? currentPath.slice(0, currentPath.lastIndexOf('/')) : ''
178
+ const raw = `${baseDir}${baseDir === '' ? '' : '/'}${spec}`
179
+ const parts = []
180
+ for (const part of raw.split('/')) {
181
+ if (part === '' || part === '.') continue
182
+ if (part === '..') parts.pop()
183
+ else parts.push(part)
184
+ }
185
+ const base = parts.join('/')
186
+ return [
187
+ base,
188
+ `${base}.js`, `${base}.ts`, `${base}.jsx`, `${base}.tsx`, `${base}.mjs`, `${base}.cjs`,
189
+ `${base}/index.js`, `${base}/index.ts`, `${base}/index.jsx`, `${base}/index.tsx`,
190
+ ]
191
+ }
192
+
108
193
  async function listCandidates(root, textBudgets) {
109
194
  /* Git 项目用 git ls-files(尊重 .gitignore、含未跟踪文件),否则 BFS 遍历。 */
110
195
  let isGit = false
@@ -201,8 +286,7 @@ function findDefinitionsInText(text, relPath, word, patterns, results, current)
201
286
  void current
202
287
  }
203
288
 
204
- export function register(router, env) {
205
- router.method('code.definition', async (body) => {
289
+ export async function definition(body, env) {
206
290
  const project = env.projects.ensure(typeof body.root === 'string' ? body.root : '')
207
291
  const root = project.root
208
292
  const rawPath = typeof body.path === 'string' ? body.path : ''
@@ -233,6 +317,10 @@ export function register(router, env) {
233
317
  const patterns = definitionPatterns(word)
234
318
  const startedAt = Date.now()
235
319
  const current = { path: relPath, dir: relPath.includes('/') ? relPath.slice(0, relPath.lastIndexOf('/')) : '' }
320
+ /* import 解析:命中导入来源的文件给高权重,避免在 home 根目录这种大项目里点到同名变量 */
321
+ const importMap = parseImportMap(text)
322
+ const importedSpec = importMap.get(word)
323
+ const importTargets = new Set(importedSpec === undefined ? [] : importTargetPaths(relPath, importedSpec))
236
324
  const results = []
237
325
  /* 1) 当前文件(用编辑器传来的内容,能命中未保存的改动) */
238
326
  findDefinitionsInText(text, relPath, word, patterns, results, current)
@@ -254,6 +342,7 @@ export function register(router, env) {
254
342
  if (buffer.includes(0)) continue
255
343
  const candidateText = buffer.toString('utf8')
256
344
  if (!candidateText.includes(word)) continue
345
+ if (isMinifiedText(candidateText)) continue
257
346
  findDefinitionsInText(candidateText, candidate, word, patterns, results, current)
258
347
  }
259
348
  /* 去重 + 打分 + 排序 */
@@ -263,13 +352,14 @@ export function register(router, env) {
263
352
  const key = `${item.path}:${item.line}:${item.column}`
264
353
  if (seen.has(key)) continue
265
354
  seen.add(key)
355
+ const candidate = { ...item, importBoost: importTargets.has(item.path) }
266
356
  matches.push({
267
357
  path: item.path,
268
358
  line: item.line,
269
359
  column: item.column,
270
360
  kind: item.kind,
271
361
  preview: item.preview,
272
- score: scoreMatch(item, current),
362
+ score: scoreMatch(candidate, current),
273
363
  })
274
364
  }
275
365
  matches.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path) || a.line - b.line)
@@ -279,5 +369,8 @@ export function register(router, env) {
279
369
  current: { path: relPath, line, column },
280
370
  truncated: matches.length > MAX_MATCHES,
281
371
  }
282
- })
372
+ }
373
+
374
+ export function register(router, env) {
375
+ router.method('code.definition', (body) => definition(body, env))
283
376
  }
package/host/fs.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * 所有路径都必须是「已打开项目根」内的相对路径,防止越权访问任意磁盘。
4
4
  */
5
5
  import { createHash, randomUUID } from 'node:crypto'
6
+ import { statSync } from 'node:fs'
6
7
  import { createReadStream } from 'node:fs'
7
8
  import { access, cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
8
9
  import { execFile } from 'node:child_process'
@@ -11,7 +12,6 @@ import { constants } from 'node:fs'
11
12
  import { tmpdir } from 'node:os'
12
13
  import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
13
14
  import { ApiError, badRequest } from './context.js'
14
- import { register as registerCodeNavigation } from './code.js'
15
15
 
16
16
  const TEXT_LIMIT = 4 * 1024 * 1024
17
17
  const runCommand = promisify(execFile)
@@ -244,9 +244,18 @@ async function listProjectCandidates(root, project, maxScanned) {
244
244
  }
245
245
 
246
246
  export function register(router, env) {
247
- /* 代码导航(Cmd+点击跳定义)注册在 fs 模块里:host 热重载按 host/*.js 的 mtime 触发,
248
- 如果单开一个模块,需要重启 Host 才能挂上;挂在 fs 上改代码即可热生效。 */
249
- registerCodeNavigation(router, env)
247
+ /* 代码导航(Cmd+点击跳定义):实现放在 code.js,但 Host 热重载只按 host/*.js 的 mtime
248
+ 触发,因此这里用带 mtime 的 query 动态 import,code.js 改动后下一次请求就能热生效。 */
249
+ router.method('code.definition', async (body) => {
250
+ let stamp = '0'
251
+ try {
252
+ stamp = String(statSync(new URL('./code.js', import.meta.url)).mtimeMs)
253
+ } catch {
254
+ stamp = '0'
255
+ }
256
+ const module = await import(new URL(`./code.js?gufa-code-def=${stamp}`, import.meta.url).href)
257
+ return module.definition(body, env)
258
+ })
250
259
 
251
260
  router.method('fs.list', async (body) => {
252
261
  const root = await projectOf(env, body)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.78",
3
+ "version": "1.3.82",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -399,7 +399,10 @@
399
399
  if (gufaReadyMonaco() === null) gufaMonacoPromise = null
400
400
  }
401
401
 
402
- /* ── model / URI ────────────────────────────────────────────────────── */
402
+ /** 这些声明类型算「定义级」,多个同名时值得让用户选;普通 const/赋值等弱匹配不轻易弹列表。 */
403
+ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export'])
404
+
405
+ /* ── model / URI ────────────────────────────────────────────────────── */
403
406
 
404
407
  /**
405
408
  * tab → Monaco model URI:file:///<root>/<path>(root 为项目绝对路径)。
@@ -824,11 +827,38 @@
824
827
  })
825
828
  const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
826
829
  if (matches.length === 0) return
827
- if (matches.length === 1) {
828
- G.bus.emit('editor:open-at', { path: matches[0].path, line: matches[0].line, column: matches[0].column })
830
+ const openMatch = (item) => G.bus.emit('editor:open-at', { path: item.path, line: item.line, column: item.column })
831
+ const currentPath = result.current !== null && result.current !== undefined && typeof result.current.path === 'string' ? result.current.path : null
832
+ const top = matches[0]
833
+ const topScore = Number(top.score) || 0
834
+ /* 当前文件里的声明:直接跳,不打扰 */
835
+ if (currentPath !== null && top.path === currentPath) {
836
+ openMatch(top)
837
+ return
838
+ }
839
+ const isStrong = (item) => GUFA_DEFINITION_STRONG_KINDS.has(item.kind)
840
+ /* 弱匹配(const/赋值等)只有在很近/很确定时才跳,避免点属性名时跳到别的仓库同名变量 */
841
+ if (!isStrong(top) && topScore < 50) return
842
+ if (topScore < 30) return
843
+ const cluster = matches.filter((item) => (Number(item.score) || 0) >= topScore - 8).slice(0, 8)
844
+ if (cluster.length === 1) {
845
+ openMatch(cluster[0])
846
+ return
847
+ }
848
+ const declCluster = cluster.filter((item) => isStrong(item))
849
+ if (declCluster.length === 0) {
850
+ const secondScore = matches.length > 1 ? Number(matches[1].score) || 0 : 0
851
+ if (topScore >= 50 && topScore - secondScore >= 10) {
852
+ openMatch(top)
853
+ }
854
+ return
855
+ }
856
+ const distinctFiles = new Set(declCluster.map((item) => item.path))
857
+ if (distinctFiles.size === 1) {
858
+ openMatch(declCluster[0])
829
859
  return
830
860
  }
831
- G.bus.emit('definition:pick', { word: result.word ?? word, matches, x: event.clientX, y: event.clientY })
861
+ G.bus.emit('definition:pick', { word: result.word ?? word, matches: declCluster, x: event.clientX, y: event.clientY })
832
862
  } catch {
833
863
  /* ignore */
834
864
  }