AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(extension): save a Xiaohongshu note from the context menu
tianma-if97b1defef28b
diff --git a/apps/extension/FIREFOX_STORE_LISTING.md b/apps/extension/FIREFOX_STORE_LISTING.mdindex 7825970b..b996e31b 100644--- a/apps/extension/FIREFOX_STORE_LISTING.md+++ b/apps/extension/FIREFOX_STORE_LISTING.md@@ -3,7 +3,7 @@## Listing- Name: EdgeEver Web Clipper-- Summary: Save a webpage, selected text, an image, an X post, or a GitHub repository to your EdgeEver instance.+- Summary: Save a webpage, selected text, an image, an X post, a Xiaohongshu note, or a GitHub repository to your EdgeEver instance.- Category: Bookmarks- Homepage: https://edgeever.org- Support: https://github.com/tianma-if/edgeever/issues@@ -11,11 +11,12 @@## Description-EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, or a GitHub repository's address and description directly to the self-hosted EdgeEver instance you configure.+EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, or a GitHub repository's address and description directly to the self-hosted EdgeEver instance you configure.- Extract readable article content, or right-click selected text and save that passage only.- Right-click an image and save that image file as a new note. From Google Search, the note records Google Search and the keyword.- On X, right-click the post text and save the full post, including text behind Show more, plus photos already shown.+- On Xiaohongshu, right-click the note text and save the title, text, and photos. Comments are left out.- On a GitHub repository page or code tree, right-click the page background, the description, or the README text and save the repository address and description.- These commands stay on the top-level right-click menu.- Convert captured HTML to Markdown locally.@@ -23,7 +24,7 @@ EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked i- Send content directly to your instance without an EdgeEver-operated relay.- No advertising, analytics, tracking, or telemetry.-Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads and sends page content only after you click **Clip current page**, **Save selection to EdgeEver**, **Save image to EdgeEver**, **Save this post to EdgeEver**, or **Save this repository to EdgeEver**.+Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads and sends page content only after you click **Clip current page**, **Save selection to EdgeEver**, **Save image to EdgeEver**, **Save this post to EdgeEver**, **Save this Xiaohongshu note to EdgeEver**, or **Save this repository to EdgeEver**.## Data collection and transmission@@ -44,7 +45,8 @@ The project maintainers do not receive or retain this data. Instance settings ar7. On a normal webpage, right-click an image, choose **Save image to EdgeEver**, and verify the new note contains the image.8. Open one X post page, right-click the post text (not a photo), choose **Save this post to EdgeEver**, and verify the note contains the post text and the post link.9. Open one GitHub repository page, right-click the description or README text, choose **Save this repository to EdgeEver**, and verify the note contains the repository address and description.-10. Verify the created notes in the review EdgeEver instance.+10. Open one Xiaohongshu note, right-click the note text (not a photo), choose **Save this Xiaohongshu note to EdgeEver**, and verify the note contains the title, text, and source link.+11. Verify the created notes in the review EdgeEver instance.Restricted browser pages, extension stores, built-in PDF viewers, and other privileged pages cannot be captured.@@ -68,15 +70,16 @@ The reviewable source is the repository source before Vite bundling. Third-party## 中文商店说明-EdgeEver 网页剪藏插件可将当前网页、选中的文字、右键选中的图片,或 X 上的一条推文直接保存到用户配置的自托管 EdgeEver 实例。+EdgeEver 网页剪藏插件可将当前网页、选中的文字、右键选中的图片、X 上的一条推文,或小红书上的一篇笔记直接保存到用户配置的自托管 EdgeEver 实例。- 提取适合阅读的文章正文。选中文字后右键,只保存这一段。- 在图片上右键,把图片文件存成一条新笔记。从 Google 搜索保存时,笔记记录“Google 搜索”和关键词。- 在 X 上右键推文正文。长文会先展开“显示更多”,再保存全文和已经显示的图片。+- 在小红书笔记正文上右键,保存标题、正文和图片。评论不会写入。- 这些命令直接出现在右键菜单的第一级。- 在浏览器本地将 HTML 转换为 Markdown。- 可选择默认 EdgeEver 笔记本。- 数据直接发送到用户自己的实例,不经过 EdgeEver 中转服务。- 不包含广告、分析、追踪或遥测。-使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在用户点击“剪藏当前网页”,或选择“保存选中文字到 EdgeEver”“保存图片到 EdgeEver”“保存这条推文到 EdgeEver”后读取并发送网页内容。+使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在用户点击“剪藏当前网页”,或选择“保存选中文字到 EdgeEver”“保存图片到 EdgeEver”“保存这条推文到 EdgeEver”“保存这篇小红书笔记到 EdgeEver”后读取并发送网页内容。diff --git a/apps/extension/README.md b/apps/extension/README.mdindex 2ec483bc..229611ab 100644--- a/apps/extension/README.md+++ b/apps/extension/README.md@@ -11,6 +11,7 @@ Chrome, Edge, and Firefox Manifest V3 extension for saving the current webpage,- Right-click an image and choose **Save image to EdgeEver**. The image file is uploaded into a new note in the default notebook, with the source page linked underneath. An image saved from Google Search records “Google Search” and the search keyword instead of the results URL.- Select text on a page, right-click, and choose **Save selection to EdgeEver**. That passage is saved as a new note in the default notebook, with the source page linked underneath. The rest of the page is not included.- On X, right-click the post text and choose **Save this post to EdgeEver**. The post text, author, time, and photos already shown in that post are saved into one note. Text folded behind Show more is expanded first, so a long post is saved in full. Right-clicking a photo saves that image instead, so the command stays on the top-level menu. A single-post page can be saved immediately. On a timeline, the extension asks once for access to X so it can remember the post under the pointer.+- On Xiaohongshu, right-click the note text and choose **Save this Xiaohongshu note to EdgeEver**. The title, text, author, time, location, and photos go into one note. Comments are left out. Right-clicking a photo saves that image instead. An open note can be saved immediately. On the feed, the extension asks once for access to Xiaohongshu so it can remember the note under the pointer; open that note before saving if its full text is not on the page.- On a GitHub repository page or code tree, right-click the page background, the description, or the README text and choose **Save this repository to EdgeEver**. The note keeps the repository address, the About text, and the homepage, language, license, and topics when the page shows them. An empty About falls back to the README's first paragraph. Issue, discussion, and single-file pages are left unsaved. The toolbar action uses the same card on those repository pages. Right-clicking a link or an image keeps the existing selection and image commands, so this one stays on the top-level menu.- When the page cannot hand over the image bytes, the extension asks once for access to that image's site. After that, later images from the same site save directly.- Create a searchable EdgeEver memo with the source URL and a `web-clip` tag.diff --git a/apps/extension/STORE_LISTING.md b/apps/extension/STORE_LISTING.mdindex 92bd8051..c1c768f6 100644--- a/apps/extension/STORE_LISTING.md+++ b/apps/extension/STORE_LISTING.md@@ -27,11 +27,11 @@ Select the matching language in the Chrome Web Store developer dashboard and ent#### Summary-将当前网页、选中文字、右键图片、X 推文或 GitHub 仓库保存到你自托管的 EdgeEver 实例。+将当前网页、选中文字、右键图片、X 推文、小红书笔记或 GitHub 仓库保存到你自托管的 EdgeEver 实例。#### Detailed description-EdgeEver Web Clipper 可以把当前网页、选中的文字、右键选中的图片、X 上的一条推文,或 GitHub 仓库的地址和简介保存到自托管的 EdgeEver 实例。+EdgeEver Web Clipper 可以把当前网页、选中的文字、右键选中的图片、X 上的一条推文、小红书上的一篇笔记,或 GitHub 仓库的地址和简介保存到自托管的 EdgeEver 实例。主要功能:@@ -39,13 +39,14 @@ EdgeEver Web Clipper 可以把当前网页、选中的文字、右键选中的- 选中一段文字后右键,选择“保存选中文字到 EdgeEver”,只保存这段文字。- 在图片上右键,选择“保存图片到 EdgeEver”,把图片文件存成一条新笔记。- 在 X 上右键推文正文,选择“保存这条推文到 EdgeEver”。长文会先展开“显示更多”,再保存全文和已经显示的图片。+- 在小红书笔记正文上右键,选择“保存这篇小红书笔记到 EdgeEver”。标题、正文和图片会存成一条笔记,评论不会写入。- 在 GitHub 仓库主页或代码目录上,右键页面空白、简介或 README 正文,选择“保存这个仓库到 EdgeEver”。笔记保留仓库地址和简介;页面上有主页、语言、许可证和话题时一并写入。- 这几项命令直接出现在右键菜单的第一级。- 在笔记中保留来源和剪藏时间。从 Google 搜索保存的图片记录“Google 搜索”和关键词。- 可选择默认笔记本,并自动添加 `web-clip` 标签。- 网页内容直接发送到你配置的 EdgeEver 实例,不经过开发者的中转服务器。-使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在你点击“剪藏当前网页”,或选择“保存选中文字到 EdgeEver”“保存图片到 EdgeEver”“保存这条推文到 EdgeEver”“保存这个仓库到 EdgeEver”后读取当前标签页。图片若无法由页面直接交出,才会再向你请求该图片所在网站的访问权限。+使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在你点击“剪藏当前网页”,或选择“保存选中文字到 EdgeEver”“保存图片到 EdgeEver”“保存这条推文到 EdgeEver”“保存这篇小红书笔记到 EdgeEver”“保存这个仓库到 EdgeEver”后读取当前标签页。图片若无法由页面直接交出,才会再向你请求该图片所在网站的访问权限。EdgeEver 是开源、自托管的现代笔记工作区。项目主页与源代码:https://github.com/tianma-if/edgeever@@ -53,11 +54,11 @@ EdgeEver 是开源、自托管的现代笔记工作区。项目主页与源代#### Summary-Save a webpage, selected text, a right-clicked image, an X post, or a GitHub repository to your self-hosted EdgeEver.+Save a webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, or a GitHub repository to your self-hosted EdgeEver.#### Detailed description-EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, or a GitHub repository's address and description to your self-hosted EdgeEver instance.+EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, or a GitHub repository's address and description to your self-hosted EdgeEver instance.Key features:@@ -65,13 +66,14 @@ Key features:- Select text, right-click, and choose “Save selection to EdgeEver” to store that passage only.- Right-click an image and choose “Save image to EdgeEver” to store the image file as a new note.- On X, right-click the post text and choose “Save this post to EdgeEver”. Long posts are expanded before saving, so the full text and already shown photos go into one note.+- On Xiaohongshu, right-click the note text and choose “Save this Xiaohongshu note to EdgeEver”. The title, text, and photos go into one note. Comments are left out.- On a GitHub repository page or code tree, right-click the page background, the description, or the README text and choose “Save this repository to EdgeEver”. The note keeps the address and description, plus the homepage, language, license, and topics when the page shows them.- These commands stay on the top-level right-click menu.- Preserve the source and clipping time in the note. An image saved from Google Search records “Google Search” and the keyword.- Select a default notebook and add the `web-clip` tag automatically.- Send webpage content directly to your configured EdgeEver instance without a developer-operated relay server.-Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads the current tab only after you click “Clip current page” or choose “Save selection to EdgeEver”, “Save image to EdgeEver”, “Save this post to EdgeEver”, or “Save this repository to EdgeEver”. It asks for access to an image's site only when that page cannot provide the image file.+Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads the current tab only after you click “Clip current page” or choose “Save selection to EdgeEver”, “Save image to EdgeEver”, “Save this post to EdgeEver”, “Save this Xiaohongshu note to EdgeEver”, or “Save this repository to EdgeEver”. It asks for access to an image's site only when that page cannot provide the image file.EdgeEver is an open-source, self-hosted modern notes workspace. Project homepage and source code: https://github.com/tianma-if/edgeever@@ -79,15 +81,15 @@ EdgeEver is an open-source, self-hosted modern notes workspace. Project homepage### Single purpose-Save the current webpage, user-selected text, a user-chosen image, one X post, or one GitHub repository card to the self-hosted EdgeEver instance explicitly configured by the user.+Save the current webpage, user-selected text, a user-chosen image, one X post, one Xiaohongshu note, or one GitHub repository card to the self-hosted EdgeEver instance explicitly configured by the user.### Permission justifications-- `activeTab`: Read the active page only after the user clicks the extension's save action or chooses Save selection to EdgeEver, Save image to EdgeEver, Save this post to EdgeEver, or Save this repository to EdgeEver.-- `contextMenus`: Add one top-level item for the thing the user right-clicked: selected text, an image, an X post, or a GitHub repository page. It runs only after the user selects that item.+- `activeTab`: Read the active page only after the user clicks the extension's save action or chooses Save selection to EdgeEver, Save image to EdgeEver, Save this post to EdgeEver, Save this Xiaohongshu note to EdgeEver, or Save this repository to EdgeEver.+- `contextMenus`: Add one top-level item for the thing the user right-clicked: selected text, an image, an X post, a Xiaohongshu note, or a GitHub repository page. It runs only after the user selects that item.- `scripting`: Inject the packaged capture script into the active page after the user initiates a capture.- `storage`: Store the user's EdgeEver instance URL, API token, and default notebook ID locally.-- Optional host permissions: Send API requests only to the EdgeEver instance origin the user approves. If a page cannot provide an image file, the extension can also ask for access to that image's site, or to all sites when the user explicitly chooses that option, and uses it only to download the image the user chose to save. Saving a post from an X timeline asks for access to X so the extension can remember which post was under the pointer. The script on X only records that target and runs after the user allows it.+- Optional host permissions: Send API requests only to the EdgeEver instance origin the user approves. If a page cannot provide an image file, the extension can also ask for access to that image's site, or to all sites when the user explicitly chooses that option, and uses it only to download the image the user chose to save. Saving a post from an X timeline asks for access to X so the extension can remember which post was under the pointer. The script on X only records that target and runs after the user allows it. Saving a note from a Xiaohongshu feed asks for access to Xiaohongshu for the same reason. An open note page can be saved without that extra permission.### Data disclosuresdiff --git a/apps/extension/manifest.base.json b/apps/extension/manifest.base.jsonindex 99dcfbb9..a2d503dd 100644--- a/apps/extension/manifest.base.json+++ b/apps/extension/manifest.base.json@@ -31,6 +31,14 @@],"js": ["assets/tweet-target.js"],"run_at": "document_start"+ },+ {+ "matches": [+ "https://www.xiaohongshu.com/*",+ "https://xiaohongshu.com/*"+ ],+ "js": ["assets/xhs-target.js"],+ "run_at": "document_start"}]}diff --git a/apps/extension/manifest.test.mjs b/apps/extension/manifest.test.mjsindex 4a8a994a..cec5ebfc 100644--- a/apps/extension/manifest.test.mjs+++ b/apps/extension/manifest.test.mjs@@ -31,6 +31,14 @@ describe("extension manifests", () => {js: ["assets/tweet-target.js"],run_at: "document_start",},+ {+ matches: [+ "https://www.xiaohongshu.com/*",+ "https://xiaohongshu.com/*",+ ],+ js: ["assets/xhs-target.js"],+ run_at: "document_start",+ },]);}});diff --git a/apps/extension/options.html b/apps/extension/options.htmlindex f0dd83b0..1a438253 100644--- a/apps/extension/options.html+++ b/apps/extension/options.html@@ -12,6 +12,7 @@<p class="hint" data-i18n="selectionSaveHint">Select text on a page, right-click, and choose “Save selection to EdgeEver”. It is saved as a new note in the default notebook selected below.</p><p class="hint" data-i18n="tweetSaveHint">On X, right-click a post and choose “Save this post to EdgeEver”. The visible text and photos go into one new note in the same notebook.</p><p class="hint" data-i18n="githubRepoSaveHint">On a GitHub repository page or code tree, right-click the page background, the description, or the README text and choose “Save this repository to EdgeEver”. The address and description are saved as a new note in the default notebook selected above.</p>+ <p class="hint" data-i18n="xhsSaveHint">On Xiaohongshu, right-click the note text and choose “Save this Xiaohongshu note to EdgeEver”. The title, text, and photos go into one new note. Comments are left out.</p><form id="settings-form"><label><span data-i18n="instanceAddress">EdgeEver instance URL</span>diff --git a/apps/extension/package.json b/apps/extension/package.jsonindex 886bb10e..7001970f 100644--- a/apps/extension/package.json+++ b/apps/extension/package.json@@ -9,7 +9,7 @@"dev": "vite --config vite.config.ts","lint:firefox": "web-ext lint --source-dir dist-firefox --output text","package:firefox": "bun run build:firefox && bun run lint:firefox && web-ext build --source-dir dist-firefox --artifacts-dir web-ext-artifacts --overwrite-dest",- "test": "bun test manifest.test.mjs image-clip.test.mjs tweet-clip.test.mjs selection-clip.test.mjs github-repo.test.mjs"+ "test": "bun test manifest.test.mjs image-clip.test.mjs tweet-clip.test.mjs selection-clip.test.mjs github-repo.test.mjs xhs-clip.test.mjs"},"dependencies": {"@mozilla/readability": "^0.6.0",diff --git a/apps/extension/popup.html b/apps/extension/popup.htmlindex 9e54a41f..61a6f114 100644--- a/apps/extension/popup.html+++ b/apps/extension/popup.html@@ -14,7 +14,7 @@<p class="hint" data-i18n="webClipper">Web Clipper</p></div></header>- <p class="popup-description" data-i18n="popupDescription">Clip the current page or selection. Right-click selected text to save that passage, right-click an image to save it, right-click a post on X to save that post, or right-click a GitHub repository page to save its address and description.</p>+ <p class="popup-description" data-i18n="popupDescription">Clip the current page or selection. Right-click selected text to save that passage, right-click an image to save it, right-click a post on X to save that post, right-click a Xiaohongshu note to save that note, or right-click a GitHub repository page to save its address and description.</p><button id="save" class="save-button" type="button"><svg aria-hidden="true" viewBox="0 0 24 24" width="18" height="18"><path d="M5 4.75A1.75 1.75 0 0 1 6.75 3h8.836c.464 0 .91.184 1.238.513l1.663 1.663c.329.328.513.774.513 1.238v12.836A1.75 1.75 0 0 1 17.25 21H6.75A1.75 1.75 0 0 1 5 19.25V4.75Z" />diff --git a/apps/extension/public/_locales/en/messages.json b/apps/extension/public/_locales/en/messages.jsonindex c9fc1fe2..61ba16c8 100644--- a/apps/extension/public/_locales/en/messages.json+++ b/apps/extension/public/_locales/en/messages.json@@ -12,7 +12,7 @@"message": "Web Clipper"},"popupDescription": {- "message": "Clip the current page or selection. Right-click selected text to save that passage, right-click an image to save it, right-click a post on X to save that post, or right-click a GitHub repository page to save its address and description."+ "message": "Clip the current page or selection. Right-click selected text to save that passage, right-click an image to save it, right-click a post on X to save that post, right-click a Xiaohongshu note to save that note, or right-click a GitHub repository page to save its address and description."},"saveCurrentPage": {"message": "Clip current page"@@ -350,5 +350,50 @@},"githubRepoTopicsLabel": {"message": "Topics"+ },+ "saveXhsToEdgeEver": {+ "message": "Save this Xiaohongshu note to EdgeEver"+ },+ "xhsSaveHint": {+ "message": "On Xiaohongshu, right-click the note text and choose “Save this Xiaohongshu note to EdgeEver”. The title, text, and photos go into one new note. Comments are left out. Right-clicking a photo still saves that image only."+ },+ "savingXhs": {+ "message": "Saving this note…"+ },+ "xhsSaved": {+ "message": "Saved this note."+ },+ "xhsNotFound": {+ "message": "Could not find that note. Open it, then right-click the text."+ },+ "xhsNeedsOpen": {+ "message": "Open the note, then right-click its text."+ },+ "xhsPermissionIntro": {+ "message": "The feed has many notes. Allow access to Xiaohongshu so the clipper can remember the note under the pointer. After that, right-click the same note once more. Only the note you choose is saved to the clipper's default notebook."+ },+ "xhsPermissionToast": {+ "message": "Allow access to Xiaohongshu to choose a note on the feed. Then right-click that note again."+ },+ "xhsRightClickAgain": {+ "message": "Notes on the feed can be recognized now. Right-click that note again."+ },+ "allowXhsAccess": {+ "message": "Allow access to Xiaohongshu"+ },+ "xhsPermissionDenied": {+ "message": "Access was not allowed. Right-click the note again to retry."+ },+ "xhsPermissionReady": {+ "message": "Access allowed. Go back and right-click that note again."+ },+ "xhsNoteFallbackTitle": {+ "message": "Xiaohongshu note"+ },+ "xhsSaveWindowTitle": {+ "message": "Save this Xiaohongshu note to EdgeEver"+ },+ "xhsLocationLabel": {+ "message": "Location"}}diff --git a/apps/extension/public/_locales/ja/messages.json b/apps/extension/public/_locales/ja/messages.jsonindex d1ea976c..e7ed5d94 100644--- a/apps/extension/public/_locales/ja/messages.json+++ b/apps/extension/public/_locales/ja/messages.json@@ -12,7 +12,7 @@"message": "Web Clipper"},"popupDescription": {- "message": "表示中のページや選択した内容を取り込みます。選択した文字の右クリックでその文章を、画像の右クリックで画像を、X 上の投稿の右クリックでその投稿を、GitHub のリポジトリページの右クリックでアドレスと紹介文を保存できます。"+ "message": "表示中のページや選択した内容を取り込みます。選択した文字の右クリックでその文章を、画像の右クリックで画像を、X 上の投稿の右クリックでその投稿を、小紅書のノート本文の右クリックでそのノートを、GitHub のリポジトリページの右クリックでアドレスと紹介文を保存できます。"},"saveCurrentPage": {"message": "このページを取り込む"@@ -350,5 +350,50 @@},"githubRepoTopicsLabel": {"message": "トピック"+ },+ "saveXhsToEdgeEver": {+ "message": "この小紅書ノートを EdgeEver に保存"+ },+ "xhsSaveHint": {+ "message": "小紅書でノート本文を右クリックし、「この小紅書ノートを EdgeEver に保存」を選びます。タイトル、本文、画像が 1 件のノートになります。コメントは含めません。画像を右クリックした場合は、その画像だけを保存します。"+ },+ "savingXhs": {+ "message": "このノートを保存しています…"+ },+ "xhsSaved": {+ "message": "このノートを保存しました。"+ },+ "xhsNotFound": {+ "message": "このノートを特定できませんでした。ノートを開いてから、本文を右クリックしてください。"+ },+ "xhsNeedsOpen": {+ "message": "ノートを開いてから、本文を右クリックしてください。"+ },+ "xhsPermissionIntro": {+ "message": "フィードには複数のノートがあります。ポインタの下にあるノートを覚えるには、小紅書へのアクセスを許可してください。許可したあと、同じノートをもう一度右クリックします。選んだノートだけを、クリップ拡張機能の既定ノートブックに保存します。"+ },+ "xhsPermissionToast": {+ "message": "フィードでノートを選ぶには、小紅書へのアクセスを許可してください。そのあと、もう一度右クリックします。"+ },+ "xhsRightClickAgain": {+ "message": "フィードのノートを識別できるようになりました。そのノートをもう一度右クリックしてください。"+ },+ "allowXhsAccess": {+ "message": "小紅書へのアクセスを許可"+ },+ "xhsPermissionDenied": {+ "message": "アクセスは許可されませんでした。ノートをもう一度右クリックしてやり直してください。"+ },+ "xhsPermissionReady": {+ "message": "許可しました。ページに戻り、そのノートをもう一度右クリックしてください。"+ },+ "xhsNoteFallbackTitle": {+ "message": "小紅書のノート"+ },+ "xhsSaveWindowTitle": {+ "message": "この小紅書ノートを EdgeEver に保存"+ },+ "xhsLocationLabel": {+ "message": "場所"}}diff --git a/apps/extension/public/_locales/zh_CN/messages.json b/apps/extension/public/_locales/zh_CN/messages.jsonindex e5a6005a..de8acb5e 100644--- a/apps/extension/public/_locales/zh_CN/messages.json+++ b/apps/extension/public/_locales/zh_CN/messages.json@@ -12,7 +12,7 @@"message": "网页剪藏"},"popupDescription": {- "message": "剪藏当前网页或选中内容。选中文字后右键可以保存这段文字;在图片上右键可以保存图片;在 X 上右键可以保存这条推文;在 GitHub 仓库页上右键可以保存仓库地址和简介。"+ "message": "剪藏当前网页或选中内容。选中文字后右键可以保存这段文字;在图片上右键可以保存图片;在 X 上右键可以保存这条推文;在小红书笔记正文上右键可以保存这篇笔记;在 GitHub 仓库页上右键可以保存仓库地址和简介。"},"saveCurrentPage": {"message": "剪藏当前网页"@@ -350,5 +350,50 @@},"githubRepoTopicsLabel": {"message": "话题"+ },+ "saveXhsToEdgeEver": {+ "message": "保存这篇小红书笔记到 EdgeEver"+ },+ "xhsSaveHint": {+ "message": "在小红书笔记正文上右键,选择“保存这篇小红书笔记到 EdgeEver”。标题、正文和笔记里的图片会存成一条新笔记,评论不会写入。右键图片仍然只保存这张图片。"+ },+ "savingXhs": {+ "message": "正在保存这篇笔记……"+ },+ "xhsSaved": {+ "message": "已把这篇笔记存成一条笔记。"+ },+ "xhsNotFound": {+ "message": "没有定位到这篇笔记。请先打开笔记,再在正文上右键。"+ },+ "xhsNeedsOpen": {+ "message": "请先打开这篇笔记,再在正文上右键。"+ },+ "xhsPermissionIntro": {+ "message": "首页上有很多篇笔记。允许访问小红书之后,插件才能记住指针下的这一篇。允许后,请再在同一篇笔记上右键一次。只会把你选中的这篇存进剪藏插件的默认笔记本。"+ },+ "xhsPermissionToast": {+ "message": "需要允许访问小红书,才能在首页上选中这篇笔记。允许后请再右键一次。"+ },+ "xhsRightClickAgain": {+ "message": "已经可以识别首页上的笔记。请再在这篇笔记上右键一次。"+ },+ "allowXhsAccess": {+ "message": "允许访问小红书"+ },+ "xhsPermissionDenied": {+ "message": "没有获得访问权限。请再在笔记上右键一次来重新授权。"+ },+ "xhsPermissionReady": {+ "message": "已允许。回到页面,再在这篇笔记上右键一次。"+ },+ "xhsNoteFallbackTitle": {+ "message": "一篇小红书笔记"+ },+ "xhsSaveWindowTitle": {+ "message": "保存这篇小红书笔记到 EdgeEver"+ },+ "xhsLocationLabel": {+ "message": "地点"}}diff --git a/apps/extension/src/background.ts b/apps/extension/src/background.tsindex 4b7488e3..3f2e3a25 100644--- a/apps/extension/src/background.ts+++ b/apps/extension/src/background.ts@@ -43,6 +43,14 @@ import {statusIdFromPageUrl,tweetNoteTitle,} from "./tweet-clip";+import {+ isXhsPageRead,+ noteIdFromPageUrl,+ readXhsStateInPage,+ resolveXhsNote,+ saveCapturedXhsNote,+ xhsNoteTitle,+} from "./xhs-clip";import { t } from "./i18n";type CapturedPage = {@@ -83,6 +91,13 @@ const GITHUB_DOCUMENT_PATTERNS = ["https://github.com/*","https://www.github.com/*",];+const XHS_MENU_ID = "save-xhs";+const PENDING_XHS_KEY = "pendingXhsPermission";+const XHS_WINDOW_KEY = "xhsSaveWindowId";+const XHS_DOCUMENT_PATTERNS = [+ "https://www.xiaohongshu.com/*",+ "https://xiaohongshu.com/*",+];const toMarkdown = (page: CapturedPage) => {const capturedAt = new Date().toISOString();@@ -392,10 +407,16 @@ const openTweetPermissionWindow = async (tabId: number | null) => {await focusExtensionWindow("tweet-save.html", TWEET_WINDOW_KEY, 560);};+const openXhsPermissionWindow = async (tabId: number | null) => {+ await chrome.storage.session.set({ [PENDING_XHS_KEY]: { tabId } });+ await focusExtensionWindow("xhs-save.html", XHS_WINDOW_KEY, 560);+};+let pendingCapture: ((page: CapturedPage) => void) | null = null;const pendingImageReads = new Map<string, (result: unknown) => void>();const pendingTweetReads = new Map<string, (result: unknown) => void>();const pendingGithubReads = new Map<string, (result: unknown) => void>();+const pendingXhsReads = new Map<string, (result: unknown) => void>();let clipQueue = Promise.resolve();let completingImageSave = false;@@ -657,6 +678,130 @@ const saveTweetFromMenu = async (}};+const injectXhsReader = async (tabId: number, frameId: number | null, payload: unknown) => {+ const target = scriptTarget(tabId, frameId);+ await chrome.scripting.executeScript({+ target,+ func: (value: unknown) => {+ (globalThis as { __edgeeverXhsClipPayload?: unknown }).__edgeeverXhsClipPayload = value;+ },+ args: [payload],+ });+ await chrome.scripting.executeScript({+ target,+ files: ["assets/capture-xhs.js"],+ });+};++const injectXhsTarget = async (tabId: number) => {+ await chrome.scripting.executeScript({+ target: { tabId },+ files: ["assets/xhs-target.js"],+ });+};++const readXhsStateFromPage = async (tabId: number, frameId: number | null) => {+ try {+ const [injected] = await chrome.scripting.executeScript({+ target: scriptTarget(tabId, frameId),+ world: "MAIN",+ func: readXhsStateInPage,+ });+ return isXhsPageRead(injected?.result) && injected.result.ok ? injected.result : null;+ } catch {+ // Older pages can block the main world. The DOM reader below still runs.+ return null;+ }+};++const readXhsFromPage = async (tabId: number, frameId: number | null) => {+ const requestId = crypto.randomUUID();+ const result = await new Promise<unknown>((resolve, reject) => {+ const timeout = setTimeout(() => {+ pendingXhsReads.delete(requestId);+ reject(new Error("timeout"));+ }, 10_000);+ pendingXhsReads.set(requestId, (value) => {+ clearTimeout(timeout);+ resolve(value);+ });+ void injectXhsReader(tabId, frameId, { requestId }).catch((error: unknown) => {+ clearTimeout(timeout);+ pendingXhsReads.delete(requestId);+ reject(error);+ });+ });+ return isXhsPageRead(result) ? result : { ok: false as const, reason: "not-found" as const };+};++const describeXhsError = (error: unknown) => {+ const message = error instanceof Error ? error.message : "";+ if (message === t("xhsNotFound") || message === t("xhsNeedsOpen")) return message;+ return describeImageError(error);+};++const saveXhsFromMenu = async (+ info: { pageUrl?: string; frameId?: number },+ tab?: { id?: number; url?: string },+) => {+ const tabId = typeof tab?.id === "number" ? tab.id : null;+ const frameId = typeof info.frameId === "number" ? info.frameId : null;+ const pageUrl = tab?.url || info.pageUrl || "";+ try {+ const settings = await ensureClipperReady();+ if (!tabId) throw new Error(t("xhsNotFound"));+ const noteId = noteIdFromPageUrl(pageUrl);+ if (!noteId && !await hasTweetSitePermission(pageUrl)) {+ await openXhsPermissionWindow(tabId);+ await showFeedback(tabId, frameId, t("xhsPermissionToast"), "success");+ return;+ }++ await showFeedback(tabId, frameId, t("savingXhs"), "success");+ const page = await readXhsStateFromPage(tabId, frameId) ?? await readXhsFromPage(tabId, frameId);+ if (!page.ok && page.reason === "needs-listener") {+ await injectXhsTarget(tabId);+ await showFeedback(tabId, frameId, t("xhsRightClickAgain"), "success");+ return;+ }+ if (!page.ok && page.reason === "needs-open") throw new Error(t("xhsNeedsOpen"));+ if (!page.ok) throw new Error(t("xhsNotFound"));+ const note = resolveXhsNote(page, pageUrl);+ if (!note) throw new Error(t("xhsNotFound"));++ const images = [];+ const alt = note.title || t("imageAltFallback");+ for (const url of note.imageUrls) {+ const stored = await readTweetImage(tabId, frameId, url, alt);+ if (stored) images.push(stored);+ }+ await saveCapturedXhsNote(imageNoteClient(settings), {+ notebookId: settings.notebookId,+ title: xhsNoteTitle({ ...note, fallback: t("xhsNoteFallbackTitle") }),+ nickname: note.nickname,+ noteTitle: note.title,+ body: note.body,+ datetime: note.datetime,+ location: note.location,+ noteUrl: note.noteUrl,+ images,+ capturedAt: new Date().toISOString(),+ sourceLabel: t("sourceLabel"),+ capturedAtLabel: t("capturedAtLabel"),+ timeLabel: t("tweetTimeLabel"),+ locationLabel: t("xhsLocationLabel"),+ altFallback: t("imageAltFallback"),+ });+ await showFeedback(tabId, frameId, t("xhsSaved"), "success");+ } catch (error) {+ const message = describeXhsError(error);+ if (message === t("completePluginConfiguration") || message === t("instancePermissionRequired")) {+ await chrome.runtime.openOptionsPage();+ }+ await showFeedback(tabId, frameId, message, "error");+ }+};+const isGithubRepoSource = (value: unknown): value is GithubRepoPageSource => {if (!value || typeof value !== "object") return false;const record = value as Partial<GithubRepoPageSource>;@@ -870,8 +1015,8 @@ const registerClipMenus = () => {// Chrome and Firefox fold an extension into a submenu when more than one of// its items is visible. These contexts stay disjoint so each command remains// on the top-level menu: a photo saves the image, selected words save the- // passage, the rest of an X post saves the post, and a GitHub repository- // page saves the repository.+ // passage, the rest of an X post saves the post, a GitHub repository page+ // saves the repository, and the rest of a Xiaohongshu note saves the note.// Link context is omitted because a linked image would otherwise show both// commands. Recreate from scratch so a previous registration cannot keep an// overlapping item.@@ -914,6 +1059,14 @@ const createClipMenus = () => {}, () => {void chrome.runtime.lastError;});+ chrome.contextMenus.create({+ id: XHS_MENU_ID,+ title: t("saveXhsToEdgeEver"),+ contexts: ["page", "video"],+ documentUrlPatterns: XHS_DOCUMENT_PATTERNS,+ }, () => {+ void chrome.runtime.lastError;+ });};chrome.runtime.onInstalled.addListener(registerClipMenus);@@ -934,17 +1087,24 @@ chrome.contextMenus.onClicked.addListener((info: { menuItemId?: string | number;}if (info.menuItemId === GITHUB_REPO_MENU_ID) {void enqueueClip(() => saveGithubRepoFromMenu(info, tab));+ return;+ }+ if (info.menuItemId === XHS_MENU_ID) {+ void enqueueClip(() => saveXhsFromMenu(info, tab));}});chrome.windows.onRemoved.addListener((windowId: number) => {- void chrome.storage.session.get([IMAGE_SAVE_WINDOW_KEY, TWEET_WINDOW_KEY]).then((stored: Record<string, unknown>) => {+ void chrome.storage.session.get([IMAGE_SAVE_WINDOW_KEY, TWEET_WINDOW_KEY, XHS_WINDOW_KEY]).then((stored: Record<string, unknown>) => {if (stored[IMAGE_SAVE_WINDOW_KEY] === windowId) {void chrome.storage.session.remove(IMAGE_SAVE_WINDOW_KEY);}if (stored[TWEET_WINDOW_KEY] === windowId) {void chrome.storage.session.remove(TWEET_WINDOW_KEY);}+ if (stored[XHS_WINDOW_KEY] === windowId) {+ void chrome.storage.session.remove(XHS_WINDOW_KEY);+ }}).catch(() => undefined);});@@ -973,6 +1133,12 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedPreturn false;}+ if (message.type === "pageXhsRead" && message.requestId) {+ pendingXhsReads.get(message.requestId)?.(message.result);+ pendingXhsReads.delete(message.requestId);+ return false;+ }+if (message.type === "activateTweetTarget") {void (async () => {const stored = await chrome.storage.session.get(PENDING_TWEET_KEY);@@ -990,6 +1156,23 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedPreturn true;}+ if (message.type === "activateXhsTarget") {+ void (async () => {+ const stored = await chrome.storage.session.get(PENDING_XHS_KEY);+ const pending = stored[PENDING_XHS_KEY] as { tabId?: number | null } | undefined;+ if (typeof pending?.tabId === "number") {+ try {+ await injectXhsTarget(pending.tabId);+ } catch {+ // The tab can be saved on the next right-click after it reloads.+ }+ }+ await chrome.storage.session.remove(PENDING_XHS_KEY);+ sendResponse({ ok: true });+ })().catch(() => sendResponse({ ok: false }));+ return true;+ }+if (message.type === "getPendingImageSave") {void readPendingImageSave().then((pending) => {sendResponse(pending ? { originPattern: pending.originPattern, host: pending.host } : null);diff --git a/apps/extension/src/capture-xhs.ts b/apps/extension/src/capture-xhs.tsnew file mode 100644index 00000000..47896156--- /dev/null+++ b/apps/extension/src/capture-xhs.ts@@ -0,0 +1,211 @@+// Injected on demand. Reads the open Xiaohongshu note, or the note marked by+// xhs-target.js. Must stay import-free.+(() => {+ const root = globalThis as typeof globalThis & {+ __edgeeverXhsTarget?: boolean;+ __edgeeverXhsClipPayload?: { requestId?: string };+ };+ const payload = root.__edgeeverXhsClipPayload;+ delete root.__edgeeverXhsClipPayload;+ if (!payload || typeof payload.requestId !== "string") return;+ const requestId = payload.requestId;++ const finish = (result: Record<string, unknown>) => {+ void chrome.runtime.sendMessage({ type: "pageXhsRead", requestId, result });+ };++ // Keep identical to noteIdFromPath in xhs-clip.ts.+ const noteIdFromPath = (pathname: string) => {+ const direct = pathname.match(/^\/(?:explore|discovery\/item)\/([0-9a-fA-F]{16,32})(?=\/|$)/);+ if (direct?.[1]) return direct[1];+ const profile = pathname.match(/^\/user\/profile\/[^/]+\/([0-9a-fA-F]{16,32})(?=\/|$)/);+ return profile?.[1] ?? "";+ };++ const noteIdFromHref = (href: string) => {+ if (!href) return "";+ try {+ return noteIdFromPath(new URL(href, location.href).pathname);+ } catch {+ return "";+ }+ };++ const asString = (value: unknown) => (typeof value === "string" ? value : "");++ const asNumber = (value: unknown) => {+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);+ return 0;+ };++ const emptyImage = (url = "") => ({ url, urlDefault: "", urlPre: "", infoList: [] as Array<{ imageScene: string; url: string }> });++ type Snapshot = {+ noteId: string;+ title: string;+ desc: string;+ nickname: string;+ timeMs: number;+ timeText: string;+ location: string;+ tags: string[];+ images: Array<{ url: string; urlDefault: string; urlPre: string; infoList: Array<{ imageScene: string; url: string }> }>;+ };++ const hasContent = (note: Snapshot) => Boolean(note.title || note.desc || note.nickname || note.images.length > 0);++ const stateRoot = () => {+ const state = (window as unknown as {+ __INITIAL_STATE__?: {+ note?: {+ noteDetailMap?: Record<string, unknown>;+ currentNoteId?: unknown;+ firstNoteId?: unknown;+ };+ };+ }).__INITIAL_STATE__;+ return state?.note ?? null;+ };++ const readStateNote = (noteId: string) => {+ const map = stateRoot()?.noteDetailMap;+ if (!map || !noteId) return null;+ const entry = map[noteId];+ if (!entry || typeof entry !== "object") return null;+ const record = entry as { note?: unknown };+ if (record.note && typeof record.note === "object") return record.note as Record<string, unknown>;+ return record as Record<string, unknown>;+ };++ const snapshotFromState = (note: Record<string, unknown> | null, noteId: string): Snapshot | null => {+ if (!note) return null;+ const user = note.user && typeof note.user === "object" ? note.user as Record<string, unknown> : {};+ const tags: string[] = [];+ if (Array.isArray(note.tagList)) {+ for (const tag of note.tagList) {+ if (tags.length >= 40) break;+ const name = tag && typeof tag === "object" ? asString((tag as { name?: unknown }).name) : "";+ if (name) tags.push(name);+ }+ }+ const images: Snapshot["images"] = [];+ if (Array.isArray(note.imageList)) {+ for (const image of note.imageList) {+ if (images.length >= 18 || !image || typeof image !== "object") continue;+ const source = image as { url?: unknown; urlDefault?: unknown; urlPre?: unknown; infoList?: unknown };+ const infoList: Array<{ imageScene: string; url: string }> = [];+ if (Array.isArray(source.infoList)) {+ for (const info of source.infoList) {+ if (infoList.length >= 8 || !info || typeof info !== "object") continue;+ const item = info as { imageScene?: unknown; url?: unknown };+ infoList.push({ imageScene: asString(item.imageScene), url: asString(item.url) });+ }+ }+ images.push({+ url: asString(source.url),+ urlDefault: asString(source.urlDefault),+ urlPre: asString(source.urlPre),+ infoList,+ });+ }+ }+ return {+ noteId: asString(note.noteId) || noteId,+ title: asString(note.title),+ desc: asString(note.desc),+ nickname: asString(user.nickname) || asString(user.nickName),+ timeMs: asNumber(note.time),+ timeText: "",+ location: asString(note.ipLocation),+ tags,+ images,+ };+ };++ const clean = (value: string) => value.replace(/\u00a0/g, " ").replace(/[ \t]+\n/g, "\n").trim();++ const textOf = (node: Element | null) => {+ if (!node) return "";+ const element = node as HTMLElement;+ return clean(element.innerText || element.textContent || "");+ };++ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++ const expandFolded = async (scope: Element) => {+ const desc = scope.querySelector("#detail-desc, .desc, .note-content");+ if (!desc) return;+ const control = [...desc.querySelectorAll("button, span, div")].find((node) => {+ const text = (node.textContent || "").replace(/\s+/g, "");+ return text === "展开" || text === "展开全文";+ });+ if (!control) return;+ (control as HTMLElement).click();+ await sleep(300);+ };++ const snapshotFromDom = (scope: Element, noteId: string): Snapshot => {+ const authorRoot = scope.querySelector(".author-wrapper, .author-container, .author");+ const descRoot = scope.querySelector("#detail-desc .note-text") || scope.querySelector("#detail-desc, .note-text, .desc");+ const dateNode = scope.querySelector(".note-scroller .date, .bottom-container .date");+ const tags = [...scope.querySelectorAll("#detail-desc a.tag, #detail-desc a[href*='search_result']")]+ .map((node) => clean(node.textContent || ""))+ .filter(Boolean)+ .slice(0, 40);+ const media = scope.querySelector(".media-container, .swiper, .swiper-container, .note-slider") || scope;+ const images: Snapshot["images"] = [];+ for (const img of media.querySelectorAll("img")) {+ if (images.length >= 18) break;+ if (img.closest(".avatar, .comment, .comments-container, .comments-el, .author, .author-wrapper, .author-container")) continue;+ if (img.naturalWidth > 0 && img.naturalHeight > 0 && img.naturalWidth < 48 && img.naturalHeight < 48) continue;+ const src = img.currentSrc || img.src;+ if (!src || src.startsWith("data:") || src.startsWith("blob:")) continue;+ if (images.some((image) => image.url === src)) continue;+ images.push(emptyImage(src));+ }+ return {+ noteId,+ title: textOf(scope.querySelector("#detail-title, .title")),+ desc: textOf(descRoot),+ nickname: clean(authorRoot?.querySelector(".username, .name")?.textContent || ""),+ timeMs: 0,+ timeText: textOf(dateNode),+ location: "",+ tags,+ images,+ };+ };++ void (async () => {+ try {+ const pageId = noteIdFromPath(location.pathname);+ const marked = document.querySelector("[data-edgeever-xhs-target='1']");+ const markedId = marked?.getAttribute("data-edgeever-xhs-note-id")+ || noteIdFromHref(marked?.querySelector("a[href]")?.getAttribute("href") || "");+ const detail = document.querySelector("#noteContainer");+ if (!pageId && !markedId && !detail) {+ finish({ ok: false, reason: root.__edgeeverXhsTarget ? "not-found" : "needs-listener" });+ return;+ }+ const noteState = stateRoot();+ const stateCurrent = asString(noteState?.currentNoteId) || asString(noteState?.firstNoteId);+ let noteId = pageId;+ if (!noteId && detail) noteId = stateCurrent || markedId;+ if (!noteId) noteId = markedId;++ let snapshot = snapshotFromState(readStateNote(noteId), noteId);+ if ((!snapshot || !hasContent(snapshot)) && detail) {+ await expandFolded(detail);+ snapshot = snapshotFromDom(detail, noteId);+ }+ if (!snapshot || !hasContent(snapshot)) {+ finish({ ok: false, reason: !detail && markedId ? "needs-open" : "not-found" });+ return;+ }+ finish({ ok: true, ...snapshot, noteId: snapshot.noteId || noteId });+ } catch {+ finish({ ok: false, reason: "not-found" });+ }+ })();+})();diff --git a/apps/extension/src/xhs-clip.ts b/apps/extension/src/xhs-clip.tsnew file mode 100644index 00000000..13c3f854--- /dev/null+++ b/apps/extension/src/xhs-clip.ts@@ -0,0 +1,465 @@+import { imageAltText, type ImageNoteClient } from "./image-clip";++const XHS_HOSTS = new Set([+ "xiaohongshu.com",+ "www.xiaohongshu.com",+]);++const MAX_XHS_IMAGES = 18;++export type XhsImageSource = {+ url: string;+ urlDefault: string;+ urlPre: string;+ infoList: Array<{ imageScene: string; url: string }>;+};++export type XhsPageSuccess = {+ ok: true;+ noteId: string;+ title: string;+ desc: string;+ nickname: string;+ timeMs: number;+ timeText: string;+ location: string;+ tags: string[];+ images: XhsImageSource[];+};++export type XhsPageFailure = {+ ok: false;+ reason: "not-found" | "needs-listener" | "needs-open";+};++export type XhsPageRead = XhsPageSuccess | XhsPageFailure;++export type ResolvedXhsNote = {+ noteId: string;+ nickname: string;+ title: string;+ body: string;+ datetime: string;+ location: string;+ noteUrl: string;+ imageUrls: string[];+};++export type XhsNoteImage = {+ resourceId: string;+ alt: string;+};++// Keep identical to noteIdFromPath in capture-xhs.ts and xhs-target.ts.+const noteIdFromPath = (pathname: string) => {+ const direct = pathname.match(/^\/(?:explore|discovery\/item)\/([0-9a-fA-F]{16,32})(?=\/|$)/);+ if (direct?.[1]) return direct[1];+ const profile = pathname.match(/^\/user\/profile\/[^/]+\/([0-9a-fA-F]{16,32})(?=\/|$)/);+ return profile?.[1] ?? "";+};++const escapeMarkdownLabel = (value: string) =>+ value.replace(/[\r\n]+/g, " ").replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]");++const markdownDestination = (value: string) =>+ value.replace(/\\/g, "%5C").replace(/ /g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29");++const sceneRank = (scene: string) => {+ const value = scene.toUpperCase();+ if (value.includes("ORG")) return 0;+ if (value.includes("DFT")) return 1;+ if (value.includes("PRV") || value.includes("PREV") || value.includes("THUMB")) return 5;+ if (value.startsWith("WB_")) return 2;+ return 4;+};++const isXhsImageHost = (hostname: string) => {+ const host = hostname.toLowerCase();+ if (host.includes("avatar")) return false;+ return host === "xhscdn.com"+ || host.endsWith(".xhscdn.com")+ || host === "xhscdn.net"+ || host.endsWith(".xhscdn.net")+ || host === "xiaohongshu.com"+ || host.endsWith(".xiaohongshu.com");+};++export const noteIdFromPageUrl = (pageUrl: string) => {+ try {+ const url = new URL(pageUrl);+ if (!XHS_HOSTS.has(url.hostname.toLowerCase())) return "";+ return noteIdFromPath(url.pathname);+ } catch {+ return "";+ }+};++export const canonicalNoteUrl = (pageUrl: string, noteId: string) => {+ if (!noteId) return "";+ const next = new URL(`https://www.xiaohongshu.com/explore/${noteId}`);+ try {+ const url = new URL(pageUrl);+ const token = url.searchParams.get("xsec_token");+ const source = url.searchParams.get("xsec_source");+ if (token) next.searchParams.set("xsec_token", token);+ if (source) next.searchParams.set("xsec_source", source);+ } catch {+ // The note id still identifies the post when the page URL cannot be parsed.+ }+ return next.toString();+};++export const normalizeXhsPhotoUrl = (value: string) => {+ const raw = value.trim();+ if (!raw || raw.startsWith("data:") || raw.startsWith("blob:")) return "";+ try {+ const url = new URL(raw);+ if (url.protocol !== "http:" && url.protocol !== "https:") return "";+ if (!isXhsImageHost(url.hostname)) return "";+ if (url.pathname.toLowerCase().includes("avatar")) return "";+ if (/\.(mp4|mov|m3u8)$/i.test(url.pathname)) return "";+ if (url.protocol === "http:") url.protocol = "https:";+ return url.toString();+ } catch {+ return "";+ }+};++const photoKey = (value: string) => {+ try {+ const url = new URL(value);+ return `${url.hostname.toLowerCase()}${url.pathname.replace(/![^/]*$/, "").toLowerCase()}`;+ } catch {+ return value;+ }+};++export const imageUrlsFromXhsImages = (images: XhsImageSource[]) => {+ const urls: string[] = [];+ const seen = new Set<string>();+ for (const image of images) {+ if (urls.length >= MAX_XHS_IMAGES) break;+ const ranked: Array<{ rank: number; url: string }> = [];+ for (const info of image.infoList) {+ if (info.url) ranked.push({ rank: sceneRank(info.imageScene), url: info.url });+ }+ if (image.urlDefault) ranked.push({ rank: 1, url: image.urlDefault });+ if (image.url) ranked.push({ rank: 3, url: image.url });+ if (image.urlPre) ranked.push({ rank: 5, url: image.urlPre });+ ranked.sort((left, right) => left.rank - right.rank);+ for (const item of ranked) {+ const normalized = normalizeXhsPhotoUrl(item.url);+ if (!normalized) continue;+ const key = photoKey(normalized);+ if (seen.has(key)) break;+ seen.add(key);+ urls.push(normalized);+ break;+ }+ }+ return urls;+};++export const cleanXhsText = (value: string) => {+ const lines = value.replace(/\r/g, "").split("\n").map((line) => line.trim());+ while (lines.length > 0 && !lines[0]) lines.shift();+ while (lines.length > 0 && !lines[lines.length - 1]) lines.pop();+ return lines.join("\n").replace(/\n{3,}/g, "\n\n").replace(/\n?(展开全文|展开|收起)\s*$/u, "").trim();+};++export const xhsBodyText = (desc: string, tags: string[]) => {+ const text = cleanXhsText(desc);+ const missing: string[] = [];+ for (const tag of tags) {+ const bare = tag.replace(/^#/, "").replace(/\[话题\]#?$/u, "").trim();+ if (!bare || text.includes(bare)) continue;+ missing.push(`#${bare}`);+ }+ if (missing.length === 0) return text;+ const line = missing.join(" ");+ return text ? `${text}\n${line}` : line;+};++export const splitXhsDateText = (value: string) => {+ const text = value.replace(/\s+/g, " ").trim();+ if (!text) return { timeText: "", location: "" };+ const match = text.match(/^(.*?)(?:\s+)([^\s]+)$/);+ const head = match?.[1]?.trim() ?? "";+ const tail = match?.[2]?.trim() ?? "";+ if (head && tail && /(前|昨天|今天|编辑于|\d{4}[-/.]\d{1,2}|\d{1,2}[-/.]\d{1,2})/.test(head) && !/(前|昨天|今天)/.test(tail)) {+ return { timeText: head, location: tail };+ }+ return { timeText: text, location: "" };+};++export const xhsTimeIso = (timeMs: number) => {+ if (!Number.isFinite(timeMs) || timeMs <= 0) return "";+ const ms = timeMs < 1e11 ? timeMs * 1000 : timeMs;+ const date = new Date(ms);+ if (Number.isNaN(date.getTime())) return "";+ return date.toISOString();+};++const isImageSource = (value: unknown): value is XhsImageSource => {+ if (!value || typeof value !== "object") return false;+ const image = value as Partial<XhsImageSource>;+ return typeof image.url === "string"+ && typeof image.urlDefault === "string"+ && typeof image.urlPre === "string"+ && Array.isArray(image.infoList)+ && image.infoList.every((info) => {+ const item = info as { imageScene?: unknown; url?: unknown };+ return typeof item?.imageScene === "string" && typeof item?.url === "string";+ });+};++export const isXhsPageRead = (value: unknown): value is XhsPageRead => {+ if (!value || typeof value !== "object") return false;+ const record = value as Partial<XhsPageSuccess> & Partial<XhsPageFailure>;+ if (record.ok === false) {+ return record.reason === "not-found" || record.reason === "needs-listener" || record.reason === "needs-open";+ }+ if (record.ok !== true) return false;+ return typeof record.noteId === "string"+ && typeof record.title === "string"+ && typeof record.desc === "string"+ && typeof record.nickname === "string"+ && typeof record.timeMs === "number"+ && typeof record.timeText === "string"+ && typeof record.location === "string"+ && Array.isArray(record.tags)+ && record.tags.every((tag) => typeof tag === "string")+ && Array.isArray(record.images)+ && record.images.every((image) => isImageSource(image));+};++export const resolveXhsNote = (read: XhsPageSuccess, pageUrl: string): ResolvedXhsNote | null => {+ const noteId = read.noteId || noteIdFromPageUrl(pageUrl);+ const split = splitXhsDateText(read.timeText);+ const nickname = read.nickname.replace(/\s+/g, " ").trim();+ const title = read.title.replace(/\s+/g, " ").trim();+ const body = xhsBodyText(read.desc, read.tags);+ const imageUrls = imageUrlsFromXhsImages(read.images);+ if (!title && !body && !nickname && imageUrls.length === 0) return null;+ return {+ noteId,+ nickname,+ title,+ body,+ datetime: xhsTimeIso(read.timeMs) || split.timeText,+ location: read.location.replace(/\s+/g, " ").trim() || split.location,+ noteUrl: canonicalNoteUrl(pageUrl, noteId) || pageUrl,+ imageUrls,+ };+};++export const xhsNoteTitle = (input: { title: string; nickname: string; body: string; fallback: string }) => {+ const heading = input.title.replace(/\s+/g, " ").trim();+ if (heading) return heading.slice(0, 160);+ const first = cleanXhsText(input.body).split("\n").map((line) => line.trim()).find(Boolean) ?? "";+ const name = input.nickname.replace(/\s+/g, " ").trim();+ const combined = name && first ? `${name}: ${first}` : (first || name || input.fallback);+ return combined.replace(/\s+/g, " ").trim().slice(0, 160);+};++export const xhsNoteMarkdown = (input: {+ nickname: string;+ title: string;+ body: string;+ datetime: string;+ location: string;+ noteUrl: string;+ images: XhsNoteImage[];+ capturedAt: string;+ sourceLabel: string;+ capturedAtLabel: string;+ timeLabel: string;+ locationLabel: string;+ altFallback: string;+}) => {+ const blocks: string[] = [];+ const nickname = input.nickname.replace(/\s+/g, " ").trim();+ if (nickname) blocks.push(nickname);+ const title = input.title.replace(/\s+/g, " ").trim();+ const body = cleanXhsText(input.body);+ if (title && !body.startsWith(title)) blocks.push(title);+ if (body) blocks.push(body);+ if (input.images.length > 0) {+ blocks.push(input.images.map((image) => (+ `}/blob)`+ )).join("\n\n"));+ }+ const footer = [+ input.noteUrl ? `${input.sourceLabel}: [${escapeMarkdownLabel(input.noteUrl)}](${markdownDestination(input.noteUrl)})` : "",+ input.datetime ? `${input.timeLabel}: ${input.datetime}` : "",+ input.location ? `${input.locationLabel}: ${input.location}` : "",+ `${input.capturedAtLabel}: ${input.capturedAt}`,+ ].filter(Boolean);+ blocks.push(footer.join("\n\n"));+ return blocks.join("\n\n");+};++export const saveCapturedXhsNote = async (+ client: ImageNoteClient,+ input: {+ notebookId: string;+ title: string;+ nickname: string;+ noteTitle: string;+ body: string;+ datetime: string;+ location: string;+ noteUrl: string;+ images: Array<{ bytes: Uint8Array; mimeType: string; filename: string; alt: string }>;+ capturedAt: string;+ sourceLabel: string;+ capturedAtLabel: string;+ timeLabel: string;+ locationLabel: string;+ altFallback: string;+ },+) => {+ let notebookId = input.notebookId;+ if (!notebookId) {+ const listed = await client.listNotebooks();+ notebookId = listed.notebooks[0]?.id ?? "";+ }+ if (!notebookId) throw new Error("no-notebook");++ const markdownFor = (images: XhsNoteImage[]) => xhsNoteMarkdown({+ nickname: input.nickname,+ title: input.noteTitle,+ body: input.body,+ datetime: input.datetime,+ location: input.location,+ noteUrl: input.noteUrl,+ images,+ capturedAt: input.capturedAt,+ sourceLabel: input.sourceLabel,+ capturedAtLabel: input.capturedAtLabel,+ timeLabel: input.timeLabel,+ locationLabel: input.locationLabel,+ altFallback: input.altFallback,+ });+ const created = await client.createMemo({+ notebookId,+ title: input.title,+ contentMarkdown: markdownFor([]),+ tags: ["web-clip"],+ });+ const memoId = created.memo.id;+ if (!memoId) throw new Error("create-missing-id");+ if (input.images.length === 0) return { memoId, resourceIds: [] as string[] };++ const uploaded: XhsNoteImage[] = [];+ for (const image of input.images) {+ try {+ const resource = await client.uploadImage(memoId, image);+ if (resource.id) uploaded.push({ resourceId: resource.id, alt: image.alt });+ } catch {+ // The text note is still useful when one attachment cannot be stored.+ }+ }+ if (uploaded.length === 0) return { memoId, resourceIds: [] as string[] };++ try {+ const session = await client.createEditSession(memoId);+ await client.saveMemo(memoId, {+ editSessionId: session.editSession.id,+ expectedRevision: session.editSession.baseRevision,+ expectedContentHash: session.editSession.baseContentHash,+ contentMarkdown: markdownFor(uploaded),+ });+ } catch {+ // Leave the text note in place when attaching images fails.+ }+ return { memoId, resourceIds: uploaded.map((image) => image.resourceId) };+};++// Runs in the page's main world, where window.__INITIAL_STATE__ lives.+// Keep this function free of closures: Chrome serializes it with toString().+export function readXhsStateInPage(): XhsPageRead {+ const noteIdFromPath = (pathname: string) => {+ const direct = pathname.match(/^\/(?:explore|discovery\/item)\/([0-9a-fA-F]{16,32})(?=\/|$)/);+ if (direct?.[1]) return direct[1];+ const profile = pathname.match(/^\/user\/profile\/[^/]+\/([0-9a-fA-F]{16,32})(?=\/|$)/);+ return profile?.[1] ?? "";+ };+ const asString = (value: unknown) => (typeof value === "string" ? value : "");+ const asNumber = (value: unknown) => {+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);+ return 0;+ };+ try {+ const state = (window as unknown as {+ __INITIAL_STATE__?: {+ note?: {+ noteDetailMap?: Record<string, unknown>;+ currentNoteId?: unknown;+ firstNoteId?: unknown;+ };+ };+ }).__INITIAL_STATE__;+ const noteRoot = state?.note;+ if (!noteRoot?.noteDetailMap) return { ok: false, reason: "not-found" };+ const detailOpen = Boolean(document.querySelector("#noteContainer"));+ const noteId = noteIdFromPath(location.pathname)+ || (detailOpen ? asString(noteRoot.currentNoteId) || asString(noteRoot.firstNoteId) : "");+ if (!noteId) return { ok: false, reason: "not-found" };+ const entry = noteRoot.noteDetailMap[noteId];+ if (!entry || typeof entry !== "object") return { ok: false, reason: "not-found" };+ const record = entry as { note?: unknown };+ const note = record.note && typeof record.note === "object"+ ? record.note as Record<string, unknown>+ : record as Record<string, unknown>;+ const user = note.user && typeof note.user === "object" ? note.user as Record<string, unknown> : {};+ const tags: string[] = [];+ if (Array.isArray(note.tagList)) {+ for (const tag of note.tagList) {+ if (tags.length >= 40) break;+ const name = tag && typeof tag === "object" ? asString((tag as { name?: unknown }).name) : "";+ if (name) tags.push(name);+ }+ }+ const images: XhsImageSource[] = [];+ if (Array.isArray(note.imageList)) {+ for (const image of note.imageList) {+ if (images.length >= 18 || !image || typeof image !== "object") continue;+ const source = image as { url?: unknown; urlDefault?: unknown; urlPre?: unknown; infoList?: unknown };+ const infoList: XhsImageSource["infoList"] = [];+ if (Array.isArray(source.infoList)) {+ for (const info of source.infoList) {+ if (infoList.length >= 8 || !info || typeof info !== "object") continue;+ const item = info as { imageScene?: unknown; url?: unknown };+ infoList.push({ imageScene: asString(item.imageScene), url: asString(item.url) });+ }+ }+ images.push({+ url: asString(source.url),+ urlDefault: asString(source.urlDefault),+ urlPre: asString(source.urlPre),+ infoList,+ });+ }+ }+ const title = asString(note.title);+ const desc = asString(note.desc);+ const nickname = asString(user.nickname) || asString(user.nickName);+ if (!title && !desc && !nickname && images.length === 0) return { ok: false, reason: "not-found" };+ return {+ ok: true,+ noteId: asString(note.noteId) || noteId,+ title,+ desc,+ nickname,+ timeMs: asNumber(note.time),+ timeText: "",+ location: asString(note.ipLocation),+ tags,+ images,+ };+ } catch {+ return { ok: false, reason: "not-found" };+ }+}diff --git a/apps/extension/src/xhs-save.ts b/apps/extension/src/xhs-save.tsnew file mode 100644index 00000000..bc536350--- /dev/null+++ b/apps/extension/src/xhs-save.ts@@ -0,0 +1,41 @@+import "./styles.css";+import { localizeDocument, t } from "./i18n";++localizeDocument();+document.title = t("xhsSaveWindowTitle");++const status = document.querySelector<HTMLParagraphElement>("#status");+const allowButton = document.querySelector<HTMLButtonElement>("#allow");++const setStatus = (message: string, kind: "normal" | "error" | "success" = "normal") => {+ if (!status) return;+ status.textContent = message;+ status.dataset.kind = kind;+};++allowButton?.addEventListener("click", () => {+ if (!allowButton) return;+ allowButton.disabled = true;+ void (async () => {+ let granted = false;+ try {+ granted = await chrome.permissions.request({+ origins: ["https://www.xiaohongshu.com/*", "https://xiaohongshu.com/*"],+ });+ } catch {+ granted = false;+ }+ if (!granted) {+ setStatus(t("xhsPermissionDenied"), "error");+ allowButton.disabled = false;+ return;+ }+ try {+ await chrome.runtime.sendMessage({ type: "activateXhsTarget" });+ } catch {+ // The page can still be saved on the next right-click after a reload.+ }+ setStatus(t("xhsPermissionReady"), "success");+ window.setTimeout(() => window.close(), 1600);+ })();+});diff --git a/apps/extension/src/xhs-target.ts b/apps/extension/src/xhs-target.tsnew file mode 100644index 00000000..a12ac019--- /dev/null+++ b/apps/extension/src/xhs-target.ts@@ -0,0 +1,48 @@+// Content script for xiaohongshu.com. It only remembers which note was under+// the pointer so a later menu click can save that post. No imports: content+// scripts are classic scripts, and this file is also injected again after the+// user grants access.+(() => {+ const root = globalThis as typeof globalThis & { __edgeeverXhsTarget?: boolean };+ if (root.__edgeeverXhsTarget) return;+ root.__edgeeverXhsTarget = true;++ // Keep identical to noteIdFromPath in xhs-clip.ts.+ const noteIdFromPath = (pathname: string) => {+ const direct = pathname.match(/^\/(?:explore|discovery\/item)\/([0-9a-fA-F]{16,32})(?=\/|$)/);+ if (direct?.[1]) return direct[1];+ const profile = pathname.match(/^\/user\/profile\/[^/]+\/([0-9a-fA-F]{16,32})(?=\/|$)/);+ return profile?.[1] ?? "";+ };++ const noteIdFromHref = (href: string) => {+ if (!href) return "";+ try {+ return noteIdFromPath(new URL(href, location.href).pathname);+ } catch {+ return "";+ }+ };++ document.addEventListener("contextmenu", (event) => {+ const rawTarget = event.target;+ const element = rawTarget instanceof Element+ ? rawTarget+ : rawTarget instanceof Node+ ? rawTarget.parentElement+ : null;+ if (!element) return;+ for (const node of document.querySelectorAll("[data-edgeever-xhs-target]")) {+ node.removeAttribute("data-edgeever-xhs-target");+ node.removeAttribute("data-edgeever-xhs-note-id");+ }+ const detail = element.closest("#noteContainer");+ const card = detail ? null : element.closest("section.note-item, .note-item");+ const target = detail || card;+ if (!target) return;+ target.setAttribute("data-edgeever-xhs-target", "1");+ const href = target.querySelector("a[href]")?.getAttribute("href") || "";+ const noteId = noteIdFromHref(href) || noteIdFromPath(location.pathname);+ if (noteId) target.setAttribute("data-edgeever-xhs-note-id", noteId);+ }, true);+})();diff --git a/apps/extension/vite.config.ts b/apps/extension/vite.config.tsindex db0edf08..64babad6 100644--- a/apps/extension/vite.config.ts+++ b/apps/extension/vite.config.ts@@ -34,8 +34,11 @@ export default defineConfig({"capture-image": fileURLToPath(new URL("./src/capture-image.ts", import.meta.url)),"capture-tweet": fileURLToPath(new URL("./src/capture-tweet.ts", import.meta.url)),"capture-github": fileURLToPath(new URL("./src/capture-github.ts", import.meta.url)),+ "capture-xhs": fileURLToPath(new URL("./src/capture-xhs.ts", import.meta.url)),"tweet-target": fileURLToPath(new URL("./src/tweet-target.ts", import.meta.url)),"tweet-save": fileURLToPath(new URL("./tweet-save.html", import.meta.url)),+ "xhs-target": fileURLToPath(new URL("./src/xhs-target.ts", import.meta.url)),+ "xhs-save": fileURLToPath(new URL("./xhs-save.html", import.meta.url)),},output: {entryFileNames: "assets/[name].js",diff --git a/apps/extension/xhs-clip.test.mjs b/apps/extension/xhs-clip.test.mjsnew file mode 100644index 00000000..8cda3c86--- /dev/null+++ b/apps/extension/xhs-clip.test.mjs@@ -0,0 +1,250 @@+import { readFileSync } from "node:fs";+import { describe, expect, test } from "bun:test";+import {+ canonicalNoteUrl,+ cleanXhsText,+ imageUrlsFromXhsImages,+ noteIdFromPageUrl,+ readXhsStateInPage,+ resolveXhsNote,+ saveCapturedXhsNote,+ splitXhsDateText,+ xhsBodyText,+ xhsNoteMarkdown,+ xhsNoteTitle,+ xhsTimeIso,+} from "./src/xhs-clip.ts";++const noteId = "64b8f2e1000000001a01ebee";+const pageUrl = `https://www.xiaohongshu.com/explore/${noteId}?xsec_token=CBjuq-token&xsec_source=app_share&foo=1`;++const labels = {+ capturedAt: "2026-09-26T00:00:00.000Z",+ sourceLabel: "来源",+ capturedAtLabel: "抓取时间",+ timeLabel: "时间",+ locationLabel: "地点",+ altFallback: "图片",+};++const read = {+ ok: true,+ noteId,+ title: "世赛现场,会贴瓷砖的女生帅爆了",+ desc: "谁说贴瓷砖是男生的主场\n#世界技能大赛",+ nickname: "王小猫",+ timeMs: Date.parse("2026-09-20T08:00:00.000Z"),+ timeText: "",+ location: "上海",+ tags: ["世界技能大赛", "瓷砖铺贴"],+ images: [{+ url: "",+ urlDefault: "http://sns-webpic-qc.xhscdn.com/note/cover!nd_dft_wlteh_webp_3",+ urlPre: "http://sns-webpic-qc.xhscdn.com/note/cover!nd_prv_wlteh_webp_3",+ infoList: [+ { imageScene: "WB_PRV", url: "http://sns-webpic-qc.xhscdn.com/note/cover!nd_prv_wlteh_webp_3" },+ { imageScene: "WB_DFT", url: "https://sns-webpic-qc.xhscdn.com/note/cover!nd_dft_wlteh_webp_3" },+ ],+ }],+};++describe("xiaohongshu addresses", () => {+ test("reads a note id from a detail page and ignores the feed", () => {+ expect(noteIdFromPageUrl(pageUrl)).toBe(noteId);+ expect(noteIdFromPageUrl(`https://www.xiaohongshu.com/discovery/item/${noteId}`)).toBe(noteId);+ expect(noteIdFromPageUrl(`https://www.xiaohongshu.com/user/profile/abc123/${noteId}?xsec_token=1`)).toBe(noteId);+ expect(noteIdFromPageUrl("https://www.xiaohongshu.com/explore")).toBe("");+ expect(noteIdFromPageUrl("https://x.com/home")).toBe("");+ expect(canonicalNoteUrl(pageUrl, noteId)).toBe(+ `https://www.xiaohongshu.com/explore/${noteId}?xsec_token=CBjuq-token&xsec_source=app_share`,+ );+ });+});++describe("xiaohongshu note content", () => {+ test("keeps the note text, missing tags, display photo, and source link", () => {+ expect(cleanXhsText("谁说贴瓷砖是男生的主场\n展开")).toBe("谁说贴瓷砖是男生的主场");+ expect(xhsBodyText(read.desc, read.tags)).toBe("谁说贴瓷砖是男生的主场\n#世界技能大赛\n#瓷砖铺贴");+ expect(splitXhsDateText("6天前 上海")).toEqual({ timeText: "6天前", location: "上海" });+ expect(splitXhsDateText("昨天 12:30 上海")).toEqual({ timeText: "昨天 12:30", location: "上海" });+ expect(xhsTimeIso(read.timeMs)).toBe("2026-09-20T08:00:00.000Z");+ const resolved = resolveXhsNote(read, pageUrl);+ expect(resolved?.imageUrls).toEqual(["https://sns-webpic-qc.xhscdn.com/note/cover!nd_dft_wlteh_webp_3"]);+ expect(xhsNoteTitle({ title: resolved.title, nickname: resolved.nickname, body: resolved.body, fallback: "一篇小红书笔记" }))+ .toBe("世赛现场,会贴瓷砖的女生帅爆了");+ const markdown = xhsNoteMarkdown({+ ...labels,+ nickname: resolved.nickname,+ title: resolved.title,+ body: resolved.body,+ datetime: resolved.datetime,+ location: resolved.location,+ noteUrl: resolved.noteUrl,+ images: [{ resourceId: "res_1", alt: "封面]图" }],+ });+ expect(markdown.startsWith("王小猫")).toBe(true);+ expect(markdown).toContain("世赛现场,会贴瓷砖的女生帅爆了");+ expect(markdown).toContain("#瓷砖铺贴");+ expect(markdown).toContain("");+ expect(markdown).toContain(`(https://www.xiaohongshu.com/explore/${noteId}?xsec_token=CBjuq-token&xsec_source=app_share)`);+ expect(markdown).toContain("地点: 上海");+ expect(markdown).not.toContain("xhscdn.com");+ expect(markdown).not.toContain("foo=1");+ });++ test("uses the visible date when the page has no timestamp, and skips avatars", () => {+ const resolved = resolveXhsNote({+ ...read,+ title: "",+ timeMs: 0,+ timeText: "编辑于 6天前 上海",+ location: "",+ images: [{+ url: "https://sns-avatar-qc.xhscdn.com/avatar/cat.jpg",+ urlDefault: "",+ urlPre: "",+ infoList: [],+ }, {+ url: "https://example.com/not-a-note.jpg",+ urlDefault: "https://ci.xiaohongshu.com/note/second.jpg",+ urlPre: "",+ infoList: [],+ }],+ }, pageUrl);+ expect(resolved?.datetime).toBe("编辑于 6天前");+ expect(resolved?.location).toBe("上海");+ expect(resolved?.imageUrls).toEqual(["https://ci.xiaohongshu.com/note/second.jpg"]);+ expect(xhsNoteTitle({ title: "", nickname: "王小猫", body: resolved.body, fallback: "一篇小红书笔记" }))+ .toBe("王小猫: 谁说贴瓷砖是男生的主场");+ expect(imageUrlsFromXhsImages([{+ url: "https://sns-webpic-qc.xhscdn.com/note/clip.mp4",+ urlDefault: "",+ urlPre: "",+ infoList: [],+ }])).toEqual([]);+ });++ test("reads note state in the page world without calling extension helpers", () => {+ const source = readXhsStateInPage.toString();+ expect(source).toContain("__INITIAL_STATE__");+ expect(source).toContain("noteDetailMap");+ expect(source).not.toContain("noteIdFromPageUrl");+ expect(source).not.toContain("resolveXhsNote");+ });++ test("keeps the note id parser identical in the page scripts", () => {+ const library = readFileSync(new URL("./src/xhs-clip.ts", import.meta.url), "utf8");+ const parser = library.match(/const noteIdFromPath = \(pathname: string\) => \{[\s\S]*?\n\};/);+ const compact = (source) => source.replace(/^[ \t]+/gm, "");+ expect(parser?.[0]).toBeTruthy();+ for (const file of ["./src/capture-xhs.ts", "./src/xhs-target.ts"]) {+ const page = readFileSync(new URL(file, import.meta.url), "utf8");+ expect(compact(page)).toContain(compact(parser[0]));+ }+ const background = readFileSync(new URL("./src/background.ts", import.meta.url), "utf8");+ const patterns = background.slice(background.indexOf("const XHS_DOCUMENT_PATTERNS"), background.indexOf("const XHS_DOCUMENT_PATTERNS") + 220);+ const block = background.slice(background.indexOf("id: XHS_MENU_ID"), background.indexOf("id: XHS_MENU_ID") + 280);+ expect(patterns).toContain("https://www.xiaohongshu.com/*");+ expect(patterns).toContain("https://xiaohongshu.com/*");+ expect(block).toContain('contexts: ["page", "video"]');+ expect(block).toContain("documentUrlPatterns: XHS_DOCUMENT_PATTERNS");+ expect(block).not.toContain("selection");+ expect(block).not.toContain('"image"');+ });+});++describe("saveCapturedXhsNote", () => {+ const client = (overrides = {}) => {+ const order = [];+ const calls = { saved: null, created: null };+ return {+ order,+ calls,+ api: {+ listNotebooks: async () => {+ order.push("list");+ return { notebooks: [{ id: "nb_first" }] };+ },+ createMemo: async (body) => {+ order.push("create");+ calls.created = body;+ return { memo: { id: "memo_1" } };+ },+ uploadImage: async () => {+ order.push("upload");+ return { id: "res_1" };+ },+ createEditSession: async () => {+ order.push("session");+ return { editSession: { id: "edit_1", baseRevision: 0, baseContentHash: "a".repeat(64) } };+ },+ saveMemo: async (_memoId, body) => {+ order.push("save");+ calls.saved = body;+ },+ deleteMemo: async () => {+ order.push("delete");+ },+ createWithImage: async () => {+ order.push("with-image");+ return { memoId: "memo_1", resourceId: "res_1" };+ },+ ...overrides,+ },+ };+ };++ const input = {+ notebookId: "nb_inbox",+ title: "世赛现场,会贴瓷砖的女生帅爆了",+ nickname: "王小猫",+ noteTitle: "世赛现场,会贴瓷砖的女生帅爆了",+ body: "谁说贴瓷砖是男生的主场",+ datetime: "2026-09-20T08:00:00.000Z",+ location: "上海",+ noteUrl: canonicalNoteUrl(pageUrl, noteId),+ capturedAt: labels.capturedAt,+ sourceLabel: labels.sourceLabel,+ capturedAtLabel: labels.capturedAtLabel,+ timeLabel: labels.timeLabel,+ locationLabel: labels.locationLabel,+ altFallback: labels.altFallback,+ };++ test("creates a text note when the post has no photo", async () => {+ const fixture = client();+ const saved = await saveCapturedXhsNote(fixture.api, { ...input, images: [] });+ expect(saved).toEqual({ memoId: "memo_1", resourceIds: [] });+ expect(fixture.order).toEqual(["create"]);+ expect(fixture.calls.created.tags).toEqual(["web-clip"]);+ expect(fixture.calls.created.contentMarkdown).toContain("谁说贴瓷砖是男生的主场");+ });++ test("keeps the text note when a photo cannot be uploaded", async () => {+ const fixture = client({+ uploadImage: async () => {+ throw new Error("Missing required scope: write:resources");+ },+ });+ const saved = await saveCapturedXhsNote(fixture.api, {+ ...input,+ notebookId: "",+ images: [{ bytes: Uint8Array.of(1), mimeType: "image/jpeg", filename: "cover.jpg", alt: "封面" }],+ });+ expect(saved.memoId).toBe("memo_1");+ expect(saved.resourceIds).toEqual([]);+ expect(fixture.order).toEqual(["list", "create"]);+ });++ test("attaches an uploaded photo to the same note", async () => {+ const fixture = client();+ const saved = await saveCapturedXhsNote(fixture.api, {+ ...input,+ images: [{ bytes: Uint8Array.of(1), mimeType: "image/jpeg", filename: "cover.jpg", alt: "封面" }],+ });+ expect(saved.resourceIds).toEqual(["res_1"]);+ expect(fixture.order).toEqual(["create", "upload", "session", "save"]);+ expect(fixture.calls.saved.contentMarkdown).toContain("](/api/v1/resources/res_1/blob)");+ expect(fixture.calls.created.contentMarkdown.includes("](/api/v1/resources/")).toBe(false);+ });+});diff --git a/apps/extension/xhs-save.html b/apps/extension/xhs-save.htmlnew file mode 100644index 00000000..d865bf5c--- /dev/null+++ b/apps/extension/xhs-save.html@@ -0,0 +1,19 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title data-i18n="xhsSaveWindowTitle">Save this Xiaohongshu note to EdgeEver</title>+ </head>+ <body>+ <main class="image-save-shell">+ <h1 data-i18n="xhsSaveWindowTitle">Save this Xiaohongshu note to EdgeEver</h1>+ <p class="hint" data-i18n="xhsPermissionIntro">The feed has many notes. Allow access to Xiaohongshu so the clipper can remember the note under the pointer. After that, right-click the same note once more. Only the note you choose is saved to the clipper's default notebook.</p>+ <div class="image-save-actions">+ <button id="allow" type="button" data-i18n="allowXhsAccess">Allow access to Xiaohongshu</button>+ </div>+ <p id="status" class="status" role="status"></p>+ </main>+ <script type="module" src="/src/xhs-save.ts"></script>+ </body>+</html>