dsh-mobile-ios 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,853 @@
1
+ // lib/client.js — 桌面端 UI 注入模块(X3)
2
+ //
3
+ // 契约(考古自社区 dsh-mobile 0.8.11 的 lib/client.js):
4
+ // 宿主 web app 按包的 `exports["./client"]` 加载本文件,浏览器里执行到
5
+ // `window.__ModuleLoader__.load({ id, factory })` 注册模块;
6
+ // factory 返回的模块需导出 `apply(ctx)` 与 `inject = ["slots"]`,
7
+ // 宿主把 slots 服务注入进来,UI 通过 slots 挂载。
8
+ //
9
+ // 我们挂两个东西:
10
+ // 1. 左下角侧栏 banner(slot: sidebar.footer.action)——手机图标 + 「iOS移动伴侣」
11
+ // + 连接状态点;窄栏(rail)只留图标。
12
+ // 2. 点击展开的状态面板(原生 DOM overlay,宿主未提供 react-dom)——
13
+ // 网关状态 / 适配器 / 已配对设备 / 隧道 / 生成配对码。
14
+ //
15
+ // 如实边界:网关端口被占会自动顺延(3081–3085 探测);面板数据来自
16
+ // /mobile/v1/desktop/summary(回环-only,无敏感字段),拿不到就明确显示
17
+ // 「网关不可达」,绝不编造状态。
18
+ window.__ModuleLoader__.load({
19
+ id: 'dsh-mobile-ios',
20
+ factory: (require) => {
21
+ var module = { exports: {} };
22
+ var exports = module.exports;
23
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
24
+
25
+ let react = require('react');
26
+
27
+ // ── 状态 ─────────────────────────────────────────────────────
28
+ const PORT_CANDIDATES = [3081, 3082, 3083, 3084, 3085];
29
+ let gatewayPort = null;
30
+ let summary = null; // /desktop/summary 结果或 null
31
+ let probing = false;
32
+
33
+ function baseUrl() {
34
+ return gatewayPort ? `http://127.0.0.1:${gatewayPort}` : null;
35
+ }
36
+
37
+ async function fetchJson(path, options, timeoutMs = 1500) {
38
+ const base = baseUrl();
39
+ if (!base) throw new Error('gateway-not-found');
40
+ const controller = new AbortController();
41
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
42
+ try {
43
+ const res = await fetch(base + path, { ...options, signal: controller.signal });
44
+ const body = await res.json();
45
+ if (!res.ok) throw Object.assign(new Error(body?.error?.message || res.statusText), { body });
46
+ return body;
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+ }
51
+
52
+ /** 探测网关端口(顺延容忍),成功后拉一次摘要 */
53
+ async function probe() {
54
+ if (probing) return;
55
+ probing = true;
56
+ try {
57
+ let found = null;
58
+ for (const port of PORT_CANDIDATES) {
59
+ const controller = new AbortController();
60
+ const timer = setTimeout(() => controller.abort(), 700);
61
+ try {
62
+ const res = await fetch(`http://127.0.0.1:${port}/mobile/v1/health`, { signal: controller.signal });
63
+ if (res.ok) { found = port; break; }
64
+ } catch {} // 端口不是我们/没起,继续探
65
+ finally { clearTimeout(timer); }
66
+ }
67
+ // 必须跟着探到的结果走:只在成功时赋值、失败时清空。
68
+ // 以前失败会保留旧端口,网关换端口后一直去敲那个死端口(若被别的服务
69
+ // 占用还会解析出非 JSON),面板就一直红着。
70
+ gatewayPort = found;
71
+ if (gatewayPort) summary = await fetchJson('/mobile/v1/desktop/summary').catch(() => null);
72
+ else summary = null;
73
+ } finally {
74
+ probing = false;
75
+ }
76
+ }
77
+
78
+ /** 面板打开时的轻量刷新:端口已经探到,只拉摘要并重绘,不再重复扫端口。 */
79
+ async function refreshSummary() {
80
+ if (!gatewayPort || summaryFetching) return;
81
+ summaryFetching = true;
82
+ try {
83
+ const next = await fetchJson('/mobile/v1/desktop/summary').catch(() => null);
84
+ if (next?.ok) {
85
+ summary = next;
86
+ renderSummary();
87
+ }
88
+ } finally {
89
+ summaryFetching = false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * 首屏快速补探。
95
+ *
96
+ * 宿主重启时插件先于网关绑端口加载,第一次探测必然落空;
97
+ * 只靠 15 秒轮询会让面板红着不动,用户看到的就是「插件坏了」。
98
+ */
99
+ async function probeUntilUp(attempts = 5, delayMs = 1200) {
100
+ for (let i = 0; i < attempts; i += 1) {
101
+ await probe();
102
+ if (summary && summary.ok) return;
103
+ if (i < attempts - 1) await new Promise((resolve) => { setTimeout(resolve, delayMs); });
104
+ }
105
+ }
106
+
107
+ /** 生成配对码(本机动作,回环-only 端点)。route 显式选路:'lan' | 'tunnel' | undefined=自动 */
108
+ async function issuePairingCode(route) {
109
+ return fetchJson('/mobile/v1/pairing/code', {
110
+ method: 'POST',
111
+ headers: { 'content-type': 'application/json' },
112
+ body: JSON.stringify({ deviceName: '待连接设备', ...(route ? { route } : {}) }),
113
+ }, 2500);
114
+ }
115
+
116
+ /** 隧道启停(本机管理面动作,回环-only 端点) */
117
+ /** 单台下线:管理面动作,与出码同样的本机约束,绝不走公网域名。 */
118
+ async function revokeDevice(deviceId) {
119
+ return fetchJson('/mobile/v1/pairing/revoke-device', {
120
+ method: 'POST',
121
+ headers: { 'content-type': 'application/json' },
122
+ body: JSON.stringify({ deviceId }),
123
+ }, 2500);
124
+ }
125
+
126
+ async function tunnelAction(action) {
127
+ // start 首次会顺带「开通固定地址 + 等公网注册 + DNS 复查」,实测经常超过 20s;
128
+ // 以前 20s 就掐断,用户点第一次报错、点第二次才出码——就是这里太短。
129
+ return fetchJson(`/mobile/v1/tunnel/${action}`, { method: 'POST' }, action === 'start' ? 60000 : 25000);
130
+ }
131
+
132
+ // ── 样式 ─────────────────────────────────────────────────────
133
+ const STYLE_ID = 'dsh-mios-style';
134
+ function installStyle() {
135
+ if (document.getElementById(STYLE_ID)) return;
136
+ const style = document.createElement('style');
137
+ style.id = STYLE_ID;
138
+ // 主题跟随宿主:颜色全部走 CSS 变量,.light 类由 detectHostTheme() 动态切换。
139
+ // 以前全硬编码深色,宿主开浅色主题时面板像一块黑补丁(2026-11-18 真机反馈)。
140
+ style.textContent = `
141
+ .dsh-mios-trigger { display: inline-flex; align-items: center; gap: 7px; background: none;
142
+ border: none; color: inherit; cursor: pointer; padding: 6px 8px; border-radius: 8px;
143
+ font: inherit; line-height: 1; }
144
+ .dsh-mios-trigger:hover { background: rgba(255,255,255,.08); }
145
+ .dsh-mios-trigger.is-rail { padding: 8px; }
146
+ .dsh-mios-dot { width: 7px; height: 7px; border-radius: 50%; flex: none; }
147
+ .dsh-mios-dot.ok { background: #3fb27f; }
148
+ .dsh-mios-dot.down { background: #d94f3d; }
149
+ .dsh-mios-panel { --bg: #171b24; --fg: #e8eaf0; --muted: #8b93a3; --border: #303a52;
150
+ --border-hover: #4a5678; --shadow: rgba(0,0,0,.5); --fg-soft: rgba(232,234,240,.7);
151
+ --muted-border: rgba(139,147,163,.45); --muted-bg: rgba(139,147,163,.12);
152
+ --muted-bg-hover: rgba(139,147,163,.2); }
153
+ .dsh-mios-panel.light { --bg: #ffffff; --fg: #1f2430; --muted: #6b7280; --border: #d9dee8;
154
+ --border-hover: #9aa5bd; --shadow: rgba(31,36,48,.18); --fg-soft: rgba(31,36,48,.7);
155
+ --muted-border: rgba(107,114,128,.4); --muted-bg: rgba(107,114,128,.1);
156
+ --muted-bg-hover: rgba(107,114,128,.18); }
157
+ .dsh-mios-panel { position: fixed; left: 14px; bottom: 52px; width: 300px; z-index: 99990;
158
+ background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 14px;
159
+ box-shadow: 0 14px 44px var(--shadow); font: 13px/1.6 -apple-system, "PingFang SC", sans-serif;
160
+ padding: 14px; }
161
+ .dsh-mios-panel h3 { margin: 0 0 10px; font-size: 14px; display: flex; align-items: center; gap: 8px; }
162
+ .dsh-mios-upd { margin-left: auto; background: none; border: 1px solid var(--border); border-radius: 7px;
163
+ color: var(--muted); font: 500 11px/1.4 inherit, sans-serif; cursor: pointer; padding: 3px 8px; }
164
+ .dsh-mios-upd:hover { color: var(--fg); border-color: var(--border-hover); }
165
+ .upd-result { margin: -4px 0 10px; font-size: 11px; color: var(--muted); line-height: 1.5; }
166
+ .upd-result.has-update { color: #3fb27f; }
167
+ .dsh-mios-panel .row { display: flex; justify-content: space-between; gap: 8px; color: var(--muted); margin: 3px 0; }
168
+ .dsh-mios-panel .row b { color: var(--fg); font-weight: 600; text-align: right; max-width: 170px;
169
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
170
+ .dsh-mios-device-toggle { background: none; border: none; color: var(--muted); cursor: pointer;
171
+ font: inherit; padding: 0; display: inline-flex; align-items: center; gap: 5px; }
172
+ .dsh-mios-device-toggle:hover { color: var(--fg); }
173
+ .dsh-mios-devices { margin: 2px 0 6px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
174
+ .dsh-mios-devices[hidden] { display: none; }
175
+ .dsh-mios-device-row { display: flex; align-items: center; gap: 8px; padding: 5px 10px;
176
+ font-size: 11px; color: var(--muted); border-top: 1px solid var(--border); }
177
+ .dsh-mios-device-row:first-child { border-top: none; }
178
+ .dsh-mios-device-name { flex: 1; min-width: 0; overflow-wrap: anywhere; white-space: normal;
179
+ line-height: 1.35; color: var(--fg); }
180
+ .dsh-mios-device-online { color: #3fb27f; flex: none; }
181
+ .dsh-mios-device-offline { color: var(--muted); flex: none; }
182
+ .dsh-mios-device-kick { margin-left: auto; background: none; border: 1px solid rgba(217,79,61,.4); border-radius: 4px;
183
+ color: #c97a6d; cursor: pointer; font-family: inherit; font-size: 9px; font-weight: 500;
184
+ line-height: 1.3; padding: 1px 5px; flex: none; }
185
+ .dsh-mios-device-kick:hover { color: #d94f3d; border-color: rgba(217,79,61,.7); }
186
+ .dsh-mios-devices-empty { padding: 6px 8px; font-size: 11px; color: var(--muted); }
187
+ .dsh-mios-panel .pairbtn { width: 100%; margin-top: 10px; padding: 8px 0; border-radius: 9px;
188
+ border: 1px solid rgba(63,178,127,.45); background: rgba(63,178,127,.14); color: #3fb27f;
189
+ font: 600 13px/1.4 inherit-font, sans-serif; cursor: pointer; }
190
+ .dsh-mios-panel .pairbtn:disabled { opacity: .5; cursor: default; }
191
+ .dsh-mios-banner { border: 1px solid var(--border); border-radius: 10px; padding: 10px 10px 11px; margin-top: 10px; }
192
+ .dsh-mios-banner h4 { margin: 0; font-size: 12px; font-weight: 600; color: var(--fg);
193
+ display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
194
+ .dsh-mios-banner .banner-state { font-size: 11px; font-weight: 400; color: var(--muted);
195
+ max-width: 190px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
196
+ .dsh-mios-banner .banner-guide { margin-top: 4px; font-size: 11px; color: var(--muted); line-height: 1.5; }
197
+ .dsh-mios-banner .banner-addr { margin-top: 4px; font-size: 11px; color: var(--muted);
198
+ font-family: ui-monospace, "SF Mono", Menlo, monospace; word-break: break-all; line-height: 1.5; }
199
+ .dsh-mios-banner .pairbtn { margin-top: 8px; }
200
+ .dsh-mios-banner .tunnelbtn { border-color: var(--muted-border); background: var(--muted-bg); color: var(--muted); }
201
+ .dsh-mios-banner .tunnelbtn:hover:not(:disabled) { border-color: var(--fg-soft); color: var(--fg); background: var(--muted-bg-hover); }
202
+ .dsh-mios-banner .tunnelbtn:disabled { opacity: .5; cursor: default; }
203
+ .dsh-mios-banner .stopbtn { margin-top: 6px; padding: 5px 0; font-weight: 500;
204
+ border-color: rgba(217,79,61,.4); background: none; color: #c97a6d; }
205
+ .dsh-mios-banner .stopbtn:hover:not(:disabled) { border-color: rgba(217,79,61,.7); color: #d94f3d; }
206
+ .dsh-mios-panel .code { margin-top: 10px; text-align: center; font-size: 30px; letter-spacing: 8px;
207
+ font-weight: 700; color: var(--fg); font-variant-numeric: tabular-nums; }
208
+ .dsh-mios-qr { margin-top: 10px; padding: 10px; background: #fff; border-radius: 10px;
209
+ display: flex; justify-content: center; }
210
+ .dsh-mios-qr svg { width: 180px; height: 180px; display: block; }
211
+ .dsh-mios-panel .err { margin-top: 10px; font-size: 12px; color: #d94f3d; text-align: center; }
212
+ .dsh-mios-panel footer { margin-top: 10px; font-size: 11px; color: var(--muted); text-align: center; }
213
+ .dsh-mios-close { margin-left: auto; background: none; border: none; color: var(--muted);
214
+ font-size: 16px; cursor: pointer; padding: 2px 6px; }
215
+ `;
216
+ document.head.append(style);
217
+ }
218
+
219
+ // ── 面板(原生 DOM;宿主无 react-dom) ───────────────────────
220
+ // 双 banner 布局:上面「局域网连接」,下面「远程通道连接」。
221
+ // 远程 banner 是合并后的单一主按钮:没开过→开通;开过没跑→开启并出码;
222
+ // 跑着→直接出码。停止远程是旁边的小按钮,只在该停的时候出现。
223
+ const PANEL_TITLE = 'DSH iOS移动伴侣';
224
+ const BANNER_LABEL = '📱 iOS移动伴侣';
225
+ // 插件更新检查:读 npm registry 的 latest(与「添加插件」安装源同源)。
226
+ // npm 官方源带 CORS *,桌面端 webview 可直接 fetch;npmmirror 作国内备用。
227
+ const PLUGIN_NAME = 'dsh-mobile-ios';
228
+ const PLUGIN_REGISTRIES = [
229
+ 'https://registry.npmjs.org',
230
+ 'https://registry.npmmirror.com',
231
+ ];
232
+ const stripUrl = (u) => String(u || '').replace(/^https?:\/\//, '');
233
+ const stripLocal = (h) => String(h || '').replace(/\.local$/i, '');
234
+
235
+ let panelEl = null;
236
+ let tunnelBusy = false;
237
+ const bannerBusy = { lan: false, remote: false };
238
+ let outsideCloser = null;
239
+ let devicesExpanded = false;
240
+ let kickingDeviceId = null;
241
+ // 面板打开期间的摘要刷新:probe() 只更新数据不重绘,正是「扫码后要关掉重开才更新」的根因。
242
+ let summaryPollTimer = null;
243
+ let summaryFetching = false;
244
+ let lastDeviceSignature = null;
245
+
246
+ /** 探测宿主主题:显式标记(class/data-theme)→ body 亮度启发 → 系统偏好。
247
+ * Electron 宿主切换主题只改页面 class,matchMedia 不一定跟着变,所以三级都查。 */
248
+ function detectHostTheme() {
249
+ const root = document.documentElement;
250
+ const body = document.body;
251
+ const marked = `${root.className} ${body?.className || ''} ${root.getAttribute('data-theme') || ''} ${body?.getAttribute('data-theme') || ''} ${root.getAttribute('data-color-mode') || ''}`.toLowerCase();
252
+ if (/\bdark\b/.test(marked)) return 'dark';
253
+ if (/\blight\b/.test(marked)) return 'light';
254
+ // 亮度启发:宿主页面底色亮就是浅色主题(面板挂在这个页面上,跟它一致最直观)。
255
+ // 全黑或全透明底色不可判,落到系统偏好。
256
+ const bgc = body ? getComputedStyle(body).backgroundColor
257
+ : getComputedStyle(root).backgroundColor;
258
+ const m = bgc.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
259
+ if (m && (+m[1] + +m[2] + +m[3]) > 0) {
260
+ return (0.2126 * +m[1] + 0.7152 * +m[2] + 0.0722 * +m[3]) > 140 ? 'light' : 'dark';
261
+ }
262
+ return window.matchMedia?.('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
263
+ }
264
+
265
+ /** 面板主题实时跟随宿主:每次渲染都重判(用户可能中途切主题)。 */
266
+ function applyPanelTheme() {
267
+ if (!panelEl) return;
268
+ panelEl.classList.toggle('light', detectHostTheme() === 'light');
269
+ }
270
+
271
+ function removePanel() {
272
+ panelEl?.remove();
273
+ panelEl = null;
274
+ if (summaryPollTimer) {
275
+ clearInterval(summaryPollTimer);
276
+ summaryPollTimer = null;
277
+ }
278
+ lastDeviceSignature = null;
279
+ if (outsideCloser) {
280
+ document.removeEventListener('pointerdown', outsideCloser);
281
+ outsideCloser = null;
282
+ }
283
+ }
284
+
285
+ function row(label, valueId) {
286
+ const div = document.createElement('div');
287
+ div.className = 'row';
288
+ const l = document.createElement('span');
289
+ l.textContent = label;
290
+ const v = document.createElement('b');
291
+ v.id = valueId;
292
+ v.textContent = '—';
293
+ div.append(l, v);
294
+ return div;
295
+ }
296
+
297
+ /** 「同时在线设备」行:标签可点开展开在线设备清单,右侧显示 在线/上限。 */
298
+ function deviceRows() {
299
+ const wrap = document.createElement('div');
300
+ const head = document.createElement('div');
301
+ head.className = 'row';
302
+ const toggle = document.createElement('button');
303
+ toggle.className = 'dsh-mios-device-toggle';
304
+ toggle.id = 'dsh-mios-device-toggle';
305
+ toggle.type = 'button';
306
+ toggle.textContent = '▸';
307
+ toggle.setAttribute('aria-label', '展开或收起当前在线设备清单');
308
+ const label = document.createElement('span');
309
+ label.textContent = '同时在线设备(最多5台)';
310
+ const left = document.createElement('span');
311
+ left.append(toggle, label);
312
+ const value = document.createElement('b');
313
+ value.id = 'dsh-mios-devices';
314
+ value.textContent = '—';
315
+ head.append(left, value);
316
+ toggle.addEventListener('click', () => {
317
+ devicesExpanded = !devicesExpanded;
318
+ renderDeviceList();
319
+ });
320
+ const list = document.createElement('div');
321
+ list.className = 'dsh-mios-devices';
322
+ list.id = 'dsh-mios-devices-list';
323
+ list.hidden = true;
324
+ wrap.append(head, list);
325
+ return wrap;
326
+ }
327
+
328
+ /** 在线设备清单:默认折叠;只列当前在线设备(同时在线上限 5 台),下线逐台二次确认。 */
329
+ function renderDeviceList() {
330
+ const box = panelEl?.querySelector('#dsh-mios-devices-list');
331
+ if (!box) return;
332
+ box.hidden = !devicesExpanded;
333
+ const toggle = panelEl.querySelector('#dsh-mios-device-toggle');
334
+ if (toggle) toggle.textContent = devicesExpanded ? '▾' : '▸';
335
+ box.replaceChildren();
336
+ if (!summary?.ok) return;
337
+ // 后端已限制活跃设备上限;这里再按在线态筛选并截到 5,保证面板只展示真实并发连接。
338
+ const devices = (summary.pairing?.devices || []).filter((d) => d.online).slice(0, 5);
339
+ if (!devices.length) {
340
+ const empty = document.createElement('div');
341
+ empty.className = 'dsh-mios-devices-empty';
342
+ empty.textContent = '当前没有在线设备';
343
+ box.append(empty);
344
+ return;
345
+ }
346
+ for (const device of devices) {
347
+ const line = document.createElement('div');
348
+ line.className = 'dsh-mios-device-row';
349
+ const name = document.createElement('span');
350
+ name.className = 'dsh-mios-device-name';
351
+ name.textContent = device.deviceName || '未命名设备';
352
+ name.title = name.textContent;
353
+ const state = document.createElement('span');
354
+ state.className = device.online ? 'dsh-mios-device-online' : 'dsh-mios-device-offline';
355
+ state.textContent = device.online ? '在线' : '离线';
356
+ const kick = document.createElement('button');
357
+ kick.className = 'dsh-mios-device-kick';
358
+ kick.textContent = kickingDeviceId === device.deviceId ? '处理中' : '下线';
359
+ kick.disabled = kickingDeviceId !== null;
360
+ kick.title = `将 ${name.textContent} 从这台电脑移除`;
361
+ kick.addEventListener('click', async () => {
362
+ // 二次确认:下线会让那台手机立刻失去读任务的能力,不能误点。
363
+ if (!window.confirm(`确定让「${name.textContent}」下线?该设备需要重新扫码才能再次连接。`)) return;
364
+ kickingDeviceId = device.deviceId;
365
+ renderDeviceList();
366
+ try {
367
+ await revokeDevice(device.deviceId);
368
+ await probe();
369
+ } catch (err) {
370
+ window.alert('下线失败:' + (err?.body?.error?.message || err.message));
371
+ } finally {
372
+ kickingDeviceId = null;
373
+ renderSummary();
374
+ }
375
+ });
376
+ line.append(name, state, kick);
377
+ box.append(line);
378
+ }
379
+ }
380
+
381
+ function renderSummary() {
382
+ if (!panelEl) return;
383
+ applyPanelTheme();
384
+ const dot = panelEl.querySelector('#dsh-mios-panel-dot');
385
+ const ok = !!(summary && summary.ok);
386
+ dot.className = 'dsh-mios-dot ' + (ok ? 'ok' : 'down');
387
+ const set = (id, text) => { const el = panelEl.querySelector('#' + id); if (el) el.textContent = text; };
388
+ set('dsh-mios-adapter', ok ? `v${summary.version}` : '—');
389
+ set('dsh-mios-host', ok ? (stripLocal(summary.hostName) || '未上报') : '—');
390
+ if (ok) {
391
+ const max = summary.pairing?.maxDevices ?? 5;
392
+ const online = summary.pairing?.onlineDevices ?? 0;
393
+ set('dsh-mios-devices', `${online}/${max} 台`);
394
+ } else {
395
+ set('dsh-mios-devices', '—');
396
+ }
397
+ // 只有设备名/在线态/顺序变化才重建列表:1.2s 刷新不能让 hover 提示和下线按钮闪烁。
398
+ const devices = ok ? (summary.pairing?.devices || []) : [];
399
+ const signature = devices
400
+ .map((d) => `${d.deviceId}\u0000${d.deviceName || ''}\u0000${d.online ? 1 : 0}`)
401
+ .join('\u0001');
402
+ if (signature !== lastDeviceSignature) {
403
+ lastDeviceSignature = signature;
404
+ renderDeviceList();
405
+ }
406
+
407
+ // ── 局域网 banner ──
408
+ const lan = ok ? summary.lan : null;
409
+ const lanState = panelEl.querySelector('#dsh-mios-lan-state');
410
+ if (lanState) lanState.textContent = ok ? (lan ? `电脑地址 ${lan}` : '未获取到局域网地址') : '网关不可达';
411
+ const lanCodeBtn = panelEl.querySelector('#dsh-mios-lan-code');
412
+ if (lanCodeBtn) {
413
+ lanCodeBtn.disabled = !ok || !lan || bannerBusy.lan;
414
+ lanCodeBtn.title = ok && lan ? '' : '网关不可达或没有局域网地址';
415
+ }
416
+
417
+ // ── 远程通道 banner ──
418
+ // 四种事实分开说:运行中 / 已开通但没开 / 根本没开通 / 域名没生效。
419
+ // 「域名未生效」必须单列:地址开出来了但公网解析不到,显示「已开通」会误导人去扫码。
420
+ const tunnel = ok ? summary.tunnel : null;
421
+ const dnsBroken = tunnel && tunnel.dnsOk === false;
422
+ const running = !!(tunnel && tunnel.state === 'running' && !dnsBroken);
423
+ const remoteState = panelEl.querySelector('#dsh-mios-remote-state');
424
+ if (remoteState) {
425
+ remoteState.textContent = !tunnel
426
+ ? '—'
427
+ : dnsBroken
428
+ ? '解析异常 · 未开启'
429
+ : running
430
+ ? '已开启'
431
+ : tunnel.provisioned && tunnel.fixedUrl
432
+ ? '已开通 · 未开启'
433
+ : tunnel.mode === 'named' ? '未开通固定地址' : tunnel.state;
434
+ }
435
+ // 固定地址独占一行完整显示,不再和状态词挤在一起被省略号截断
436
+ const remoteAddr = panelEl.querySelector('#dsh-mios-remote-addr');
437
+ if (remoteAddr) {
438
+ const addr = tunnel && (tunnel.fixedUrl || tunnel.url);
439
+ remoteAddr.textContent = tunnel && tunnel.provisioned ? stripUrl(addr) : '—';
440
+ // 默认色交给 CSS 变量(跟随主题);只有解析异常时才覆盖成红色
441
+ remoteAddr.style.color = dnsBroken ? '#d94f3d' : '';
442
+ }
443
+ const mainBtn = panelEl.querySelector('#dsh-mios-remote-main');
444
+ if (mainBtn) {
445
+ // 出码态走绿色主按钮;开启态走灰色次按钮(悬浮变白),视觉上分清两件事
446
+ mainBtn.className = 'pairbtn' + (running || dnsBroken ? '' : ' tunnelbtn');
447
+ mainBtn.style.display = tunnel && tunnel.state !== 'disabled' ? '' : 'none';
448
+ mainBtn.disabled = tunnelBusy || bannerBusy.remote || dnsBroken;
449
+ mainBtn.textContent = dnsBroken
450
+ ? '域名解析异常,暂不可开启'
451
+ : running
452
+ ? (bannerBusy.remote ? '生成中…' : '生成配对码(远程)')
453
+ : tunnel.mode === 'named'
454
+ ? (tunnel.provisioned ? '开启远程并生成配对码' : '开启远程(分配固定地址)')
455
+ : '启动隧道(外网连接)';
456
+ }
457
+ const stopBtn = panelEl.querySelector('#dsh-mios-remote-stop');
458
+ if (stopBtn) {
459
+ // 停止按钮只在该停的时候出现:没开过/没在跑都没有「停」可言
460
+ stopBtn.style.display = running && !tunnelBusy ? '' : 'none';
461
+ stopBtn.disabled = tunnelBusy;
462
+ }
463
+ // 远程码跟着可用性走:不是 running 就收起(与「停止即收码」同一语义,
464
+ // 兜住任何没经过停止按钮的路径,比如进程意外退出)。
465
+ if (!running && !bannerBusy.remote) {
466
+ panelEl.querySelector('#dsh-mios-remote-main')?.closest('.dsh-mios-banner')
467
+ ?.querySelectorAll('.dsh-mios-code-slot, .err').forEach((e) => e.remove());
468
+ }
469
+
470
+ // 提示行只承载告警与错误:没有告警就整行隐藏,不再放固定说明文字
471
+ const hint = panelEl.querySelector('#dsh-mios-hint');
472
+ if (hint) {
473
+ const warn = ok ? summary.tunnel?.warning : null;
474
+ hint.textContent = warn ? `⚠️ ${warn}` : '';
475
+ hint.style.color = '#e0a03c';
476
+ hint.style.display = warn ? '' : 'none';
477
+ }
478
+ }
479
+
480
+ /** 双 banner 里的一块:标题 + 状态行 + 指引一句 + 内容区 */
481
+ function bannerBox(title, stateId, guideText) {
482
+ const box = document.createElement('div');
483
+ box.className = 'dsh-mios-banner';
484
+ const head = document.createElement('h4');
485
+ head.textContent = title;
486
+ const state = document.createElement('span');
487
+ state.className = 'banner-state';
488
+ state.id = stateId;
489
+ state.textContent = '—';
490
+ head.append(state);
491
+ const guide = document.createElement('div');
492
+ guide.className = 'banner-guide';
493
+ guide.textContent = guideText;
494
+ box.append(head, guide);
495
+ return box;
496
+ }
497
+
498
+ /** 出码结果挂进所属 banner:QR + 码 + 地址说明(同一 banner 只保留最新一码) */
499
+ function mountCode(banner, issued) {
500
+ banner.querySelectorAll('.dsh-mios-code-slot').forEach((e) => e.remove());
501
+ const slot = document.createElement('div');
502
+ slot.className = 'dsh-mios-code-slot';
503
+ if (issued.qrSvg) {
504
+ const qr = document.createElement('div');
505
+ qr.className = 'dsh-mios-qr';
506
+ qr.innerHTML = issued.qrSvg;
507
+ slot.append(qr);
508
+ }
509
+ const code = document.createElement('div');
510
+ code.className = 'code';
511
+ code.textContent = issued.code;
512
+ const addr = document.createElement('div');
513
+ addr.style.cssText = 'margin-top:6px;text-align:center;font-size:12px;color:#3fb27f;';
514
+ addr.textContent = issued.route === 'tunnel'
515
+ ? `扫码连接 · 公网固定地址 ${stripUrl(issued.address)}`
516
+ : issued.address
517
+ ? `扫码连接 · 局域网 ${issued.address}`
518
+ : '手机填电脑局域网地址 + 此码';
519
+ slot.append(code, addr);
520
+ banner.append(slot);
521
+ }
522
+
523
+ /** banner 内的出码按钮统一行为:busy → 出码 → 失败在 banner 内显错 */
524
+ function bindCodeBtn(btn, banner, route) {
525
+ btn.addEventListener('click', async () => {
526
+ if (bannerBusy[route]) return;
527
+ bannerBusy[route] = true;
528
+ btn.disabled = true;
529
+ btn.textContent = '生成中…';
530
+ try {
531
+ mountCode(banner, await issuePairingCode(route));
532
+ } catch (err) {
533
+ banner.querySelectorAll('.dsh-mios-code-slot').forEach((e) => e.remove());
534
+ const errEl = document.createElement('div');
535
+ errEl.className = 'err';
536
+ errEl.textContent = '生成失败:' + (err?.body?.error?.message || err.message);
537
+ banner.append(errEl);
538
+ } finally {
539
+ bannerBusy[route] = false;
540
+ btn.textContent = '重新生成配对码';
541
+ renderSummary();
542
+ }
543
+ });
544
+ }
545
+
546
+ function showPanel() {
547
+ if (panelEl) return;
548
+ // 打开期间持续轻量刷新:扫码上线、改名、下线都能立刻反映,无需关掉重开。
549
+ if (summaryPollTimer) clearInterval(summaryPollTimer);
550
+ summaryPollTimer = setInterval(refreshSummary, 1200);
551
+ installStyle();
552
+ panelEl = document.createElement('div');
553
+ panelEl.className = 'dsh-mios-panel';
554
+
555
+ const header = document.createElement('h3');
556
+ const dot = document.createElement('span');
557
+ dot.id = 'dsh-mios-panel-dot';
558
+ dot.className = 'dsh-mios-dot down';
559
+ const title = document.createElement('span');
560
+ title.textContent = PANEL_TITLE;
561
+ // 插件更新:放在关闭按钮左边,点开内联结果,不弹窗不跳页
562
+ const updBtn = document.createElement('button');
563
+ updBtn.className = 'dsh-mios-upd';
564
+ updBtn.textContent = '插件更新';
565
+ updBtn.addEventListener('click', () => checkPluginUpdate());
566
+ const close = document.createElement('button');
567
+ close.className = 'dsh-mios-close';
568
+ close.textContent = '✕';
569
+ close.setAttribute('aria-label', '关闭面板');
570
+ close.addEventListener('click', removePanel);
571
+ header.append(dot, title, updBtn, close);
572
+ const updResult = document.createElement('div');
573
+ updResult.id = 'dsh-mios-upd-result';
574
+ updResult.style.display = 'none';
575
+
576
+ const body = document.createElement('div');
577
+ body.append(
578
+ row('插件版本', 'dsh-mios-adapter'),
579
+ row('电脑名称', 'dsh-mios-host'),
580
+ deviceRows(),
581
+ );
582
+
583
+ // ── banner 1:局域网连接(在家 · 直连 · 始终可用) ──
584
+ const lanBanner = bannerBox('局域网连接', 'dsh-mios-lan-state', '手机与电脑连同一个 Wi-Fi,直连不走外网。适合在家日常用。');
585
+ const lanCodeBtn = document.createElement('button');
586
+ lanCodeBtn.className = 'pairbtn';
587
+ lanCodeBtn.id = 'dsh-mios-lan-code';
588
+ lanCodeBtn.textContent = '生成配对码';
589
+ bindCodeBtn(lanCodeBtn, lanBanner, 'lan');
590
+ lanBanner.append(lanCodeBtn);
591
+
592
+ // ── banner 2:远程通道连接(出门 · 固定域名 · 一个主按钮走完) ──
593
+ // 「开启远程」与「生成配对码」合并成一个主按钮:没开过→开通;
594
+ // 开过没跑→开启并出码;跑着→直接出码。停止是旁边的小按钮。
595
+ const remoteBanner = bannerBox('远程通道连接', 'dsh-mios-remote-state', '出门在外扫码连固定域名,电脑和手机不必在同一网络。');
596
+ const remoteAddr = document.createElement('div');
597
+ remoteAddr.id = 'dsh-mios-remote-addr';
598
+ remoteAddr.className = 'banner-addr';
599
+ remoteAddr.textContent = '—';
600
+ remoteBanner.append(remoteAddr);
601
+ const mainBtn = document.createElement('button');
602
+ mainBtn.className = 'pairbtn';
603
+ mainBtn.id = 'dsh-mios-remote-main';
604
+ mainBtn.textContent = '开启远程并生成配对码';
605
+ mainBtn.addEventListener('click', () => remoteMainAction(remoteBanner));
606
+ const stopBtn = document.createElement('button');
607
+ stopBtn.className = 'pairbtn stopbtn';
608
+ stopBtn.id = 'dsh-mios-remote-stop';
609
+ stopBtn.textContent = '停止远程';
610
+ stopBtn.addEventListener('click', stopRemoteAction);
611
+ remoteBanner.append(mainBtn, stopBtn);
612
+
613
+ const hint = document.createElement('div');
614
+ hint.id = 'dsh-mios-hint';
615
+ hint.style.cssText = 'margin-top:8px;font-size:11px;color:#e0a03c;line-height:1.5;';
616
+ hint.style.display = 'none';
617
+
618
+ const footer = document.createElement('footer');
619
+ footer.textContent = 'iPhone/iPad App → 连接 → 扫码(约 2 分钟有效)';
620
+
621
+ panelEl.append(header, updResult, body, lanBanner, remoteBanner, hint, footer);
622
+ document.body.append(panelEl);
623
+ applyPanelTheme();
624
+ placePanelAboveTrigger();
625
+ renderSummary();
626
+ probe();
627
+
628
+ // 点击面板/触发 banner 以外的任意区域即关闭(✕ 之外的第二条路)
629
+ outsideCloser = (ev) => {
630
+ if (!panelEl) return;
631
+ const t = ev.target;
632
+ if (panelEl.contains(t) || (t.closest && t.closest('.dsh-mios-trigger'))) return;
633
+ removePanel();
634
+ };
635
+ document.addEventListener('pointerdown', outsideCloser);
636
+ }
637
+
638
+ /** 面板底边对齐触发 banner 顶边:不遮挡 banner,屏幕放不下就整体上推并内滚。 */
639
+ function placePanelAboveTrigger() {
640
+ const trigger = document.querySelector('.dsh-mios-trigger');
641
+ if (trigger) {
642
+ const rect = trigger.getBoundingClientRect();
643
+ panelEl.style.left = `${Math.max(10, Math.round(rect.left))}px`;
644
+ panelEl.style.bottom = `${Math.max(10, Math.round(window.innerHeight - rect.top + 8))}px`;
645
+ }
646
+ panelEl.style.maxHeight = 'min(72vh, 640px)';
647
+ panelEl.style.overflowY = 'auto';
648
+ }
649
+
650
+ /** 更新检查:与「添加插件」同源,读 npm registry 的 latest 比对当前版本。
651
+ * 404 = 包未发布(本地开发版);网络失败 = 如实报不可达,二者不混为一谈。 */
652
+ async function checkPluginUpdate() {
653
+ const box = panelEl?.querySelector('#dsh-mios-upd-result');
654
+ if (!box) return;
655
+ box.style.display = '';
656
+ box.textContent = '正在检查更新…';
657
+ box.className = 'upd-result';
658
+ const current = summary?.version || '';
659
+ let latest = '';
660
+ let sawNotFound = false;
661
+ let lastError = null;
662
+ for (const base of PLUGIN_REGISTRIES) {
663
+ try {
664
+ const res = await fetch(`${base}/${PLUGIN_NAME}/latest`, { signal: AbortSignal.timeout(6000) });
665
+ if (res.status === 404) { sawNotFound = true; continue; }
666
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
667
+ const meta = await res.json();
668
+ if (meta?.version) { latest = String(meta.version); break; }
669
+ } catch (e) {
670
+ lastError = e;
671
+ }
672
+ }
673
+ if (!latest) {
674
+ box.className = 'upd-result';
675
+ if (sawNotFound) {
676
+ box.textContent = '插件尚未发布到 npm,当前为本地开发版。'
677
+ + '更新方式:拉取仓库最新代码后重启 DSH 桌面端,插件会随源码热重载。';
678
+ } else {
679
+ box.textContent = `更新源暂不可达${lastError ? `(${lastError.message})` : ''},无法确认是否有新版本。`;
680
+ }
681
+ return;
682
+ }
683
+ if (compareVersions(latest, current) > 0) {
684
+ box.className = 'upd-result has-update';
685
+ box.textContent = `发现新版 v${latest}(当前 v${current}):到 DSH 插件页卸载本插件后重新安装,或输包名 ${PLUGIN_NAME}@${latest} 更新。`;
686
+ } else {
687
+ box.className = 'upd-result';
688
+ box.textContent = `已是最新版本 v${current}(npm v${latest})。`;
689
+ }
690
+ }
691
+
692
+ function compareVersions(a, b) {
693
+ const parse = (s) => String(s || '').replace(/^v/i, '').split('-')[0].split('.').map((n) => parseInt(n, 10) || 0);
694
+ const [pa, pb] = [parse(a), parse(b)];
695
+ for (let i = 0; i < 3; i += 1) {
696
+ if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
697
+ }
698
+ return 0;
699
+ }
700
+
701
+ /** 等 summary 反映出「远程已可用」:服务端 start 会等到注册成功才返回,
702
+ * 但客户端超时/轮询窗口内可能还没看到,这里统一补轮询兜底。 */
703
+ async function waitForTunnelUp(attempts = 8, delayMs = 1500) {
704
+ for (let i = 0; i < attempts; i += 1) {
705
+ await probe();
706
+ renderSummary();
707
+ const t = summary?.tunnel;
708
+ if (t && t.state === 'running' && t.dnsOk !== false) return true;
709
+ if (i < attempts - 1) await new Promise((resolve) => { setTimeout(resolve, delayMs); });
710
+ }
711
+ return false;
712
+ }
713
+
714
+ /** 远程主按钮:一条动作链走完「确保在跑 → 出码」。一次点击出码,绝不让人点两下。 */
715
+ async function remoteMainAction(banner) {
716
+ if (tunnelBusy || bannerBusy.remote) return;
717
+ const mainBtn = panelEl?.querySelector('#dsh-mios-remote-main');
718
+ const running = summary?.tunnel?.state === 'running' && summary?.tunnel?.dnsOk !== false;
719
+ try {
720
+ if (!running) {
721
+ tunnelBusy = true;
722
+ if (mainBtn) mainBtn.textContent = '开启中…';
723
+ let startErr = null;
724
+ try {
725
+ await tunnelAction('start');
726
+ } catch (err) {
727
+ // 客户端超时 ≠ 服务端失败:cloudflared 可能还在注册路上。
728
+ // 不直接报错收场,继续轮询等它真的起来(或确认起不来)。
729
+ startErr = err;
730
+ }
731
+ const up = await waitForTunnelUp();
732
+ if (!up) {
733
+ // 真没起来才报错;错误信息优先用服务端带回来的
734
+ const t = summary?.tunnel;
735
+ const msg = startErr?.body?.error?.message
736
+ || (t?.dnsOk === false ? '固定域名尚未在公网生效,请稍后再试' : null)
737
+ || startErr?.message || '远程通道未能开启';
738
+ throw Object.assign(new Error(msg), { body: startErr?.body });
739
+ }
740
+ }
741
+ bannerBusy.remote = true;
742
+ if (mainBtn) mainBtn.textContent = '生成中…';
743
+ mountCode(banner, await issuePairingCode('tunnel'));
744
+ } catch (err) {
745
+ const hint = panelEl?.querySelector('#dsh-mios-hint');
746
+ if (hint) {
747
+ hint.textContent = `⚠️ ${err?.body?.error?.message || err.message}`;
748
+ hint.style.display = '';
749
+ hint.style.color = '#d94f3d';
750
+ }
751
+ } finally {
752
+ tunnelBusy = false;
753
+ bannerBusy.remote = false;
754
+ renderSummary();
755
+ }
756
+ }
757
+
758
+ async function stopRemoteAction() {
759
+ if (tunnelBusy) return;
760
+ tunnelBusy = true;
761
+ const stopBtn = panelEl?.querySelector('#dsh-mios-remote-stop');
762
+ if (stopBtn) stopBtn.textContent = '停止中…';
763
+ try {
764
+ await tunnelAction('stop');
765
+ } catch (err) {
766
+ const hint = panelEl?.querySelector('#dsh-mios-hint');
767
+ if (hint) {
768
+ hint.textContent = `⚠️ ${err?.body?.error?.message || err.message}`;
769
+ hint.style.display = '';
770
+ hint.style.color = '#d94f3d';
771
+ }
772
+ }
773
+ // 停止即收码:远程关了,码还挂在屏幕上只会误导人去扫
774
+ panelEl?.querySelectorAll('#dsh-mios-remote-main')
775
+ .forEach((btn) => btn.closest('.dsh-mios-banner')?.querySelectorAll('.dsh-mios-code-slot, .err')
776
+ .forEach((e) => e.remove()));
777
+ await probe();
778
+ renderSummary();
779
+ tunnelBusy = false;
780
+ }
781
+
782
+ function togglePanel() {
783
+ if (panelEl) removePanel();
784
+ else showPanel();
785
+ }
786
+
787
+ // ── banner(slot 渲染,React 元素) ──────────────────────────
788
+ // 注意:slot 渲染回调不是 React 组件(宿主按回调取元素),不能用 hooks;
789
+ // 状态点读模块级 summary,新鲜度由 apply 里的轮询保证,
790
+ // 宿主重渲侧栏时自然取到最新值。面板打开时另有主动 probe()。
791
+
792
+ const STATUS_OK = { stroke: '#3fb27f', fill: 'rgba(63,178,127,.18)' };
793
+ const STATUS_DOWN = { stroke: '#d94f3d', fill: 'rgba(217,79,61,.18)' };
794
+
795
+ function PhoneIcon() {
796
+ return react.createElement('svg', {
797
+ 'aria-hidden': true, focusable: false, width: 16, height: 16,
798
+ viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor',
799
+ strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round',
800
+ },
801
+ react.createElement('rect', { x: 4, y: 1, width: 8, height: 14, rx: 2 }),
802
+ react.createElement('path', { d: 'M7 12h2' }));
803
+ }
804
+
805
+ function apply(ctx) {
806
+ installStyle();
807
+
808
+ // 轮询保持 summary 新鲜(banner 状态点 + 面板数据共用)
809
+ probeUntilUp();
810
+ const pollTimer = setInterval(probe, 15000);
811
+
812
+ // 状态面板打开期间保持轮询:banner 的 useGatewayStatus 只在宿主渲染时活跃
813
+ const disposeSlot = ctx.slots.inject('sidebar.footer.action', () =>
814
+ ctx.slots.register(
815
+ { name: 'sidebar.footer.action', id: 'dsh-mobile-ios' },
816
+ ({ wide }) => {
817
+ const ok = !!(summary && summary.ok);
818
+ const tone = ok ? STATUS_OK : STATUS_DOWN;
819
+ return react.createElement('button', {
820
+ className: `dsh-mios-trigger${wide ? '' : ' is-rail'}`,
821
+ type: 'button',
822
+ title: PANEL_TITLE,
823
+ 'aria-label': PANEL_TITLE,
824
+ onClick: togglePanel,
825
+ },
826
+ react.createElement('span', {
827
+ className: 'dsh-mios-dot ' + (ok ? 'ok' : 'down'),
828
+ style: { background: tone.stroke },
829
+ }),
830
+ // 名称左边不再放 SVG 手机图标:wide 模式有「📱」emoji 就够了;
831
+ // 窄栏(rail)没有名字,图标仍是唯一的视觉标识,保留。
832
+ wide ? undefined : react.createElement(PhoneIcon),
833
+ wide ? react.createElement('span', null, BANNER_LABEL) : undefined);
834
+ }
835
+ )
836
+ );
837
+
838
+ return () => {
839
+ clearInterval(pollTimer);
840
+ disposeSlot();
841
+ removePanel();
842
+ document.getElementById(STYLE_ID)?.remove();
843
+ };
844
+ }
845
+
846
+ const inject = ['slots'];
847
+ exports.apply = apply;
848
+ exports.inject = inject;
849
+ exports.__test = { PORT_CANDIDATES, STATUS_OK, STATUS_DOWN };
850
+
851
+ return module.exports;
852
+ },
853
+ });