@dsh-workbench/adapter-runtime 0.0.0-stage → 1.0.0-beta.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-workbench contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # @dsh-workbench/adapter-runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 工作台运行时的强耦合适配器组合:opencli、browser、data。
4
+
5
+ ## 模块
6
+
7
+ ```text
8
+ src/cli/ opencli 命令、隔离运行时、窗口参数
9
+ src/browser/ 页面读取与查找
10
+ src/data/ DataReader(http / browser / command / recipe / 批量 recipe / 公共通道)
11
+ channel/ 随包出货的 opencli 插件(workbench fetch / workbench send)
12
+ ```
13
+
14
+ 三者共享命令解析、隔离路径、session 和错误形状,所以放在同一个包内,但保持独立目录。
15
+
16
+ `channel/` 不是源码目录:它是**资产**,不进 `tsc`、不进 barrel,只被复制进隔离运行时
17
+ (`plugins-npm` → peer symlink → `opencli plugin install`)。`cookie` / `cookieValue` 两种凭据来源
18
+ 的配方会先走它,跑不起来就回落页面脚本;`endpoint` / `meta` / `global` / `storage` 永远走页面脚本。
19
+
20
+ ## 入口
21
+
22
+ ```ts
23
+ import { createDataReader, browserRead, createOpencli } from '@dsh-workbench/adapter-runtime';
24
+ import { scriptOf, scriptOfMany, describeRecipe } from '@dsh-workbench/shared/host';
25
+ ```
26
+
27
+ ## 边界
28
+
29
+ 只依赖 `@dsh-workbench/shared`;不依赖 supply、profile、probe,也不依赖 core 内部。
30
+ `src/data` 可以依赖 `src/browser`,`src/browser` 可以依赖 `src/cli`,反向禁止。
31
+
32
+ ## 验证
33
+
34
+ ```bash
35
+ pnpm --filter @dsh-workbench/adapter-runtime run build
36
+ pnpm --filter @dsh-workbench/adapter-runtime run test
37
+ ```
@@ -0,0 +1,237 @@
1
+ export const API_VERSION = 1;
2
+
3
+ export const DEFAULT_TIMEOUT_MS = 25_000;
4
+ export const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
5
+ const MAX_MAX_BYTES = 8 * 1024 * 1024;
6
+
7
+ const CREDENTIAL_HEADERS = [
8
+ 'authorization',
9
+ 'cookie',
10
+ 'x-api-key',
11
+ 'x-auth-token',
12
+ 'x-csrf-token',
13
+ 'x-xsrf-token',
14
+ ];
15
+
16
+ function fail(code, message) {
17
+ return { ok: false, code, message };
18
+ }
19
+
20
+ function asRecord(value) {
21
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
22
+ }
23
+
24
+ function textOf(value) {
25
+ return typeof value === 'string' ? value.trim() : value === undefined || value === null ? '' : String(value);
26
+ }
27
+
28
+ function positiveIntOf(value, fallback, max) {
29
+ if (value === undefined || value === null || value === '') return fallback;
30
+ const number = Number(value);
31
+ if (!Number.isInteger(number) || number <= 0) throw new Error(`不是正整数:${String(value)}`);
32
+ if (max !== undefined && number > max) throw new Error(`超过上限 ${max}:${String(value)}`);
33
+ return number;
34
+ }
35
+
36
+ export function apiProblemOf(value) {
37
+ return Number(value) === API_VERSION
38
+ ? undefined
39
+ : `这条通道只认 --api ${API_VERSION},收到 ${textOf(value) || '(空)'}:壳与插件的版本对不上`;
40
+ }
41
+
42
+ export function headersOf(raw) {
43
+ const text = textOf(raw);
44
+ if (text === '') return {};
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(text);
48
+ } catch {
49
+ throw new Error('--headers 不是合法 JSON');
50
+ }
51
+ const record = asRecord(parsed);
52
+ if (record === undefined) throw new Error('--headers 要是对象');
53
+ const out = {};
54
+ for (const [name, value] of Object.entries(record)) {
55
+ if (name.trim() === '') throw new Error('--headers 的键不能为空');
56
+ if (typeof value !== 'string') throw new Error(`--headers.${name} 要是字符串`);
57
+ if (CREDENTIAL_HEADERS.includes(name.toLowerCase())) {
58
+ throw new Error(`--headers 里不许写凭据头 ${name}:凭据只能走 --jar / --cookie`);
59
+ }
60
+ out[name] = value;
61
+ }
62
+ return out;
63
+ }
64
+
65
+ export function urlOf(raw) {
66
+ const text = textOf(raw);
67
+ if (text === '') throw new Error('--url 不能为空');
68
+ let url;
69
+ try {
70
+ url = new URL(text);
71
+ } catch {
72
+ throw new Error(`--url 不是合法地址:${text}`);
73
+ }
74
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('--url 只认 http(s)');
75
+ return url;
76
+ }
77
+
78
+ export function domainsOf(url) {
79
+ const labels = url.hostname.split('.');
80
+ return labels.length > 2 ? [url.hostname, labels.slice(1).join('.')] : [url.hostname];
81
+ }
82
+
83
+ export async function jarOf(page, url) {
84
+ const jar = new Map();
85
+ for (const domain of domainsOf(url)) {
86
+ const cookies = await page.getCookies({ domain });
87
+ for (const cookie of cookies ?? []) {
88
+ if (typeof cookie?.name !== 'string' || typeof cookie.value !== 'string') continue;
89
+ if (!jar.has(cookie.name)) jar.set(cookie.name, cookie.value);
90
+ }
91
+ }
92
+ return jar;
93
+ }
94
+
95
+ function cookieHeaderOf(jar) {
96
+ return [...jar].map(([name, value]) => `${name}=${value}`).join('; ');
97
+ }
98
+
99
+ export function placeOf(raw) {
100
+ const text = textOf(raw);
101
+ if (text === '') return undefined;
102
+ const at = text.indexOf(':');
103
+ if (at <= 0) throw new Error(`--place 要是 header:<名> / query:<名> / body:<字段>,收到 ${text}`);
104
+ const where = text.slice(0, at);
105
+ const name = text.slice(at + 1);
106
+ if (name === '') throw new Error('--place 的键不能为空');
107
+ if (where !== 'header' && where !== 'query' && where !== 'body') {
108
+ throw new Error(`不认识的 --place:${where}(只认 header / query / body)`);
109
+ }
110
+ if (where === 'body' && name.includes('.')) {
111
+ throw new Error('--place body 只放顶层字段');
112
+ }
113
+ return { where, name };
114
+ }
115
+
116
+ function setBodyField(body, contentType, field, token) {
117
+ if (contentType === 'form') {
118
+ const params = new URLSearchParams(body === undefined ? '' : body);
119
+ params.set(field, token);
120
+ return params.toString();
121
+ }
122
+ let parsed;
123
+ try {
124
+ parsed = body === undefined || body === '' ? {} : JSON.parse(body);
125
+ } catch {
126
+ throw new Error('--place body 需要 --body 是 JSON 对象');
127
+ }
128
+ const record = asRecord(parsed);
129
+ if (record === undefined) throw new Error('--place body 需要 --body 是 JSON 对象');
130
+ record[field] = token;
131
+ return JSON.stringify(record);
132
+ }
133
+
134
+ function contentTypeOf(raw) {
135
+ const text = textOf(raw);
136
+ if (text === '' || text === 'json') return 'json';
137
+ if (text === 'form') return 'form';
138
+ throw new Error(`--content-type 只认 json / form,收到 ${text}`);
139
+ }
140
+
141
+ function tokenOf(jar, kwargs) {
142
+ const name = textOf(kwargs.cookie);
143
+ if (name === '') return undefined;
144
+ if (jar === undefined) throw new Error('--cookie 要配上 --jar cookie');
145
+ const token = jar.get(name);
146
+ if (token === undefined || token === '') {
147
+ throw new Error(`登录态里没有 cookie ${name}(可能是未登录,或者名字不对)`);
148
+ }
149
+ return token;
150
+ }
151
+
152
+ export async function perform(page, kwargs, method) {
153
+ const apiProblem = apiProblemOf(kwargs.api);
154
+ if (apiProblem !== undefined) throw new Error(apiProblem);
155
+ const url = urlOf(kwargs.url);
156
+ const headers = headersOf(kwargs.headers);
157
+ const jarMode = textOf(kwargs.jar || 'cookie');
158
+ if (jarMode !== 'cookie' && jarMode !== 'none') throw new Error(`--jar 只认 cookie / none,收到 ${jarMode}`);
159
+ const timeoutMs = positiveIntOf(kwargs.timeout, DEFAULT_TIMEOUT_MS);
160
+ const maxBytes = positiveIntOf(kwargs.maxBytes, DEFAULT_MAX_BYTES, MAX_MAX_BYTES);
161
+ const contentType = contentTypeOf(kwargs.contentType);
162
+ const place = placeOf(kwargs.place);
163
+ const prefix = textOf(kwargs.prefix);
164
+
165
+ const jar = jarMode === 'cookie' ? await jarOf(page, url) : undefined;
166
+ if (jar !== undefined) {
167
+ const cookie = cookieHeaderOf(jar);
168
+ if (cookie !== '') headers['cookie'] = cookie;
169
+ }
170
+
171
+ const token = tokenOf(jar, kwargs);
172
+ let body = textOf(kwargs.body) === '' ? undefined : String(kwargs.body);
173
+ let href = url.toString();
174
+
175
+ if (token !== undefined) {
176
+ if (place === undefined) throw new Error('给了 --cookie 就要给 --place');
177
+ if (place.where === 'header') headers[place.name] = prefix + token;
178
+ else if (place.where === 'query') {
179
+ const query = new URLSearchParams(url.search);
180
+ query.set(place.name, token);
181
+ url.search = query.toString();
182
+ href = url.toString();
183
+ } else {
184
+ body = setBodyField(body, contentType, place.name, token);
185
+ }
186
+ }
187
+
188
+ if (body !== undefined && !Object.keys(headers).some((name) => name.toLowerCase() === 'content-type')) {
189
+ headers['content-type'] = contentType === 'form' ? 'application/x-www-form-urlencoded' : 'application/json';
190
+ }
191
+
192
+ let response;
193
+ try {
194
+ response = await fetch(href, {
195
+ method,
196
+ headers,
197
+ redirect: 'follow',
198
+ signal: AbortSignal.timeout(timeoutMs),
199
+ ...(body === undefined ? {} : { body }),
200
+ });
201
+ } catch (error) {
202
+ if (error?.name === 'TimeoutError') return fail('timeout', `超过 ${Math.round(timeoutMs / 1000)} 秒没有返回`);
203
+ return fail('fetch-failed', error?.message || String(error));
204
+ }
205
+
206
+ const text = await response.text();
207
+ if (new TextEncoder().encode(text).length > maxBytes) {
208
+ return fail('too-large', `返回超过 ${Math.round(maxBytes / 1024)} KB`);
209
+ }
210
+ if (response.status === 401 || response.status === 403) return fail('not-logged-in', `HTTP ${response.status}`);
211
+ if (!response.ok) return fail(`http-${response.status}`, text.slice(0, 200));
212
+
213
+ const kind = textOf(kwargs.kind) === 'text' ? 'text' : 'json';
214
+ if (kind === 'text') return { ok: true, text };
215
+ try {
216
+ return { ok: true, data: JSON.parse(text) };
217
+ } catch {
218
+ return fail('shape', '返回的不是 JSON(可能跳到登录页了)');
219
+ }
220
+ }
221
+
222
+ export function argOf(name, extra = {}) {
223
+ return { name, ...extra };
224
+ }
225
+
226
+ export const SHARED_ARGS = [
227
+ argOf('api', { type: 'int', required: true, help: '通道协议版本(壳与插件对表用)' }),
228
+ argOf('url', { required: true, help: '绝对地址(http/https)' }),
229
+ argOf('jar', { default: 'cookie', help: 'cookie:带浏览器登录态;none:不带' }),
230
+ argOf('cookie', { help: '从登录态里取这一格的值当凭据(cookieValue 来源)' }),
231
+ argOf('place', { help: '凭据放哪:header:<名> / query:<名> / body:<字段>' }),
232
+ argOf('prefix', { help: '放在头里时的前缀,例如 "Bearer "' }),
233
+ argOf('headers', { help: '额外请求头(JSON;不许写凭据头)' }),
234
+ argOf('kind', { default: 'json', help: '响应形状:json / text' }),
235
+ argOf('timeout', { type: 'int', default: DEFAULT_TIMEOUT_MS, help: '超时毫秒' }),
236
+ argOf('maxBytes', { type: 'int', default: DEFAULT_MAX_BYTES, help: '响应体上限(字节)' }),
237
+ ];
@@ -0,0 +1,14 @@
1
+ import { cli } from '@jackwener/opencli/registry';
2
+ import { perform, SHARED_ARGS } from './core.js';
3
+
4
+ cli({
5
+ site: 'workbench',
6
+ name: 'fetch',
7
+ access: 'read',
8
+ description: '用浏览器登录态在 Node 侧发一条 GET(工作台配方通道)',
9
+ browser: true,
10
+ navigateBefore: false,
11
+ defaultFormat: 'json',
12
+ args: SHARED_ARGS,
13
+ func: async (page, kwargs) => perform(page, kwargs, 'GET'),
14
+ });
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "workbench",
3
+ "version": "0.1.0",
4
+ "description": "DSH 工作台的公共通道:用浏览器登录态在 Node 侧发请求",
5
+ "opencli": ">=1.8.0 <2.0.0"
6
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "opencli-plugin-workbench",
3
+ "version": "1.0.0-beta.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "DSH 工作台的公共通道:带浏览器登录态的 Node 侧 fetch,只服务 cookie / cookieValue 两种凭据来源",
7
+ "peerDependencies": {
8
+ "@jackwener/opencli": ">=1.8.0 <2.0.0"
9
+ }
10
+ }
@@ -0,0 +1,27 @@
1
+ import { cli } from '@jackwener/opencli/registry';
2
+ import { perform, SHARED_ARGS } from './core.js';
3
+
4
+ const WRITE_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];
5
+
6
+ cli({
7
+ site: 'workbench',
8
+ name: 'send',
9
+ access: 'write',
10
+ description: '用浏览器登录态在 Node 侧发一条写请求(工作台配方通道;只有写工具会调它)',
11
+ browser: true,
12
+ navigateBefore: false,
13
+ defaultFormat: 'json',
14
+ args: [
15
+ ...SHARED_ARGS,
16
+ { name: 'method', required: true, help: `写方法:${WRITE_METHODS.join(' / ')}` },
17
+ { name: 'body', help: '请求体(json 时是 JSON 字符串,form 时是 k=v&k=v)' },
18
+ { name: 'contentType', default: 'json', help: '请求体类型:json / form' },
19
+ ],
20
+ func: async (page, kwargs) => {
21
+ const method = String(kwargs.method ?? '').toUpperCase();
22
+ if (!WRITE_METHODS.includes(method)) {
23
+ throw new Error(`--method 只认 ${WRITE_METHODS.join(' / ')},收到 ${String(kwargs.method ?? '')}`);
24
+ }
25
+ return perform(page, kwargs, method);
26
+ },
27
+ });
@@ -0,0 +1,38 @@
1
+ import type { DshShell } from '@dsh-workbench/shared';
2
+ export interface BrowserFindEntry {
3
+ readonly text: string;
4
+ readonly tag: string;
5
+ readonly nth: number;
6
+ }
7
+ export interface BrowserFindResult {
8
+ readonly ok: boolean;
9
+ readonly code: string;
10
+ readonly at: number;
11
+ readonly entries: readonly BrowserFindEntry[];
12
+ readonly count: number;
13
+ readonly message: string;
14
+ readonly hint?: string;
15
+ readonly detail?: string;
16
+ readonly helpUrl?: string;
17
+ }
18
+ export interface BrowserFindOptions {
19
+ readonly shell: DshShell;
20
+ readonly css: string;
21
+ readonly url?: string;
22
+ readonly command?: string;
23
+ readonly session?: string;
24
+ readonly limit?: number;
25
+ readonly textMax?: number;
26
+ readonly open?: boolean;
27
+ readonly timeoutMs?: number;
28
+ readonly settleMs?: number;
29
+ }
30
+ export declare function cellRowsOf(entries: readonly {
31
+ readonly text?: string;
32
+ }[], minCells?: number): string[][];
33
+ export declare function cellRows(text: string): string[];
34
+ export declare function entriesOf(value: unknown): BrowserFindEntry[];
35
+ export declare function reasonOf(stdout: string, stderr: string): string;
36
+ export declare function sameOrigin(left: string, right: string): boolean;
37
+ export declare function urlOf(stdout: string): string;
38
+ export declare function browserFind(options: BrowserFindOptions): Promise<BrowserFindResult>;
@@ -0,0 +1,242 @@
1
+ import { parseJsonLoose } from '@dsh-workbench/shared/host';
2
+ import { BROWSER_READ_SESSION } from './browser-read.js';
3
+ import { backgroundLine } from '../cli/index.js';
4
+ import { runShell } from '@dsh-workbench/shared/host';
5
+ const DEFAULT_TIMEOUT_MS = 25000;
6
+ const DEFAULT_SETTLE_MS = 2500;
7
+ const URL_TIMEOUT_MS = 8000;
8
+ const DEFAULT_LIMIT = 50;
9
+ const DEFAULT_TEXT_MAX = 200;
10
+ export function cellRowsOf(entries, minCells = 2) {
11
+ const rows = [];
12
+ for (const entry of entries) {
13
+ const text = typeof entry?.text === 'string' ? entry.text : '';
14
+ const cells = text
15
+ .split('\n')
16
+ .map((one) => one.trim())
17
+ .filter((one) => one !== '');
18
+ if (cells.length >= minCells)
19
+ rows.push(cells);
20
+ }
21
+ return rows;
22
+ }
23
+ export function cellRows(text) {
24
+ return text
25
+ .split('\n')
26
+ .map((one) => one.trim())
27
+ .filter((one) => one !== '');
28
+ }
29
+ function asRecord(value) {
30
+ return typeof value === 'object' && value !== null ? value : undefined;
31
+ }
32
+ function textOf(value) {
33
+ return typeof value === 'string' ? value.trim() : '';
34
+ }
35
+ export function entriesOf(value) {
36
+ const record = asRecord(value);
37
+ const raw = record === undefined ? undefined : record['entries'];
38
+ if (!Array.isArray(raw))
39
+ return [];
40
+ const entries = [];
41
+ for (const one of raw) {
42
+ const item = asRecord(one);
43
+ if (item === undefined)
44
+ continue;
45
+ const nth = typeof item['nth'] === 'number' ? item['nth'] : entries.length;
46
+ entries.push({ text: textOf(item['text']), tag: textOf(item['tag']), nth });
47
+ }
48
+ return entries;
49
+ }
50
+ export function reasonOf(stdout, stderr) {
51
+ const parsed = asRecord(parseJsonLoose(stdout));
52
+ const error = parsed === undefined ? undefined : asRecord(parsed['error']);
53
+ const message = error === undefined ? '' : textOf(error['message']);
54
+ if (message !== '')
55
+ return message;
56
+ const source = stderr.trim() === '' ? stdout : stderr;
57
+ const lines = source
58
+ .split('\n')
59
+ .map((one) => one.trim())
60
+ .filter((one) => one !== '');
61
+ return (lines[lines.length - 1] ?? '').slice(-200);
62
+ }
63
+ function hintOf(stdout) {
64
+ const parsed = asRecord(parseJsonLoose(stdout));
65
+ const error = parsed === undefined ? undefined : asRecord(parsed['error']);
66
+ const hint = error === undefined ? '' : textOf(error['hint']);
67
+ return hint === '' ? undefined : hint;
68
+ }
69
+ export function sameOrigin(left, right) {
70
+ try {
71
+ return new URL(left).origin === new URL(right).origin;
72
+ }
73
+ catch {
74
+ return false;
75
+ }
76
+ }
77
+ export function urlOf(stdout) {
78
+ const lines = stdout
79
+ .split('\n')
80
+ .map((one) => one.trim())
81
+ .filter((one) => one !== '');
82
+ const first = (lines[0] ?? '').replace(/^url:\s*/i, '').trim();
83
+ const bare = first.replace(/^["']+|["']+$/g, '');
84
+ if (bare.startsWith('{')) {
85
+ const parsed = asRecord(parseJsonLoose(bare));
86
+ const url = parsed === undefined ? '' : textOf(parsed['url']);
87
+ if (url !== '')
88
+ return url;
89
+ }
90
+ return bare;
91
+ }
92
+ async function currentUrl(shell, command, session) {
93
+ const line = backgroundLine(command, ['browser', session, 'get', 'url', '--window', 'background']);
94
+ try {
95
+ const result = await runShell(shell, line, { timeoutMs: URL_TIMEOUT_MS });
96
+ if (result.exitCode !== 0)
97
+ return '';
98
+ return urlOf(result.stdout);
99
+ }
100
+ catch {
101
+ return '';
102
+ }
103
+ }
104
+ function sleep(ms) {
105
+ return new Promise((resolve) => setTimeout(resolve, ms));
106
+ }
107
+ async function findOnce(shell, command, session, css, limit, textMax, timeoutMs) {
108
+ const line = backgroundLine(command, [
109
+ 'browser',
110
+ session,
111
+ 'find',
112
+ '--css',
113
+ css,
114
+ '--limit',
115
+ String(limit),
116
+ '--text-max',
117
+ String(textMax),
118
+ '--window',
119
+ 'background',
120
+ ]);
121
+ const result = await runShell(shell, line, { timeoutMs });
122
+ if (result.timedOut) {
123
+ return { kind: 'timeout', detail: `没在 ${Math.round(timeoutMs / 1000)} 秒内返回` };
124
+ }
125
+ if (result.exitCode !== 0) {
126
+ return {
127
+ kind: 'failed',
128
+ detail: reasonOf(result.stdout, result.stderr),
129
+ ...(hintOf(result.stdout) === undefined ? {} : { hint: hintOf(result.stdout) }),
130
+ };
131
+ }
132
+ const entries = entriesOf(parseJsonLoose(result.stdout));
133
+ return { kind: 'ok', entries, stdout: result.stdout };
134
+ }
135
+ async function openOnce(shell, command, session, url, timeoutMs) {
136
+ const line = backgroundLine(command, ['browser', session, 'open', url, '--window', 'background']);
137
+ let result;
138
+ try {
139
+ result = await runShell(shell, line, { timeoutMs });
140
+ }
141
+ catch (error) {
142
+ return error instanceof Error ? error.message : String(error);
143
+ }
144
+ if (result.timedOut)
145
+ return `没在 ${Math.round(timeoutMs / 1000)} 秒内打开`;
146
+ if (result.exitCode !== 0) {
147
+ const reason = reasonOf(result.stdout, result.stderr);
148
+ return reason === '' ? `opencli 打开失败(退出码 ${String(result.exitCode ?? '?')})` : reason;
149
+ }
150
+ return undefined;
151
+ }
152
+ export async function browserFind(options) {
153
+ const { shell, css, url, open = true } = options;
154
+ const command = options.command ?? 'opencli';
155
+ const session = options.session ?? BROWSER_READ_SESSION;
156
+ const limit = options.limit ?? DEFAULT_LIMIT;
157
+ const textMax = options.textMax ?? DEFAULT_TEXT_MAX;
158
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
159
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
160
+ const at = Date.now();
161
+ const find = async () => {
162
+ try {
163
+ return await findOnce(shell, command, session, css, limit, textMax, timeoutMs);
164
+ }
165
+ catch (error) {
166
+ return {
167
+ kind: 'failed',
168
+ detail: error instanceof Error ? error.message : String(error),
169
+ hint: '确认后台服务能跑起来,再重试',
170
+ };
171
+ }
172
+ };
173
+ const canMove = open && url !== undefined;
174
+ if (canMove) {
175
+ const here = await currentUrl(shell, command, session);
176
+ if (here !== '' && !sameOrigin(here, url)) {
177
+ const opened = await openOnce(shell, command, session, url, timeoutMs);
178
+ if (opened !== undefined) {
179
+ return {
180
+ ok: false,
181
+ code: 'cli-exec-failed',
182
+ at,
183
+ entries: [],
184
+ count: 0,
185
+ message: '打不开那个页面',
186
+ hint: '在浏览器里手动打开一次,然后重试',
187
+ detail: opened,
188
+ helpUrl: url,
189
+ };
190
+ }
191
+ await sleep(settleMs);
192
+ }
193
+ }
194
+ let outcome = await find();
195
+ if (outcome === undefined) {
196
+ return { ok: false, code: 'cli-exec-failed', at, entries: [], count: 0, message: '没找到元素' };
197
+ }
198
+ if (outcome.kind === 'failed' && canMove) {
199
+ const opened = await openOnce(shell, command, session, url, timeoutMs);
200
+ if (opened === undefined) {
201
+ await sleep(settleMs);
202
+ const second = await find();
203
+ if (second !== undefined)
204
+ outcome = second;
205
+ }
206
+ }
207
+ if (outcome.kind === 'timeout') {
208
+ return {
209
+ ok: false,
210
+ code: 'cli-timeout',
211
+ at,
212
+ entries: [],
213
+ count: 0,
214
+ message: '这次没找到元素(等超时了)',
215
+ hint: '稍后重试',
216
+ detail: outcome.detail,
217
+ ...(url === undefined ? {} : { helpUrl: url }),
218
+ };
219
+ }
220
+ if (outcome.kind === 'failed') {
221
+ const detail = outcome.detail;
222
+ return {
223
+ ok: false,
224
+ code: 'cli-exec-failed',
225
+ at,
226
+ entries: [],
227
+ count: 0,
228
+ message: detail === '' ? '没找到元素(opencli 命令失败)' : `没找到元素:${detail}`,
229
+ ...(outcome.hint === undefined ? {} : { hint: outcome.hint }),
230
+ ...(detail === '' ? {} : { detail }),
231
+ ...(url === undefined ? {} : { helpUrl: url }),
232
+ };
233
+ }
234
+ return {
235
+ ok: true,
236
+ code: 'ok',
237
+ at,
238
+ entries: outcome.entries,
239
+ count: outcome.entries.length,
240
+ message: outcome.entries.length === 0 ? '页面上没有匹配的元素' : `找到 ${String(outcome.entries.length)} 个元素`,
241
+ };
242
+ }
@@ -0,0 +1,27 @@
1
+ import type { DshShell } from '@dsh-workbench/shared';
2
+ import { BROWSER_READ_SESSION, BROWSER_RECORD_SESSION, BROWSER_SCREEN_SESSION } from '@dsh-workbench/shared/host';
3
+ export { BROWSER_READ_SESSION, BROWSER_RECORD_SESSION, BROWSER_SCREEN_SESSION };
4
+ export interface BrowserReadResult {
5
+ readonly ok: boolean;
6
+ readonly code: string;
7
+ readonly at: number;
8
+ readonly value?: unknown;
9
+ readonly pageCode?: string;
10
+ readonly message: string;
11
+ readonly hint?: string;
12
+ readonly detail?: string;
13
+ readonly helpUrl?: string;
14
+ }
15
+ export interface BrowserReadOptions {
16
+ readonly shell: DshShell;
17
+ readonly script: string;
18
+ readonly url?: string;
19
+ readonly loginUrl?: string;
20
+ readonly command?: string;
21
+ readonly session?: string;
22
+ readonly open?: boolean;
23
+ readonly timeoutMs?: number;
24
+ readonly retryMs?: number;
25
+ readonly settleMs?: number;
26
+ }
27
+ export declare function browserRead(options: BrowserReadOptions): Promise<BrowserReadResult>;