dsh-reading-inbox 0.1.1 → 0.2.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/README.en.md +13 -9
- package/README.md +13 -9
- package/VERIFY.md +17 -0
- package/index.js +3 -2
- package/package.json +5 -3
- package/src/annotations.js +187 -0
- package/src/markdown.js +22 -2
- package/src/routes.js +28 -0
- package/src/store.js +148 -2
- package/src/tools.js +145 -0
- package/web/app.js +342 -1
- package/web/index.html +12 -0
- package/web/style.css +165 -0
package/README.en.md
CHANGED
|
@@ -27,8 +27,9 @@ This plugin is the small implementation of those three things. Everything stays
|
|
|
27
27
|
|
|
28
28
|
- **One-step clipping** — paste a URL; Readability extracts the article; Markdown + original HTML + title/author/date/source/excerpt are saved.
|
|
29
29
|
- **Inbox UI** — unread / reading / read / archived, search, tag filters, reading view, copy link, export Markdown.
|
|
30
|
+
- **Highlights and notes** — select text to highlight it (yellow / green / blue / red) and add a note. Anchors use quote + surrounding context, so a re-clip re-locates them automatically; missing text becomes stale instead of landing on the wrong sentence. Markdown export includes active annotations.
|
|
30
31
|
- **Local full-text search** — CJK is indexed as unigrams + bigrams, Latin as words; title and tags are boosted. No model call.
|
|
31
|
-
- **Agent tools** — `reading_clip`, `reading_search`, `reading_list`, `reading_read`, `reading_update`.
|
|
32
|
+
- **Agent tools** — `reading_clip`, `reading_search`, `reading_list`, `reading_read`, `reading_update`, `reading_highlight`.
|
|
32
33
|
- **Slash command** — `/inbox <url> [tag1,tag2]` without leaving the conversation.
|
|
33
34
|
- **Chinese-web friendly** — detects GBK / GB2312 / UTF-8 / Big5 so pages do not turn into mojibake.
|
|
34
35
|
- **Safe defaults** — http/https only; every redirect hop is re-validated; DNS answers are checked again at connect time (DNS rebinding defense); loopback, private networks, CGNAT, link-local and cloud metadata addresses are rejected; hard caps of 5 MB, 20 seconds and 5 redirects.
|
|
@@ -67,8 +68,9 @@ Restart `dsh web`. A **Reading inbox** row appears in the sidebar, and `/inbox`
|
|
|
67
68
|
|
|
68
69
|
1. Paste a URL into the top bar and press Enter.
|
|
69
70
|
2. Click an item to read it. Mark read, archive, copy the link, export Markdown, or edit tags on the right.
|
|
70
|
-
3.
|
|
71
|
-
4.
|
|
71
|
+
3. Select text in the article: a highlight toolbar appears. Pick a color, add an optional note, and save.
|
|
72
|
+
4. The search box searches title, body, tags and source as you type.
|
|
73
|
+
5. Click any tag to filter by it; click a highlight or “Locate” in the annotation list to jump back to the source sentence.
|
|
72
74
|
|
|
73
75
|
### Ask the agent
|
|
74
76
|
|
|
@@ -84,7 +86,7 @@ Search my saved articles about SSRF and read the key paragraphs
|
|
|
84
86
|
Mark that article as read and add the tag security
|
|
85
87
|
```
|
|
86
88
|
|
|
87
|
-
The model calls `reading_clip`, `reading_search`, `reading_read` and `
|
|
89
|
+
The model calls `reading_clip`, `reading_search`, `reading_read`, `reading_update` and `reading_highlight`. The plugin adds a system-prompt section explaining when to use them.
|
|
88
90
|
|
|
89
91
|
### Slash command
|
|
90
92
|
|
|
@@ -103,6 +105,7 @@ Command output is shown in the UI only; the full article is not pushed into mode
|
|
|
103
105
|
| `reading_list` | List by date, filtered by status/tag. |
|
|
104
106
|
| `reading_read` | Read a Markdown slice by id; use `offset` / `nextOffset` for long articles and `hasMore` to know whether it is complete. |
|
|
105
107
|
| `reading_update` | Change status or tags. Status: `unread` / `reading` / `read` / `archived`. |
|
|
108
|
+
| `reading_highlight` | Create/list/update/delete highlights and notes. `action` is `create` / `list` / `update` / `delete`; `create` takes a `quote` from the article (or `startOffset`/`endOffset`), plus optional `note` and `color`. |
|
|
106
109
|
|
|
107
110
|
## Configuration
|
|
108
111
|
|
|
@@ -130,7 +133,8 @@ Set these in the shell that starts DSH, or in the profile's `.env`, then restart
|
|
|
130
133
|
└── <id>/
|
|
131
134
|
├── article.md # clean Markdown body
|
|
132
135
|
├── original.html # original HTML snapshot (archive only, never rendered)
|
|
133
|
-
|
|
136
|
+
├── annotations.json # highlights/notes (created on the first annotation)
|
|
137
|
+
└── meta.json # title, URL, author, date, tags, status, annotation count
|
|
134
138
|
```
|
|
135
139
|
|
|
136
140
|
Back up the whole directory, or sync `clips/` and `index.json`.
|
|
@@ -156,7 +160,7 @@ npm test
|
|
|
156
160
|
npm run verify
|
|
157
161
|
```
|
|
158
162
|
|
|
159
|
-
`npm run verify` starts a local test page and walks the whole path: fetch → extract → index → search → read → export. It prints machine-readable JSON.
|
|
163
|
+
`npm run verify` starts a local test page and walks the whole path: fetch → extract → index → search → read → annotate → export. It prints machine-readable JSON.
|
|
160
164
|
|
|
161
165
|
Local UI:
|
|
162
166
|
|
|
@@ -171,7 +175,7 @@ See [VERIFY.md](VERIFY.md) for the end-to-end check inside a real DSH.
|
|
|
171
175
|
|
|
172
176
|
```sh
|
|
173
177
|
npm run build:client # rebuild client/client.js with esbuild
|
|
174
|
-
npm test #
|
|
178
|
+
npm test # 27 tests: extraction, rendering, SSRF, DNS checks, annotation anchoring, store races, search, routes, client bundle
|
|
175
179
|
npm run verify # end-to-end self-check
|
|
176
180
|
```
|
|
177
181
|
|
|
@@ -188,14 +192,14 @@ Layout:
|
|
|
188
192
|
|
|
189
193
|
## Limits and roadmap
|
|
190
194
|
|
|
191
|
-
0.
|
|
195
|
+
0.2.0 is deliberately small:
|
|
192
196
|
|
|
193
197
|
- [ ] SPA / login / anti-bot pages may yield no article; add a Playwright fallback.
|
|
194
198
|
- [ ] Images still point at remote URLs; download them into `clips/<id>/assets/` for a full offline archive.
|
|
195
199
|
- [ ] No PDF support; use `dsh-pdf-mineru` or a document reader for PDFs.
|
|
196
200
|
- [ ] No browser extension or RSS import yet.
|
|
197
201
|
- [ ] No sync/backup yet; the directory is portable.
|
|
198
|
-
- [ ] Search is local BM25-style ranking; add chunking and highlighting next.
|
|
202
|
+
- [ ] Search is local BM25-style ranking; add chunking and result highlighting next.
|
|
199
203
|
|
|
200
204
|
## License
|
|
201
205
|
|
package/README.md
CHANGED
|
@@ -27,8 +27,9 @@ DSH 已经有 `web_fetch`、`read_url` 这类“读一次”的工具,但它
|
|
|
27
27
|
|
|
28
28
|
- **一键剪藏**:粘贴 URL → Readability 提取正文 → Markdown + 原文 HTML + 标题/作者/日期/来源/摘要。
|
|
29
29
|
- **收件箱界面**:未读 / 在读 / 已读 / 归档,搜索、标签筛选、详情阅读、复制链接、导出 Markdown。
|
|
30
|
+
- **划线与批注**:选中正文文字即可高亮(黄 / 绿 / 蓝 / 红),写笔记;批注按“引文 + 前后文”锚定,文章重新抓取后自动重定位,失败会标为失效而不是错贴。导出 Markdown 时带上有效批注。
|
|
30
31
|
- **全文检索**:中文按单字 + 二元组切分,英文按词切分;标题和标签权重更高。纯本地,不调用模型。
|
|
31
|
-
- **Agent 工具**:`reading_clip`、`reading_search`、`reading_list`、`reading_read`、`reading_update`。
|
|
32
|
+
- **Agent 工具**:`reading_clip`、`reading_search`、`reading_list`、`reading_read`、`reading_update`、`reading_highlight`。
|
|
32
33
|
- **斜杠命令**:`/inbox <url> [tag1,tag2]`,不离开对话就能收藏。
|
|
33
34
|
- **中文网页友好**:自动识别 GBK / GB2312 / UTF-8 / Big5 编码,避免乱码。
|
|
34
35
|
- **安全默认**:只允许 http/https;逐跳校验重定向;DNS 解析结果在连接时再校验一次(防 DNS rebinding);拒绝本机/内网/云元数据地址;5 MB、20 秒、5 次重定向的硬上限。
|
|
@@ -67,8 +68,9 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
|
|
|
67
68
|
|
|
68
69
|
1. 把网页链接粘贴到顶部的输入框,回车。
|
|
69
70
|
2. 左侧点击文章开始阅读;右侧可以标记已读、归档、复制链接、导出 Markdown、编辑标签。
|
|
70
|
-
3.
|
|
71
|
-
4.
|
|
71
|
+
3. 选中正文文字,会浮出高亮工具栏:选颜色、写批注(可选),点“保存高亮”。
|
|
72
|
+
4. 搜索框支持标题、正文、标签、来源;输入即搜。
|
|
73
|
+
5. 点标签可以按标签筛选;点正文里的高亮或批注列表里的“定位”可以回到原文。
|
|
72
74
|
|
|
73
75
|
### 让 Agent 帮你
|
|
74
76
|
|
|
@@ -84,7 +86,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
|
|
|
84
86
|
把刚才那篇标记为已读,再加一个标签:security
|
|
85
87
|
```
|
|
86
88
|
|
|
87
|
-
模型会调用 `reading_clip`、`reading_search`、`reading_read`、`reading_update`。系统提示里已经写了这些工具的使用时机。
|
|
89
|
+
模型会调用 `reading_clip`、`reading_search`、`reading_read`、`reading_update`、`reading_highlight`。系统提示里已经写了这些工具的使用时机。
|
|
88
90
|
|
|
89
91
|
### 斜杠命令
|
|
90
92
|
|
|
@@ -103,6 +105,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
|
|
|
103
105
|
| `reading_list` | 按时间列出,支持状态/标签过滤。 |
|
|
104
106
|
| `reading_read` | 按 id 读取 Markdown 切片;用 `offset` / `nextOffset` 翻长文,`hasMore` 判断是否读完。 |
|
|
105
107
|
| `reading_update` | 修改阅读状态或标签。状态:`unread` / `reading` / `read` / `archived`。 |
|
|
108
|
+
| `reading_highlight` | 对文章做划线/批注:`action` 为 `create` / `list` / `update` / `delete`;`create` 传原文里的 `quote`(或 `startOffset`/`endOffset`),可选 `note` 和 `color`。 |
|
|
106
109
|
|
|
107
110
|
## 配置
|
|
108
111
|
|
|
@@ -130,7 +133,8 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
|
|
|
130
133
|
└── <id>/
|
|
131
134
|
├── article.md # 干净正文(Markdown)
|
|
132
135
|
├── original.html # 原始 HTML 快照(只存档,不渲染)
|
|
133
|
-
|
|
136
|
+
├── annotations.json # 划线/批注(首次批注时生成)
|
|
137
|
+
└── meta.json # 标题、URL、作者、日期、标签、状态、批注数
|
|
134
138
|
```
|
|
135
139
|
|
|
136
140
|
`index.json` 是唯一索引;可以直接备份整个目录,或只同步 `clips/` 和 `index.json`。
|
|
@@ -156,7 +160,7 @@ npm test
|
|
|
156
160
|
npm run verify
|
|
157
161
|
```
|
|
158
162
|
|
|
159
|
-
`npm run verify` 会启动一个本地测试页,走完“抓取 → 提取 → 索引 → 搜索 → 读取 → 导出”整条链路,并输出机器可读的 JSON。
|
|
163
|
+
`npm run verify` 会启动一个本地测试页,走完“抓取 → 提取 → 索引 → 搜索 → 读取 → 批注 → 导出”整条链路,并输出机器可读的 JSON。
|
|
160
164
|
|
|
161
165
|
本地看界面:
|
|
162
166
|
|
|
@@ -171,7 +175,7 @@ npm run dev # http://127.0.0.1:4173/dsh-reading-inbox/
|
|
|
171
175
|
|
|
172
176
|
```sh
|
|
173
177
|
npm run build:client # 重新构建 client/client.js(esbuild)
|
|
174
|
-
npm test #
|
|
178
|
+
npm test # 27 个测试:提取、渲染、SSRF、DNS 校验、批注锚定、存储竞态、检索、路由、客户端 bundle
|
|
175
179
|
npm run verify # 端到端自检
|
|
176
180
|
```
|
|
177
181
|
|
|
@@ -188,14 +192,14 @@ npm run verify # 端到端自检
|
|
|
188
192
|
|
|
189
193
|
## 限制与 Roadmap
|
|
190
194
|
|
|
191
|
-
当前版本是 0.
|
|
195
|
+
当前版本是 0.2.0,刻意不做大而全:
|
|
192
196
|
|
|
193
197
|
- [ ] SPA / 登录页 / 反爬页可能提取不到正文;下一步加 Playwright fallback。
|
|
194
198
|
- [ ] 图片仍引用远程地址;下一步下载到 `clips/<id>/assets/` 做完整离线存档。
|
|
195
199
|
- [ ] 暂不支持 PDF;PDF 请用 `dsh-pdf-mineru` 或文档阅读插件。
|
|
196
200
|
- [ ] 暂无浏览器扩展 / RSS 导入;先做 URL 输入和 Agent 工具。
|
|
197
201
|
- [ ] 暂无同步/备份;先保证本地目录可复制。
|
|
198
|
-
- [ ] 检索是本地 BM25
|
|
202
|
+
- [ ] 检索是本地 BM25 风格排序;下一步加标题/正文分块与搜索结果高亮。
|
|
199
203
|
|
|
200
204
|
## 许可
|
|
201
205
|
|
package/VERIFY.md
CHANGED
|
@@ -46,6 +46,15 @@ dsh --profile inbox-web --no-open --port 4191
|
|
|
46
46
|
|
|
47
47
|
如果 `example.com` 正文太短,换一篇真实文章。错误应显示在底部 toast,而不是空白。
|
|
48
48
|
|
|
49
|
+
### 3.1 高亮与批注
|
|
50
|
+
|
|
51
|
+
1. 在正文里选中一段文字,应浮出高亮工具栏。
|
|
52
|
+
2. 点一个颜色、写一条批注(可选),点“保存高亮”。
|
|
53
|
+
3. 期望:正文出现彩色高亮,右侧出现“批注”区块;`clips/<id>/annotations.json` 生成;详情头部显示批注数。
|
|
54
|
+
4. 点批注列表里的“定位”,应滚回原文高亮处。
|
|
55
|
+
5. 点“导出 Markdown”,下载文件里应出现 `## 批注` 和刚才的引文/笔记。
|
|
56
|
+
6. 直接访问 `http://127.0.0.1:4191/dsh-reading-inbox/api/items/<id>/annotations`,应返回 `{ ok: true, annotations: [...] }`。
|
|
57
|
+
|
|
49
58
|
## 4. Agent 工具
|
|
50
59
|
|
|
51
60
|
在对话里说:
|
|
@@ -72,6 +81,14 @@ dsh --profile inbox-web --no-open --port 4191
|
|
|
72
81
|
|
|
73
82
|
期望:`reading_update` 成功,收件箱里状态变为“已读”。
|
|
74
83
|
|
|
84
|
+
再问:
|
|
85
|
+
|
|
86
|
+
```text
|
|
87
|
+
把刚才那篇里的“阅读不是收藏”划线,批注:这是全文的核心
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
期望:模型调用 `reading_highlight`(`action: create`),收件箱里出现对应高亮和批注。
|
|
91
|
+
|
|
75
92
|
## 5. 斜杠命令
|
|
76
93
|
|
|
77
94
|
```text
|
package/index.js
CHANGED
|
@@ -11,8 +11,8 @@ const webDir = fileURLToPath(new URL('./web/', import.meta.url))
|
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Mount the reading inbox: storage under ~/.dsh-reading-inbox, a web panel on
|
|
14
|
-
* the host webserver,
|
|
15
|
-
* prompt section so the model knows when to clip and
|
|
14
|
+
* the host webserver, six reading_* tools, a /inbox command, and one system
|
|
15
|
+
* prompt section so the model knows when to clip, search, and annotate.
|
|
16
16
|
*/
|
|
17
17
|
export function apply(ctx) {
|
|
18
18
|
const config = loadConfig()
|
|
@@ -70,6 +70,7 @@ export function apply(ctx) {
|
|
|
70
70
|
'本机已安装阅读收件箱(dsh-reading-inbox)。',
|
|
71
71
|
'当用户说“收藏 / 剪藏 / 稍后读 / 保存这个链接”时,调用 reading_clip。',
|
|
72
72
|
'回答关于已保存文章的问题前,先用 reading_search 找到 clip id,再用 reading_read 读原文。',
|
|
73
|
+
'当用户要求划线、高亮、批注、标记重点时,调用 reading_highlight:create 传 clip id 和原文中的 quote,可选 note/color;list 查看已有批注;update/delete 需要 annotationId。',
|
|
73
74
|
'不要编造收件箱里没有的内容;如果搜索没有结果,明确说没有保存过。',
|
|
74
75
|
].join(''),
|
|
75
76
|
}), 'dsh-reading-inbox: system prompt')
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-reading-inbox",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "DeepSeek Harness 的阅读收件箱:网页剪藏、Markdown
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "DeepSeek Harness 的阅读收件箱:网页剪藏、Markdown 存档、划线批注、标签、全文检索与 Agent 工具。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
7
7
|
"exports": {
|
|
@@ -67,7 +67,9 @@
|
|
|
67
67
|
"web-clipper",
|
|
68
68
|
"markdown",
|
|
69
69
|
"reading",
|
|
70
|
-
"inbox"
|
|
70
|
+
"inbox",
|
|
71
|
+
"highlights",
|
|
72
|
+
"annotations"
|
|
71
73
|
],
|
|
72
74
|
"license": "MIT",
|
|
73
75
|
"repository": {
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
const MAX_QUOTE_CHARS = 2_000
|
|
2
|
+
const MAX_NOTE_CHARS = 2_000
|
|
3
|
+
const CONTEXT_CHARS = 32
|
|
4
|
+
const MAX_OCCURRENCES = 100
|
|
5
|
+
|
|
6
|
+
export const ANNOTATION_COLORS = ['yellow', 'green', 'blue', 'red']
|
|
7
|
+
|
|
8
|
+
export function normalizeQuote(value) {
|
|
9
|
+
return String(value ?? '').trim().slice(0, MAX_QUOTE_CHARS)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function normalizeNote(value) {
|
|
13
|
+
return String(value ?? '').trim().slice(0, MAX_NOTE_CHARS)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function normalizeColor(value) {
|
|
17
|
+
return ANNOTATION_COLORS.includes(value) ? value : 'yellow'
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function codePoints(text) {
|
|
21
|
+
return Array.from(String(text ?? ''))
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function validRange(start, end, length) {
|
|
25
|
+
return Number.isInteger(start) && Number.isInteger(end) && start >= 0 && end > start && end <= length
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function utf16IndexToCodePoint(text, index) {
|
|
29
|
+
let count = 0
|
|
30
|
+
for (let i = 0; i < index; i += 1) {
|
|
31
|
+
const code = text.charCodeAt(i)
|
|
32
|
+
if (code >= 0xd800 && code <= 0xdbff && i + 1 < index) i += 1
|
|
33
|
+
count += 1
|
|
34
|
+
}
|
|
35
|
+
return count
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function commonPrefixLength(a, b) {
|
|
39
|
+
const left = codePoints(a)
|
|
40
|
+
const right = codePoints(b)
|
|
41
|
+
const limit = Math.min(left.length, right.length)
|
|
42
|
+
let index = 0
|
|
43
|
+
while (index < limit && left[index] === right[index]) index += 1
|
|
44
|
+
return index
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function commonSuffixLength(a, b) {
|
|
48
|
+
const left = codePoints(a)
|
|
49
|
+
const right = codePoints(b)
|
|
50
|
+
const limit = Math.min(left.length, right.length)
|
|
51
|
+
let index = 0
|
|
52
|
+
while (index < limit && left[left.length - 1 - index] === right[right.length - 1 - index]) index += 1
|
|
53
|
+
return index
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function contextOf(chars, start, end) {
|
|
57
|
+
return {
|
|
58
|
+
prefix: chars.slice(Math.max(0, start - CONTEXT_CHARS), start).join(''),
|
|
59
|
+
suffix: chars.slice(end, end + CONTEXT_CHARS).join(''),
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function occurrences(text, quote) {
|
|
64
|
+
const found = []
|
|
65
|
+
let from = 0
|
|
66
|
+
while (found.length < MAX_OCCURRENCES) {
|
|
67
|
+
const index = text.indexOf(quote, from)
|
|
68
|
+
if (index === -1) break
|
|
69
|
+
const start = utf16IndexToCodePoint(text, index)
|
|
70
|
+
found.push({ start, end: start + codePoints(quote).length })
|
|
71
|
+
from = index + Math.max(1, quote.length)
|
|
72
|
+
}
|
|
73
|
+
return found
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function chooseOccurrence(chars, text, quote, annotation) {
|
|
77
|
+
const candidates = occurrences(text, quote)
|
|
78
|
+
if (candidates.length === 0) return null
|
|
79
|
+
const hint = Number.isInteger(annotation.startOffset) ? annotation.startOffset : -1
|
|
80
|
+
let best = null
|
|
81
|
+
for (const candidate of candidates) {
|
|
82
|
+
const around = contextOf(chars, candidate.start, candidate.end)
|
|
83
|
+
const score =
|
|
84
|
+
(annotation.prefix ? commonSuffixLength(annotation.prefix, around.prefix) : 0) +
|
|
85
|
+
(annotation.suffix ? commonPrefixLength(annotation.suffix, around.suffix) : 0)
|
|
86
|
+
const distance = hint >= 0 ? Math.abs(candidate.start - hint) : 0
|
|
87
|
+
if (
|
|
88
|
+
best === null ||
|
|
89
|
+
score > best.score ||
|
|
90
|
+
(score === best.score && distance < best.distance)
|
|
91
|
+
) {
|
|
92
|
+
best = { ...candidate, score, distance }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return best
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Return an annotation with offsets resolved against the current article text.
|
|
100
|
+
* Stored offsets are a hint; quote + prefix/suffix is the source of truth when
|
|
101
|
+
* the article has been re-extracted. A missing quote yields status "stale"
|
|
102
|
+
* instead of silently highlighting the wrong text.
|
|
103
|
+
*/
|
|
104
|
+
export function resolveAnnotation(text, annotation) {
|
|
105
|
+
const chars = codePoints(text)
|
|
106
|
+
const quote = normalizeQuote(annotation?.quote)
|
|
107
|
+
const start = annotation?.startOffset
|
|
108
|
+
const end = annotation?.endOffset
|
|
109
|
+
|
|
110
|
+
if (quote === '') {
|
|
111
|
+
if (validRange(start, end, chars.length)) {
|
|
112
|
+
const fallback = chars.slice(start, end).join('')
|
|
113
|
+
if (fallback !== '') {
|
|
114
|
+
const around = contextOf(chars, start, end)
|
|
115
|
+
return {
|
|
116
|
+
...annotation,
|
|
117
|
+
quote: fallback,
|
|
118
|
+
...around,
|
|
119
|
+
startOffset: start,
|
|
120
|
+
endOffset: end,
|
|
121
|
+
status: 'active',
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return { ...annotation, startOffset: -1, endOffset: -1, status: 'stale' }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (validRange(start, end, chars.length) && chars.slice(start, end).join('') === quote) {
|
|
129
|
+
const around = contextOf(chars, start, end)
|
|
130
|
+
return { ...annotation, ...around, startOffset: start, endOffset: end, status: 'active' }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const match = chooseOccurrence(chars, String(text), quote, annotation)
|
|
134
|
+
if (match === null) {
|
|
135
|
+
return { ...annotation, startOffset: -1, endOffset: -1, status: 'stale' }
|
|
136
|
+
}
|
|
137
|
+
const around = contextOf(chars, match.start, match.end)
|
|
138
|
+
return { ...annotation, ...around, startOffset: match.start, endOffset: match.end, status: 'active' }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Validate a user/agent supplied quote or offset pair and compute the context
|
|
143
|
+
* that will be persisted. Throws when the quote cannot be located, so the UI
|
|
144
|
+
* never stores an annotation that cannot be rendered.
|
|
145
|
+
*/
|
|
146
|
+
export function buildAnnotationAnchor(text, input = {}) {
|
|
147
|
+
const chars = codePoints(text)
|
|
148
|
+
const quote = normalizeQuote(input.quote)
|
|
149
|
+
const hintStart = Number.isInteger(input.startOffset) ? input.startOffset : -1
|
|
150
|
+
const hintEnd = Number.isInteger(input.endOffset) ? input.endOffset : -1
|
|
151
|
+
|
|
152
|
+
let resolved
|
|
153
|
+
if (quote === '') {
|
|
154
|
+
if (!validRange(hintStart, hintEnd, chars.length)) {
|
|
155
|
+
throw new Error('需要 quote,或有效的 startOffset/endOffset')
|
|
156
|
+
}
|
|
157
|
+
const selected = chars.slice(hintStart, hintEnd).join('')
|
|
158
|
+
if (selected.trim() === '') throw new Error('选区为空')
|
|
159
|
+
resolved = { start: hintStart, end: hintEnd, quote: selected }
|
|
160
|
+
} else if (validRange(hintStart, hintEnd, chars.length) && chars.slice(hintStart, hintEnd).join('') === quote) {
|
|
161
|
+
resolved = { start: hintStart, end: hintEnd, quote }
|
|
162
|
+
} else {
|
|
163
|
+
const match = chooseOccurrence(chars, String(text), quote, {
|
|
164
|
+
quote,
|
|
165
|
+
prefix: input.prefix,
|
|
166
|
+
suffix: input.suffix,
|
|
167
|
+
startOffset: hintStart,
|
|
168
|
+
})
|
|
169
|
+
if (match === null) throw new Error('找不到引文;文章可能已更新')
|
|
170
|
+
resolved = { start: match.start, end: match.end, quote }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const around = contextOf(chars, resolved.start, resolved.end)
|
|
174
|
+
return {
|
|
175
|
+
quote: resolved.quote,
|
|
176
|
+
startOffset: resolved.start,
|
|
177
|
+
endOffset: resolved.end,
|
|
178
|
+
prefix: around.prefix,
|
|
179
|
+
suffix: around.suffix,
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function resolveAnnotations(text, annotations = []) {
|
|
184
|
+
return (Array.isArray(annotations) ? annotations : [])
|
|
185
|
+
.filter(annotation => annotation !== null && typeof annotation === 'object' && typeof annotation.id === 'string')
|
|
186
|
+
.map(annotation => resolveAnnotation(text, annotation))
|
|
187
|
+
}
|
package/src/markdown.js
CHANGED
|
@@ -267,7 +267,7 @@ export function renderMarkdown(markdown) {
|
|
|
267
267
|
})
|
|
268
268
|
}
|
|
269
269
|
|
|
270
|
-
export function exportMarkdown(meta, body) {
|
|
270
|
+
export function exportMarkdown(meta, body, annotations = []) {
|
|
271
271
|
const frontmatter = dumpYaml({
|
|
272
272
|
title: meta.title,
|
|
273
273
|
url: meta.url,
|
|
@@ -285,5 +285,25 @@ export function exportMarkdown(meta, body) {
|
|
|
285
285
|
const source = meta.author
|
|
286
286
|
? `> 来源:[${meta.site || meta.url}](${meta.url}) · ${meta.author}`
|
|
287
287
|
: `> 来源:[${meta.site || meta.url}](${meta.url})`
|
|
288
|
-
|
|
288
|
+
|
|
289
|
+
const usable = (Array.isArray(annotations) ? annotations : [])
|
|
290
|
+
.filter(annotation => annotation !== null && typeof annotation === 'object' && annotation.status !== 'stale')
|
|
291
|
+
const annotationBlock = usable.length === 0 ? '' : `\n## 批注\n\n${usable.map(annotation => {
|
|
292
|
+
const quote = String(annotation.quote ?? '').replaceAll('\n', '\n> ')
|
|
293
|
+
const note = String(annotation.note ?? '').trim()
|
|
294
|
+
return `> ${quote}${note === '' ? '' : `\n\n**笔记:** ${note}`}`
|
|
295
|
+
}).join('\n\n')}\n`
|
|
296
|
+
|
|
297
|
+
return `---\n${frontmatter}\n---\n\n# ${safeTitle}\n\n${source}\n\n${String(body ?? '').trim()}\n${annotationBlock}`
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* The plain text a reader sees in the rendered article. Highlight offsets are
|
|
302
|
+
* stored against this projection, not against Markdown source, so UI selections
|
|
303
|
+
* and server-side validation use the same coordinates.
|
|
304
|
+
*/
|
|
305
|
+
export function renderedText(markdown) {
|
|
306
|
+
const html = renderMarkdown(markdown)
|
|
307
|
+
const document = parseHTML(`<!doctype html><html><body>${html}</body></html>`).document
|
|
308
|
+
return String(document.body?.textContent ?? '')
|
|
289
309
|
}
|
package/src/routes.js
CHANGED
|
@@ -174,6 +174,34 @@ async function handleApi(req, res, url, inbox) {
|
|
|
174
174
|
return writeError(res, 405, 'method not allowed')
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
if (segments.length === 3 && segments[2] === 'annotations') {
|
|
178
|
+
if (method === 'GET') {
|
|
179
|
+
const annotations = await inbox.listAnnotations(id)
|
|
180
|
+
return writeJson(res, 200, { ok: true, annotations, count: annotations.length })
|
|
181
|
+
}
|
|
182
|
+
if (method === 'POST') {
|
|
183
|
+
const body = await readJsonBody(req)
|
|
184
|
+
const annotation = await inbox.addAnnotation(id, body)
|
|
185
|
+
const annotations = await inbox.listAnnotations(id)
|
|
186
|
+
return writeJson(res, 200, { ok: true, annotation, annotations, count: annotations.length })
|
|
187
|
+
}
|
|
188
|
+
return writeError(res, 405, 'method not allowed')
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (segments.length === 4 && segments[2] === 'annotations') {
|
|
192
|
+
const annotationId = decodeSegment(segments[3])
|
|
193
|
+
if (method === 'PATCH') {
|
|
194
|
+
const body = await readJsonBody(req)
|
|
195
|
+
const annotation = await inbox.updateAnnotation(id, annotationId, body)
|
|
196
|
+
return writeJson(res, 200, { ok: true, annotation })
|
|
197
|
+
}
|
|
198
|
+
if (method === 'DELETE') {
|
|
199
|
+
const result = await inbox.deleteAnnotation(id, annotationId)
|
|
200
|
+
return writeJson(res, 200, { ok: true, ...result })
|
|
201
|
+
}
|
|
202
|
+
return writeError(res, 405, 'method not allowed')
|
|
203
|
+
}
|
|
204
|
+
|
|
177
205
|
if (segments.length === 3 && segments[2] === 'export') {
|
|
178
206
|
if (method !== 'GET') return writeError(res, 405, 'method not allowed')
|
|
179
207
|
const result = await inbox.export(id)
|