dsh-inline-link-preview 0.0.0-stage → 0.5.0-beta.2
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/LICENSE +21 -0
- package/README.md +77 -2
- package/assets/icon-180.png +0 -0
- package/assets/inline-preview-flow.png +0 -0
- package/assets/supported-sources.png +0 -0
- package/build-client.js +13 -0
- package/client.js +208 -0
- package/composer.js +141 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +6 -0
- package/index.js +214 -0
- package/link-policy.js +61 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/npm-adapter.js +90 -0
- package/package.json +67 -4
- package/public-fetch.js +266 -0
- package/test/host.test.js +168 -0
- package/test/inline.test.js +256 -0
- package/test/npm-adapter.test.js +163 -0
- package/test/public-fetch.test.js +432 -0
- package/test/title.test.js +127 -0
- package/title.js +190 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-inline-link-preview contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,78 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 行内链接预览 (Inline Link Preview)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
在 **DeepSeek Harness** 聊天输入框中单独粘贴支持的链接后,自动尝试获取标题,并在原位显示为行内的「图标 + 标题」;复制或发送时仍保留原始网址,而不是标题或网页正文。
|
|
4
|
+
|
|
5
|
+
> **说明**:本插件(npm 包:`dsh-inline-link-preview`)仅用于 **DeepSeek Harness**,不是 DeepSeek 官网网页聊天页面的插件。本项目版本为 `0.5.0-beta.2`,声明兼容的 DeepSeek Harness 版本范围为 `>=0.2.2-rc.5 <0.2.3-0`,不承诺兼容其他版本。
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## 效果示例
|
|
10
|
+
|
|
11
|
+
无需输入 `@`,也无需先发送消息。在聊天输入框中(包括一段话中间)**单独粘贴**一条支持的链接即可:
|
|
12
|
+
|
|
13
|
+
- **粘贴**:`https://example.com/`
|
|
14
|
+
- **输入框显示**:`📄 Example Domain`
|
|
15
|
+
- **复制或发送**:仍为 `https://example.com/`(不会替换成纯标题,也不会自动附带网页或文档正文)
|
|
16
|
+
|
|
17
|
+
嵌入句子中时,例如先输入 `请看 再写摘要`,把光标放到两个空格之间再单独粘贴 `https://example.com/`:
|
|
18
|
+
|
|
19
|
+
- **输入框显示**:`请看 📄 Example Domain 再写摘要`
|
|
20
|
+
- **复制或发送**:`请看 https://example.com/ 再写摘要`
|
|
21
|
+
|
|
22
|
+
点击行内标题可直接打开原链接;如果标题读取失败、超时或遇到登录验证,原网址会保留在输入框里,照常作为普通链接发送。
|
|
23
|
+
|
|
24
|
+
## 支持哪些链接?
|
|
25
|
+
|
|
26
|
+
| 链接类型 | 说明与前置条件 |
|
|
27
|
+
| --- | --- |
|
|
28
|
+
| **飞书 / Lark 文档与知识库** | 支持 `feishu.cn`、`larksuite.com`、`larkoffice.com` 及其子域的 HTTPS `/docx/…`、`/wiki/…`。运行 DeepSeek Harness 的主机需安装并登录 `lark-cli`,且登录账号拥有文档查看权限。 |
|
|
29
|
+
| **GitHub 公开页面** | 支持公开仓库、Issue、Pull Request 等公开页面;不需要 GitHub Token,也不读取私有仓库登录态。 |
|
|
30
|
+
| **npm 包页面** | 支持公开包及其明确版本页面;优先从 npm 官方注册表验证包名和版本后生成标题,不读取浏览器登录态。注册表查询失败或校验未通过时可能退回普通网页标题,后者未经注册表独立校验。 |
|
|
31
|
+
| **微信公众号文章** | 支持 `mp.weixin.qq.com/s/…` 或 `/s?__biz=…&mid=…` 等文章分享链接。遇到微信验证或文章失效时,可能无法获取标题,此时保留原网址。 |
|
|
32
|
+
| **普通公开网页** | 支持使用域名的公开 HTTP(S) 页面,需可正常访问且 HTML 含可用标题或静态标题元数据;并非所有公开网页都能预览。只用公开网页时不需要 `lark-cli`。 |
|
|
33
|
+
|
|
34
|
+

|
|
35
|
+
|
|
36
|
+
## 安装和试用 Beta
|
|
37
|
+
|
|
38
|
+
包名 `dsh-inline-link-preview`,本项目版本 `0.5.0-beta.2`,声明兼容范围为 **DSH `>=0.2.2-rc.5 <0.2.3-0`**,开发和打包使用 Node.js 22。若正使用本地旧包 `@local/dsh-feishu-link-preview`,请先备份未发的草稿,再停用旧包,**不要同时启用两个版本**。
|
|
39
|
+
|
|
40
|
+
- **从 npm 安装精确 Beta 版本**(以桌面版 profile 为例):
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
dsh plugin --profile desktop add dsh-inline-link-preview@0.5.0-beta.2
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
- **拿到预发布压缩包时**:可先在独立 DSH profile 试装。在压缩包所在目录运行:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
dsh plugin --profile link-preview-beta add "$PWD/dsh-inline-link-preview-0.5.0-beta.2.tgz"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
打开对应 profile,确认插件「行内链接预览」已启用,刷新窗口(macOS:`⌘R`)。试试上面的 `https://example.com/` 例子,等标题出现前先不要移动光标。插件市场是否能搜到,取决于该 profile 启用的索引是否已收录这个版本。
|
|
53
|
+
|
|
54
|
+
## 为什么有时还是网址?(主要限制)
|
|
55
|
+
|
|
56
|
+
- **仅处理单条粘贴**:当前一次只处理单独粘贴的一条链接。含说明的整段文字、多条链接或文件按原样粘贴;不会自动扫描旧草稿或改写已发送消息。
|
|
57
|
+
- **不覆盖后续编辑**:标题返回前如果继续打字、移动光标、改变选区、发送或切换会话,插件不会用迟到的结果覆盖草稿。需要重试时,选中那段网址重新粘贴即可。
|
|
58
|
+
- **受目标页面与权限限制**:遇登录页、验证码、网络超时、非 HTML 或仅靠 JavaScript 才渲染标题的页面,可能无法获取标题,此时原网址照常可发。飞书文档可先检查 `lark-cli` 登录状态和文档权限,等待约一分钟后再试。
|
|
59
|
+
|
|
60
|
+
## 粘贴时会访问哪里?(网络与隐私说明)
|
|
61
|
+
|
|
62
|
+
- **访问发生在粘贴时,不是发送时**:公开网页由运行 DeepSeek Harness 的主机直接请求目标站点,**不使用**浏览器 Cookie 或 Referer,**不经过**第三方预览服务,也不执行目标页面脚本。目标网站可以看到运行主机的网络出口来源、请求路径和查询参数。npm 包页面会先向固定的 npm 官方注册表查询包名和版本;原链接的查询参数和片段不会传给注册表。
|
|
63
|
+
- **可选公共 DNS(默认关闭)**:只有在运行 DSH 的进程环境中明确设置 `DSH_INLINE_PREVIEW_CLOUDFLARE_DNS=1`,且系统 DNS 仅返回 `198.18.0.0/15` 特殊代理地址时,才会向 Cloudflare `1.1.1.1` 查询该网址的**域名**,不发送网址路径、查询参数或片段。这会绕过系统的部分自定义 DNS 策略,Cloudflare 仍可获知所查询的域名和网络出口;不适合希望域名只交由系统 DNS 处理的环境。结果仍需通过全部公网地址校验并固定连接,每次跳转重新验证;无需时取消该环境变量并重启 DSH。桌面图形应用通常不会继承在终端中临时设置的变量,必须确保变量传入 DSH 进程;旧版 `0.5.0-beta.1` 没有此选项。
|
|
64
|
+
- **不会自动访问的地址**:本机 / 内网地址、直接写 IP 的地址、非标准端口,以及含已知凭证或操作特征的链接,不会作为普通网页自动请求。但识别规则无法覆盖所有具有副作用的公开 URL;请勿粘贴访问后可能执行操作的链接。HTTPS 页面不会降级跳转到 HTTP。
|
|
65
|
+
- **飞书与微信查询**:飞书标题通过 `lark-cli drive +inspect --as user` 获取,查询时只传文档路径;微信查询只传文章标识。两者的**可识别的部分临时登录参数**会从可复制、可发送的引用中移除,但**不保证能清除链接中的所有敏感信息**,请勿将其当成通用敏感链接清洗器。
|
|
66
|
+
- **只返回标题,不附带正文**:标题查询只向编辑器返回标题,不会自动把网页或飞书文档正文附到发送内容中;主机在内存中缓存结果(成功 10 分钟、失败 1 分钟)。
|
|
67
|
+
- **本地访问日志提示**:编辑器向本机 Harness 服务查询标题时,目标地址会出现在请求的查询参数中;如果启用了 Web 服务或反向代理访问日志,这些日志可能记录该地址和文档标识,请按需配置日志保留与访问权限。
|
|
68
|
+
|
|
69
|
+
## 开发与许可
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
npm run build
|
|
73
|
+
npm test
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
无需安装第三方 npm 依赖。构建会从[粘贴逻辑](./composer.js)和[链接识别规则](./link-policy.js)生成客户端入口;测试会检查入口与源码一致,并离线验证标题提取、粘贴行为和网络请求边界。
|
|
77
|
+
|
|
78
|
+
[MIT 许可证](./LICENSE) · 非 DeepSeek、飞书、GitHub 或微信的官方插件。
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/build-client.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// DSH's loader consumes a standalone browser script. Bundle the two self-contained source
|
|
2
|
+
// functions deterministically at build time, without runtime module imports or a CDN.
|
|
3
|
+
import { readFile, writeFile } from 'node:fs/promises'
|
|
4
|
+
const here = name => new URL(name, import.meta.url)
|
|
5
|
+
const policy = await readFile(here('link-policy.js'), 'utf8')
|
|
6
|
+
const ui = await readFile(here('composer.js'), 'utf8')
|
|
7
|
+
const { name } = JSON.parse(await readFile(here('package.json'), 'utf8'))
|
|
8
|
+
const bundle = `// Generated by npm run build; edit link-policy.js or composer.js instead.\n;(() => {\n${policy.replace('export function parseLink(', 'function parseLink(')}\n${ui.replace('export function composer(', 'function composer(')}\nwindow.__ModuleLoader__.load({ id: ${JSON.stringify(name)}, factory(require) { return composer(require, parseLink) } })\n})()\n`
|
|
9
|
+
if (process.argv.includes('--check')) {
|
|
10
|
+
if (await readFile(here('client.js'), 'utf8') !== bundle) throw Error('client.js is stale; run npm run build')
|
|
11
|
+
} else {
|
|
12
|
+
await writeFile(here('client.js'), bundle)
|
|
13
|
+
}
|
package/client.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// Generated by npm run build; edit link-policy.js or composer.js instead.
|
|
2
|
+
;(() => {
|
|
3
|
+
// Pure policy shared by the Host and the dependency-free browser bundle (see build-client.js).
|
|
4
|
+
// lookup: safe metadata address; ref: the text copied/sent/opened. Never replace ref with a redirect.
|
|
5
|
+
function parseLink(text) {
|
|
6
|
+
if (typeof text !== 'string' || text.length > 16384) return null
|
|
7
|
+
const raw = text.trim()
|
|
8
|
+
if (!/^https?:\/\//i.test(raw) || /[\s\\<>\u0000-\u001f\u007f\ufffc]/u.test(raw)) return null
|
|
9
|
+
let url
|
|
10
|
+
try { url = new URL(raw) } catch { return null }
|
|
11
|
+
if (url.username || url.password || url.port) return null
|
|
12
|
+
const host = url.hostname
|
|
13
|
+
if (!/^(?:[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?\.)+[a-z][a-z\d-]*$/i.test(host) ||
|
|
14
|
+
/\.(?:local|localhost|internal|intranet|lan|home|corp|test|example|invalid|onion|alt|arpa)$/i.test(host)) return null
|
|
15
|
+
|
|
16
|
+
const feishu = /(?:^|\.)(?:feishu\.cn|larksuite\.com|larkoffice\.com)$/i.test(host)
|
|
17
|
+
const wechat = host === 'mp.weixin.qq.com'
|
|
18
|
+
const feishuSecret = /^(?:disposable_login_token|(?:user_|tenant_|app_)?access_token|refresh_token|id_token)$/i
|
|
19
|
+
const webSecret = /^(?:x-amz-.+|x-goog-.+|(?:.*[_-])?(?:token|secret|signature|credential|password|ticket|sessionid|auth|jwt|sig)(?:[_-].*)?|api[_-]?key|access[_-]?key(?:id)?|authkey|passwd|oauth|code|sso|key|session)$/i
|
|
20
|
+
const wxSecret = /^(?:pass_ticket|appmsg_token|wxtoken|key|uin|exportkey|wx_header)$/i
|
|
21
|
+
|
|
22
|
+
// Preserve escaping/order of unaffected fields, including ordinary paragraph anchors.
|
|
23
|
+
const strip = fields => fields.split('&').filter(field => {
|
|
24
|
+
let key
|
|
25
|
+
try { key = decodeURIComponent(field.split('=', 1)[0]) } catch { return true }
|
|
26
|
+
return feishu ? !feishuSecret.test(key) : !wxSecret.test(key) && !webSecret.test(key)
|
|
27
|
+
}).join('&')
|
|
28
|
+
function cleanShareRef() {
|
|
29
|
+
const query = url.search.slice(1), clean = strip(query)
|
|
30
|
+
if (clean !== query) url.search = clean
|
|
31
|
+
const hash = url.hash.slice(1), split = hash.indexOf('?')
|
|
32
|
+
const fields = strip(hash.slice(split + 1))
|
|
33
|
+
const cleanHash = split < 0 ? fields : strip(hash.slice(0, split)) + (fields ? '?' + fields : '')
|
|
34
|
+
if (cleanHash !== hash) url.hash = cleanHash
|
|
35
|
+
return url.href
|
|
36
|
+
}
|
|
37
|
+
if (feishu) {
|
|
38
|
+
const doc = /^\/(docx|wiki)\/[A-Za-z0-9_-]{8,128}\/?$/.exec(url.pathname)
|
|
39
|
+
if (url.protocol !== 'https:' || !doc) return null // never send another Feishu resource to the web reader
|
|
40
|
+
return { kind: doc[1], lookup: url.origin + url.pathname.replace(/\/$/, ''), ref: cleanShareRef() }
|
|
41
|
+
}
|
|
42
|
+
if (wechat) {
|
|
43
|
+
// Copied article links often carry temporary WeChat parameters. Only article identity goes on the wire.
|
|
44
|
+
const lookup = new URL('https://mp.weixin.qq.com' + url.pathname)
|
|
45
|
+
if (/^\/s\/?$/.test(url.pathname)) {
|
|
46
|
+
if (!url.searchParams.get('__biz') || !(url.searchParams.get('mid') || url.searchParams.get('appmsgid'))) return null
|
|
47
|
+
for (const key of ['__biz', 'mid', 'appmsgid', 'idx', 'sn']) {
|
|
48
|
+
const value = url.searchParams.get(key)
|
|
49
|
+
if (value) lookup.searchParams.set(key, value)
|
|
50
|
+
}
|
|
51
|
+
} else if (!/^\/s\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) return null
|
|
52
|
+
return { kind: 'wechat', lookup: lookup.href, ref: cleanShareRef() }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Never automatically visit known credential/action URLs. Leave their normal paste untouched.
|
|
56
|
+
if (Array.from(url.searchParams.keys()).some(key => webSecret.test(key) || feishuSecret.test(key))) return null
|
|
57
|
+
if (/(?:^|[?&#])(?:access_token|id_token|refresh_token|token|code|api[_-]?key)=/i.test(url.hash)) return null
|
|
58
|
+
let path
|
|
59
|
+
try { path = decodeURIComponent(url.pathname) } catch { return null }
|
|
60
|
+
if (/(?:^|\/)(?:login|log[-_]?in|sign[-_]?in|log[-_]?out|sign[-_]?out|oauth2?|sso|captcha|unsubscribe|reset[-_]?password|verify[-_]?email|magic[-_]?link|webhooks?)(?:\/|$)/i.test(path)) return null
|
|
61
|
+
url.hash = '' // fragments are for the user's navigation only
|
|
62
|
+
return { kind: /^(?:www\.)?github\.com$/i.test(host) ? 'github' : 'web', lookup: url.href, ref: raw }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Installed as a plain DSH module-loader factory by build-client.js. No editor-private imports.
|
|
66
|
+
function composer(require, parseLink) {
|
|
67
|
+
const SOURCE = 'feishu-link-preview' // stable across upgrades for restored drafts
|
|
68
|
+
const SLOT = 'conversation.input.overlay'
|
|
69
|
+
const NS = 'feishuLinkPreview'
|
|
70
|
+
const CAPTURE = { capture: true }
|
|
71
|
+
|
|
72
|
+
async function readTitle(url, signal) {
|
|
73
|
+
const response = await fetch(`/feishu-link-preview?url=${encodeURIComponent(url)}`, {
|
|
74
|
+
credentials: 'same-origin', headers: { accept: 'application/json' },
|
|
75
|
+
cache: 'no-store', signal: AbortSignal.any([signal, AbortSignal.timeout(10000)]),
|
|
76
|
+
})
|
|
77
|
+
if (!response.ok) return ''
|
|
78
|
+
const body = await response.json()
|
|
79
|
+
return body?.ok === true && typeof body.title === 'string' ? body.title.trim().replace(/\s+/gu, ' ') : ''
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// null leaves an ordinary paste to DSH. Otherwise the fallback URL is inserted synchronously.
|
|
83
|
+
function pasteLink(text, api, signal) {
|
|
84
|
+
const link = parseLink(text)
|
|
85
|
+
if (!link || signal.aborted || !api.current()) return null
|
|
86
|
+
const before = api.actions.captureInsertion()
|
|
87
|
+
const leading = text.slice(0, text.length - text.trimStart().length), trailing = text.slice(text.trimEnd().length)
|
|
88
|
+
if (!api.actions.insertText(leading + link.ref + trailing, before)) return null
|
|
89
|
+
const after = api.actions.captureInsertion()
|
|
90
|
+
// Use editor offsets (a previous chip/quote counts as one), not indexOf in the expanded draft.
|
|
91
|
+
const start = before.start + leading.length, end = start + link.ref.length, pasteEnd = end + trailing.length
|
|
92
|
+
if (after.start !== pasteEnd || after.end !== pasteEnd) return Promise.resolve(false)
|
|
93
|
+
const span = { start, end, draftRev: after.draftRev }
|
|
94
|
+
return (async () => {
|
|
95
|
+
let title = ''
|
|
96
|
+
try { title = await api.readTitle(link.lookup, signal) } catch { /* Keep the usable link. */ }
|
|
97
|
+
if (signal.aborted || !api.current()) return false
|
|
98
|
+
const caret = api.actions.captureInsertion()
|
|
99
|
+
if (caret.draftRev !== span.draftRev || caret.start !== pasteEnd || caret.end !== pasteEnd) return false
|
|
100
|
+
if (!title) { api.unavailable(link.kind); return false }
|
|
101
|
+
const inserted = api.session.bail(api.session, 'slash/input-insert-reference', { span, reference: {
|
|
102
|
+
source: SOURCE, appearance: 'file', ref: link.ref, clipboardText: link.ref, label: title,
|
|
103
|
+
} }) === true
|
|
104
|
+
if (inserted && trailing) {
|
|
105
|
+
// The native chip leaves the caret before any pasted suffix and may add one ASCII space.
|
|
106
|
+
// Touch only our own separator/whitespace in this synchronous turn, never the text after it.
|
|
107
|
+
const chipEnd = start + 1, addedSpace = trailing[0] !== ' ', pos = api.actions.captureInsertion()
|
|
108
|
+
if (pos.draftRev === span.draftRev + 1 && pos.start === chipEnd + Number(addedSpace) && pos.end === pos.start) {
|
|
109
|
+
const finish = pos.end + trailing.length
|
|
110
|
+
api.actions.insertText(addedSpace ? trailing : '', {
|
|
111
|
+
start: addedSpace ? chipEnd : finish, end: finish, draftRev: pos.draftRev,
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return inserted
|
|
116
|
+
})()
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function watchInterruptions(card, view, cancel) {
|
|
120
|
+
const interrupt = event => {
|
|
121
|
+
// Actual editing is caught by beforeinput/IME and the draft revision. Navigation is
|
|
122
|
+
// checked against the captured selection; pressing Right at the end or Cmd+C is harmless.
|
|
123
|
+
if (event.type === 'keydown' && !['Enter', 'Escape', 'Tab'].includes(event.key)) return
|
|
124
|
+
cancel()
|
|
125
|
+
}
|
|
126
|
+
const events = ['focusout', 'beforeinput', 'compositionstart', 'pointerdown', 'keydown']
|
|
127
|
+
for (const type of events) card.addEventListener(type, interrupt, CAPTURE)
|
|
128
|
+
view?.addEventListener('blur', cancel)
|
|
129
|
+
return () => {
|
|
130
|
+
for (const type of events) card.removeEventListener(type, interrupt, CAPTURE)
|
|
131
|
+
view?.removeEventListener('blur', cancel)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const source = {
|
|
136
|
+
trigger: '@', name: SOURCE, showGroupTitle: false,
|
|
137
|
+
candidates: async () => [], onPick: () => undefined,
|
|
138
|
+
codec: { clipboardText: ref => ref, serialize: async ref => ref },
|
|
139
|
+
openReference(_session, { ref }) {
|
|
140
|
+
const link = parseLink(ref)
|
|
141
|
+
if (!link) return false
|
|
142
|
+
window.open(link.ref, '_blank', 'noopener,noreferrer')
|
|
143
|
+
return true
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function apply(ctx) {
|
|
148
|
+
const React = require('react')
|
|
149
|
+
const sessions = ctx.get('sessions')
|
|
150
|
+
ctx.effect(() => ctx.locale.register(NS, {
|
|
151
|
+
zh: {
|
|
152
|
+
document: '未读到飞书标题,已保留网址。请确认登录和文档权限,约一分钟后可重新粘贴。',
|
|
153
|
+
publicPage: '未能读取公开标题,已保留网址,可照常发送。',
|
|
154
|
+
},
|
|
155
|
+
en: {
|
|
156
|
+
document: 'Title unavailable; the URL is unchanged. Check your lark-cli sign-in and document access, then paste again in a minute.',
|
|
157
|
+
publicPage: 'No public title was available. The URL is still here and can be sent as usual.',
|
|
158
|
+
},
|
|
159
|
+
}), 'link-preview: paste feedback')
|
|
160
|
+
const t = ctx.locale.bind(NS)
|
|
161
|
+
ctx.effect(() => ctx.get('inputTriggers').registerSource(source), 'link-preview: native reference codec')
|
|
162
|
+
|
|
163
|
+
function PasteScope({ sessionId, inputActions }) {
|
|
164
|
+
const marker = React.useRef(null)
|
|
165
|
+
React.useEffect(() => {
|
|
166
|
+
const binding = sessions.binding(sessionId)
|
|
167
|
+
const card = marker.current?.closest('[data-composer-card]')
|
|
168
|
+
if (!binding || !card || !inputActions) return
|
|
169
|
+
const input = ctx.get('conversation').input.for(binding.ctx)
|
|
170
|
+
let pending
|
|
171
|
+
const cancel = () => { pending?.abort(); pending = undefined }
|
|
172
|
+
function paste(event) {
|
|
173
|
+
cancel()
|
|
174
|
+
const editor = event.target?.closest?.('[data-composer-input][contenteditable="true"]')
|
|
175
|
+
const data = event.clipboardData
|
|
176
|
+
if (!editor || editor.closest('[data-composer-card]') !== card || !event.cancelable || event.defaultPrevented || !data || data.files.length) return
|
|
177
|
+
const controller = new AbortController()
|
|
178
|
+
const current = () => editor.isConnected && editor.isContentEditable &&
|
|
179
|
+
editor.contains(editor.ownerDocument.activeElement) && sessions.binding(sessionId) === binding &&
|
|
180
|
+
input.state.getSnapshot().phase === 'plain'
|
|
181
|
+
const result = pasteLink(data.getData('text/plain'), {
|
|
182
|
+
session: binding.ctx, actions: inputActions, current, readTitle,
|
|
183
|
+
unavailable: kind => input.notify('error', t(kind === 'docx' || kind === 'wiki' ? 'document' : 'publicPage')),
|
|
184
|
+
}, controller.signal)
|
|
185
|
+
if (result === null) return
|
|
186
|
+
event.preventDefault()
|
|
187
|
+
event.stopPropagation()
|
|
188
|
+
pending = controller
|
|
189
|
+
result.finally(() => { if (pending === controller) pending = undefined }).catch(() => {})
|
|
190
|
+
}
|
|
191
|
+
// No public paste hook in 0.2.2: scope to this composer, never edit or style its DOM.
|
|
192
|
+
card.addEventListener('paste', paste, CAPTURE)
|
|
193
|
+
const stopWatching = watchInterruptions(card, card.ownerDocument.defaultView, cancel)
|
|
194
|
+
return () => {
|
|
195
|
+
cancel()
|
|
196
|
+
stopWatching()
|
|
197
|
+
card.removeEventListener('paste', paste, CAPTURE)
|
|
198
|
+
}
|
|
199
|
+
}, [sessionId, inputActions])
|
|
200
|
+
return React.createElement('span', { ref: marker, hidden: true, 'aria-hidden': true })
|
|
201
|
+
}
|
|
202
|
+
ctx.slots.inject(SLOT, () => ctx.slots.register({ name: SLOT, id: SOURCE, order: 10 }, PasteScope))
|
|
203
|
+
}
|
|
204
|
+
return { inject: ['slots', 'sessions', 'conversation', 'inputTriggers', 'locale'], apply, parseLink, pasteLink, watchInterruptions }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
window.__ModuleLoader__.load({ id: "dsh-inline-link-preview", factory(require) { return composer(require, parseLink) } })
|
|
208
|
+
})()
|
package/composer.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Installed as a plain DSH module-loader factory by build-client.js. No editor-private imports.
|
|
2
|
+
export function composer(require, parseLink) {
|
|
3
|
+
const SOURCE = 'feishu-link-preview' // stable across upgrades for restored drafts
|
|
4
|
+
const SLOT = 'conversation.input.overlay'
|
|
5
|
+
const NS = 'feishuLinkPreview'
|
|
6
|
+
const CAPTURE = { capture: true }
|
|
7
|
+
|
|
8
|
+
async function readTitle(url, signal) {
|
|
9
|
+
const response = await fetch(`/feishu-link-preview?url=${encodeURIComponent(url)}`, {
|
|
10
|
+
credentials: 'same-origin', headers: { accept: 'application/json' },
|
|
11
|
+
cache: 'no-store', signal: AbortSignal.any([signal, AbortSignal.timeout(10000)]),
|
|
12
|
+
})
|
|
13
|
+
if (!response.ok) return ''
|
|
14
|
+
const body = await response.json()
|
|
15
|
+
return body?.ok === true && typeof body.title === 'string' ? body.title.trim().replace(/\s+/gu, ' ') : ''
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// null leaves an ordinary paste to DSH. Otherwise the fallback URL is inserted synchronously.
|
|
19
|
+
function pasteLink(text, api, signal) {
|
|
20
|
+
const link = parseLink(text)
|
|
21
|
+
if (!link || signal.aborted || !api.current()) return null
|
|
22
|
+
const before = api.actions.captureInsertion()
|
|
23
|
+
const leading = text.slice(0, text.length - text.trimStart().length), trailing = text.slice(text.trimEnd().length)
|
|
24
|
+
if (!api.actions.insertText(leading + link.ref + trailing, before)) return null
|
|
25
|
+
const after = api.actions.captureInsertion()
|
|
26
|
+
// Use editor offsets (a previous chip/quote counts as one), not indexOf in the expanded draft.
|
|
27
|
+
const start = before.start + leading.length, end = start + link.ref.length, pasteEnd = end + trailing.length
|
|
28
|
+
if (after.start !== pasteEnd || after.end !== pasteEnd) return Promise.resolve(false)
|
|
29
|
+
const span = { start, end, draftRev: after.draftRev }
|
|
30
|
+
return (async () => {
|
|
31
|
+
let title = ''
|
|
32
|
+
try { title = await api.readTitle(link.lookup, signal) } catch { /* Keep the usable link. */ }
|
|
33
|
+
if (signal.aborted || !api.current()) return false
|
|
34
|
+
const caret = api.actions.captureInsertion()
|
|
35
|
+
if (caret.draftRev !== span.draftRev || caret.start !== pasteEnd || caret.end !== pasteEnd) return false
|
|
36
|
+
if (!title) { api.unavailable(link.kind); return false }
|
|
37
|
+
const inserted = api.session.bail(api.session, 'slash/input-insert-reference', { span, reference: {
|
|
38
|
+
source: SOURCE, appearance: 'file', ref: link.ref, clipboardText: link.ref, label: title,
|
|
39
|
+
} }) === true
|
|
40
|
+
if (inserted && trailing) {
|
|
41
|
+
// The native chip leaves the caret before any pasted suffix and may add one ASCII space.
|
|
42
|
+
// Touch only our own separator/whitespace in this synchronous turn, never the text after it.
|
|
43
|
+
const chipEnd = start + 1, addedSpace = trailing[0] !== ' ', pos = api.actions.captureInsertion()
|
|
44
|
+
if (pos.draftRev === span.draftRev + 1 && pos.start === chipEnd + Number(addedSpace) && pos.end === pos.start) {
|
|
45
|
+
const finish = pos.end + trailing.length
|
|
46
|
+
api.actions.insertText(addedSpace ? trailing : '', {
|
|
47
|
+
start: addedSpace ? chipEnd : finish, end: finish, draftRev: pos.draftRev,
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return inserted
|
|
52
|
+
})()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function watchInterruptions(card, view, cancel) {
|
|
56
|
+
const interrupt = event => {
|
|
57
|
+
// Actual editing is caught by beforeinput/IME and the draft revision. Navigation is
|
|
58
|
+
// checked against the captured selection; pressing Right at the end or Cmd+C is harmless.
|
|
59
|
+
if (event.type === 'keydown' && !['Enter', 'Escape', 'Tab'].includes(event.key)) return
|
|
60
|
+
cancel()
|
|
61
|
+
}
|
|
62
|
+
const events = ['focusout', 'beforeinput', 'compositionstart', 'pointerdown', 'keydown']
|
|
63
|
+
for (const type of events) card.addEventListener(type, interrupt, CAPTURE)
|
|
64
|
+
view?.addEventListener('blur', cancel)
|
|
65
|
+
return () => {
|
|
66
|
+
for (const type of events) card.removeEventListener(type, interrupt, CAPTURE)
|
|
67
|
+
view?.removeEventListener('blur', cancel)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const source = {
|
|
72
|
+
trigger: '@', name: SOURCE, showGroupTitle: false,
|
|
73
|
+
candidates: async () => [], onPick: () => undefined,
|
|
74
|
+
codec: { clipboardText: ref => ref, serialize: async ref => ref },
|
|
75
|
+
openReference(_session, { ref }) {
|
|
76
|
+
const link = parseLink(ref)
|
|
77
|
+
if (!link) return false
|
|
78
|
+
window.open(link.ref, '_blank', 'noopener,noreferrer')
|
|
79
|
+
return true
|
|
80
|
+
},
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function apply(ctx) {
|
|
84
|
+
const React = require('react')
|
|
85
|
+
const sessions = ctx.get('sessions')
|
|
86
|
+
ctx.effect(() => ctx.locale.register(NS, {
|
|
87
|
+
zh: {
|
|
88
|
+
document: '未读到飞书标题,已保留网址。请确认登录和文档权限,约一分钟后可重新粘贴。',
|
|
89
|
+
publicPage: '未能读取公开标题,已保留网址,可照常发送。',
|
|
90
|
+
},
|
|
91
|
+
en: {
|
|
92
|
+
document: 'Title unavailable; the URL is unchanged. Check your lark-cli sign-in and document access, then paste again in a minute.',
|
|
93
|
+
publicPage: 'No public title was available. The URL is still here and can be sent as usual.',
|
|
94
|
+
},
|
|
95
|
+
}), 'link-preview: paste feedback')
|
|
96
|
+
const t = ctx.locale.bind(NS)
|
|
97
|
+
ctx.effect(() => ctx.get('inputTriggers').registerSource(source), 'link-preview: native reference codec')
|
|
98
|
+
|
|
99
|
+
function PasteScope({ sessionId, inputActions }) {
|
|
100
|
+
const marker = React.useRef(null)
|
|
101
|
+
React.useEffect(() => {
|
|
102
|
+
const binding = sessions.binding(sessionId)
|
|
103
|
+
const card = marker.current?.closest('[data-composer-card]')
|
|
104
|
+
if (!binding || !card || !inputActions) return
|
|
105
|
+
const input = ctx.get('conversation').input.for(binding.ctx)
|
|
106
|
+
let pending
|
|
107
|
+
const cancel = () => { pending?.abort(); pending = undefined }
|
|
108
|
+
function paste(event) {
|
|
109
|
+
cancel()
|
|
110
|
+
const editor = event.target?.closest?.('[data-composer-input][contenteditable="true"]')
|
|
111
|
+
const data = event.clipboardData
|
|
112
|
+
if (!editor || editor.closest('[data-composer-card]') !== card || !event.cancelable || event.defaultPrevented || !data || data.files.length) return
|
|
113
|
+
const controller = new AbortController()
|
|
114
|
+
const current = () => editor.isConnected && editor.isContentEditable &&
|
|
115
|
+
editor.contains(editor.ownerDocument.activeElement) && sessions.binding(sessionId) === binding &&
|
|
116
|
+
input.state.getSnapshot().phase === 'plain'
|
|
117
|
+
const result = pasteLink(data.getData('text/plain'), {
|
|
118
|
+
session: binding.ctx, actions: inputActions, current, readTitle,
|
|
119
|
+
unavailable: kind => input.notify('error', t(kind === 'docx' || kind === 'wiki' ? 'document' : 'publicPage')),
|
|
120
|
+
}, controller.signal)
|
|
121
|
+
if (result === null) return
|
|
122
|
+
event.preventDefault()
|
|
123
|
+
event.stopPropagation()
|
|
124
|
+
pending = controller
|
|
125
|
+
result.finally(() => { if (pending === controller) pending = undefined }).catch(() => {})
|
|
126
|
+
}
|
|
127
|
+
// No public paste hook in 0.2.2: scope to this composer, never edit or style its DOM.
|
|
128
|
+
card.addEventListener('paste', paste, CAPTURE)
|
|
129
|
+
const stopWatching = watchInterruptions(card, card.ownerDocument.defaultView, cancel)
|
|
130
|
+
return () => {
|
|
131
|
+
cancel()
|
|
132
|
+
stopWatching()
|
|
133
|
+
card.removeEventListener('paste', paste, CAPTURE)
|
|
134
|
+
}
|
|
135
|
+
}, [sessionId, inputActions])
|
|
136
|
+
return React.createElement('span', { ref: marker, hidden: true, 'aria-hidden': true })
|
|
137
|
+
}
|
|
138
|
+
ctx.slots.inject(SLOT, () => ctx.slots.register({ name: SLOT, id: SOURCE, order: 10 }, PasteScope))
|
|
139
|
+
}
|
|
140
|
+
return { inject: ['slots', 'sessions', 'conversation', 'inputTriggers', 'locale'], apply, parseLink, pasteLink, watchInterruptions }
|
|
141
|
+
}
|
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-label="Inline link preview">
|
|
2
|
+
<rect width="64" height="64" rx="14" fill="#3370ff"/>
|
|
3
|
+
<path d="M20 15h16l10 10v24H20z" fill="none" stroke="#ffffff" stroke-width="3" stroke-linejoin="round"/>
|
|
4
|
+
<path d="M36 15v10h10" fill="none" stroke="#ffffff" stroke-width="3" stroke-linejoin="round"/>
|
|
5
|
+
<path d="M26 32h14M26 38h12M26 44h9" fill="none" stroke="#ffffff" stroke-width="3" stroke-linecap="round"/>
|
|
6
|
+
</svg>
|