@chendaleiq/dsh-chrome 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.en.md +98 -0
- package/README.md +85 -2
- package/cordis.patch.yml +23 -0
- package/docs/DETAIL.md +23 -0
- package/docs/TESTING.md +75 -0
- package/extension/_locales/en/messages.json +43 -0
- package/extension/_locales/zh_CN/messages.json +43 -0
- package/extension/manifest.json +16 -0
- package/extension/popup.html +29 -0
- package/extension/popup.js +63 -0
- package/extension/service_worker.js +314 -0
- package/icon.svg +9 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +61 -4
- package/scripts/bridge.mjs +23 -0
- package/scripts/setup.mjs +94 -0
- package/scripts/verify.mjs +50 -0
- package/src/auto-bridge.js +29 -0
- package/src/bridge-client.js +63 -0
- package/src/bridge-server.js +245 -0
- package/src/index.js +117 -0
- package/src/onboard.js +70 -0
- package/src/screenshot.js +35 -0
- package/src/tools.js +440 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
/* DSH Chrome Connector — service worker.
|
|
2
|
+
* Polls GET /next (25s long-poll), executes tab/page actions,
|
|
3
|
+
* POSTs back to /result. Matches projects/dsh-chrome/src/bridge-server.js.
|
|
4
|
+
*
|
|
5
|
+
* Wire actions implemented:
|
|
6
|
+
* tab.version / tab.list / tab.activate / tab.new / tab.close
|
|
7
|
+
* page.navigate / page.snapshot / page.screenshot / page.evaluate / page.fill
|
|
8
|
+
* Everything else returns an explicit "unsupported in 0.1.0" error (fail-closed).
|
|
9
|
+
*/
|
|
10
|
+
const BRIDGE = "http://127.0.0.1:17319";
|
|
11
|
+
const EXT_VERSION = "0.1.0";
|
|
12
|
+
let polling = false;
|
|
13
|
+
let uidSeq = 0;
|
|
14
|
+
|
|
15
|
+
async function pollOnce() {
|
|
16
|
+
if (polling) return;
|
|
17
|
+
polling = true;
|
|
18
|
+
await heartbeat("attempt", false);
|
|
19
|
+
try {
|
|
20
|
+
const res = await fetch(`${BRIDGE}/next?name=${encodeURIComponent("DSH Chrome Connector")}`, { cache: "no-store" });
|
|
21
|
+
if (res.ok) {
|
|
22
|
+
const msg = await res.json().catch(() => null);
|
|
23
|
+
if (msg && msg.type === "command" && msg.command) {
|
|
24
|
+
const { id, action, params } = msg.command;
|
|
25
|
+
try {
|
|
26
|
+
const result = await handleAction(action, params || {});
|
|
27
|
+
await postResult({ id, ok: true, result });
|
|
28
|
+
await heartbeat("command");
|
|
29
|
+
} catch (e) {
|
|
30
|
+
await postResult({ id, ok: false, error: String((e && e.message) || e) });
|
|
31
|
+
await heartbeat("command-error");
|
|
32
|
+
}
|
|
33
|
+
} else {
|
|
34
|
+
await heartbeat("idle");
|
|
35
|
+
}
|
|
36
|
+
} else {
|
|
37
|
+
await heartbeat(`http-${res.status}`);
|
|
38
|
+
}
|
|
39
|
+
} catch {
|
|
40
|
+
await heartbeat("fetch-failed");
|
|
41
|
+
// bridge down — 歇 2 秒再试,避免空转打满循环
|
|
42
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
43
|
+
} finally {
|
|
44
|
+
polling = false;
|
|
45
|
+
}
|
|
46
|
+
// 紧循环:有无命令都立刻下一次 /next(服务端 hold 25s,空闲开销可忽略)。
|
|
47
|
+
// 靠这个保证命令下发延迟在秒级,而不是等 30-60s 的闹钟。
|
|
48
|
+
pollOnce();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// 每次轮询都写 storage:popup 直接读,不靠 SW 存活。用户报问题时看这三行就够。
|
|
52
|
+
async function heartbeat(state, bump = true) {
|
|
53
|
+
try {
|
|
54
|
+
const { swHeartbeat = {} } = await chrome.storage.local.get("swHeartbeat");
|
|
55
|
+
const polls = (swHeartbeat.polls || 0) + (bump ? 1 : 0);
|
|
56
|
+
await chrome.storage.local.set({
|
|
57
|
+
swHeartbeat: { polls, state, at: Date.now(), version: EXT_VERSION },
|
|
58
|
+
});
|
|
59
|
+
console.log(`[dsh-chrome] poll #${polls}: ${state}`);
|
|
60
|
+
} catch {
|
|
61
|
+
// storage 不可用也不影响轮询本身
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function postResult(body) {
|
|
66
|
+
for (let i = 0; i < 3; i += 1) {
|
|
67
|
+
try {
|
|
68
|
+
const res = await fetch(`${BRIDGE}/result`, {
|
|
69
|
+
method: "POST",
|
|
70
|
+
headers: { "content-type": "application/json" },
|
|
71
|
+
body: JSON.stringify(body),
|
|
72
|
+
});
|
|
73
|
+
if (res.ok || (res.status >= 400 && res.status < 500)) return;
|
|
74
|
+
} catch {
|
|
75
|
+
// retry
|
|
76
|
+
}
|
|
77
|
+
await new Promise((r) => setTimeout(r, 250 * (i + 1)));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function rememberOwnedTab(id) {
|
|
82
|
+
const { ownedTabs = [] } = await chrome.storage.local.get("ownedTabs");
|
|
83
|
+
const key = String(id);
|
|
84
|
+
if (!ownedTabs.includes(key)) {
|
|
85
|
+
ownedTabs.push(key);
|
|
86
|
+
await chrome.storage.local.set({ ownedTabs });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function forgetOwnedTab(id) {
|
|
91
|
+
const { ownedTabs = [] } = await chrome.storage.local.get("ownedTabs");
|
|
92
|
+
await chrome.storage.local.set({ ownedTabs: ownedTabs.filter((t) => t !== String(id)) });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function resolveTabId(params) {
|
|
96
|
+
if (params.tabId !== undefined && params.tabId !== null && params.tabId !== "") {
|
|
97
|
+
const id = Number(params.tabId);
|
|
98
|
+
if (!Number.isFinite(id)) throw new Error(`invalid tabId: ${params.tabId}`);
|
|
99
|
+
return id;
|
|
100
|
+
}
|
|
101
|
+
const [active] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
|
|
102
|
+
if (!active || active.id === undefined) throw new Error("no active tab");
|
|
103
|
+
return active.id;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function handleAction(action, params) {
|
|
107
|
+
switch (action) {
|
|
108
|
+
case "tab.version":
|
|
109
|
+
return { extensionVersion: EXT_VERSION, bridge: BRIDGE, userAgent: navigator.userAgent };
|
|
110
|
+
case "tab.list": {
|
|
111
|
+
const tabs = await chrome.tabs.query({});
|
|
112
|
+
return tabs.map((t) => ({ id: String(t.id), title: t.title || "", url: t.url || "" }));
|
|
113
|
+
}
|
|
114
|
+
case "tab.activate": {
|
|
115
|
+
if (params.tabId === undefined) throw new Error("missing tabId");
|
|
116
|
+
const id = await resolveTabId(params);
|
|
117
|
+
const tab = await chrome.tabs.update(id, { active: true });
|
|
118
|
+
return { ok: true, activeTabId: String(tab.id) };
|
|
119
|
+
};
|
|
120
|
+
case "tab.close": {
|
|
121
|
+
if (params.tabId === undefined) throw new Error("missing tabId");
|
|
122
|
+
const id = await resolveTabId(params);
|
|
123
|
+
await chrome.tabs.remove(id);
|
|
124
|
+
await forgetOwnedTab(id);
|
|
125
|
+
return { closed: String(params.tabId) };
|
|
126
|
+
}
|
|
127
|
+
case "tab.new": {
|
|
128
|
+
const tab = await chrome.tabs.create({
|
|
129
|
+
url: typeof params.url === "string" && params.url !== "" ? params.url : "about:blank",
|
|
130
|
+
active: false,
|
|
131
|
+
});
|
|
132
|
+
await rememberOwnedTab(tab.id);
|
|
133
|
+
return { id: String(tab.id), title: tab.title || "", url: tab.pendingUrl || tab.url || "" };
|
|
134
|
+
}
|
|
135
|
+
case "page.navigate": {
|
|
136
|
+
if (typeof params.url !== "string" || params.url === "") throw new Error("missing url");
|
|
137
|
+
const id = await resolveTabId(params);
|
|
138
|
+
const tab = await chrome.tabs.update(id, { url: params.url });
|
|
139
|
+
return { ok: true, url: tab.pendingUrl || tab.url || params.url, title: tab.title || "" };
|
|
140
|
+
}
|
|
141
|
+
case "page.snapshot": {
|
|
142
|
+
const id = await resolveTabId(params);
|
|
143
|
+
const [{ result }] = await chrome.scripting.executeScript({
|
|
144
|
+
target: { tabId: id },
|
|
145
|
+
func: snapshotPage,
|
|
146
|
+
});
|
|
147
|
+
const maxNodes = Math.max(10, Math.min(500, Number(params.maxNodes) || 120));
|
|
148
|
+
const nodes = Array.isArray(result) ? result.slice(0, maxNodes) : [];
|
|
149
|
+
const lines = nodes.map((n) => `[ref=${n.uid}] ${n.role} ${JSON.stringify(n.name || "").slice(0, 80)}`.trim());
|
|
150
|
+
const refId = `snap-${Date.now().toString(36)}-${(uidSeq += 1)}`;
|
|
151
|
+
return { snapshot: lines.join("\n"), refId, truncated: Array.isArray(result) ? result.length - nodes.length : 0 };
|
|
152
|
+
}
|
|
153
|
+
case "page.screenshot": {
|
|
154
|
+
const id = await resolveTabId(params);
|
|
155
|
+
const windowId = (await chrome.tabs.get(id)).windowId;
|
|
156
|
+
const dataUrl = await chrome.tabs.captureVisibleTab(windowId, { format: "png" });
|
|
157
|
+
return { dataUrl, fullPage: false, tabId: String(id) };
|
|
158
|
+
}
|
|
159
|
+
case "page.fill": {
|
|
160
|
+
const id = await resolveTabId(params);
|
|
161
|
+
const [{ result }] = await chrome.scripting.executeScript({
|
|
162
|
+
target: { tabId: id },
|
|
163
|
+
func: fillPage,
|
|
164
|
+
args: [params.mode === "discover" ? "discover" : "fill", Array.isArray(params.fields) ? params.fields : []],
|
|
165
|
+
});
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
case "page.evaluate": {
|
|
169
|
+
if (typeof params.expression !== "string" || params.expression === "") throw new Error("missing expression");
|
|
170
|
+
const id = await resolveTabId(params);
|
|
171
|
+
const [{ result }] = await chrome.scripting.executeScript({
|
|
172
|
+
target: { tabId: id },
|
|
173
|
+
world: "MAIN",
|
|
174
|
+
func: (expr) => {
|
|
175
|
+
try {
|
|
176
|
+
// eslint-disable-next-line no-eval
|
|
177
|
+
const value = eval(expr);
|
|
178
|
+
return { ok: true, value: value === undefined ? null : JSON.parse(JSON.stringify(value)) };
|
|
179
|
+
} catch (e) {
|
|
180
|
+
return { ok: false, error: String((e && e.message) || e) };
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
args: [params.expression],
|
|
184
|
+
});
|
|
185
|
+
if (!result || result.ok !== true) throw new Error((result && result.error) || "evaluate failed");
|
|
186
|
+
return { value: result.value };
|
|
187
|
+
}
|
|
188
|
+
default:
|
|
189
|
+
throw new Error(`unsupported in 0.1.0: ${action}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Runs in the page (isolated world): flat accessible-ish element list. */
|
|
194
|
+
function snapshotPage() {
|
|
195
|
+
const out = [];
|
|
196
|
+
let n = 0;
|
|
197
|
+
const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_ELEMENT);
|
|
198
|
+
while (walker.nextNode() && out.length < 500) {
|
|
199
|
+
const el = walker.currentNode;
|
|
200
|
+
const tag = el.tagName ? el.tagName.toLowerCase() : "";
|
|
201
|
+
if (["script", "style", "noscript", "svg", "path"].includes(tag)) continue;
|
|
202
|
+
const role = el.getAttribute("role") || tag;
|
|
203
|
+
const name = (el.getAttribute("aria-label") || el.innerText || el.value || "").trim().replace(/\s+/g, " ").slice(0, 120);
|
|
204
|
+
if (!name && !["a", "button", "input", "select", "textarea"].includes(tag)) continue;
|
|
205
|
+
n += 1;
|
|
206
|
+
out.push({ uid: `el-${n}`, role, name });
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Runs in the page (isolated world). Fully static — no eval, so page CSP
|
|
213
|
+
* (and the extension's own CSP) cannot block it.
|
|
214
|
+
* mode "discover": list visible form controls with generated selectors.
|
|
215
|
+
* mode "fill": [{ selector, value?, click? }] — set values with native
|
|
216
|
+
* setters + input/change events (React-friendly), or click.
|
|
217
|
+
*/
|
|
218
|
+
function fillPage(mode, fields) {
|
|
219
|
+
const cssPath = (el) => {
|
|
220
|
+
if (el.id) return "#" + CSS.escape(el.id);
|
|
221
|
+
const parts = [];
|
|
222
|
+
let cur = el;
|
|
223
|
+
while (cur && cur !== document.body && parts.length < 6) {
|
|
224
|
+
let seg = cur.tagName.toLowerCase();
|
|
225
|
+
const parent = cur.parentElement;
|
|
226
|
+
if (parent) {
|
|
227
|
+
const sibs = Array.prototype.filter.call(parent.children, (c) => c.tagName === cur.tagName);
|
|
228
|
+
if (sibs.length > 1) seg += ":nth-of-type(" + (sibs.indexOf(cur) + 1) + ")";
|
|
229
|
+
}
|
|
230
|
+
parts.unshift(seg);
|
|
231
|
+
cur = parent;
|
|
232
|
+
}
|
|
233
|
+
return parts.join(" > ");
|
|
234
|
+
};
|
|
235
|
+
const labelOf = (el) => {
|
|
236
|
+
if (el.id) {
|
|
237
|
+
const lab = document.querySelector('label[for="' + el.id + '"]');
|
|
238
|
+
if (lab && lab.innerText) return lab.innerText.trim().replace(/\s+/g, " ").slice(0, 80);
|
|
239
|
+
}
|
|
240
|
+
return ((el.getAttribute("aria-label") || el.placeholder || el.name || "").trim().replace(/\s+/g, " ").slice(0, 80));
|
|
241
|
+
};
|
|
242
|
+
if (mode === "discover") {
|
|
243
|
+
const els = Array.prototype.filter.call(
|
|
244
|
+
document.querySelectorAll("input, select, textarea, button"),
|
|
245
|
+
(e) => e.offsetParent !== null,
|
|
246
|
+
);
|
|
247
|
+
return {
|
|
248
|
+
fields: els.slice(0, 50).map((el) => ({
|
|
249
|
+
selector: cssPath(el),
|
|
250
|
+
tag: el.tagName.toLowerCase(),
|
|
251
|
+
type: el.type || "",
|
|
252
|
+
label: labelOf(el),
|
|
253
|
+
})),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
const out = [];
|
|
257
|
+
for (const f of fields) {
|
|
258
|
+
const el = document.querySelector(f.selector);
|
|
259
|
+
if (!el) {
|
|
260
|
+
out.push({ selector: f.selector, ok: false, error: "not found" });
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
if (f.click) {
|
|
264
|
+
el.click();
|
|
265
|
+
out.push({ selector: f.selector, ok: true, clicked: true });
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const tag = el.tagName.toLowerCase();
|
|
269
|
+
if (tag === "select") {
|
|
270
|
+
const want = String(f.value === undefined ? "" : f.value).trim();
|
|
271
|
+
const opts = Array.prototype.slice.call(el.options);
|
|
272
|
+
const idx = opts.findIndex((o) => o.value === f.value || o.text.trim() === want);
|
|
273
|
+
if (idx < 0) {
|
|
274
|
+
out.push({ selector: f.selector, ok: false, error: "option not found" });
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
el.selectedIndex = idx;
|
|
278
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
279
|
+
out.push({ selector: f.selector, ok: true });
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (el.type === "checkbox") {
|
|
283
|
+
el.checked = !!f.value && f.value !== "false" && f.value !== "0";
|
|
284
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
285
|
+
out.push({ selector: f.selector, ok: true });
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
const proto = tag === "textarea" ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
|
|
289
|
+
const setter = Object.getOwnPropertyDescriptor(proto, "value");
|
|
290
|
+
if (setter && setter.set) setter.set.call(el, String(f.value === undefined ? "" : f.value));
|
|
291
|
+
else el.value = f.value === undefined ? "" : f.value;
|
|
292
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
293
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
294
|
+
out.push({ selector: f.selector, ok: true });
|
|
295
|
+
}
|
|
296
|
+
return { fields: out };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
chrome.runtime.onInstalled.addListener(() => {
|
|
300
|
+
// 0.5 分钟是期望值:Chrome 会按自身下限钳制,失败也不影响轮询(setInterval + poll-now 兜底)。
|
|
301
|
+
try {
|
|
302
|
+
chrome.alarms.create("dsh-bridge-keepalive", { periodInMinutes: 0.5 });
|
|
303
|
+
} catch {
|
|
304
|
+
// 无闹钟也能跑:前台 pollOnce + 弹窗手动唤醒
|
|
305
|
+
}
|
|
306
|
+
pollOnce();
|
|
307
|
+
});
|
|
308
|
+
chrome.runtime.onStartup.addListener(() => pollOnce());
|
|
309
|
+
chrome.runtime.onMessage.addListener((msg) => {
|
|
310
|
+
if (msg && msg.type === "poll-now") pollOnce();
|
|
311
|
+
});
|
|
312
|
+
chrome.alarms.onAlarm.addListener(() => pollOnce());
|
|
313
|
+
setInterval(pollOnce, 1000);
|
|
314
|
+
pollOnce();
|
package/icon.svg
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="dsh-chrome">
|
|
2
|
+
<rect width="64" height="64" rx="14" fill="#0EA5E9"/>
|
|
3
|
+
<g fill="none" stroke="#fff" stroke-width="3.4" stroke-linecap="round">
|
|
4
|
+
<rect x="12" y="16" width="40" height="26" rx="5"/>
|
|
5
|
+
<path d="M12 24h40"/>
|
|
6
|
+
<circle cx="16.5" cy="20" r="1.6" fill="#fff" stroke="none"/>
|
|
7
|
+
<path d="M24 50l4-5h8l4 5"/>
|
|
8
|
+
</g>
|
|
9
|
+
</svg>
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chendaleiq/dsh-chrome",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Control local Chrome from DSH: status, tabs, snapshot, navigate, screenshot, evaluate.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "src/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.js",
|
|
10
|
+
"./locale/*.json": "./locale/*.json",
|
|
11
|
+
"./icon": "./icon.svg",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src/**/*.js",
|
|
16
|
+
"extension/**/*",
|
|
17
|
+
"scripts/*.mjs",
|
|
18
|
+
"cordis.patch.yml",
|
|
19
|
+
"locale/*.json",
|
|
20
|
+
"docs/DETAIL.md",
|
|
21
|
+
"docs/TESTING.md",
|
|
22
|
+
"icon.svg",
|
|
23
|
+
"README.md",
|
|
24
|
+
"README.en.md",
|
|
25
|
+
"LICENSE",
|
|
26
|
+
"CHANGELOG.md"
|
|
27
|
+
],
|
|
28
|
+
"dsh": {
|
|
29
|
+
"bundle": {
|
|
30
|
+
"patch": "./cordis.patch.yml"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"icon": "./icon.svg",
|
|
34
|
+
"author": "chendaleiQ",
|
|
35
|
+
"keywords": [
|
|
36
|
+
"dsh",
|
|
37
|
+
"dsh-plugin",
|
|
38
|
+
"deepseek-harness",
|
|
39
|
+
"chrome",
|
|
40
|
+
"cdp",
|
|
41
|
+
"browser",
|
|
42
|
+
"local-first",
|
|
43
|
+
"macos"
|
|
44
|
+
],
|
|
45
|
+
"scripts": {
|
|
46
|
+
"test": "node --test \"test/*.test.mjs\"",
|
|
47
|
+
"verify": "node scripts/verify.mjs"
|
|
48
|
+
},
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+https://github.com/chendaleiQ/dsh-chrome.git"
|
|
52
|
+
},
|
|
53
|
+
"homepage": "https://github.com/chendaleiQ/dsh-chrome#readme",
|
|
54
|
+
"bugs": {
|
|
55
|
+
"url": "https://github.com/chendaleiQ/dsh-chrome/issues"
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public"
|
|
59
|
+
},
|
|
60
|
+
"engines": {
|
|
61
|
+
"node": ">=22"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* dsh-chrome 本地桥独立入口:node scripts/bridge.mjs [--port 17319]
|
|
4
|
+
* DSH 插件加载时会自动起桥(端口被占则当 client);这个脚本用于
|
|
5
|
+
* LaunchAgent 开机自启,或手动常驻。
|
|
6
|
+
*/
|
|
7
|
+
import { createBridge } from "../src/bridge-server.js";
|
|
8
|
+
|
|
9
|
+
const portArg = process.argv.indexOf("--port");
|
|
10
|
+
const port = Number(portArg === -1 ? process.env.DSH_CHROME_BRIDGE_PORT || 17319 : process.argv[portArg + 1]);
|
|
11
|
+
const host = process.env.DSH_CHROME_BRIDGE_HOST || "127.0.0.1";
|
|
12
|
+
|
|
13
|
+
const bridge = createBridge({ host, port });
|
|
14
|
+
bridge
|
|
15
|
+
.listen()
|
|
16
|
+
.then(() => console.log(`[dsh-chrome] bridge listening on http://${host}:${port}`))
|
|
17
|
+
.catch((e) => {
|
|
18
|
+
console.error(`[dsh-chrome] cannot listen on ${host}:${port}: ${e.message}`);
|
|
19
|
+
process.exit(1);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
process.on("SIGTERM", () => bridge.close().then(() => process.exit(0)));
|
|
23
|
+
process.on("SIGINT", () => bridge.close().then(() => process.exit(0)));
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* dsh-chrome 一键安装检查:node scripts/setup.mjs [--install-launchd|--uninstall-launchd]
|
|
4
|
+
* 中文说明见 README.md,English version see README.en.md.
|
|
5
|
+
*
|
|
6
|
+
* 做的事:
|
|
7
|
+
* 1. Node 版本检查(>= 22)
|
|
8
|
+
* 2. 跑全量单测(node --test)
|
|
9
|
+
* 3. 桥状态检查(17319 有没有在跑、谁在跑)
|
|
10
|
+
* 4. 打印扩展加载步骤(带绝对路径,开箱即贴)
|
|
11
|
+
* 5. --install-launchd:写入 ~/Library/LaunchAgents 开机自启并立即启动
|
|
12
|
+
* 6. 打印 DSH 侧安装提示
|
|
13
|
+
*/
|
|
14
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
15
|
+
import { existsSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { dirname, join, resolve } from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
|
|
20
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
21
|
+
const LABEL = "com.chendaleiq.dsh-chrome-bridge";
|
|
22
|
+
const PLIST = join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
23
|
+
const args = new Set(process.argv.slice(2));
|
|
24
|
+
const ok = (m) => console.log(` ✓ ${m}`);
|
|
25
|
+
const warn = (m) => console.log(` ! ${m}`);
|
|
26
|
+
const fail = (m) => {
|
|
27
|
+
console.error(` ✗ ${m}`);
|
|
28
|
+
process.exitCode = 1;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
console.log("== 1/5 Node 版本 / Node version ==");
|
|
32
|
+
const major = Number(process.versions.node.split(".")[0]);
|
|
33
|
+
if (major >= 22) ok(`node ${process.versions.node}`);
|
|
34
|
+
else fail(`need node >= 22, got ${process.versions.node}`);
|
|
35
|
+
|
|
36
|
+
console.log("== 2/5 单测 / tests ==");
|
|
37
|
+
const t = spawnSync(process.execPath, ["--test", "test/*.test.mjs"], { cwd: root, encoding: "utf8" });
|
|
38
|
+
if (t.status === 0) ok("all tests pass");
|
|
39
|
+
else {
|
|
40
|
+
fail("tests failed");
|
|
41
|
+
console.error((t.stdout || "").split("\n").slice(-15).join("\n"));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
console.log("== 3/5 桥状态 / bridge ==");
|
|
45
|
+
try {
|
|
46
|
+
const st = await (await fetch("http://127.0.0.1:17319/status")).json();
|
|
47
|
+
ok(`bridge up: connected=${st.connected} client=${st.clientName || "(none)"}`);
|
|
48
|
+
} catch {
|
|
49
|
+
warn("bridge not running (DSH 插件加载时会自动起;或见第 5 步开机自启)");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
console.log("== 4/5 扩展 / extension ==");
|
|
53
|
+
console.log(` chrome://extensions → 开发者模式 → 加载已解压的扩展 → 选择:\n ${join(root, "extension")}`);
|
|
54
|
+
console.log(" Load unpacked at chrome://extensions (Developer mode on):");
|
|
55
|
+
console.log(` ${join(root, "extension")}`);
|
|
56
|
+
|
|
57
|
+
if (args.has("--install-launchd")) {
|
|
58
|
+
console.log("== 5/5 开机自启 / LaunchAgent ==");
|
|
59
|
+
mkdirSync(dirname(PLIST), { recursive: true });
|
|
60
|
+
const plist =
|
|
61
|
+
`<?xml version="1.0" encoding="UTF-8"?>\n` +
|
|
62
|
+
`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n` +
|
|
63
|
+
`<plist version="1.0"><dict>\n` +
|
|
64
|
+
` <key>Label</key><string>${LABEL}</string>\n` +
|
|
65
|
+
` <key>ProgramArguments</key><array><string>${process.execPath}</string><string>${join(root, "scripts", "bridge.mjs")}</string></array>\n` +
|
|
66
|
+
` <key>WorkingDirectory</key><string>${root}</string>\n` +
|
|
67
|
+
` <key>RunAtLoad</key><true/>\n` +
|
|
68
|
+
` <key>KeepAlive</key><true/>\n` +
|
|
69
|
+
` <key>StandardOutPath</key><string>/tmp/dsh-chrome-bridge.log</string>\n` +
|
|
70
|
+
` <key>StandardErrorPath</key><string>/tmp/dsh-chrome-bridge.err</string>\n` +
|
|
71
|
+
`</dict></plist>\n`;
|
|
72
|
+
writeFileSync(PLIST, plist);
|
|
73
|
+
try {
|
|
74
|
+
execFileSync("launchctl", ["bootout", `gui/${process.getuid()}`, PLIST], { stdio: "ignore" });
|
|
75
|
+
} catch { /* not loaded yet */ }
|
|
76
|
+
execFileSync("launchctl", ["bootstrap", `gui/${process.getuid()}`, PLIST]);
|
|
77
|
+
ok(`installed ${PLIST} and started`);
|
|
78
|
+
} else if (args.has("--uninstall-launchd")) {
|
|
79
|
+
try {
|
|
80
|
+
execFileSync("launchctl", ["bootout", `gui/${process.getuid()}`, PLIST], { stdio: "ignore" });
|
|
81
|
+
} catch { /* ignore */ }
|
|
82
|
+
if (existsSync(PLIST)) rmSync(PLIST);
|
|
83
|
+
ok("launchd entry removed (bridge stops being auto-started)");
|
|
84
|
+
} else {
|
|
85
|
+
console.log("== 5/5 开机自启(可选) / autostart (optional) ==");
|
|
86
|
+
console.log(" node scripts/setup.mjs --install-launchd 开机自启桥 / autostart bridge on login");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
console.log("");
|
|
90
|
+
console.log("DSH 侧安装 / install into DSH:");
|
|
91
|
+
console.log(` plugin_manager → install_bundle → target: ${resolve(root)}`);
|
|
92
|
+
console.log(" (当面装:插件页 → Add plugin → 选上面这个目录 / Plugins → Add plugin → pick it)");
|
|
93
|
+
if (process.exitCode) console.log("\nDone with errors — fix the ✗ lines above.");
|
|
94
|
+
else console.log("\nDone. Bridge + extension + DSH 三件套按上面 4/5/DSH 三步走。");
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-chrome 一键真机验证(全新重写)。
|
|
3
|
+
* 用法:node scripts/verify.mjs [--port 17319] [--wait-secs 120] [--snapshot]
|
|
4
|
+
* 桥没在跑就先起桥(见 docs/TESTING.md);扩展没连就等到 --wait-secs,超时报 2。
|
|
5
|
+
*/
|
|
6
|
+
import { bridgeSend, bridgeStatus } from "../src/bridge-client.js";
|
|
7
|
+
|
|
8
|
+
function arg(name, fallback) {
|
|
9
|
+
const i = process.argv.indexOf(name);
|
|
10
|
+
return i === -1 ? fallback : process.argv[i + 1];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const port = Number(arg("--port", "17319"));
|
|
14
|
+
const waitSecs = Number(arg("--wait-secs", "120"));
|
|
15
|
+
const wantSnapshot = process.argv.includes("--snapshot");
|
|
16
|
+
const baseUrl = `http://127.0.0.1:${port}`;
|
|
17
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
18
|
+
|
|
19
|
+
const deadline = Date.now() + waitSecs * 1000;
|
|
20
|
+
let status = await bridgeStatus(baseUrl);
|
|
21
|
+
while (!status.connected && Date.now() < deadline) {
|
|
22
|
+
const left = Math.ceil((deadline - Date.now()) / 1000);
|
|
23
|
+
process.stdout.write(`\rwaiting for extension… ${left}s `);
|
|
24
|
+
await sleep(2000);
|
|
25
|
+
status = await bridgeStatus(baseUrl);
|
|
26
|
+
}
|
|
27
|
+
process.stdout.write("\n");
|
|
28
|
+
if (!status.connected) {
|
|
29
|
+
console.error(`timeout: no extension polled ${baseUrl} within ${waitSecs}s (lastSeenAt=${status.lastSeenAt || 0})`);
|
|
30
|
+
process.exit(2);
|
|
31
|
+
}
|
|
32
|
+
console.log(`connected: ${status.clientName || "(unknown client)"}`);
|
|
33
|
+
|
|
34
|
+
const send = (action, params = {}, timeoutMs = 20000) => bridgeSend(baseUrl, action, params, timeoutMs);
|
|
35
|
+
|
|
36
|
+
const version = await send("tab.version", {});
|
|
37
|
+
console.log(`extensionVersion=${version.extensionVersion} userAgent=${String(version.userAgent || "").slice(0, 80)}`);
|
|
38
|
+
|
|
39
|
+
const tabs = await send("tab.list", {});
|
|
40
|
+
const list = Array.isArray(tabs) ? tabs : [];
|
|
41
|
+
console.log(`tabs=${list.length}`);
|
|
42
|
+
for (const t of list.slice(0, 10)) console.log(` - [${t.id}] ${String(t.title || "").slice(0, 60)} ${t.url || ""}`);
|
|
43
|
+
|
|
44
|
+
if (wantSnapshot) {
|
|
45
|
+
const snap = await send("page.snapshot", { maxNodes: 40 }, 25000);
|
|
46
|
+
const text = String(snap.snapshot || "").slice(0, 2000);
|
|
47
|
+
console.log(`--- snapshot (${snap.truncated || 0} more) ---`);
|
|
48
|
+
console.log(text);
|
|
49
|
+
}
|
|
50
|
+
console.log("VERIFY_PASS");
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-chrome — 桥自启(纯模块,可单测)。Host 插件自己起回环桥,
|
|
3
|
+
* 端口被占(另一个会话已起)就当 client 用,不抛错。
|
|
4
|
+
* dispose 会等 listen 落定:自己起的才关,蹭别人的不动。
|
|
5
|
+
*/
|
|
6
|
+
import { createBridge } from "./bridge-server.js";
|
|
7
|
+
|
|
8
|
+
export function ensureBridge({ bridgeHost, bridgePort }) {
|
|
9
|
+
const bridge = createBridge({ host: bridgeHost, port: bridgePort });
|
|
10
|
+
let owned = null;
|
|
11
|
+
const started = bridge
|
|
12
|
+
.listen()
|
|
13
|
+
.then(() => {
|
|
14
|
+
owned = true;
|
|
15
|
+
})
|
|
16
|
+
.catch(() => {
|
|
17
|
+
owned = false;
|
|
18
|
+
});
|
|
19
|
+
return {
|
|
20
|
+
started,
|
|
21
|
+
isOwned: () => owned,
|
|
22
|
+
dispose: () =>
|
|
23
|
+
started
|
|
24
|
+
.then(() => {
|
|
25
|
+
if (owned) return bridge.close().catch(() => {});
|
|
26
|
+
})
|
|
27
|
+
.catch(() => {}),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-chrome — DSH 侧本地桥客户端。
|
|
3
|
+
*
|
|
4
|
+
* 最小 wire 协议:
|
|
5
|
+
* GET /status -> { url, mode, connected, lastSeenAt, clientName }
|
|
6
|
+
* POST /command { id, action, params } -> { ok, result } 或 { ok:false, error }
|
|
7
|
+
*
|
|
8
|
+
* 不依赖任何第三方包,只用 Node 全局 fetch。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const DEFAULT_HOST = "127.0.0.1";
|
|
12
|
+
const DEFAULT_PORT = 17319;
|
|
13
|
+
|
|
14
|
+
export function bridgeUrlOf(config = {}) {
|
|
15
|
+
const host = config.bridgeHost || process.env.DSH_CHROME_BRIDGE_HOST || DEFAULT_HOST;
|
|
16
|
+
const port = Number(config.bridgePort || process.env.DSH_CHROME_BRIDGE_PORT || DEFAULT_PORT);
|
|
17
|
+
return `http://${host}:${port}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function bridgeStatus(baseUrl, timeoutMs = 3000) {
|
|
21
|
+
const ctrl = new AbortController();
|
|
22
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
23
|
+
try {
|
|
24
|
+
const res = await fetch(`${baseUrl}/status`, { signal: ctrl.signal });
|
|
25
|
+
if (!res.ok) return { connected: false, httpStatus: res.status };
|
|
26
|
+
return await res.json();
|
|
27
|
+
} catch (error) {
|
|
28
|
+
return { connected: false, error: error?.message || String(error) };
|
|
29
|
+
} finally {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let seq = 0;
|
|
35
|
+
|
|
36
|
+
export async function bridgeSend(baseUrl, action, params = {}, timeoutMs = 30000, parentSignal) {
|
|
37
|
+
const ctrl = new AbortController();
|
|
38
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
39
|
+
const onParentAbort = () => ctrl.abort();
|
|
40
|
+
if (parentSignal) {
|
|
41
|
+
if (parentSignal.aborted) {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
throw new Error(`bridge ${action} aborted before send`);
|
|
44
|
+
}
|
|
45
|
+
parentSignal.addEventListener("abort", onParentAbort, { once: true });
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const res = await fetch(`${baseUrl}/command`, {
|
|
49
|
+
method: "POST",
|
|
50
|
+
headers: { "content-type": "application/json" },
|
|
51
|
+
body: JSON.stringify({ id: `dsh-${Date.now()}-${(seq += 1)}`, action, params }),
|
|
52
|
+
signal: ctrl.signal,
|
|
53
|
+
});
|
|
54
|
+
const body = await res.json().catch(() => ({}));
|
|
55
|
+
if (!res.ok || body.ok === false) {
|
|
56
|
+
throw new Error(body.error || `bridge HTTP ${res.status}`);
|
|
57
|
+
}
|
|
58
|
+
return body.result;
|
|
59
|
+
} finally {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
if (parentSignal) parentSignal.removeEventListener("abort", onParentAbort);
|
|
62
|
+
}
|
|
63
|
+
}
|