@xiaoqiong0v0/opencode-browser-tool 1.11.0 → 1.12.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.
@@ -0,0 +1,248 @@
1
+ /**
2
+ * console / network 日志流的输出格式化(纯函数,供 `bt_cli` 与单测复用)。
3
+ *
4
+ * 聚合由 shell 侧完成(console `group=burst|none`;network `group=burst|key|none`),
5
+ * 这里只把结构化 item 渲染成模型可读的紧凑文本:不改写计数、不二次聚合。
6
+ * 输出给模型的文本最后统一走 `sanitizeForModel`(绝对路径 → `<path>`)。
7
+ */
8
+ import { tf } from "../i18n/index.js";
9
+ import { sanitizeForModel } from "./sanitize.js";
10
+ /** 模型可见日志文本上限(字符):日志是多行正文,不能沿用默认 300 的短文案上限 */
11
+ export const MAX_LOG_TEXT_CHARS = 20000;
12
+ /** 聚合计数后缀:只有 count > 1 才显示,避免单条噪声 */
13
+ function countSuffix(count) {
14
+ return typeof count === "number" && count > 1 ? ` (x${count})` : "";
15
+ }
16
+ /** 取 stack 首行(异常条目只展示首行,完整栈不进上下文) */
17
+ function firstLine(text) {
18
+ return String(text).split(/\r?\n/, 1)[0].trim();
19
+ }
20
+ /** 渲染单条 console 日志:`[level] msg (xN) phase=… source=…`,异常追加 stack 首行 */
21
+ export function formatConsoleItem(item) {
22
+ const level = item.level || "log";
23
+ const msg = item.msg ?? "";
24
+ const parts = [`[${level}] ${msg}${countSuffix(item.count)}`];
25
+ if (item.phase)
26
+ parts.push(`phase=${item.phase}`);
27
+ if (item.source)
28
+ parts.push(`source=${item.source}`);
29
+ const line = parts.join(" ");
30
+ const stack = item.stack ? firstLine(item.stack) : "";
31
+ return stack ? `${line}\n stack: ${stack}` : line;
32
+ }
33
+ /** 批量渲染 console 条目(空数组返回空数组,由调用方给「空结果」文案) */
34
+ export function formatConsoleItems(items) {
35
+ return (items || []).map(formatConsoleItem);
36
+ }
37
+ /** 展示用 URL 上限(字符):超出保留 host + 末尾 60 字符 */
38
+ const MAX_URL_CHARS = 120;
39
+ /** 超长 URL 保留的末尾字符数(中间用 `…` 省略) */
40
+ const URL_TAIL_CHARS = 60;
41
+ /** 省略标记 */
42
+ const URL_ELLIPSIS = "…";
43
+ /**
44
+ * 判断 network 条目是否属于页面文档本身(用于推断同源基准)。
45
+ * shell 侧契约里文档请求的 `type` 是 `doc`(Windows `document` 已归一为 `doc`)。
46
+ */
47
+ function isDocumentType(type) {
48
+ const t = (type || "").toLowerCase();
49
+ return t === "doc" || t === "document";
50
+ }
51
+ /** 从同批条目推断页面 origin(取第一条文档请求);推断不出返回 `undefined` */
52
+ function inferPageOrigin(items) {
53
+ for (const it of items) {
54
+ if (!isDocumentType(it.type))
55
+ continue;
56
+ try {
57
+ return new URL(String(it.url || "")).origin;
58
+ }
59
+ catch {
60
+ // 该条 URL 不可解析:继续找下一条
61
+ }
62
+ }
63
+ return undefined;
64
+ }
65
+ /**
66
+ * 拼接并压到 `MAX_URL_CHARS` 内:超长时保留前缀(host)+ 末尾 `URL_TAIL_CHARS` 字符。
67
+ * @param prefix 前缀(同源为 `host`,跨域/绝对为 `scheme//host`)
68
+ * @param tail path + query
69
+ * @returns 紧凑展示串
70
+ */
71
+ function compactUrl(prefix, tail) {
72
+ const full = `${prefix}${tail}`;
73
+ if (full.length <= MAX_URL_CHARS)
74
+ return full;
75
+ const keepFrom = Math.max(0, tail.length - URL_TAIL_CHARS);
76
+ return `${prefix}/${URL_ELLIPSIS}${tail.slice(keepFrom)}`;
77
+ }
78
+ /**
79
+ * URL → 紧凑展示:同源去 scheme 保留 `host + path + query`(`web.zhihjy.cn/js/app.js`),
80
+ * 跨域保留完整 URL(`https://other.host/...`);超长保留 host + 末尾 60 字符。
81
+ *
82
+ * **绝不以 `/` 开头输出裸路径**——`sanitizeForModel` 会把裸 POSIX 路径掩码成 `<path>`
83
+ * (`/api/*`、`/notify/*` 例外),那是历史实测里 `[200] GET <path>` 的根因。
84
+ *
85
+ * @param raw 原始 URL(CDP 上报,通常为绝对 URL)
86
+ * @param opts.origin 页面 origin(用于判定同源;缺省时退化为去 scheme 形式)
87
+ * @returns 展示串;空输入返回空串
88
+ */
89
+ export function displayUrl(raw, opts) {
90
+ const s = (raw || "").trim();
91
+ if (!s)
92
+ return "";
93
+ let u;
94
+ try {
95
+ u = new URL(s);
96
+ }
97
+ catch {
98
+ // 相对/不可解析:加 `./` 前缀,既保留原信息又避免被当成绝对路径掩码
99
+ return s.startsWith("/") ? `.${s}` : s;
100
+ }
101
+ if (!u.host)
102
+ return s; // `data:` / `about:blank` 等无 host 的 URL 原样返回
103
+ const tail = `${u.pathname}${u.search}`;
104
+ const crossOrigin = Boolean(opts?.origin) && opts?.origin !== u.origin;
105
+ return crossOrigin
106
+ ? compactUrl(`${u.protocol}//${u.host}`, tail)
107
+ : compactUrl(u.host, tail);
108
+ }
109
+ /** initiator 前缀类型(Windows CDP 会带 `script ` / `fetch ` 等前缀) */
110
+ const INITIATOR_TYPES = new Set([
111
+ "document", "script", "stylesheet", "image", "font", "xhr", "fetch",
112
+ "other", "subresource", "media", "manifest", "texttrack", "websocket",
113
+ "parser", "preflight",
114
+ ]);
115
+ /** 只显示类型、不显示 URL 的 initiator(解析器/预检/文档本身) */
116
+ const INITIATOR_TYPE_ONLY = new Set(["parser", "preflight", "document"]);
117
+ /** 无归因时的占位(调用方据此不输出 `from`) */
118
+ const INITIATOR_FALLBACK = "other";
119
+ /** URL scheme 前缀(`https://` / `ws://` …) */
120
+ const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
121
+ /** `file:line` / `file:line:col` 的行号后缀 */
122
+ const LINE_SUFFIX_RE = /^(.*?):(\d+)(?::\d+)?$/;
123
+ /**
124
+ * initiator → 紧凑归因:去掉类型前缀与 scheme/host,只留**最后两段 + `:line`**
125
+ * (如 `js/chunk-vendors.js:3498`)。
126
+ *
127
+ * 健壮性:空值 / `other` / 解析不出文件名 / 行号为 `0`(CDP 无行号时的占位,如 `BASE_DIGITAL:0`)
128
+ * 统一返回 `other`;**绝不以 `/` 开头输出**(裸路径会被 `sanitizeForModel` 掩码)。
129
+ * Linux 的 `subresource` / `document` 无栈,原样保留。
130
+ *
131
+ * @param raw 原始 initiator(`<type> <url>:<line>` 或平台标记)
132
+ * @returns 归因串;无归因时为 `other`
133
+ */
134
+ export function shortInitiator(raw) {
135
+ let s = (raw || "").trim();
136
+ if (!s)
137
+ return INITIATOR_FALLBACK;
138
+ const sp = s.indexOf(" ");
139
+ const type = sp > 0 ? s.slice(0, sp).toLowerCase() : "";
140
+ if (type && INITIATOR_TYPE_ONLY.has(type))
141
+ return type;
142
+ if (sp > 0 && INITIATOR_TYPES.has(type))
143
+ s = s.slice(sp + 1).trim();
144
+ if (!s || s.toLowerCase() === INITIATOR_FALLBACK)
145
+ return INITIATOR_FALLBACK;
146
+ // 去 scheme + host(首段是主机名,不参与「最后两段」)
147
+ const hadHost = URL_SCHEME_RE.test(s);
148
+ s = s.replace(URL_SCHEME_RE, "").replace(/^\/+/, "");
149
+ s = s.split(/[?#]/, 1)[0] || "";
150
+ const segs = s.split(/[\\/]/).filter(Boolean);
151
+ if (hadHost && segs.length)
152
+ segs.shift();
153
+ if (!segs.length)
154
+ return INITIATOR_FALLBACK;
155
+ const m = LINE_SUFFIX_RE.exec(segs[segs.length - 1]);
156
+ const line = m ? m[2] : "";
157
+ const file = m ? m[1] : segs[segs.length - 1];
158
+ if (!file)
159
+ return INITIATOR_FALLBACK;
160
+ if (line && Number(line) === 0)
161
+ return INITIATOR_FALLBACK;
162
+ const tail = [segs.length >= 2 ? segs[segs.length - 2] : "", file].filter(Boolean).join("/");
163
+ return line ? `${tail}:${line}` : tail;
164
+ }
165
+ /**
166
+ * 渲染 headers(形状按契约未定:对象 / 数组 / 字符串均容错)。
167
+ * 默认已由服务端脱敏(Authorization/Cookie/Set-Cookie → `<redacted>`);
168
+ * `--reveal-secrets` 时展示原值,风险见 README。
169
+ */
170
+ export function formatHeaders(headers) {
171
+ if (headers === undefined || headers === null)
172
+ return "";
173
+ if (typeof headers === "string")
174
+ return headers.trim();
175
+ if (Array.isArray(headers))
176
+ return headers.map((h) => String(h)).join("; ");
177
+ if (typeof headers === "object") {
178
+ return Object.entries(headers)
179
+ .map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(", ") : String(v)}`)
180
+ .join("; ");
181
+ }
182
+ return String(headers);
183
+ }
184
+ /** `from` 归因的展示值:`other` 视为无归因,不输出(避免每行都挂 `from other`) */
185
+ function initiatorLabel(raw) {
186
+ const s = shortInitiator(raw);
187
+ return s === INITIATOR_FALLBACK ? "" : s;
188
+ }
189
+ /**
190
+ * 渲染单条 network 请求:`[status] METHOD host/path (xN) 30ms avg 失败: … from file:line phase=…`
191
+ * @param item network 条目
192
+ * @param opts.includeHeaders 是否附加 headers
193
+ * @param opts.pageOrigin 页面 origin(判定同源用;缺省退化为去 scheme 形式)
194
+ */
195
+ export function formatNetworkItem(item, opts) {
196
+ const statusNum = typeof item.status === "number" ? item.status : Number(item.status);
197
+ const status = Number.isFinite(statusNum) ? statusNum : 0;
198
+ const badge = `[${status}]`.padEnd(5);
199
+ const method = (item.method || "?").toUpperCase();
200
+ const url = displayUrl(item.url, { origin: opts?.pageOrigin });
201
+ const count = typeof item.count === "number" && item.count > 1 ? item.count : 0;
202
+ // shell 聚合只保留同组**最后一条**的耗时(无 avg/min/max 字段),因此标注 `last`,
203
+ // 不谎报平均值(契约示例里的 `avg (min-max)` 需要契约外字段,见交付说明)。
204
+ const duration = typeof item.durationMs === "number" && Number.isFinite(item.durationMs)
205
+ ? `${Math.round(item.durationMs)}ms${count ? " last" : ""}`
206
+ : "";
207
+ const failed = item.failure
208
+ ? tf("cli.log.failed", { reason: item.failure })
209
+ : status === 0 ? tf("cli.log.failed_unknown") : "";
210
+ const from = initiatorLabel(item.initiator);
211
+ const parts = [`${badge} ${method} ${url}${countSuffix(item.count)}`];
212
+ if (duration)
213
+ parts.push(duration);
214
+ if (failed)
215
+ parts.push(failed);
216
+ if (from)
217
+ parts.push(`from ${from}`);
218
+ if (item.phase)
219
+ parts.push(`phase=${item.phase}`);
220
+ const line = parts.join(" ");
221
+ const headers = opts?.includeHeaders ? formatHeaders(item.headers) : "";
222
+ return headers ? `${line}\n headers: ${headers}` : line;
223
+ }
224
+ /**
225
+ * 批量渲染 network 条目;页面 origin 由同批的文档请求(`type=doc`)推断,
226
+ * 用于把同源 URL 压成 `host/path`、跨域 URL 保留完整形式。
227
+ */
228
+ export function formatNetworkItems(items, opts) {
229
+ const list = items || [];
230
+ const pageOrigin = opts?.pageOrigin ?? inferPageOrigin(list);
231
+ return list.map((item) => formatNetworkItem(item, { includeHeaders: opts?.includeHeaders, pageOrigin }));
232
+ }
233
+ /** 缓冲逐出说明:有丢弃才追加,避免正常输出噪声 */
234
+ export function droppedNote(dropped) {
235
+ return typeof dropped === "number" && dropped > 0 ? tf("cli.log.dropped", { n: dropped }) : "";
236
+ }
237
+ /**
238
+ * 拼装最终文本:多行 + 可选「丢弃条目」说明,再统一脱敏(绝对路径 → `<path>`)。
239
+ * 空结果返回空串,由命令层给「可能无日志/已导航/在其它标签」的明确文案。
240
+ */
241
+ export function renderLogText(lines, dropped) {
242
+ const body = [lines.join("\n"), droppedNote(dropped)].filter(Boolean).join("\n");
243
+ if (!body)
244
+ return "";
245
+ // `file:///C:/x` / `file:///home/x` 里的绝对路径 sanitizeForModel 不会命中(URL 保护 + 前导 `/`),
246
+ // 在日志出口先整体掩码;http(s) URL 仍原样保留(模型需要看接口地址)。
247
+ return sanitizeForModel(body.replace(/\bfile:\/\/[^\s"'<>]+/gi, "<path>"), MAX_LOG_TEXT_CHARS);
248
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * `type`(向当前焦点插入文本,不清空)的纯逻辑:文本校验、`@file:` 解析、输出格式化。
3
+ *
4
+ * 文件读取与 containment 由调用方注入(`index.ts` 复用 `evaluate` 的 `readEvalFile`),
5
+ * 这里不含任何 IO,便于 `tests/unit/type-text.test.mjs` 直接调用 dist 产物。
6
+ * 上限与 Rust 侧 `keyboard.rs` 的 `TYPE_TEXT_MAX_BYTES` 同口径(8 KiB,按字节计)。
7
+ */
8
+ import { tf } from "../i18n/index.js";
9
+ /** 单次插入文本上限(字节;0 长度之外的入参超过即拒绝) */
10
+ export const TYPE_TEXT_MAX_BYTES = 8 * 1024;
11
+ /** `--text` 的文件引用前缀(与 `evaluate` 的 `@file:` 同形) */
12
+ export const TYPE_FILE_PREFIX = "@file:";
13
+ /**
14
+ * 校验待插入文本。
15
+ *
16
+ * @param text 实际要插入的文本(`@file:` 已解析后的内容)
17
+ * @returns `required`=空文本;`too_large`=超过 8 KiB;`null`=通过
18
+ */
19
+ export function typeTextIssue(text) {
20
+ if (text.length === 0)
21
+ return "required";
22
+ if (Buffer.byteLength(text, "utf-8") > TYPE_TEXT_MAX_BYTES)
23
+ return "too_large";
24
+ return null;
25
+ }
26
+ /**
27
+ * 解析 `--text`:`@file:<path>` 交给注入的读取器(与 `evaluate` 同一套 containment),
28
+ * 其余一律视为内联文本。
29
+ *
30
+ * @param raw 模型传入的原始 `--text` 值
31
+ * @param readFile 文件读取器(越界 / 超限 / 读失败都返回 `{error}`,由调用方复用 `readEvalFile`)
32
+ * @returns 插入文本,或可直接回模型的错误文案
33
+ */
34
+ export function resolveTypeText(raw, readFile) {
35
+ if (!raw.startsWith(TYPE_FILE_PREFIX))
36
+ return { text: raw };
37
+ const path = raw.slice(TYPE_FILE_PREFIX.length).trim();
38
+ if (!path)
39
+ return { error: tf("cli.err.type_text_required") };
40
+ const read = readFile(path);
41
+ if ("error" in read)
42
+ return { error: read.error };
43
+ return { text: read.content };
44
+ }
45
+ /**
46
+ * 渲染 `type` 的成功输出。
47
+ *
48
+ * @param inserted 服务端回报的插入字符数
49
+ * @param selector 本次显式聚焦的选择器(空串表示沿用当前焦点)
50
+ * @param entered 是否补发了 Enter
51
+ * @returns `typed N char(s) into <selector|focused element>[ + Enter]`
52
+ */
53
+ export function formatTypeOutput(inserted, selector, entered) {
54
+ const target = selector || tf("cli.out.type.focused");
55
+ const suffix = entered ? tf("cli.out.type.enter") : "";
56
+ return tf("cli.out.type", { n: inserted, target }) + suffix;
57
+ }
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@xiaoqiong0v0/opencode-browser-tool",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "opencode 浏览器工具插件:WebView2 外壳渲染 + 零注入视觉元素选取面板",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
7
7
  "build": "tsc",
8
8
  "dev": "tsc --watch",
9
+ "test": "npm run build && node --test \"tests/unit/*.test.mjs\"",
9
10
  "build:frontend": "cd frontend && npm install && npm run build"
10
11
  },
11
12
  "keywords": [