dsh-knit 0.11.0 → 0.12.0
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/CHANGELOG.md +532 -0
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/package.json +4 -3
- package/src/client/client.js +191 -1
- package/src/host/index.js +18 -1
- package/src/host/links.js +304 -0
- package/test/client.test.mjs +180 -0
- package/test/fixture.mjs +6 -1
- package/test/host-http.test.mjs +80 -2
- package/test/links.test.mjs +271 -0
package/src/client/client.js
CHANGED
|
@@ -85,6 +85,15 @@ window.__ModuleLoader__.load({
|
|
|
85
85
|
'preview.openLocalBtn': '在本地打开',
|
|
86
86
|
'preview.close': '收起预览',
|
|
87
87
|
'preview.resizeTitle': '拖动调整高度',
|
|
88
|
+
// v0.12 引用条。⚠️ 不放任何表情符号(test/i18n.test.mjs 有守卫)。
|
|
89
|
+
'links.summary': '被引用 {in} · 引用了 {out}',
|
|
90
|
+
'links.incoming': '被引用',
|
|
91
|
+
'links.outgoing': '引用了',
|
|
92
|
+
'links.noneIn': '没有被引用',
|
|
93
|
+
'links.noneOut': '没有引用别的文档',
|
|
94
|
+
'links.more': '还有 {count} 篇',
|
|
95
|
+
'links.failed': '引用关系读取失败',
|
|
96
|
+
'links.incomplete': '工作区较大,结果可能不完整',
|
|
88
97
|
'preview.rawFallback': '原生 Markdown 渲染不可用,下面是纯文本。请看控制台的 [knit] 日志。',
|
|
89
98
|
'code.copy': '复制',
|
|
90
99
|
'code.copied': '已复制',
|
|
@@ -174,6 +183,14 @@ window.__ModuleLoader__.load({
|
|
|
174
183
|
'preview.openLocalBtn': 'Open locally',
|
|
175
184
|
'preview.close': 'Close preview',
|
|
176
185
|
'preview.resizeTitle': 'Drag to resize',
|
|
186
|
+
'links.summary': 'Referenced by {in} · links to {out}',
|
|
187
|
+
'links.incoming': 'Referenced by',
|
|
188
|
+
'links.outgoing': 'Links to',
|
|
189
|
+
'links.noneIn': 'Not referenced by anything',
|
|
190
|
+
'links.noneOut': 'Links to no other document',
|
|
191
|
+
'links.more': '{count} more',
|
|
192
|
+
'links.failed': 'Could not read references',
|
|
193
|
+
'links.incomplete': 'Large workspace — results may be incomplete',
|
|
177
194
|
'preview.rawFallback': 'Native Markdown rendering is unavailable — showing plain text. Check the [knit] logs in the console.',
|
|
178
195
|
'code.copy': 'Copy',
|
|
179
196
|
'code.copied': 'Copied',
|
|
@@ -283,6 +300,9 @@ window.__ModuleLoader__.load({
|
|
|
283
300
|
const LIST_API = '/knit/api/recent'
|
|
284
301
|
const DOC_API = '/knit/api/doc'
|
|
285
302
|
const RAW_API = '/knit/api/raw'
|
|
303
|
+
// v0.12:某篇的「谁引用了它 / 它引用了谁」。与上面三条一样是**同源相对地址**,
|
|
304
|
+
// 所以仍然满足「客户端零网络出口」那条守卫(test/security.test.mjs)。
|
|
305
|
+
const LINKS_API = '/knit/api/links'
|
|
286
306
|
|
|
287
307
|
/** 轮询间隔。 */
|
|
288
308
|
const POLL_MS = 5000
|
|
@@ -529,6 +549,32 @@ body[data-ds-dark-theme] .knit-preview{box-shadow:0 -8px 24px rgba(0,0,0,.38)}
|
|
|
529
549
|
color:var(--dsw-alias-label-secondary,#9aa0a6);font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
530
550
|
.knit-preview-note{font-size:11px;color:var(--dsw-alias-label-caption,#80868b);padding:2px 0 8px}
|
|
531
551
|
|
|
552
|
+
/* ── 引用条(v0.12)────────────────────────────────────
|
|
553
|
+
夹在预览头与正文之间的一层。全用中性令牌:它是「信息」,不是「操作」。
|
|
554
|
+
注意 CSS 里不要写反引号 —— 这段样式是模板字符串,一个反引号就会把它截断。 */
|
|
555
|
+
.knit-links{flex:none;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.08));
|
|
556
|
+
font-size:11px;color:var(--dsw-alias-label-secondary,#9aa0a6)}
|
|
557
|
+
.knit-links-state{padding:5px 12px;color:var(--dsw-alias-label-caption,#80868b)}
|
|
558
|
+
.knit-links-head{box-sizing:border-box;display:flex;align-items:center;gap:6px;width:100%;
|
|
559
|
+
padding:5px 12px;background:transparent;border:none;cursor:pointer;text-align:left;
|
|
560
|
+
font:inherit;color:inherit}
|
|
561
|
+
.knit-links-head:hover{background:var(--knit-hover-bg,rgba(255,255,255,.03))}
|
|
562
|
+
.knit-links-arrow{flex:none;width:10px;font-size:9px;opacity:.75}
|
|
563
|
+
.knit-links-summary{flex:1 1 auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
564
|
+
.knit-links-note{padding:2px 12px 6px;color:var(--dsw-alias-label-caption,#80868b)}
|
|
565
|
+
.knit-links-body{padding:0 12px 8px;max-height:180px;overflow:auto}
|
|
566
|
+
.knit-links-group + .knit-links-group{margin-top:6px}
|
|
567
|
+
.knit-links-label{font-weight:600;color:var(--dsw-alias-label-caption,#80868b);margin-bottom:2px}
|
|
568
|
+
.knit-links-empty{color:var(--dsw-alias-label-caption,#80868b);padding:1px 0}
|
|
569
|
+
.knit-links-list{list-style:none;margin:0;padding:0}
|
|
570
|
+
.knit-link-row{box-sizing:border-box;display:block;width:100%;text-align:left;padding:2px 4px;
|
|
571
|
+
border:none;background:transparent;border-radius:4px;cursor:pointer;font:inherit;color:inherit}
|
|
572
|
+
.knit-link-row:hover{background:var(--knit-hover-bg,rgba(255,255,255,.03))}
|
|
573
|
+
.knit-link-name{display:block;color:var(--dsw-alias-label-primary,#e8eaed);
|
|
574
|
+
overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
575
|
+
.knit-link-path{display:block;font-size:10px;color:var(--dsw-alias-label-caption,#80868b);
|
|
576
|
+
overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
577
|
+
|
|
532
578
|
/* ── 类型切换(文档 / 图片与视频 / 全部)────────────── */
|
|
533
579
|
/* 选中态与下面的列表行、上面的排序切换共用一套中性灰填充,**不要品牌色描边**:
|
|
534
580
|
用户的原话是「选中的时候不用加绿色、蓝色的描边,就跟下面列表一样,
|
|
@@ -988,10 +1034,76 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
988
1034
|
* @param {{preview:object,pathImages:object|null,fullscreen:boolean,onClose:Function,onOpenLocal:Function|null,onToggleFullscreen:Function,onResizeStart:Function}} props - 渲染入参
|
|
989
1035
|
* @returns {import('react').ReactElement} 元素
|
|
990
1036
|
*/
|
|
991
|
-
function PreviewPanel({ preview, pathImages, fullscreen, ratio, reading, onClose, onOpenLocal, onToggleFullscreen, onResizeStart, onScrollBody }) {
|
|
1037
|
+
function PreviewPanel({ preview, pathImages, fullscreen, ratio, reading, links, linksExpanded, onToggleLinks, onOpenLink, onClose, onOpenLocal, onToggleFullscreen, onResizeStart, onScrollBody }) {
|
|
992
1038
|
const isMedia = preview.kind === 'image' || preview.kind === 'video'
|
|
993
1039
|
const previewPath = splitRelPath(preview.rel)
|
|
994
1040
|
|
|
1041
|
+
/* ── v0.12 引用条 ────────────────────────────────────
|
|
1042
|
+
* 位置:预览头**下面**、正文**上面** —— 一条可折叠的窄条。
|
|
1043
|
+
*
|
|
1044
|
+
* 为什么不塞进正文:正文是 Markdown 渲染的,插进去会**被滚动带走**,
|
|
1045
|
+
* 还容易跟渲染器打架。预览头也放不下(38px 里已经有面包屑 + 三个按钮 + 拖拽把手)。
|
|
1046
|
+
*
|
|
1047
|
+
* 默认**折叠**,只显示两个计数,展开才占高度。空态与失败态文案**分开** ——
|
|
1048
|
+
* 「没有被引用」是一个结论,「读取失败」是另一个,不能都显示成空白。
|
|
1049
|
+
*/
|
|
1050
|
+
const linkItems = (title, items, emptyText) => h('div', { className: 'knit-links-group' },
|
|
1051
|
+
h('div', { className: 'knit-links-label' }, title),
|
|
1052
|
+
items.length === 0
|
|
1053
|
+
? h('div', { className: 'knit-links-empty' }, emptyText)
|
|
1054
|
+
: h('ul', { className: 'knit-links-list' },
|
|
1055
|
+
items.map((item) => h('li', { key: item.rel },
|
|
1056
|
+
h('button', {
|
|
1057
|
+
type: 'button',
|
|
1058
|
+
className: 'knit-link-row',
|
|
1059
|
+
title: item.rel,
|
|
1060
|
+
onClick: () => onOpenLink(item),
|
|
1061
|
+
},
|
|
1062
|
+
h('span', { className: 'knit-link-name' }, item.title),
|
|
1063
|
+
h('span', { className: 'knit-link-path' }, item.rel))))))
|
|
1064
|
+
|
|
1065
|
+
const linksBar = (() => {
|
|
1066
|
+
if (!links || !onToggleLinks) return null
|
|
1067
|
+
if (links.status === 'loading') {
|
|
1068
|
+
return h('div', { className: 'knit-links' },
|
|
1069
|
+
h('div', { className: 'knit-links-state' }, t('preview.loading')))
|
|
1070
|
+
}
|
|
1071
|
+
if (links.status !== 'ready') {
|
|
1072
|
+
return h('div', { className: 'knit-links' },
|
|
1073
|
+
h('div', { className: 'knit-links-state' }, t('links.failed')))
|
|
1074
|
+
}
|
|
1075
|
+
const incoming = links.incoming || []
|
|
1076
|
+
const outgoing = links.outgoing || []
|
|
1077
|
+
return h('div', { className: `knit-links${linksExpanded ? ' is-open' : ''}` },
|
|
1078
|
+
h('button', {
|
|
1079
|
+
type: 'button',
|
|
1080
|
+
className: 'knit-links-head',
|
|
1081
|
+
'aria-expanded': linksExpanded ? 'true' : 'false',
|
|
1082
|
+
onClick: onToggleLinks,
|
|
1083
|
+
title: links.rel,
|
|
1084
|
+
},
|
|
1085
|
+
h('span', { className: 'knit-links-arrow' }, linksExpanded ? '▾' : '▸'),
|
|
1086
|
+
h('span', { className: 'knit-links-summary' },
|
|
1087
|
+
t('links.summary', { in: links.incomingTotal || 0, out: links.outgoingTotal || 0 }))),
|
|
1088
|
+
links.limited
|
|
1089
|
+
? h('div', { className: 'knit-links-note' }, t('links.incomplete'))
|
|
1090
|
+
: null,
|
|
1091
|
+
linksExpanded
|
|
1092
|
+
? h('div', { className: 'knit-links-body' },
|
|
1093
|
+
linkItems(t('links.incoming'), incoming, t('links.noneIn')),
|
|
1094
|
+
linkItems(t('links.outgoing'), outgoing, t('links.noneOut')),
|
|
1095
|
+
(links.incomingTotal > incoming.length || links.outgoingTotal > outgoing.length)
|
|
1096
|
+
? h('div', { className: 'knit-links-note' },
|
|
1097
|
+
t('links.more', {
|
|
1098
|
+
count: Math.max(
|
|
1099
|
+
(links.incomingTotal || 0) - incoming.length,
|
|
1100
|
+
(links.outgoingTotal || 0) - outgoing.length,
|
|
1101
|
+
),
|
|
1102
|
+
}))
|
|
1103
|
+
: null)
|
|
1104
|
+
: null)
|
|
1105
|
+
})()
|
|
1106
|
+
|
|
995
1107
|
// 图片/视频不读正文,直接用同源字节地址渲染;Markdown 才走加载 / MarkdownText / 降级。
|
|
996
1108
|
const body = preview.status === 'loading'
|
|
997
1109
|
? h('div', { className: 'knit-preview-note' }, t('preview.loading'))
|
|
@@ -1057,6 +1169,8 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
1057
1169
|
title: onOpenLocal ? t('preview.openLocal', { path: preview.rel }) : preview.rel,
|
|
1058
1170
|
}, t('preview.openLocalBtn')),
|
|
1059
1171
|
h('button', { className: 'knit-preview-close', onClick: onClose, title: t('preview.close') }, '✕')),
|
|
1172
|
+
// v0.12 引用条:夹在头与正文之间,不参与正文滚动
|
|
1173
|
+
linksBar,
|
|
1060
1174
|
h('div', {
|
|
1061
1175
|
className: `knit-preview-body${isMedia ? ' is-media' : ''}`,
|
|
1062
1176
|
onScroll: onScrollBody,
|
|
@@ -1102,6 +1216,12 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
1102
1216
|
// 阅读态也不会丢。放在最后,不动前面任何 hook 的槽位。
|
|
1103
1217
|
const [readingTick, setReadingTick] = React.useState(0)
|
|
1104
1218
|
|
|
1219
|
+
// v0.12 引用关系。`null` = 还没请求;请求回来是 `{status, incoming, outgoing, …}`。
|
|
1220
|
+
// **只跟着 previewRel 走**,绝不进列表轮询路径 —— 那份解析要读全库,
|
|
1221
|
+
// 塞进「每 5 秒一次」会把面板拖垮(SDD §3.5)。
|
|
1222
|
+
const [links, setLinks] = React.useState(null)
|
|
1223
|
+
const [linksExpandedTick, setLinksExpandedTick] = React.useState(0)
|
|
1224
|
+
|
|
1105
1225
|
React.useEffect(() => {
|
|
1106
1226
|
const host = listRef.current
|
|
1107
1227
|
if (!host || typeof ResizeObserver === 'undefined') return undefined
|
|
@@ -1321,6 +1441,12 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
1321
1441
|
// 预览进入 loading 时去宿主取正文
|
|
1322
1442
|
const previewRel = preview && preview.rel
|
|
1323
1443
|
const previewStatus = preview && preview.status
|
|
1444
|
+
/**
|
|
1445
|
+
* 只有 Markdown 有引用关系 —— 链接图里只有 `.md`,所以对图片/视频请求
|
|
1446
|
+
* 必然拿到 `knit/not-found`,面板会把它显示成「读取失败」。
|
|
1447
|
+
* **与其显示一个假的失败,不如压根不请求、也不显示这一条。**
|
|
1448
|
+
*/
|
|
1449
|
+
const previewIsDoc = !preview || (preview.kind !== 'image' && preview.kind !== 'video')
|
|
1324
1450
|
|
|
1325
1451
|
/** 阅读态 = 当前这一篇被滚过。换一篇自然为 false(派生,不用复位 effect)。 */
|
|
1326
1452
|
const reading = Boolean(previewRel) && readingDocs.has(readingKey(sessionId, previewRel))
|
|
@@ -1372,6 +1498,51 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
1372
1498
|
return () => { alive = false }
|
|
1373
1499
|
}, [previewRel, previewStatus, sessionId])
|
|
1374
1500
|
|
|
1501
|
+
/**
|
|
1502
|
+
* v0.12:引用关系。**只在打开某一篇时请求一次**,换篇重取。
|
|
1503
|
+
*
|
|
1504
|
+
* 两条刻意的选择:
|
|
1505
|
+
* - 不依赖 `previewStatus` —— 引用关系与「正文读没读出来」无关
|
|
1506
|
+
* - 不进列表轮询 —— 全库解析很贵,只在用户真打开一篇时才发生
|
|
1507
|
+
* 服务端按签名缓存,所以连续换篇不会重复解析。
|
|
1508
|
+
*/
|
|
1509
|
+
React.useEffect(() => {
|
|
1510
|
+
if (!previewRel || !previewIsDoc) {
|
|
1511
|
+
setLinks(null)
|
|
1512
|
+
return undefined
|
|
1513
|
+
}
|
|
1514
|
+
let alive = true
|
|
1515
|
+
setLinks({ status: 'loading' })
|
|
1516
|
+
const run = async () => {
|
|
1517
|
+
try {
|
|
1518
|
+
const url = `${LINKS_API}?sessionId=${encodeURIComponent(sessionId)}&rel=${encodeURIComponent(previewRel)}`
|
|
1519
|
+
const res = await fetch(url, { headers: { accept: 'application/json' }, cache: 'no-store' })
|
|
1520
|
+
const data = await res.json()
|
|
1521
|
+
if (!alive) return
|
|
1522
|
+
setLinks(data && data.ok
|
|
1523
|
+
? { status: 'ready', ...data }
|
|
1524
|
+
: { status: 'error', error: hostMessage(data) })
|
|
1525
|
+
} catch (error) {
|
|
1526
|
+
if (!alive) return
|
|
1527
|
+
setLinks({ status: 'error', error: String((error && error.message) || error) })
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
run()
|
|
1531
|
+
return () => { alive = false }
|
|
1532
|
+
}, [previewRel, previewIsDoc, sessionId])
|
|
1533
|
+
|
|
1534
|
+
/** 展开 / 收起引用条。真相在模块级 `expandedLinks`,组件只留计数器(理由同阅读态)。 */
|
|
1535
|
+
const toggleLinks = React.useCallback(() => {
|
|
1536
|
+
if (!previewRel) return
|
|
1537
|
+
const key = readingKey(sessionId, previewRel)
|
|
1538
|
+
if (expandedLinks.has(key)) expandedLinks.delete(key)
|
|
1539
|
+
else expandedLinks.add(key)
|
|
1540
|
+
setLinksExpandedTick((n) => n + 1)
|
|
1541
|
+
}, [previewRel, sessionId])
|
|
1542
|
+
const linksExpanded = Boolean(previewRel)
|
|
1543
|
+
&& expandedLinks.has(readingKey(sessionId, previewRel))
|
|
1544
|
+
void linksExpandedTick
|
|
1545
|
+
|
|
1375
1546
|
// 相对路径图片解析器:按当前文档所在目录解析。MarkdownText 按引用身份 memo,
|
|
1376
1547
|
// 所以必须 useMemo 住,否则每帧都会重解析整篇 markdown。
|
|
1377
1548
|
const pathImages = React.useMemo(
|
|
@@ -1552,6 +1723,14 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
1552
1723
|
ratio,
|
|
1553
1724
|
reading,
|
|
1554
1725
|
onScrollBody,
|
|
1726
|
+
// v0.12 引用条
|
|
1727
|
+
links,
|
|
1728
|
+
linksExpanded,
|
|
1729
|
+
onToggleLinks: toggleLinks,
|
|
1730
|
+
// 点引用列表里的一项 → 就地预览那一篇。
|
|
1731
|
+
// **走订阅制 requestPreview,不碰列表** —— 用户点一下就该立刻有反应
|
|
1732
|
+
// (AGENTS.md §6.4 的教训:即时信号别藏在轮询里)。
|
|
1733
|
+
onOpenLink: (item) => requestPreview(item),
|
|
1555
1734
|
// 拿不到绝对路径就不给点(而不是点了没反应)
|
|
1556
1735
|
onOpenLocal: previewAbsPath ? openPreviewLocal : null,
|
|
1557
1736
|
onClose: closePreview,
|
|
@@ -1922,6 +2101,17 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
1922
2101
|
*/
|
|
1923
2102
|
const readingDocs = new Set()
|
|
1924
2103
|
|
|
2104
|
+
/**
|
|
2105
|
+
* 已经**展开过引用条**的文档,key 见 `readingKey`(同一个 key 约定)。
|
|
2106
|
+
*
|
|
2107
|
+
* 与 `readingDocs` 同一条理由(见 `AGENTS.md` §6.9):**「用户做过的事」不能只放
|
|
2108
|
+
* 组件 state** —— 宿主重挂载会把它清零,用户就得再点一次。
|
|
2109
|
+
* 语义是「这一篇在这个会话里被展开过」。
|
|
2110
|
+
*
|
|
2111
|
+
* @type {Set<string>}
|
|
2112
|
+
*/
|
|
2113
|
+
const expandedLinks = new Set()
|
|
2114
|
+
|
|
1925
2115
|
/**
|
|
1926
2116
|
* 阅读态的 key:同一会话里的同一篇文档算一个。
|
|
1927
2117
|
* @param {string} sessionId - 会话 id
|
package/src/host/index.js
CHANGED
|
@@ -19,6 +19,8 @@ import { join, relative, resolve, sep } from 'node:path'
|
|
|
19
19
|
import { homedir } from 'node:os'
|
|
20
20
|
import { extractKeywords, rankByRelevance, topicLabel } from './relevance.js'
|
|
21
21
|
import { registerKnitDocsTool } from './tool.js'
|
|
22
|
+
// v0.12:引用关系。`links.js` **不反过来 import 本文件**(依赖由这里注入),所以没有环。
|
|
23
|
+
import { buildLinkGraph, linksOf } from './links.js'
|
|
22
24
|
|
|
23
25
|
export const name = 'dsh-knit'
|
|
24
26
|
|
|
@@ -844,6 +846,21 @@ export function apply(ctx) {
|
|
|
844
846
|
return
|
|
845
847
|
}
|
|
846
848
|
|
|
849
|
+
if (url.pathname === `${ROUTE_PREFIX}/api/links`) {
|
|
850
|
+
// v0.12:某篇的「谁引用了它 / 它引用了谁」。
|
|
851
|
+
// 形态逐字照抄 /api/doc —— 缺 rel 走同一个错误码,不新增读文件原语:
|
|
852
|
+
// 图只用 collectDocs / readDocument 建,两者本身已强制「必须在工作区内」。
|
|
853
|
+
const rel = url.searchParams.get('rel') || ''
|
|
854
|
+
if (!rel) {
|
|
855
|
+
sendJson(res, 400, { ok: false, code: ERROR_CODES.missingRel })
|
|
856
|
+
return
|
|
857
|
+
}
|
|
858
|
+
const graph = await buildLinkGraph(root, { list: collectDocs, read: readDocument })
|
|
859
|
+
const payload = linksOf(graph, rel)
|
|
860
|
+
sendJson(res, payload.ok ? 200 : 404, payload)
|
|
861
|
+
return
|
|
862
|
+
}
|
|
863
|
+
|
|
847
864
|
sendJson(res, 404, { ok: false, code: ERROR_CODES.notFoundRoute })
|
|
848
865
|
} catch (error) {
|
|
849
866
|
sendJson(res, 500, { ok: false, code: ERROR_CODES.internal, detail: String((error && error.message) || error) })
|
|
@@ -852,7 +869,7 @@ export function apply(ctx) {
|
|
|
852
869
|
|
|
853
870
|
webCtx.effect(() => {
|
|
854
871
|
const unregister = webCtx.webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler })
|
|
855
|
-
console.log(`[${name}] route ready: ${ROUTE_PREFIX}/api/recent, ${ROUTE_PREFIX}/api/doc, ${ROUTE_PREFIX}/api/raw`)
|
|
872
|
+
console.log(`[${name}] route ready: ${ROUTE_PREFIX}/api/recent, ${ROUTE_PREFIX}/api/doc, ${ROUTE_PREFIX}/api/raw, ${ROUTE_PREFIX}/api/links`)
|
|
856
873
|
return () => unregister()
|
|
857
874
|
}, 'dsh-knit: host route')
|
|
858
875
|
})
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knit · **引用关系**(v0.12)
|
|
3
|
+
*
|
|
4
|
+
* 从工作区的 Markdown 里解析出「谁引用了谁」,供反向链接面板使用。
|
|
5
|
+
*
|
|
6
|
+
* ## 为什么是「宁可少,不可错」
|
|
7
|
+
*
|
|
8
|
+
* 设计依据是拿真实语料量出来的(`01_ Knit PRD/Knit_SDD-v0.12-链接解析与反向链接面板.md` §一):
|
|
9
|
+
*
|
|
10
|
+
* - `[[wikilink]]` 在真实语料里出现 **0 次** —— 所以**不解析 Obsidian 语法**,
|
|
11
|
+
* 真正要认的是 `` `path/x.md` ``(出现 946 次)
|
|
12
|
+
* - **歧义 basename 是最大误报源**:`SKILL.md` 有 20 个、`01_公众号正文.md` 有 12 个。
|
|
13
|
+
* 一条只写了 basename 的提及**无法确定是哪一篇** —— 而那些提及多半在讲
|
|
14
|
+
* 「文件名约定」而不是某一篇具体文档(实测 13% 的边是这么来的)
|
|
15
|
+
*
|
|
16
|
+
* 所以本模块**猜的一律不算**:解析不出来就是没有链接。
|
|
17
|
+
* 少显示一条真链接,比显示一条假链接轻。
|
|
18
|
+
*
|
|
19
|
+
* ## 这是纯解析,不碰排序
|
|
20
|
+
*
|
|
21
|
+
* 链接图当排序信号**实测补不上**词面错配那个缺口(目标文档 BM25 第 45 名 →
|
|
22
|
+
* 融合后 16~24 名,RRF 最好第 8,从未进 top-5)。所以这里只产出「关系」,不参与打分。
|
|
23
|
+
*
|
|
24
|
+
* ## 依赖是注入的,不 import `index.js`
|
|
25
|
+
*
|
|
26
|
+
* `index.js` 要 import 本模块来挂路由;如果本模块反过来 import 它的
|
|
27
|
+
* `collectDocs` / `readDocument`,就成环了。所以照 `tool.js` 的先例
|
|
28
|
+
* (`knitDocsDefinition(scan, read)`)**由调用方把两个函数传进来**。
|
|
29
|
+
* 好处不止是避环:纯函数可以拿假数据直接测,不用起文件系统。
|
|
30
|
+
*
|
|
31
|
+
* ⚠️ **已知边界**(都写在 SDD §八):不做模糊匹配、不处理 `../` 上跳、
|
|
32
|
+
* 不区分代码块内的「示例路径」、正文按 `readDocument` 的 512KB 上限截断。
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** 解析一篇正文时最多认多少条候选,防御性上限(正常文档远低于此)。 */
|
|
36
|
+
const MAX_REFS_PER_DOC = 500
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 从正文里抽出**候选**引用(还没解析成 rel)。
|
|
40
|
+
*
|
|
41
|
+
* 三种真实写法,按语料出现频次排:
|
|
42
|
+
* 1. 反引号包裹的路径 —— `` `docs/A.md` ``(946 次,主力)
|
|
43
|
+
* 2. 标准 Markdown 链接 —— `[文字](docs/A.md)`(15 次)
|
|
44
|
+
* 3. 裸路径提及 —— `见 docs/A.md`(前面必须是空白或括号,避免咬到 `a.md.bak` 这类)
|
|
45
|
+
*
|
|
46
|
+
* **不含 `[[wikilink]]`** —— 真实语料 0 次,不做。
|
|
47
|
+
*
|
|
48
|
+
* @param {string} text - 正文(原文,**不是**小写化的 haystack)
|
|
49
|
+
* @returns {string[]} 去重后的候选项,保持出现顺序
|
|
50
|
+
*/
|
|
51
|
+
export function extractRefs(text) {
|
|
52
|
+
if (typeof text !== 'string' || text === '') return []
|
|
53
|
+
const out = []
|
|
54
|
+
const seen = new Set()
|
|
55
|
+
const push = (raw) => {
|
|
56
|
+
const v = String(raw || '').trim()
|
|
57
|
+
if (!v || seen.has(v)) return
|
|
58
|
+
if (out.length >= MAX_REFS_PER_DOC) return
|
|
59
|
+
// 外链不是本工作区的文档
|
|
60
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(v)) return
|
|
61
|
+
if (!/\.md$/i.test(v)) return
|
|
62
|
+
seen.add(v)
|
|
63
|
+
out.push(v)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ① 反引号:允许空格(`00_ Knit PRD/x.md` 这种目录名真实存在),不允许换行/反引号
|
|
67
|
+
for (const m of text.matchAll(/`([^`\n]+?)`/g)) push(m[1])
|
|
68
|
+
// ② Markdown 链接:取 () 里的路径,忽略其后的 #锚点
|
|
69
|
+
for (const m of text.matchAll(/\]\(\s*([^)\s]+?)(?:#[^)\s]*)?\s*\)/g)) push(m[1])
|
|
70
|
+
// ③ 裸路径:前面是行首/空白/中文括号,路径本身不含空格(有空格就得用反引号),
|
|
71
|
+
// 末尾用 `(?![\w.])` 挡住 `a.md.bak` 这类「更长但不是 .md」的字符串
|
|
72
|
+
//
|
|
73
|
+
// ⚠️ 必须在**挖掉反引号与链接目标之后的副本**上跑。否则
|
|
74
|
+
// `` `00_ Knit PRD/x.md` `` 里的 `PRD/x.md`(前面正好是空格)会被当成
|
|
75
|
+
// 一条独立候选 —— 这是测试抓出来的真实缺陷,不是假想。
|
|
76
|
+
const masked = text
|
|
77
|
+
.replace(/`[^`\n]*`/g, (s) => ' '.repeat(s.length))
|
|
78
|
+
.replace(/\]\([^)\n]*\)/g, (s) => ' '.repeat(s.length))
|
|
79
|
+
const BARE = /(?:^|[\s((])((?:[\w\u4e00-\u9fa5.@+-]+\/)*[\w\u4e00-\u9fa5.@+-]+\.md)(?![\w.])/gm
|
|
80
|
+
for (const m of masked.matchAll(BARE)) push(m[1])
|
|
81
|
+
|
|
82
|
+
return out
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** rel 用 `/` 连接(`index.js` 保证),所以这里也按 `/` 取目录,不碰 `node:path`。 */
|
|
86
|
+
const dirOf = (rel) => {
|
|
87
|
+
const i = String(rel).lastIndexOf('/')
|
|
88
|
+
return i === -1 ? '' : String(rel).slice(0, i)
|
|
89
|
+
}
|
|
90
|
+
const baseOf = (rel) => {
|
|
91
|
+
const s = String(rel)
|
|
92
|
+
const i = s.lastIndexOf('/')
|
|
93
|
+
return i === -1 ? s : s.slice(i + 1)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 为一批 rel 建解析上下文。**纯数据,可缓存**。
|
|
98
|
+
*
|
|
99
|
+
* @param {string[]} rels - 工作区里全部文档的 rel
|
|
100
|
+
* @returns {{relSet:Set<string>, rels:string[], byBase:Map<string,string[]>}}
|
|
101
|
+
*/
|
|
102
|
+
export function createIndex(rels) {
|
|
103
|
+
const relSet = new Set(rels)
|
|
104
|
+
const byBase = new Map()
|
|
105
|
+
for (const rel of rels) {
|
|
106
|
+
const b = baseOf(rel)
|
|
107
|
+
if (!byBase.has(b)) byBase.set(b, [])
|
|
108
|
+
byBase.get(b).push(rel)
|
|
109
|
+
}
|
|
110
|
+
return { relSet, rels, byBase }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 把一条候选解析成工作区内的 rel,**解析不出来就返回 null**。
|
|
115
|
+
*
|
|
116
|
+
* 优先级(SDD §3.3,顺序本身就是设计):
|
|
117
|
+
* 1. **引用方所在目录优先** —— 这才是相对路径的语义。
|
|
118
|
+
* 所以 `docs/B.md` 里写 `README.md` 会先找 `docs/README.md`
|
|
119
|
+
* 2. 工作区根
|
|
120
|
+
* 3. **缩写后缀**:`-SDD-v0.6.md` 这种省略了公共前缀的写法(真实语料里存在),
|
|
121
|
+
* 必须**唯一命中**才算
|
|
122
|
+
* 4. **basename**:仅当全库该名字**唯一**时才算
|
|
123
|
+
* 5. 否则 → `null`(§一 的 13% 误报就是这里挡掉的)
|
|
124
|
+
*
|
|
125
|
+
* @param {string} raw - 候选项
|
|
126
|
+
* @param {object} index - `createIndex()` 的产物
|
|
127
|
+
* @param {string} [referrerRel] - 引用方的 rel;不传则跳过第 1 步
|
|
128
|
+
* @returns {string|null}
|
|
129
|
+
*/
|
|
130
|
+
export function resolveRef(raw, index, referrerRel) {
|
|
131
|
+
const v = String(raw || '').trim()
|
|
132
|
+
if (!v || !index || !(index.relSet instanceof Set)) return null
|
|
133
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(v)) return null
|
|
134
|
+
if (!/\.md$/i.test(v)) return null
|
|
135
|
+
|
|
136
|
+
// 去掉 ./ 前缀(`./docs/A.md` 是常见写法,但不是本工作区的 rel)
|
|
137
|
+
const clean = v.replace(/^\.\//, '')
|
|
138
|
+
|
|
139
|
+
// ① 引用方所在目录
|
|
140
|
+
if (referrerRel) {
|
|
141
|
+
const dir = dirOf(referrerRel)
|
|
142
|
+
if (dir) {
|
|
143
|
+
const sibling = `${dir}/${clean}`
|
|
144
|
+
if (index.relSet.has(sibling)) return sibling
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ② 工作区根
|
|
149
|
+
if (index.relSet.has(clean)) return clean
|
|
150
|
+
|
|
151
|
+
// ③ 缩写后缀:只在以 `-` 开头时试,且必须唯一
|
|
152
|
+
if (clean.startsWith('-')) {
|
|
153
|
+
const tail = clean.slice(1)
|
|
154
|
+
const hits = index.rels.filter((r) => r.endsWith(tail))
|
|
155
|
+
if (hits.length === 1) return hits[0]
|
|
156
|
+
return null
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ④ basename,仅当唯一
|
|
160
|
+
const same = index.byBase.get(baseOf(clean))
|
|
161
|
+
if (same && same.length === 1) return same[0]
|
|
162
|
+
|
|
163
|
+
// ⑤ 猜不了就不算
|
|
164
|
+
return null
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** 模块内的图缓存:一个工作区一张图。key 是 `root`,值是 `{signature, graph}`。 */
|
|
168
|
+
const CACHE = new Map()
|
|
169
|
+
/** 进行中的构建,避免并发请求解析两遍。key 是 `root`。 */
|
|
170
|
+
const INFLIGHT = new Map()
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 图签名:变了才重建。用「篇数 + 最大 mtime + 是否被扫描上限截断」——
|
|
174
|
+
* 三个都便宜(`list()` 本身已经按 mtime 缓存了元信息),且足以发现增删改。
|
|
175
|
+
*/
|
|
176
|
+
function signatureOf(listed) {
|
|
177
|
+
const docs = (listed && listed.docs) || []
|
|
178
|
+
let max = 0
|
|
179
|
+
for (const d of docs) if (d.mtimeMs > max) max = d.mtimeMs
|
|
180
|
+
return `${docs.length}:${max}:${listed && listed.truncated ? 1 : 0}`
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 建(或复用缓存的)引用图。
|
|
185
|
+
*
|
|
186
|
+
* @param {string} root - 工作区根
|
|
187
|
+
* @param {{list:Function, read:Function}} io - `list(root)` → `{docs, truncated}`;`read(root, rel)` → `{ok, text}`
|
|
188
|
+
* @returns {Promise<object>} `{ signature, docs:Map<rel,title>, out:Map<rel,Set>, in:Map<rel,Set>, limited, parsed, skipped }`
|
|
189
|
+
*/
|
|
190
|
+
export async function buildLinkGraph(root, io) {
|
|
191
|
+
const listed = await io.list(root)
|
|
192
|
+
const signature = signatureOf(listed)
|
|
193
|
+
const hit = CACHE.get(root)
|
|
194
|
+
if (hit && hit.signature === signature) return hit.graph
|
|
195
|
+
|
|
196
|
+
const pending = INFLIGHT.get(root)
|
|
197
|
+
if (pending) return pending
|
|
198
|
+
|
|
199
|
+
const work = (async () => {
|
|
200
|
+
const docs = (listed && listed.docs) || []
|
|
201
|
+
const titles = new Map(docs.map((d) => [d.rel, d.title || baseOf(d.rel)]))
|
|
202
|
+
const index = createIndex(docs.map((d) => d.rel))
|
|
203
|
+
const out = new Map()
|
|
204
|
+
let parsed = 0
|
|
205
|
+
let skipped = 0
|
|
206
|
+
|
|
207
|
+
for (const doc of docs) {
|
|
208
|
+
let text = ''
|
|
209
|
+
try {
|
|
210
|
+
const r = await io.read(root, doc.rel)
|
|
211
|
+
if (!r || r.ok !== true) {
|
|
212
|
+
skipped += 1
|
|
213
|
+
continue
|
|
214
|
+
}
|
|
215
|
+
text = r.text || ''
|
|
216
|
+
} catch {
|
|
217
|
+
skipped += 1
|
|
218
|
+
continue
|
|
219
|
+
}
|
|
220
|
+
parsed += 1
|
|
221
|
+
const targets = new Set()
|
|
222
|
+
for (const raw of extractRefs(text)) {
|
|
223
|
+
const rel = resolveRef(raw, index, doc.rel)
|
|
224
|
+
if (rel && rel !== doc.rel) targets.add(rel)
|
|
225
|
+
}
|
|
226
|
+
out.set(doc.rel, targets)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// 反向边由正向边推出来,避免两处逻辑不一致
|
|
230
|
+
const incoming = new Map(docs.map((d) => [d.rel, new Set()]))
|
|
231
|
+
for (const [from, targets] of out) {
|
|
232
|
+
for (const to of targets) {
|
|
233
|
+
if (incoming.has(to)) incoming.get(to).add(from)
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const graph = {
|
|
238
|
+
signature,
|
|
239
|
+
titles,
|
|
240
|
+
out,
|
|
241
|
+
in: incoming,
|
|
242
|
+
limited: !!(listed && listed.truncated),
|
|
243
|
+
parsed,
|
|
244
|
+
skipped,
|
|
245
|
+
}
|
|
246
|
+
CACHE.set(root, { signature, graph })
|
|
247
|
+
INFLIGHT.delete(root)
|
|
248
|
+
return graph
|
|
249
|
+
})()
|
|
250
|
+
|
|
251
|
+
INFLIGHT.set(root, work)
|
|
252
|
+
try {
|
|
253
|
+
return await work
|
|
254
|
+
} catch (err) {
|
|
255
|
+
INFLIGHT.delete(root)
|
|
256
|
+
throw err
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** 仅供测试:清掉缓存,避免用例之间互相污染。 */
|
|
261
|
+
export function resetLinkCache() {
|
|
262
|
+
CACHE.clear()
|
|
263
|
+
INFLIGHT.clear()
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** 按「对方入度降序 + rel 字典序」排 —— 引用多的文档往往是主脉络,且顺序必须稳定。 */
|
|
267
|
+
function orderBy(rels, graph) {
|
|
268
|
+
return [...rels].sort((a, b) => {
|
|
269
|
+
const da = (graph.in.get(a) || new Set()).size
|
|
270
|
+
const db = (graph.in.get(b) || new Set()).size
|
|
271
|
+
if (da !== db) return db - da
|
|
272
|
+
return a < b ? -1 : a > b ? 1 : 0
|
|
273
|
+
})
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 取某一篇的引用关系。**只返回 `rel` + `title`** —— 与 `knit_docs` 同一条纪律,
|
|
278
|
+
* 不把图、haystack 之类的内部结构泄漏给客户端。
|
|
279
|
+
*
|
|
280
|
+
* @param {object} graph - `buildLinkGraph()` 的产物
|
|
281
|
+
* @param {string} rel - 目标文档
|
|
282
|
+
* @param {number} [limit] - 每侧最多返回多少条(计数仍给全量)
|
|
283
|
+
* @returns {object} 成功 `{ok:true, …}`;未知 rel 返回 `{ok:false, code:'knit/not-found'}`
|
|
284
|
+
*/
|
|
285
|
+
export function linksOf(graph, rel, limit = 50) {
|
|
286
|
+
if (!graph || !graph.titles || !graph.titles.has(rel)) {
|
|
287
|
+
return { ok: false, code: 'knit/not-found' }
|
|
288
|
+
}
|
|
289
|
+
const cap = Number.isFinite(limit) && limit > 0 ? Math.trunc(limit) : 50
|
|
290
|
+
const map = (set) => orderBy(set || new Set(), graph)
|
|
291
|
+
.map((r) => ({ rel: r, title: graph.titles.get(r) || baseOf(r) }))
|
|
292
|
+
|
|
293
|
+
const incoming = map(graph.in.get(rel))
|
|
294
|
+
const outgoing = map(graph.out.get(rel))
|
|
295
|
+
return {
|
|
296
|
+
ok: true,
|
|
297
|
+
rel,
|
|
298
|
+
incoming: incoming.slice(0, cap),
|
|
299
|
+
outgoing: outgoing.slice(0, cap),
|
|
300
|
+
incomingTotal: incoming.length,
|
|
301
|
+
outgoingTotal: outgoing.length,
|
|
302
|
+
limited: !!graph.limited,
|
|
303
|
+
}
|
|
304
|
+
}
|