send-to-pi 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  /**
2
2
  * Send to Pi - Chrome Background Service Worker
3
+ * Version: 1.2.0
3
4
  */
4
5
 
5
6
  const DEFAULT_PORT = 18090;
@@ -7,7 +8,7 @@ const isChinese = (navigator.language || '').toLowerCase().startsWith('zh');
7
8
 
8
9
  const i18n = {
9
10
  menuSelection: isChinese ? "🚀 发送选中内容给 Pi" : "🚀 Send Selection to Pi",
10
- menuPage: isChinese ? "🚀 发送当前网页给 Pi" : "🚀 Send Current Page to Pi",
11
+ menuArticle: isChinese ? "🚀 发送精简文章给 Pi" : "🚀 Send Clean Article to Pi",
11
12
  menuLink: isChinese ? "🚀 发送此链接给 Pi" : "🚀 Send Link to Pi",
12
13
  notifyLaunchedTitle: isChinese ? "已唤起终端并预填内容" : "Terminal Launched & Prefilled",
13
14
  notifyLaunchedMsg: (term) =>
@@ -23,6 +24,10 @@ const i18n = {
23
24
  notifyNoConnMsg: isChinese
24
25
  ? "请确保本地后台 send-to-pi 守护进程已启动(默认端口 18090)。"
25
26
  : "Please ensure the local send-to-pi daemon is running (default port: 18090).",
27
+ notifyNoSelectionTitle: isChinese ? "未检测到选中文本" : "No Selection Detected",
28
+ notifyNoSelectionMsg: isChinese
29
+ ? "请先在页面上划选需要发送的文本或代码。"
30
+ : "Please select text or code on the webpage first.",
26
31
  };
27
32
 
28
33
  async function getBridgeUrl() {
@@ -34,6 +39,16 @@ async function getBridgeUrl() {
34
39
  });
35
40
  }
36
41
 
42
+ function showNotify(title, message) {
43
+ chrome.notifications.create({
44
+ type: "basic",
45
+ iconUrl: "icons/icon128.png",
46
+ title: title,
47
+ message: message,
48
+ priority: 1,
49
+ });
50
+ }
51
+
37
52
  // 注册右键菜单
38
53
  chrome.runtime.onInstalled.addListener(() => {
39
54
  chrome.contextMenus.removeAll(() => {
@@ -44,8 +59,8 @@ chrome.runtime.onInstalled.addListener(() => {
44
59
  });
45
60
 
46
61
  chrome.contextMenus.create({
47
- id: "send_page",
48
- title: i18n.menuPage,
62
+ id: "send_article",
63
+ title: i18n.menuArticle,
49
64
  contexts: ["page"],
50
65
  });
51
66
 
@@ -57,28 +72,325 @@ chrome.runtime.onInstalled.addListener(() => {
57
72
  });
58
73
  });
59
74
 
60
- // 处理右键点击事件
61
- chrome.contextMenus.onClicked.addListener(async (info, tab) => {
62
- const payload = {
63
- type: "page",
64
- text: "",
65
- title: tab ? tab.title : "",
66
- url: tab ? tab.url : "",
67
- lang: isChinese ? "zh" : "en",
68
- };
75
+ /**
76
+ * 在页面 DOM 上下文中执行的提取器(自包含函数)
77
+ * mode: 'selection' | 'article'
78
+ */
79
+ function inPageExtractor(mode) {
80
+ function domToMarkdown(rootNode) {
81
+ if (!rootNode) return "";
69
82
 
70
- if (info.menuItemId === "send_selection") {
71
- payload.type = "selection";
72
- payload.text = info.selectionText || "";
73
- } else if (info.menuItemId === "send_link") {
74
- payload.type = "link";
75
- payload.url = info.linkUrl || "";
76
- } else if (info.menuItemId === "send_page") {
77
- payload.type = "page";
83
+ function walk(node, depth) {
84
+ if (!node) return "";
85
+
86
+ if (node.nodeType === Node.TEXT_NODE) {
87
+ return node.textContent;
88
+ }
89
+
90
+ if (node.nodeType !== Node.ELEMENT_NODE) {
91
+ return "";
92
+ }
93
+
94
+ const tag = node.tagName.toLowerCase();
95
+
96
+ // 忽略不可视或干扰性标签
97
+ if (["script", "style", "noscript", "svg", "canvas", "template"].includes(tag)) {
98
+ return "";
99
+ }
100
+
101
+ // 1. 代码块 <pre>
102
+ if (tag === "pre") {
103
+ const codeElem = node.querySelector("code") || node;
104
+ const langClass = (codeElem.getAttribute("class") || "") + " " + (node.getAttribute("class") || "");
105
+ const match = langClass.match(/(?:lang(?:uage)?-|hljs-?)([a-zA-Z0-9_-]+)/i);
106
+ const lang = match ? match[1] : "";
107
+ const codeText = (codeElem.textContent || "").replace(/\r\n/g, "\n").trimEnd();
108
+ return `\n\n\`\`\`${lang}\n${codeText}\n\`\`\`\n\n`;
109
+ }
110
+
111
+ // 2. 行内代码 <code> (不在 pre 内)
112
+ if (tag === "code") {
113
+ if (node.closest("pre")) {
114
+ return node.textContent;
115
+ }
116
+ const text = node.textContent || "";
117
+ return text.includes("`") ? `\`\` ${text} \`\`` : `\`${text}\``;
118
+ }
119
+
120
+ // 3. 标题
121
+ if (/^h[1-6]$/.test(tag)) {
122
+ const level = parseInt(tag[1], 10);
123
+ const prefix = "#".repeat(level);
124
+ const text = getChildrenText(node, depth).trim();
125
+ return `\n\n${prefix} ${text}\n\n`;
126
+ }
127
+
128
+ // 4. 引用
129
+ if (tag === "blockquote") {
130
+ const content = getChildrenText(node, depth).trim();
131
+ const quoted = content
132
+ .split("\n")
133
+ .map((line) => `> ${line}`)
134
+ .join("\n");
135
+ return `\n\n${quoted}\n\n`;
136
+ }
137
+
138
+ // 5. 链接
139
+ if (tag === "a") {
140
+ const text = getChildrenText(node, depth).trim();
141
+ const href = node.getAttribute("href");
142
+ if (!text) return "";
143
+ if (href && !href.startsWith("javascript:")) {
144
+ return `[${text}](${href})`;
145
+ }
146
+ return text;
147
+ }
148
+
149
+ // 6. 强调
150
+ if (tag === "strong" || tag === "b") {
151
+ const text = getChildrenText(node, depth).trim();
152
+ return text ? `**${text}**` : "";
153
+ }
154
+ if (tag === "em" || tag === "i") {
155
+ const text = getChildrenText(node, depth).trim();
156
+ return text ? `*${text}*` : "";
157
+ }
158
+ if (tag === "s" || tag === "del" || tag === "strike") {
159
+ const text = getChildrenText(node, depth).trim();
160
+ return text ? `~~${text}~~` : "";
161
+ }
162
+
163
+ // 7. 分割线
164
+ if (tag === "hr") {
165
+ return "\n\n---\n\n";
166
+ }
167
+
168
+ // 8. 换行
169
+ if (tag === "br") {
170
+ return "\n";
171
+ }
172
+
173
+ // 9. 图片
174
+ if (tag === "img") {
175
+ const alt = node.getAttribute("alt") || "";
176
+ const src = node.getAttribute("src") || "";
177
+ return src ? `![${alt}](${src})` : "";
178
+ }
179
+
180
+ // 10. 表格
181
+ if (tag === "table") {
182
+ return renderTable(node);
183
+ }
184
+
185
+ // 11. 列表
186
+ if (tag === "ul" || tag === "ol") {
187
+ const isOrdered = tag === "ol";
188
+ let idx = 1;
189
+ const items = [];
190
+ for (const child of node.children) {
191
+ if (child.tagName && child.tagName.toLowerCase() === "li") {
192
+ const itemText = walkLi(child, depth + 1).trim();
193
+ const indent = " ".repeat(depth);
194
+ const bullet = isOrdered ? `${idx++}. ` : "* ";
195
+ items.push(`${indent}${bullet}${itemText}`);
196
+ }
197
+ }
198
+ return `\n\n${items.join("\n")}\n\n`;
199
+ }
200
+
201
+ // 12. 常用块级元素
202
+ if (["p", "div", "section", "article"].includes(tag)) {
203
+ const text = getChildrenText(node, depth).trim();
204
+ return text ? `\n\n${text}\n\n` : "";
205
+ }
206
+
207
+ return getChildrenText(node, depth);
208
+ }
209
+
210
+ function getChildrenText(node, depth) {
211
+ let result = "";
212
+ for (const child of node.childNodes) {
213
+ result += walk(child, depth);
214
+ }
215
+ return result;
216
+ }
217
+
218
+ function walkLi(liNode, depth) {
219
+ let result = "";
220
+ for (const child of liNode.childNodes) {
221
+ if (child.nodeType === Node.ELEMENT_NODE && ["ul", "ol"].includes(child.tagName.toLowerCase())) {
222
+ result += "\n" + walk(child, depth);
223
+ } else {
224
+ result += walk(child, depth);
225
+ }
226
+ }
227
+ return result;
228
+ }
229
+
230
+ function renderTable(table) {
231
+ const rows = Array.from(table.querySelectorAll("tr"));
232
+ if (!rows.length) return "";
233
+
234
+ const matrix = [];
235
+ let maxCols = 0;
236
+
237
+ for (const row of rows) {
238
+ const cells = Array.from(row.querySelectorAll("th, td")).map((cell) =>
239
+ (cell.textContent || "").replace(/\s+/g, " ").replace(/\|/g, "\\|").trim()
240
+ );
241
+ if (cells.length > maxCols) maxCols = cells.length;
242
+ matrix.push(cells);
243
+ }
244
+
245
+ if (!matrix.length || maxCols === 0) return "";
246
+
247
+ const lines = [];
248
+ const header = matrix[0];
249
+ while (header.length < maxCols) header.push("");
250
+ lines.push(`| ${header.join(" | ")} |`);
251
+
252
+ const sep = Array(maxCols).fill("---");
253
+ lines.push(`| ${sep.join(" | ")} |`);
254
+
255
+ for (let i = 1; i < matrix.length; i++) {
256
+ const row = matrix[i];
257
+ while (row.length < maxCols) row.push("");
258
+ lines.push(`| ${row.join(" | ")} |`);
259
+ }
260
+
261
+ return `\n\n${lines.join("\n")}\n\n`;
262
+ }
263
+
264
+ const rawMd = walk(rootNode, 0);
265
+ return rawMd.replace(/\n{3,}/g, "\n\n").trim();
78
266
  }
79
267
 
80
- const endpoint = await getBridgeUrl();
268
+ if (mode === "selection") {
269
+ const selection = window.getSelection();
270
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
271
+ return null;
272
+ }
273
+ const container = document.createElement("div");
274
+ for (let i = 0; i < selection.rangeCount; i++) {
275
+ container.appendChild(selection.getRangeAt(i).cloneContents());
276
+ }
277
+ const md = domToMarkdown(container);
278
+ return md || selection.toString();
279
+ }
280
+
281
+ if (mode === "article") {
282
+ // X/Twitter 页面不能读取整个 body:只尝试主 tweet 或文章节点。
283
+ const isXTwitter = /(^|\.)((twitter|x)\.com)$/i.test(window.location.hostname);
284
+ if (isXTwitter) {
285
+ const xSelectors = [
286
+ 'main [data-testid="twitter-article"]',
287
+ 'main [data-testid="article"]',
288
+ 'main article[data-testid="tweet"]',
289
+ '[data-testid="twitter-article"]',
290
+ '[data-testid="article"]',
291
+ 'article[data-testid="tweet"]',
292
+ 'main article',
293
+ 'article',
294
+ ];
295
+ let mainTweet = null;
296
+ for (const selector of xSelectors) {
297
+ mainTweet = document.querySelector(selector);
298
+ if (mainTweet) break;
299
+ }
300
+
301
+ // 某些 X 版本只标记 tweetText,向上定位其所属主 article。
302
+ if (!mainTweet) {
303
+ const tweetText = document.querySelector('[data-testid="tweetText"]');
304
+ mainTweet = tweetText ? tweetText.closest('article') : null;
305
+ }
306
+
307
+ if (!mainTweet) return null;
308
+
309
+ // X 的主 article 同时包含作者栏、头像、媒体和互动按钮。
310
+ // 只保留正文结构,避免把整个帖子壳层发送给 Pi。
311
+ const cleanTweet = mainTweet.cloneNode(true);
312
+ [
313
+ '[data-testid="User-Name"]',
314
+ '[data-testid="User-Names"]',
315
+ '[data-testid="UserDescription"]',
316
+ '[data-testid="tweetPhoto"]',
317
+ '[data-testid="videoPlayer"]',
318
+ '[role="group"]',
319
+ 'time',
320
+ 'img',
321
+ ].forEach((selector) => {
322
+ cleanTweet.querySelectorAll(selector).forEach((el) => el.remove());
323
+ });
324
+
325
+ const xMarkdown = domToMarkdown(cleanTweet);
326
+ return xMarkdown || null;
327
+ }
328
+
329
+ // Readability 简版:整页正文提取
330
+ const clone = document.body.cloneNode(true);
331
+
332
+ const removeSelectors = [
333
+ "script", "style", "noscript", "nav", "header", "footer", "aside",
334
+ "iframe", "svg", "form", "[role='navigation']", "[role='banner']",
335
+ "[role='contentinfo']", ".nav", ".menu", ".sidebar", ".ad",
336
+ ".advertisement", ".social-share", ".comments", ".comment-section"
337
+ ];
338
+ removeSelectors.forEach((sel) => {
339
+ clone.querySelectorAll(sel).forEach((el) => el.remove());
340
+ });
341
+
342
+ let mainContainer =
343
+ clone.querySelector("article") ||
344
+ clone.querySelector("main") ||
345
+ clone.querySelector("[role='main']") ||
346
+ clone.querySelector(".post-content") ||
347
+ clone.querySelector(".article-content") ||
348
+ clone.querySelector(".entry-content") ||
349
+ clone.querySelector("#content");
350
+
351
+ if (!mainContainer) {
352
+ const candidates = Array.from(clone.querySelectorAll("div, section"));
353
+ let bestElem = clone;
354
+ let maxScore = 0;
355
+
356
+ for (const el of candidates) {
357
+ const pCount = el.querySelectorAll("p").length;
358
+ const textLen = (el.textContent || "").trim().length;
359
+ const score = pCount * 100 + textLen;
360
+ if (score > maxScore) {
361
+ maxScore = score;
362
+ bestElem = el;
363
+ }
364
+ }
365
+ mainContainer = bestElem;
366
+ }
367
+
368
+ const md = domToMarkdown(mainContainer);
369
+ return md;
370
+ }
371
+
372
+ return null;
373
+ }
374
+
375
+ async function extractFromTab(tabId, mode) {
376
+ try {
377
+ const results = await chrome.scripting.executeScript({
378
+ target: { tabId },
379
+ func: inPageExtractor,
380
+ args: [mode],
381
+ });
382
+ if (results && results[0] && results[0].result) {
383
+ return results[0].result;
384
+ }
385
+ return null;
386
+ } catch (err) {
387
+ console.warn("[SendToPi] executeScript extraction failed:", err);
388
+ return null;
389
+ }
390
+ }
81
391
 
392
+ async function sendPayload(payload) {
393
+ const endpoint = await getBridgeUrl();
82
394
  try {
83
395
  const res = await fetch(endpoint, {
84
396
  method: "POST",
@@ -101,14 +413,81 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
101
413
  } catch (_err) {
102
414
  showNotify(i18n.notifyNoConnTitle, i18n.notifyNoConnMsg);
103
415
  }
416
+ }
417
+
418
+ // 处理右键点击事件
419
+ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
420
+ const tabId = tab ? tab.id : null;
421
+
422
+ if (info.menuItemId === "send_selection") {
423
+ let markdown = null;
424
+ if (tabId) {
425
+ markdown = await extractFromTab(tabId, "selection");
426
+ }
427
+ // 平滑降级:若 HTML 提取失败则回退到 selectionText
428
+ const textToSend = markdown || info.selectionText || "";
429
+
430
+ const payload = {
431
+ type: "selection",
432
+ text: textToSend,
433
+ title: tab ? tab.title : "",
434
+ url: tab ? tab.url : "",
435
+ lang: isChinese ? "zh" : "en",
436
+ };
437
+ await sendPayload(payload);
438
+ return;
439
+ }
440
+
441
+ if (info.menuItemId === "send_article") {
442
+ let articleText = null;
443
+ if (tabId) {
444
+ articleText = await extractFromTab(tabId, "article");
445
+ }
446
+
447
+ const payload = {
448
+ type: articleText ? "article" : "page",
449
+ text: articleText || "",
450
+ title: tab ? tab.title : "",
451
+ url: tab ? tab.url : "",
452
+ lang: isChinese ? "zh" : "en",
453
+ };
454
+ await sendPayload(payload);
455
+ return;
456
+ }
457
+
458
+ if (info.menuItemId === "send_link") {
459
+ const payload = {
460
+ type: "link",
461
+ text: "",
462
+ title: tab ? tab.title : "",
463
+ url: info.linkUrl || (tab ? tab.url : ""),
464
+ lang: isChinese ? "zh" : "en",
465
+ };
466
+ await sendPayload(payload);
467
+ }
104
468
  });
105
469
 
106
- function showNotify(title, message) {
107
- chrome.notifications.create({
108
- type: "basic",
109
- iconUrl: "icons/icon128.png",
110
- title: title,
111
- message: message,
112
- priority: 1,
113
- });
114
- }
470
+ // 处理快捷键事件
471
+ chrome.commands.onCommand.addListener(async (command) => {
472
+ if (command === "send-selection") {
473
+ const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
474
+ const tab = tabs[0];
475
+ if (!tab || !tab.id) return;
476
+
477
+ const extracted = await extractFromTab(tab.id, "selection");
478
+ if (!extracted || !extracted.trim()) {
479
+ showNotify(i18n.notifyNoSelectionTitle, i18n.notifyNoSelectionMsg);
480
+ return;
481
+ }
482
+
483
+ const payload = {
484
+ type: "selection",
485
+ text: extracted.trim(),
486
+ title: tab.title || "",
487
+ url: tab.url || "",
488
+ lang: isChinese ? "zh" : "en",
489
+ };
490
+
491
+ await sendPayload(payload);
492
+ }
493
+ });
@@ -1,13 +1,24 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Send to Pi (发送给 Pi)",
4
- "version": "1.0.2",
4
+ "version": "1.2.0",
5
5
  "description": "Send webpage snippets, URLs, or articles directly to your local Pi coding agent terminal.",
6
6
  "permissions": [
7
7
  "contextMenus",
8
8
  "notifications",
9
- "storage"
9
+ "storage",
10
+ "scripting",
11
+ "activeTab"
10
12
  ],
13
+ "commands": {
14
+ "send-selection": {
15
+ "suggested_key": {
16
+ "default": "Alt+Shift+S",
17
+ "mac": "Command+Shift+S"
18
+ },
19
+ "description": "Send selected text/code to Pi"
20
+ }
21
+ },
11
22
  "host_permissions": [
12
23
  "http://127.0.0.1:*/*"
13
24
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "send-to-pi",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "description": "Send webpage snippets, URLs, or articles directly to your local Pi coding agent terminal.",
5
5
  "main": "server/src/index.js",
6
6
  "bin": {
@@ -4,9 +4,10 @@
4
4
 
5
5
  ## 作用
6
6
  1. 监听本地内部端口 `127.0.0.1:18091`,接收调度服务(Bridge Daemon)转发过来的网页摘录;
7
- 2. 收到内容后,通过 Pi 的原生 API `ctx.ui.setEditorText()` **预填到终端输入框(Prefill 模式)**;
8
- 3. **绝不自作主张自动回车发送**,光标停留在内容末尾,让开发者可以自由补充指令或微调内容;
9
- 4. 终端会话启动时,自动读取冷启动时暂存的文件(`~/.pi/pending-browser-input.txt`),无缝实现“唤醒终端并填入内容”。
7
+ 2. 将每个 Pi 会话注册到 `~/.pi/send-to-pi/sessions.json`,记录最近活跃时间及 `terminal`、`window` 路由元数据;
8
+ 3. 收到内容后,通过 Pi 的原生 API `ctx.ui.setEditorText()` **预填到终端输入框(Prefill 模式)**;
9
+ 4. **绝不自作主张自动回车发送**,光标停留在内容末尾,让开发者可以自由补充指令或微调内容;
10
+ 5. 终端会话启动时,自动读取冷启动时暂存的文件(`~/.pi/pending-browser-input.txt`),无缝实现“唤醒终端并填入内容”。
10
11
 
11
12
  ## 安装方式
12
13