@xbrowser/cli 1.28.0 → 1.29.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/dist/{browser-NYYCR4O7.js → browser-2K3XYAKM.js} +5 -3
- package/dist/{browser-ZD53IMUJ.js → browser-OTEMG5NL.js} +6 -4
- package/dist/{browser-4IYIHZ6R.js → browser-XD3IOU5I.js} +8 -6
- package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-AAS55KT2.js} +4 -4
- package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-O5I7SJ24.js} +3 -3
- package/dist/{cdp-driver-HB744QB4.js → cdp-driver-XTPY7EXP.js} +1296 -852
- package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
- package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
- package/dist/{chunk-3PUOISKE.js → chunk-CO2ZVOVT.js} +496 -452
- package/dist/{chunk-V6KGBU5J.js → chunk-FCPVQFTQ.js} +1011 -1038
- package/dist/{chunk-WK3INZLA.js → chunk-GDKKVT2P.js} +750 -651
- package/dist/{chunk-HSYRAV3H.js → chunk-LFSLNHW5.js} +1846 -1358
- package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
- package/dist/{chunk-J3HXZVSN.js → chunk-N5XTLNKS.js} +1166 -868
- package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
- package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
- package/dist/{chunk-ME5FO5YV.js → chunk-NQPXZ74W.js} +1296 -852
- package/dist/{chunk-KECYFWJO.js → chunk-P33R7F2D.js} +413 -384
- package/dist/{chunk-OEC7ZSFW.js → chunk-SCYBNSOG.js} +1560 -1461
- package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
- package/dist/{chunk-IR6C24P7.js → chunk-UZ6XPUBD.js} +1030 -1048
- package/dist/cli.js +3398 -3357
- package/dist/daemon-main.js +737 -707
- package/dist/index.d.ts +362 -474
- package/dist/index.js +5730 -5689
- package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
- package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
- package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
- package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
- package/dist/{server-JXF3JOAM.js → server-LNZTDAKT.js} +4 -4
- package/dist/{server-26SE6YZR.js → server-ZTI2K5YJ.js} +7 -7
- package/dist/{session-recorder-GEZVQBKW.js → session-recorder-DF2YGH2E.js} +1 -1
- package/dist/{session-recorder-563ISSJK.js → session-recorder-R3GDGXLJ.js} +1 -1
- package/dist/{session-replayer-TXTNTG33.js → session-replayer-CLTZ2URU.js} +1 -1
- package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
- package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
- package/package.json +6 -3
|
@@ -20,171 +20,25 @@ import {
|
|
|
20
20
|
resolveLaunchOpts,
|
|
21
21
|
saveSessionDiskMeta,
|
|
22
22
|
setActivePage
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-LFSLNHW5.js";
|
|
24
24
|
import {
|
|
25
25
|
rand,
|
|
26
26
|
sleep,
|
|
27
27
|
wheelDelta
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-SMYSNO4M.js";
|
|
29
29
|
import {
|
|
30
30
|
errMsg
|
|
31
31
|
} from "./chunk-GDKLH7ZY.js";
|
|
32
32
|
|
|
33
|
-
// src/fail-codes.ts
|
|
34
|
-
var FAIL_CODES = {
|
|
35
|
-
selectorNotFound: "RETRYABLE: selector-not-found",
|
|
36
|
-
pageNotReady: "RETRYABLE: page-not-ready",
|
|
37
|
-
elementGone: "RETRYABLE: element-gone",
|
|
38
|
-
inputNotRetained: "RETRYABLE: input-not-retained",
|
|
39
|
-
captcha: "HUMAN: captcha",
|
|
40
|
-
loginWall: "HUMAN: login-wall",
|
|
41
|
-
permissionDenied: "FATAL: permission-denied",
|
|
42
|
-
targetGone: "FATAL: target-gone",
|
|
43
|
-
unknown: "FATAL: unknown"
|
|
44
|
-
};
|
|
45
|
-
function classifyFailure(message) {
|
|
46
|
-
const msg = (message || "").toLowerCase();
|
|
47
|
-
const pick = (code) => ({
|
|
48
|
-
code,
|
|
49
|
-
level: code.split(":")[0],
|
|
50
|
-
message: message || code
|
|
51
|
-
});
|
|
52
|
-
if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
|
|
53
|
-
if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
|
|
54
|
-
if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
|
|
55
|
-
if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
|
|
56
|
-
return pick(FAIL_CODES.selectorNotFound);
|
|
57
|
-
if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
|
|
58
|
-
if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
|
|
59
|
-
if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
|
|
60
|
-
return pick(FAIL_CODES.targetGone);
|
|
61
|
-
return pick(FAIL_CODES.unknown);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
33
|
// src/executor.ts
|
|
65
34
|
import {
|
|
66
|
-
ok as
|
|
67
|
-
fail as
|
|
35
|
+
ok as ok33,
|
|
36
|
+
fail as fail19,
|
|
68
37
|
isCommandResult,
|
|
69
|
-
|
|
70
|
-
TipCollector as
|
|
71
|
-
normalizeTips as normalizeTips7,
|
|
72
|
-
configureArchiveStore,
|
|
73
|
-
appendCommandToArchive,
|
|
74
|
-
checkGuard,
|
|
75
|
-
unquote as unquote2
|
|
38
|
+
normalizeTips as normalizeTips8,
|
|
39
|
+
TipCollector as TipCollector3
|
|
76
40
|
} from "@dyyz1993/xcli-core";
|
|
77
41
|
|
|
78
|
-
// src/utils/positional-params.ts
|
|
79
|
-
import { unquote } from "@dyyz1993/xcli-core";
|
|
80
|
-
function getTypeName(field) {
|
|
81
|
-
return field?._def?.typeName;
|
|
82
|
-
}
|
|
83
|
-
function unwrapField(field) {
|
|
84
|
-
const typeName = getTypeName(field);
|
|
85
|
-
if (typeName === "ZodOptional" || typeName === "ZodDefault") {
|
|
86
|
-
const innerType = field?._def?.innerType;
|
|
87
|
-
return unwrapField(innerType);
|
|
88
|
-
}
|
|
89
|
-
return field;
|
|
90
|
-
}
|
|
91
|
-
function isOptionalNumber(field) {
|
|
92
|
-
const typeName = getTypeName(field);
|
|
93
|
-
return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
|
|
94
|
-
}
|
|
95
|
-
function coerceValue(raw, field) {
|
|
96
|
-
const inner = unwrapField(field);
|
|
97
|
-
const optionalNum = isOptionalNumber(field);
|
|
98
|
-
const innerTypeName = getTypeName(inner);
|
|
99
|
-
if (innerTypeName === "ZodString") {
|
|
100
|
-
return { value: unquote(raw), skip: false };
|
|
101
|
-
}
|
|
102
|
-
if (innerTypeName === "ZodNumber") {
|
|
103
|
-
const parsed = Number(raw);
|
|
104
|
-
if (isNaN(parsed)) {
|
|
105
|
-
if (optionalNum) return { value: void 0, skip: true };
|
|
106
|
-
return { value: raw, skip: false };
|
|
107
|
-
}
|
|
108
|
-
return { value: parsed, skip: false };
|
|
109
|
-
}
|
|
110
|
-
if (innerTypeName === "ZodBoolean") {
|
|
111
|
-
if (raw === "true" || raw === "1") return { value: true, skip: false };
|
|
112
|
-
if (raw === "false" || raw === "0") return { value: false, skip: false };
|
|
113
|
-
return { value: raw, skip: false };
|
|
114
|
-
}
|
|
115
|
-
return { value: unquote(raw), skip: false };
|
|
116
|
-
}
|
|
117
|
-
function mapPositionalValues(schema, positional, existing) {
|
|
118
|
-
const result = { ...existing };
|
|
119
|
-
if (!schema || typeof schema !== "object") return result;
|
|
120
|
-
const shape = schema.shape;
|
|
121
|
-
if (!shape || typeof shape !== "object") return result;
|
|
122
|
-
const keys = Object.keys(shape);
|
|
123
|
-
let pIdx = 0;
|
|
124
|
-
for (const key of keys) {
|
|
125
|
-
if (pIdx >= positional.length) break;
|
|
126
|
-
if (result[key] !== void 0) {
|
|
127
|
-
pIdx++;
|
|
128
|
-
continue;
|
|
129
|
-
}
|
|
130
|
-
const field = shape[key];
|
|
131
|
-
const raw = positional[pIdx];
|
|
132
|
-
const { value, skip } = coerceValue(raw, field);
|
|
133
|
-
if (skip) continue;
|
|
134
|
-
result[key] = value;
|
|
135
|
-
pIdx++;
|
|
136
|
-
}
|
|
137
|
-
return result;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// src/utils/plugin-params.ts
|
|
141
|
-
function parsePluginParams(args, schema, base = {}) {
|
|
142
|
-
const params = { ...base };
|
|
143
|
-
const positionalValues = [];
|
|
144
|
-
for (let i = 0; i < args.length; i++) {
|
|
145
|
-
if (args[i] === "--" && args[i + 1]) {
|
|
146
|
-
try {
|
|
147
|
-
Object.assign(params, JSON.parse(args[i + 1]));
|
|
148
|
-
} catch {
|
|
149
|
-
}
|
|
150
|
-
break;
|
|
151
|
-
}
|
|
152
|
-
if (args[i].startsWith("--")) {
|
|
153
|
-
const key = args[i].slice(2);
|
|
154
|
-
const value = args[i + 1];
|
|
155
|
-
if (value && !value.startsWith("-")) {
|
|
156
|
-
if (value === "true") params[key] = true;
|
|
157
|
-
else if (value === "false") params[key] = false;
|
|
158
|
-
else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
|
|
159
|
-
else {
|
|
160
|
-
try {
|
|
161
|
-
const parsed = JSON.parse(value);
|
|
162
|
-
if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
|
|
163
|
-
params[key] = parsed;
|
|
164
|
-
} else {
|
|
165
|
-
params[key] = value;
|
|
166
|
-
}
|
|
167
|
-
} catch {
|
|
168
|
-
params[key] = value;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
i++;
|
|
172
|
-
} else {
|
|
173
|
-
params[key] = true;
|
|
174
|
-
}
|
|
175
|
-
} else if (!args[i].startsWith("-")) {
|
|
176
|
-
positionalValues.push(args[i]);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
Object.assign(params, mapPositionalValues(schema, positionalValues, params));
|
|
180
|
-
const result = {};
|
|
181
|
-
for (const [k, v] of Object.entries(params)) {
|
|
182
|
-
const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
183
|
-
result[camelKey] = v;
|
|
184
|
-
}
|
|
185
|
-
return result;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
42
|
// src/utils/stub-context.ts
|
|
189
43
|
import { join } from "path";
|
|
190
44
|
import { homedir } from "os";
|
|
@@ -1468,14 +1322,14 @@ var preflightCommand = registerCommand({
|
|
|
1468
1322
|
let pageUrl = null;
|
|
1469
1323
|
try {
|
|
1470
1324
|
const { fileURLToPath } = await import("url");
|
|
1471
|
-
const { join:
|
|
1472
|
-
const { existsSync:
|
|
1325
|
+
const { join: join10, dirname: dirname4 } = await import("path");
|
|
1326
|
+
const { existsSync: existsSync8 } = await import("fs");
|
|
1473
1327
|
const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
|
|
1474
1328
|
const candidates = [
|
|
1475
|
-
|
|
1476
|
-
|
|
1329
|
+
join10(dirname4(here), "..", "assets", "preflight.html"),
|
|
1330
|
+
join10(process.cwd(), "assets", "preflight.html")
|
|
1477
1331
|
];
|
|
1478
|
-
pageUrl = candidates.find((c) =>
|
|
1332
|
+
pageUrl = candidates.find((c) => existsSync8(c)) || null;
|
|
1479
1333
|
} catch {
|
|
1480
1334
|
}
|
|
1481
1335
|
if (pageUrl) {
|
|
@@ -4467,6 +4321,8 @@ var networkCommand = registerCommand({
|
|
|
4467
4321
|
|
|
4468
4322
|
// src/commands/ai-search-engines.ts
|
|
4469
4323
|
import { z as z24 } from "zod";
|
|
4324
|
+
|
|
4325
|
+
// src/commands/ai-engine-configs.ts
|
|
4470
4326
|
var ENGINE_CONFIGS = {
|
|
4471
4327
|
deepseek: {
|
|
4472
4328
|
key: "deepseek",
|
|
@@ -4719,6 +4575,8 @@ var ENGINE_CONFIGS = {
|
|
|
4719
4575
|
sendButtonSelector: "button.send-btn"
|
|
4720
4576
|
}
|
|
4721
4577
|
};
|
|
4578
|
+
|
|
4579
|
+
// src/commands/ai-search-engines.ts
|
|
4722
4580
|
var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
|
|
4723
4581
|
var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
|
|
4724
4582
|
|
|
@@ -5890,12 +5748,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
|
|
|
5890
5748
|
{"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
|
|
5891
5749
|
{"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
|
|
5892
5750
|
{"action":"done","value":"\u5B8C\u6210\u6458\u8981","thought":"\u4E3A\u4EC0\u4E48"}
|
|
5751
|
+
{"action":"back","thought":"\u70B9\u9519\u4E86/\u8DF3\u8F6C\u9519\u4E86\uFF0C\u8FD4\u56DE\u4E0A\u4E00\u9875\u91CD\u8BD5"}
|
|
5893
5752
|
{"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
|
|
5894
5753
|
|
|
5895
5754
|
\u89C4\u5219\uFF1A
|
|
5896
5755
|
1. ref \u5FC5\u987B\u539F\u6837\u6765\u81EA\u672C\u6B21\u5143\u7D20\u6E05\u5355\uFF1B\u6E05\u5355\u91CC\u6CA1\u6709\u80FD\u63A8\u8FDB\u76EE\u6807\u7684\u5143\u7D20\u5C31\u8F93\u51FA blocked\u3002
|
|
5897
5756
|
2. \u76EE\u6807\u5DF2\u5B8C\u6210\uFF08\u9875\u9762\u4E0A\u80FD\u786E\u8BA4\u7ED3\u679C\uFF09\u5C31\u8F93\u51FA done\uFF0Cvalue \u5199\u5B8C\u6210\u6458\u8981\u3002
|
|
5898
|
-
3. \u4E0D\u8981\u91CD\u590D\u521A\u5931\u8D25\u8FC7\u7684\u540C\u4E00\u52A8\u4F5C\uFF1B\u8FDE\u7EED\u5931\u8D25\u6362\u601D\u8DEF\u6216 blocked\u3002`;
|
|
5757
|
+
3. \u4E0D\u8981\u91CD\u590D\u521A\u5931\u8D25\u8FC7\u7684\u540C\u4E00\u52A8\u4F5C\uFF1B\u52A8\u4F5C\u540E\u9875\u9762\u8DF3\u5230\u4E86\u610F\u6599\u4E4B\u5916\u7684\u5730\u65B9\u5C31\u8F93\u51FA back \u8FD4\u56DE\u91CD\u8BD5\uFF1B\u8FDE\u7EED\u5931\u8D25\u6362\u601D\u8DEF\u6216 blocked\u3002`;
|
|
5899
5758
|
function extractDecision(raw) {
|
|
5900
5759
|
let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
|
|
5901
5760
|
const start = s.indexOf("{");
|
|
@@ -5946,6 +5805,7 @@ var taskCommand = registerCommand({
|
|
|
5946
5805
|
let status = "max_steps";
|
|
5947
5806
|
let summary = "";
|
|
5948
5807
|
let lastError = "";
|
|
5808
|
+
let emptyReplies = 0;
|
|
5949
5809
|
for (let step = 1; step <= p.maxSteps; step++) {
|
|
5950
5810
|
if (Date.now() - started > p.timeout) {
|
|
5951
5811
|
status = "blocked";
|
|
@@ -5965,7 +5825,7 @@ ${history.slice(-6).join("\n")}` : ""
|
|
|
5965
5825
|
].filter(Boolean).join("\n");
|
|
5966
5826
|
let raw = "";
|
|
5967
5827
|
try {
|
|
5968
|
-
raw = await
|
|
5828
|
+
raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
|
|
5969
5829
|
|
|
5970
5830
|
---
|
|
5971
5831
|
|
|
@@ -5979,6 +5839,12 @@ ${userPayload}` }], 900);
|
|
|
5979
5839
|
}
|
|
5980
5840
|
const decision = extractDecision(raw);
|
|
5981
5841
|
if (!decision || typeof decision.action !== "string") {
|
|
5842
|
+
if (!raw.trim() && emptyReplies < 2) {
|
|
5843
|
+
emptyReplies++;
|
|
5844
|
+
steps.push({ step, action: "(empty reply, re-observe)", ok: false, screenHash: obs.screenHash });
|
|
5845
|
+
history.push(`step${step}: (empty reply, retrying)`);
|
|
5846
|
+
continue;
|
|
5847
|
+
}
|
|
5982
5848
|
status = "blocked";
|
|
5983
5849
|
summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
|
|
5984
5850
|
break;
|
|
@@ -5993,6 +5859,13 @@ ${userPayload}` }], 900);
|
|
|
5993
5859
|
steps.push({ step, thought, action: "done", ok: true, screenHash });
|
|
5994
5860
|
break;
|
|
5995
5861
|
}
|
|
5862
|
+
if (action === "back") {
|
|
5863
|
+
await ctx.page?.goBack?.().catch?.(() => {
|
|
5864
|
+
});
|
|
5865
|
+
steps.push({ step, thought, action: "back", ok: true, screenHash });
|
|
5866
|
+
history.push(`step${step}: back (\u8FD4\u56DE\u4E0A\u4E00\u9875)`);
|
|
5867
|
+
continue;
|
|
5868
|
+
}
|
|
5996
5869
|
if (action === "blocked") {
|
|
5997
5870
|
status = "blocked";
|
|
5998
5871
|
summary = value || thought || "LLM judged blocked";
|
|
@@ -6733,6 +6606,8 @@ var visualTagCommand = registerCommand({
|
|
|
6733
6606
|
// src/commands/visual-tag-v2.ts
|
|
6734
6607
|
import { z as z32 } from "zod";
|
|
6735
6608
|
import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
|
|
6609
|
+
|
|
6610
|
+
// src/commands/visual-tag-v2-script.ts
|
|
6736
6611
|
var SAFE_SET2 = "ahjkmnprtw3479".split("");
|
|
6737
6612
|
var TAG_V2_SCRIPT = `
|
|
6738
6613
|
(function() {
|
|
@@ -7075,7 +6950,9 @@ var TAG_V2_SCRIPT = `
|
|
|
7075
6950
|
return JSON.stringify(window.__xbTagStats);
|
|
7076
6951
|
})()
|
|
7077
6952
|
`;
|
|
7078
|
-
|
|
6953
|
+
|
|
6954
|
+
// src/commands/visual-tag-v2.ts
|
|
6955
|
+
registerCommand({
|
|
7079
6956
|
name: "visual-tag-v2",
|
|
7080
6957
|
description: "\u5206\u8272\u6807\u6CE8\u9875\u9762\u5143\u7D20\uFF08\u7EA2=\u53EF\u70B9\u51FB \u84DD=\u8F93\u5165 \u7EFF=\u56FE\u7247 \u9EC4=\u5217\u8868 \u7D2B=\u6570\u5B57 \u6A59=\u6587\u672C\uFF09",
|
|
7081
6958
|
scope: "page",
|
|
@@ -7308,1085 +7185,1606 @@ function attachDetectAntiBot(ctx) {
|
|
|
7308
7185
|
};
|
|
7309
7186
|
}
|
|
7310
7187
|
|
|
7311
|
-
// src/
|
|
7312
|
-
|
|
7313
|
-
|
|
7314
|
-
|
|
7315
|
-
|
|
7316
|
-
import { existsSync as existsSync6, readdirSync } from "fs";
|
|
7317
|
-
import { homedir as homedir5 } from "os";
|
|
7188
|
+
// src/tips/dom-watcher.ts
|
|
7189
|
+
var DOM_WATCHER_SCRIPT = `
|
|
7190
|
+
(function() {
|
|
7191
|
+
if (window.__xbrowserDomWatcher) return;
|
|
7192
|
+
window.__xbrowserDomWatcher = true;
|
|
7318
7193
|
|
|
7319
|
-
|
|
7320
|
-
import { existsSync as existsSync4 } from "fs";
|
|
7321
|
-
import { resolve } from "path";
|
|
7194
|
+
window.__xbrowserDetectedElements = [];
|
|
7322
7195
|
|
|
7323
|
-
|
|
7324
|
-
|
|
7325
|
-
|
|
7326
|
-
|
|
7327
|
-
|
|
7328
|
-
|
|
7329
|
-
|
|
7330
|
-
|
|
7196
|
+
function getSelector(el) {
|
|
7197
|
+
if (el.id) return '#' + CSS.escape(el.id);
|
|
7198
|
+
if (el.getAttribute('aria-label')) {
|
|
7199
|
+
return el.tagName.toLowerCase() + '[aria-label="' + el.getAttribute('aria-label') + '"]';
|
|
7200
|
+
}
|
|
7201
|
+
const cls = el.className && typeof el.className === 'string'
|
|
7202
|
+
? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
|
|
7203
|
+
: '';
|
|
7204
|
+
if (cls) return el.tagName.toLowerCase() + '.' + cls;
|
|
7205
|
+
return el.tagName.toLowerCase();
|
|
7331
7206
|
}
|
|
7332
|
-
}
|
|
7333
7207
|
|
|
7334
|
-
|
|
7335
|
-
|
|
7336
|
-
|
|
7337
|
-
|
|
7338
|
-
|
|
7339
|
-
|
|
7340
|
-
|
|
7341
|
-
|
|
7342
|
-
const
|
|
7343
|
-
|
|
7344
|
-
if (
|
|
7345
|
-
|
|
7208
|
+
function isPopupLike(el) {
|
|
7209
|
+
const tag = el.tagName?.toLowerCase();
|
|
7210
|
+
if (tag === 'dialog') return true;
|
|
7211
|
+
if (tag === 'body' || tag === 'html') return false;
|
|
7212
|
+
|
|
7213
|
+
const role = el.getAttribute('role');
|
|
7214
|
+
if (['dialog', 'alertdialog', 'popover', 'alert'].includes(role)) return true;
|
|
7215
|
+
|
|
7216
|
+
const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
|
|
7217
|
+
const popupPatterns = /modal|popup|popover|overlay|drawer|sheet|lightbox|dialog/;
|
|
7218
|
+
if (popupPatterns.test(cls)) return true;
|
|
7219
|
+
|
|
7220
|
+
const style = window.getComputedStyle(el);
|
|
7221
|
+
if ((style.position === 'fixed' || style.position === 'absolute') && style.zIndex !== 'auto') {
|
|
7222
|
+
const rect = el.getBoundingClientRect();
|
|
7223
|
+
if (rect.width > 0 && rect.height > 0 && parseInt(style.zIndex) >= 100) return true;
|
|
7346
7224
|
}
|
|
7347
|
-
|
|
7348
|
-
|
|
7349
|
-
id: xbrowser.id || packageJson.name,
|
|
7350
|
-
name: xbrowser.name || packageJson.name,
|
|
7351
|
-
description: xbrowser.description || packageJson.description || "",
|
|
7352
|
-
version: xbrowser.version || packageJson.version || "1.0.0",
|
|
7353
|
-
author: xbrowser.author || this.extractAuthor(packageJson.author),
|
|
7354
|
-
homepage: xbrowser.homepage || packageJson.homepage,
|
|
7355
|
-
commands: xbrowser.commands,
|
|
7356
|
-
sites: xbrowser.sites,
|
|
7357
|
-
tags: xbrowser.tags,
|
|
7358
|
-
screenshot: xbrowser.screenshot,
|
|
7359
|
-
license: xbrowser.license || packageJson.license
|
|
7360
|
-
};
|
|
7361
|
-
return metadata;
|
|
7225
|
+
|
|
7226
|
+
return false;
|
|
7362
7227
|
}
|
|
7363
|
-
|
|
7364
|
-
|
|
7365
|
-
|
|
7366
|
-
|
|
7367
|
-
const
|
|
7368
|
-
|
|
7369
|
-
|
|
7228
|
+
|
|
7229
|
+
function categorize(el) {
|
|
7230
|
+
const tag = el.tagName?.toLowerCase();
|
|
7231
|
+
const role = el.getAttribute('role');
|
|
7232
|
+
const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
|
|
7233
|
+
|
|
7234
|
+
if (tag === 'dialog' || role === 'dialog' || role === 'alertdialog') return 'dialog';
|
|
7235
|
+
if (role === 'popover' || /popover/.test(cls)) return 'popover';
|
|
7236
|
+
if (/modal/.test(cls) && !/dropdown/.test(cls)) return 'modal';
|
|
7237
|
+
if (/toast|notification|message|notice|snack|alert/.test(cls)) return 'toast';
|
|
7238
|
+
if (/dropdown|select-menu|listbox|menu/.test(cls) || role === 'listbox') return 'dropdown';
|
|
7239
|
+
if (/tooltip|tip/.test(cls) || role === 'tooltip') return 'tooltip';
|
|
7240
|
+
if (/overlay|mask|backdrop|dimmer/.test(cls)) return 'overlay';
|
|
7241
|
+
return 'unknown';
|
|
7370
7242
|
}
|
|
7371
|
-
|
|
7372
|
-
|
|
7243
|
+
|
|
7244
|
+
function extractElement(el) {
|
|
7245
|
+
const rect = el.getBoundingClientRect();
|
|
7246
|
+
const style = window.getComputedStyle(el);
|
|
7373
7247
|
return {
|
|
7374
|
-
|
|
7375
|
-
|
|
7376
|
-
|
|
7377
|
-
|
|
7378
|
-
|
|
7379
|
-
|
|
7380
|
-
|
|
7381
|
-
|
|
7248
|
+
selector: getSelector(el),
|
|
7249
|
+
tag: el.tagName.toLowerCase(),
|
|
7250
|
+
role: el.getAttribute('role') || undefined,
|
|
7251
|
+
text: (el.textContent || '').trim().slice(0, 100) || undefined,
|
|
7252
|
+
ariaLabel: el.getAttribute('aria-label') || undefined,
|
|
7253
|
+
size: { width: Math.round(rect.width), height: Math.round(rect.height) },
|
|
7254
|
+
position: { x: Math.round(rect.x), y: Math.round(rect.y) },
|
|
7255
|
+
zIndex: parseInt(style.zIndex) || 0,
|
|
7256
|
+
category: categorize(el),
|
|
7382
7257
|
};
|
|
7383
7258
|
}
|
|
7384
|
-
|
|
7385
|
-
|
|
7386
|
-
|
|
7387
|
-
|
|
7388
|
-
|
|
7389
|
-
}
|
|
7390
|
-
|
|
7391
|
-
}
|
|
7392
|
-
static validateMetadata(metadata) {
|
|
7393
|
-
const errors = [];
|
|
7394
|
-
if (!metadata.id) errors.push("id is required");
|
|
7395
|
-
if (!metadata.name) errors.push("name is required");
|
|
7396
|
-
if (!metadata.description) errors.push("description is required");
|
|
7397
|
-
if (!metadata.version) errors.push("version is required");
|
|
7398
|
-
return errors;
|
|
7259
|
+
|
|
7260
|
+
function scanAndReport() {
|
|
7261
|
+
const results = [];
|
|
7262
|
+
document.querySelectorAll('*').forEach(el => {
|
|
7263
|
+
if (isPopupLike(el)) results.push(extractElement(el));
|
|
7264
|
+
});
|
|
7265
|
+
window.__xbrowserDetectedElements = results;
|
|
7399
7266
|
}
|
|
7400
|
-
};
|
|
7401
7267
|
|
|
7402
|
-
|
|
7403
|
-
|
|
7404
|
-
|
|
7405
|
-
|
|
7406
|
-
|
|
7407
|
-
|
|
7408
|
-
|
|
7409
|
-
|
|
7410
|
-
|
|
7411
|
-
|
|
7412
|
-
|
|
7413
|
-
|
|
7414
|
-
|
|
7415
|
-
|
|
7416
|
-
if (existsSync5(pkgPath)) {
|
|
7268
|
+
window.__xbrowserScanOverlays = function() {
|
|
7269
|
+
scanAndReport();
|
|
7270
|
+
return window.__xbrowserDetectedElements;
|
|
7271
|
+
};
|
|
7272
|
+
})();
|
|
7273
|
+
`;
|
|
7274
|
+
var DomWatcher = class {
|
|
7275
|
+
page;
|
|
7276
|
+
injected = false;
|
|
7277
|
+
constructor(page) {
|
|
7278
|
+
this.page = page;
|
|
7279
|
+
}
|
|
7280
|
+
async inject() {
|
|
7281
|
+
if (this.injected) return;
|
|
7417
7282
|
try {
|
|
7418
|
-
|
|
7283
|
+
await this.page.evaluate(DOM_WATCHER_SCRIPT);
|
|
7284
|
+
await this.page.addInitScript(DOM_WATCHER_SCRIPT);
|
|
7285
|
+
this.injected = true;
|
|
7419
7286
|
} catch {
|
|
7420
7287
|
}
|
|
7421
7288
|
}
|
|
7422
|
-
|
|
7423
|
-
|
|
7424
|
-
|
|
7425
|
-
|
|
7426
|
-
|
|
7427
|
-
|
|
7289
|
+
async scanOverlays() {
|
|
7290
|
+
try {
|
|
7291
|
+
if (!this.injected) await this.inject();
|
|
7292
|
+
const result = await this.page.evaluate(
|
|
7293
|
+
"window.__xbrowserScanOverlays ? window.__xbrowserScanOverlays() : []"
|
|
7294
|
+
);
|
|
7295
|
+
return result || [];
|
|
7296
|
+
} catch {
|
|
7297
|
+
return [];
|
|
7428
7298
|
}
|
|
7429
7299
|
}
|
|
7430
|
-
|
|
7431
|
-
|
|
7432
|
-
|
|
7433
|
-
|
|
7434
|
-
writeFileSync5(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
|
|
7435
|
-
try {
|
|
7436
|
-
execSync("npm install --production --no-package-lock --no-fund --no-audit", {
|
|
7437
|
-
cwd: pluginsDir,
|
|
7438
|
-
stdio: "pipe",
|
|
7439
|
-
timeout: 6e4,
|
|
7440
|
-
env: { ...process.env, NODE_ENV: "production" }
|
|
7441
|
-
});
|
|
7442
|
-
} catch (err) {
|
|
7443
|
-
console.warn(`\u26A0\uFE0F Failed to install shared plugin dependencies: ${err instanceof Error ? err.message : String(err)}`);
|
|
7300
|
+
};
|
|
7301
|
+
function classifyPriority(category, element) {
|
|
7302
|
+
if (category === "dialog" && element.text && /error|错误|fail|失败|denied|拒绝/i.test(element.text)) {
|
|
7303
|
+
return "p0";
|
|
7444
7304
|
}
|
|
7305
|
+
if (category === "dialog" || category === "modal") return "p1";
|
|
7306
|
+
if (category === "popover" || category === "overlay") return "p2";
|
|
7307
|
+
if (category === "toast" || category === "notification") return "p2";
|
|
7308
|
+
if (category === "dropdown") return "p3";
|
|
7309
|
+
if (category === "tooltip") return "p3";
|
|
7310
|
+
return "p2";
|
|
7445
7311
|
}
|
|
7446
7312
|
|
|
7447
|
-
// src/
|
|
7448
|
-
|
|
7449
|
-
|
|
7450
|
-
|
|
7451
|
-
|
|
7452
|
-
|
|
7453
|
-
|
|
7454
|
-
|
|
7455
|
-
|
|
7456
|
-
|
|
7457
|
-
return {
|
|
7458
|
-
version: 2,
|
|
7459
|
-
plugin: {
|
|
7460
|
-
name: site.name,
|
|
7461
|
-
url: site.url,
|
|
7462
|
-
description: site.config?.description,
|
|
7463
|
-
requiresLogin: site.config?.requiresLogin
|
|
7464
|
-
},
|
|
7465
|
-
commands
|
|
7466
|
-
};
|
|
7467
|
-
}
|
|
7468
|
-
function buildCommandContract(command, options = {}) {
|
|
7469
|
-
const extension = command.xbrowser || {};
|
|
7470
|
-
const inferredFields = fieldsFromZodObject(command.parameters);
|
|
7471
|
-
const fields = mergeFields(inferredFields, extension.form?.fields || []);
|
|
7472
|
-
const positional = extension.positional || fields.filter((field) => field.positional).map((field) => field.name);
|
|
7473
|
-
const requiresLogin = command.requiresLogin === true || options.siteRequiresLogin === true && command.name !== "login" && command.name !== "logout";
|
|
7474
|
-
const capabilities = extension.capabilities || inferCapabilities(command.scope || "project", requiresLogin);
|
|
7475
|
-
const outputSchema = command.result ? summarizeZod(command.result) : void 0;
|
|
7476
|
-
return {
|
|
7477
|
-
name: command.name,
|
|
7478
|
-
description: command.description || "",
|
|
7479
|
-
scope: command.scope || "project",
|
|
7480
|
-
requiresLogin,
|
|
7481
|
-
category: extension.category,
|
|
7482
|
-
capabilities,
|
|
7483
|
-
positional,
|
|
7484
|
-
form: {
|
|
7485
|
-
title: extension.form?.title || command.description || command.name,
|
|
7486
|
-
description: extension.form?.description,
|
|
7487
|
-
submitLabel: extension.form?.submitLabel || "Run",
|
|
7488
|
-
fields
|
|
7489
|
-
},
|
|
7490
|
-
output: extension.output || (outputSchema ? { schema: outputSchema } : void 0)
|
|
7491
|
-
};
|
|
7492
|
-
}
|
|
7493
|
-
function fieldsFromZodObject(schema) {
|
|
7494
|
-
const reflected = fieldsFromZodObjectReflected(schema);
|
|
7495
|
-
return reflected.map((field) => {
|
|
7496
|
-
const widget = widgetFor(field.type, field.enum);
|
|
7497
|
-
return {
|
|
7498
|
-
name: field.name,
|
|
7499
|
-
label: toLabel(field.name),
|
|
7500
|
-
type: field.type,
|
|
7501
|
-
widget,
|
|
7502
|
-
required: field.required,
|
|
7503
|
-
...field.description ? { description: field.description } : {},
|
|
7504
|
-
...field.default !== void 0 ? { default: field.default } : {},
|
|
7505
|
-
...field.enum ? { enum: field.enum } : {},
|
|
7506
|
-
...field.type === "array" ? { multiple: true } : {}
|
|
7507
|
-
};
|
|
7508
|
-
});
|
|
7509
|
-
}
|
|
7510
|
-
function mergeFields(inferred, overrides) {
|
|
7511
|
-
if (overrides.length === 0) return inferred;
|
|
7512
|
-
const byName = new Map(inferred.map((field) => [field.name, field]));
|
|
7513
|
-
const seen = /* @__PURE__ */ new Set();
|
|
7514
|
-
const merged = [];
|
|
7515
|
-
for (const override of overrides) {
|
|
7516
|
-
if (!override.name) continue;
|
|
7517
|
-
const base = byName.get(override.name) || {
|
|
7518
|
-
name: override.name,
|
|
7519
|
-
label: toLabel(override.name),
|
|
7520
|
-
type: "string",
|
|
7521
|
-
widget: "text",
|
|
7522
|
-
required: false
|
|
7313
|
+
// src/tips/context-tracker.ts
|
|
7314
|
+
var ContextTracker = class {
|
|
7315
|
+
history = [];
|
|
7316
|
+
maxHistory = 20;
|
|
7317
|
+
record(commandName, params) {
|
|
7318
|
+
const entry = {
|
|
7319
|
+
commandName,
|
|
7320
|
+
params,
|
|
7321
|
+
timestamp: Date.now(),
|
|
7322
|
+
targetSelector: params.selector || params.url || void 0
|
|
7523
7323
|
};
|
|
7524
|
-
|
|
7525
|
-
|
|
7526
|
-
|
|
7527
|
-
|
|
7528
|
-
if (!seen.has(field.name)) merged.push(field);
|
|
7324
|
+
this.history.push(entry);
|
|
7325
|
+
if (this.history.length > this.maxHistory) {
|
|
7326
|
+
this.history.shift();
|
|
7327
|
+
}
|
|
7529
7328
|
}
|
|
7530
|
-
|
|
7531
|
-
|
|
7532
|
-
function inferCapabilities(scope, requiresLogin) {
|
|
7533
|
-
const caps = [];
|
|
7534
|
-
if (scope === "page") caps.push("browser.page");
|
|
7535
|
-
if (scope === "browser") caps.push("browser.context");
|
|
7536
|
-
if (requiresLogin) caps.push("auth.login");
|
|
7537
|
-
return caps;
|
|
7538
|
-
}
|
|
7539
|
-
function widgetFor(type, enumValues) {
|
|
7540
|
-
if (enumValues) return "select";
|
|
7541
|
-
if (type === "boolean") return "checkbox";
|
|
7542
|
-
if (type === "number") return "number";
|
|
7543
|
-
if (type === "array") return "multi-select";
|
|
7544
|
-
if (type === "object") return "json";
|
|
7545
|
-
return "text";
|
|
7546
|
-
}
|
|
7547
|
-
function summarizeZod(schema) {
|
|
7548
|
-
const unwrapped = unwrapZod(schema);
|
|
7549
|
-
if (unwrapped.typeName === "ZodArray") {
|
|
7550
|
-
const def = unwrapped.schema?._def;
|
|
7551
|
-
return {
|
|
7552
|
-
type: "array",
|
|
7553
|
-
items: summarizeZod(def?.type || def?.innerType)
|
|
7554
|
-
};
|
|
7329
|
+
getLastCommand() {
|
|
7330
|
+
return this.history.length > 0 ? this.history[this.history.length - 1] : void 0;
|
|
7555
7331
|
}
|
|
7556
|
-
|
|
7557
|
-
|
|
7558
|
-
|
|
7559
|
-
|
|
7560
|
-
|
|
7561
|
-
|
|
7562
|
-
|
|
7332
|
+
getLastSelector() {
|
|
7333
|
+
for (let i = this.history.length - 1; i >= 0; i--) {
|
|
7334
|
+
if (this.history[i].targetSelector) {
|
|
7335
|
+
return this.history[i].targetSelector;
|
|
7336
|
+
}
|
|
7337
|
+
}
|
|
7338
|
+
return void 0;
|
|
7563
7339
|
}
|
|
7564
|
-
|
|
7565
|
-
|
|
7566
|
-
|
|
7567
|
-
|
|
7568
|
-
|
|
7569
|
-
|
|
7570
|
-
|
|
7571
|
-
}];
|
|
7572
|
-
})
|
|
7573
|
-
);
|
|
7574
|
-
}
|
|
7575
|
-
function getObjectShape(schema) {
|
|
7576
|
-
const zod = schema;
|
|
7577
|
-
const shapeOrFn = zod?.shape ?? zod?._def?.shape;
|
|
7578
|
-
if (!shapeOrFn) return void 0;
|
|
7579
|
-
return typeof shapeOrFn === "function" ? shapeOrFn() : shapeOrFn;
|
|
7580
|
-
}
|
|
7581
|
-
function toLabel(name) {
|
|
7582
|
-
return name.replace(/([A-Z])/g, " $1").replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim().replace(/^./, (char) => char.toUpperCase());
|
|
7583
|
-
}
|
|
7584
|
-
|
|
7585
|
-
// src/plugin/login-required-patch.ts
|
|
7586
|
-
import { SiteInstanceImpl } from "@dyyz1993/xcli-core";
|
|
7587
|
-
var patched = false;
|
|
7588
|
-
function patchLoginRequired() {
|
|
7589
|
-
if (patched) return;
|
|
7590
|
-
patched = true;
|
|
7591
|
-
const target = SiteInstanceImpl.prototype;
|
|
7592
|
-
const originalCommand = target.command;
|
|
7593
|
-
const wrapped = function(...args) {
|
|
7594
|
-
const result = originalCommand.apply(this, args);
|
|
7595
|
-
const [name, cmd] = args;
|
|
7596
|
-
const loginRequired = cmd.loginRequired;
|
|
7597
|
-
if (loginRequired) {
|
|
7598
|
-
const commands = this.commands;
|
|
7599
|
-
const entry = commands?.get(name);
|
|
7600
|
-
if (entry) {
|
|
7601
|
-
entry.loginRequired = loginRequired;
|
|
7602
|
-
}
|
|
7340
|
+
isLikelyTriggered(selector) {
|
|
7341
|
+
const last = this.getLastCommand();
|
|
7342
|
+
if (!last) return false;
|
|
7343
|
+
const cmd = last.commandName.toLowerCase();
|
|
7344
|
+
const target = last.targetSelector?.toLowerCase() || "";
|
|
7345
|
+
if (["click", "dblclick", "hover", "tap"].includes(cmd)) {
|
|
7346
|
+
return selector === target || selector.startsWith(target.split(/[.\[#]/)[0]);
|
|
7603
7347
|
}
|
|
7604
|
-
|
|
7605
|
-
|
|
7606
|
-
|
|
7607
|
-
|
|
7608
|
-
writable: true,
|
|
7609
|
-
configurable: true
|
|
7610
|
-
});
|
|
7611
|
-
}
|
|
7612
|
-
|
|
7613
|
-
// src/plugin/loader.ts
|
|
7614
|
-
var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
|
|
7615
|
-
var XBrowserPluginLoader = class {
|
|
7616
|
-
core;
|
|
7617
|
-
loader;
|
|
7618
|
-
options;
|
|
7619
|
-
/** 目录名 → 该插件注册的 site 名(site.name ≠ 目录名时的命令别名兜底) */
|
|
7620
|
-
dirSiteAliases = /* @__PURE__ */ new Map();
|
|
7621
|
-
constructor(options) {
|
|
7622
|
-
patchLoginRequired();
|
|
7623
|
-
this.options = options ?? {};
|
|
7624
|
-
const cwd = this.options.cwd || process.cwd();
|
|
7625
|
-
const coreConfig = {
|
|
7626
|
-
name: "xbrowser",
|
|
7627
|
-
version: "0.1.0",
|
|
7628
|
-
description: "Browser automation CLI",
|
|
7629
|
-
configDirName: ".xbrowser",
|
|
7630
|
-
envPrefix: "XBROWSER",
|
|
7631
|
-
pluginDirs: [
|
|
7632
|
-
...DEFAULT_PLUGIN_DIRS,
|
|
7633
|
-
resolve2(cwd, ".xcli/plugins")
|
|
7634
|
-
]
|
|
7635
|
-
};
|
|
7636
|
-
this.core = new Core(coreConfig);
|
|
7637
|
-
this.loader = this.core.loader;
|
|
7348
|
+
if (["fill", "type", "select", "check", "uncheck"].includes(cmd)) {
|
|
7349
|
+
return selector === target;
|
|
7350
|
+
}
|
|
7351
|
+
return false;
|
|
7638
7352
|
}
|
|
7639
|
-
|
|
7640
|
-
|
|
7353
|
+
isRecentCommand(cmdName, withinMs = 2e3) {
|
|
7354
|
+
const last = this.getLastCommand();
|
|
7355
|
+
if (!last) return false;
|
|
7356
|
+
return last.commandName === cmdName && Date.now() - last.timestamp < withinMs;
|
|
7641
7357
|
}
|
|
7642
|
-
|
|
7643
|
-
|
|
7644
|
-
* @returns The xcli-core Core instance.
|
|
7645
|
-
*/
|
|
7646
|
-
getCore() {
|
|
7647
|
-
return this.core;
|
|
7358
|
+
clear() {
|
|
7359
|
+
this.history = [];
|
|
7648
7360
|
}
|
|
7649
|
-
|
|
7650
|
-
|
|
7361
|
+
};
|
|
7362
|
+
|
|
7363
|
+
// src/tips/tip-generator.ts
|
|
7364
|
+
var SILENT_CATEGORIES = /* @__PURE__ */ new Set(["dropdown", "tooltip"]);
|
|
7365
|
+
var NOTIFICATION_CATEGORIES = /* @__PURE__ */ new Set(["toast", "notification"]);
|
|
7366
|
+
var TipGenerator = class {
|
|
7367
|
+
contextTracker;
|
|
7368
|
+
reportedSelectors = /* @__PURE__ */ new Map();
|
|
7369
|
+
dedupWindowMs = 3e4;
|
|
7370
|
+
constructor(contextTracker) {
|
|
7371
|
+
this.contextTracker = contextTracker;
|
|
7651
7372
|
}
|
|
7652
|
-
|
|
7653
|
-
|
|
7373
|
+
diff(before, after, currentElements) {
|
|
7374
|
+
const beforeSet = new Set(before.overlaySelectors);
|
|
7375
|
+
const afterSet = new Set(after.overlaySelectors);
|
|
7376
|
+
const newSelectors = [];
|
|
7377
|
+
for (const sel of afterSet) {
|
|
7378
|
+
if (!beforeSet.has(sel)) newSelectors.push(sel);
|
|
7379
|
+
}
|
|
7380
|
+
if (newSelectors.length === 0) return [];
|
|
7381
|
+
return currentElements.filter((el) => newSelectors.includes(el.selector));
|
|
7654
7382
|
}
|
|
7655
|
-
|
|
7656
|
-
|
|
7383
|
+
generate(newElements) {
|
|
7384
|
+
const tips = [];
|
|
7385
|
+
for (const el of newElements) {
|
|
7386
|
+
if (this.contextTracker.isLikelyTriggered(el.selector)) continue;
|
|
7387
|
+
if (SILENT_CATEGORIES.has(el.category)) continue;
|
|
7388
|
+
if (NOTIFICATION_CATEGORIES.has(el.category) && el.text && /success|成功|done|完成|saved|已保存/i.test(el.text)) {
|
|
7389
|
+
continue;
|
|
7390
|
+
}
|
|
7391
|
+
if (this.isRecentlyReported(el.selector)) continue;
|
|
7392
|
+
const priority = classifyPriority(el.category, el);
|
|
7393
|
+
if (priority === "p3") continue;
|
|
7394
|
+
const message = this.buildMessage(el);
|
|
7395
|
+
const suggestions = this.buildSuggestions(el);
|
|
7396
|
+
tips.push({
|
|
7397
|
+
priority,
|
|
7398
|
+
category: el.category,
|
|
7399
|
+
element: el,
|
|
7400
|
+
message,
|
|
7401
|
+
suggestions
|
|
7402
|
+
});
|
|
7403
|
+
this.reportedSelectors.set(el.selector, Date.now());
|
|
7404
|
+
}
|
|
7405
|
+
tips.sort((a, b) => {
|
|
7406
|
+
const order = { p0: 0, p1: 1, p2: 2 };
|
|
7407
|
+
return (order[a.priority] ?? 3) - (order[b.priority] ?? 3);
|
|
7408
|
+
});
|
|
7409
|
+
return tips;
|
|
7657
7410
|
}
|
|
7658
|
-
|
|
7659
|
-
|
|
7660
|
-
|
|
7661
|
-
|
|
7662
|
-
|
|
7663
|
-
|
|
7664
|
-
*/
|
|
7665
|
-
resolveSiteName(name) {
|
|
7666
|
-
if (this.core.loader.getSite(name)) return name;
|
|
7667
|
-
const aliased = this.dirSiteAliases.get(name);
|
|
7668
|
-
if (aliased && this.core.loader.getSite(aliased)) return aliased;
|
|
7669
|
-
return void 0;
|
|
7411
|
+
buildMessage(el) {
|
|
7412
|
+
const label = el.ariaLabel || el.text?.slice(0, 40) || "";
|
|
7413
|
+
const labelStr = label ? ` "${label}"` : "";
|
|
7414
|
+
const sizeStr = `${el.size.width}x${el.size.height}`;
|
|
7415
|
+
const typeLabel = this.categoryLabel(el.category);
|
|
7416
|
+
return `\u68C0\u6D4B\u5230\u65B0${typeLabel}${labelStr} (${sizeStr})\uFF0C\u9009\u62E9\u5668: ${el.selector}`;
|
|
7670
7417
|
}
|
|
7671
|
-
|
|
7672
|
-
|
|
7673
|
-
|
|
7674
|
-
|
|
7418
|
+
buildSuggestions(el) {
|
|
7419
|
+
const suggestions = [];
|
|
7420
|
+
if (el.category === "dialog" || el.category === "modal") {
|
|
7421
|
+
const confirmBtn = this.guessButtonSelector(el, ["confirm", "ok", "yes", "\u786E\u5B9A", "\u786E\u8BA4", "\u540C\u610F"]);
|
|
7422
|
+
const cancelBtn = this.guessButtonSelector(el, ["cancel", "close", "no", "\u53D6\u6D88", "\u5173\u95ED", "\u62D2\u7EDD"]);
|
|
7423
|
+
if (confirmBtn) suggestions.push(`click "${confirmBtn}"`);
|
|
7424
|
+
if (cancelBtn) suggestions.push(`click "${cancelBtn}"`);
|
|
7675
7425
|
}
|
|
7426
|
+
if (el.category === "popover" || el.category === "overlay") {
|
|
7427
|
+
suggestions.push(`click "${el.selector}"`);
|
|
7428
|
+
}
|
|
7429
|
+
if (el.category === "toast" || el.category === "notification") {
|
|
7430
|
+
suggestions.push(`text "${el.selector}"`);
|
|
7431
|
+
}
|
|
7432
|
+
if (suggestions.length === 0) {
|
|
7433
|
+
suggestions.push(`click "${el.selector}"`);
|
|
7434
|
+
}
|
|
7435
|
+
return suggestions;
|
|
7676
7436
|
}
|
|
7677
|
-
|
|
7678
|
-
const
|
|
7679
|
-
|
|
7680
|
-
|
|
7681
|
-
|
|
7682
|
-
|
|
7683
|
-
if (!commandName) return contract;
|
|
7684
|
-
return contract.commands.find((command) => command.name === commandName);
|
|
7685
|
-
}
|
|
7686
|
-
async loadPlugin(pluginPath, id) {
|
|
7687
|
-
const before = new Set(this.core.loader.getSites().map((s) => s.name));
|
|
7688
|
-
const instance = await this.loader.loadPlugin(pluginPath, id);
|
|
7689
|
-
this.recordSiteAliases(basename(dirname3(pluginPath)), before);
|
|
7690
|
-
return instance;
|
|
7437
|
+
guessButtonSelector(el, keywords) {
|
|
7438
|
+
const base = el.selector;
|
|
7439
|
+
for (const kw of keywords) {
|
|
7440
|
+
return `${base} button:has-text("${kw}"), ${base} [role="button"]:has-text("${kw}")`;
|
|
7441
|
+
}
|
|
7442
|
+
return void 0;
|
|
7691
7443
|
}
|
|
7692
|
-
|
|
7693
|
-
|
|
7444
|
+
categoryLabel(category) {
|
|
7445
|
+
const labels = {
|
|
7446
|
+
dialog: "Dialog",
|
|
7447
|
+
modal: "Modal",
|
|
7448
|
+
popover: "Popover",
|
|
7449
|
+
notification: "\u901A\u77E5",
|
|
7450
|
+
toast: "Toast",
|
|
7451
|
+
dropdown: "\u4E0B\u62C9\u83DC\u5355",
|
|
7452
|
+
tooltip: "Tooltip",
|
|
7453
|
+
overlay: "Overlay",
|
|
7454
|
+
unknown: "\u5F39\u7A97"
|
|
7455
|
+
};
|
|
7456
|
+
return labels[category] || "\u5F39\u7A97";
|
|
7694
7457
|
}
|
|
7695
|
-
|
|
7696
|
-
|
|
7458
|
+
isRecentlyReported(selector) {
|
|
7459
|
+
const lastTime = this.reportedSelectors.get(selector);
|
|
7460
|
+
if (!lastTime) return false;
|
|
7461
|
+
return Date.now() - lastTime < this.dedupWindowMs;
|
|
7697
7462
|
}
|
|
7698
|
-
|
|
7699
|
-
|
|
7700
|
-
}
|
|
7701
|
-
async scanAndLoad() {
|
|
7702
|
-
const cwd = this.options.cwd || process.cwd();
|
|
7703
|
-
const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
|
|
7704
|
-
ensurePluginDependencies(globalDir);
|
|
7705
|
-
const dirs = [
|
|
7706
|
-
resolve2(cwd, ".xcli/plugins"),
|
|
7707
|
-
resolve2(cwd, "../.xcli/plugins"),
|
|
7708
|
-
this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
|
|
7709
|
-
globalDir
|
|
7710
|
-
];
|
|
7711
|
-
const loaded = [];
|
|
7712
|
-
const seen = /* @__PURE__ */ new Set();
|
|
7713
|
-
for (const dir of dirs) {
|
|
7714
|
-
if (!existsSync6(dir)) continue;
|
|
7715
|
-
const entries = readdirSync(dir, { withFileTypes: true });
|
|
7716
|
-
for (const entry of entries) {
|
|
7717
|
-
if (!entry.isDirectory()) continue;
|
|
7718
|
-
if (seen.has(entry.name)) continue;
|
|
7719
|
-
seen.add(entry.name);
|
|
7720
|
-
const pluginDir = resolve2(dir, entry.name);
|
|
7721
|
-
let indexPath = resolve2(pluginDir, "index.js");
|
|
7722
|
-
if (!existsSync6(indexPath)) {
|
|
7723
|
-
indexPath = resolve2(pluginDir, "index.ts");
|
|
7724
|
-
}
|
|
7725
|
-
if (!existsSync6(indexPath)) continue;
|
|
7726
|
-
try {
|
|
7727
|
-
if (!existsSync6(resolve2(pluginDir, "package.json"))) {
|
|
7728
|
-
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
|
|
7729
|
-
} else {
|
|
7730
|
-
const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
|
|
7731
|
-
if (!metadata) {
|
|
7732
|
-
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has package.json but no xbrowser metadata. Add { "xbrowser": { "description": "..." } } to package.json.`);
|
|
7733
|
-
}
|
|
7734
|
-
}
|
|
7735
|
-
const instance = await this.loadPlugin(indexPath, entry.name);
|
|
7736
|
-
loaded.push(instance);
|
|
7737
|
-
} catch (err) {
|
|
7738
|
-
const errMsg2 = err instanceof Error ? err.message : String(err);
|
|
7739
|
-
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" load failed: ${errMsg2}`);
|
|
7740
|
-
if (errMsg2.includes("Cannot find module") && errMsg2.includes("shared/")) {
|
|
7741
|
-
console.warn(` \u{1F4A1} This plugin needs shared/ dependencies. Try: xbrowser plugin install shared`);
|
|
7742
|
-
}
|
|
7743
|
-
}
|
|
7744
|
-
}
|
|
7745
|
-
}
|
|
7746
|
-
return loaded;
|
|
7747
|
-
}
|
|
7748
|
-
async unload() {
|
|
7749
|
-
return this.loader.unload();
|
|
7463
|
+
resetDedup() {
|
|
7464
|
+
this.reportedSelectors.clear();
|
|
7750
7465
|
}
|
|
7751
7466
|
};
|
|
7752
|
-
|
|
7753
|
-
|
|
7754
|
-
|
|
7755
|
-
|
|
7756
|
-
function silenceSchemaWarnings(fn) {
|
|
7757
|
-
if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
|
|
7758
|
-
const originalWarn = console.warn;
|
|
7759
|
-
console.warn = (...args) => {
|
|
7760
|
-
const msg = typeof args[0] === "string" ? args[0] : "";
|
|
7761
|
-
if (msg.includes('has no "result" schema')) return;
|
|
7762
|
-
originalWarn(...args);
|
|
7467
|
+
function buildSnapshot(elements) {
|
|
7468
|
+
return {
|
|
7469
|
+
timestamp: Date.now(),
|
|
7470
|
+
overlaySelectors: elements.map((el) => el.selector)
|
|
7763
7471
|
};
|
|
7764
|
-
return fn().finally(() => {
|
|
7765
|
-
console.warn = originalWarn;
|
|
7766
|
-
});
|
|
7767
|
-
}
|
|
7768
|
-
async function getPluginLoader() {
|
|
7769
|
-
if (!pluginLoader) {
|
|
7770
|
-
pluginLoader = new XBrowserPluginLoader();
|
|
7771
|
-
}
|
|
7772
|
-
if (!pluginsScanned) {
|
|
7773
|
-
await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
|
|
7774
|
-
pluginsScanned = true;
|
|
7775
|
-
}
|
|
7776
|
-
return pluginLoader;
|
|
7777
7472
|
}
|
|
7778
7473
|
|
|
7779
|
-
// src/
|
|
7780
|
-
|
|
7781
|
-
const
|
|
7782
|
-
|
|
7783
|
-
|
|
7784
|
-
|
|
7785
|
-
|
|
7786
|
-
|
|
7787
|
-
|
|
7788
|
-
|
|
7789
|
-
|
|
7474
|
+
// src/tips/index.ts
|
|
7475
|
+
function tipsDebounceMs() {
|
|
7476
|
+
const v = parseInt(process.env.XBROWSER_TIPS_DEBOUNCE ?? "120", 10);
|
|
7477
|
+
return Number.isFinite(v) && v > 0 ? v : 0;
|
|
7478
|
+
}
|
|
7479
|
+
var SKIP_DETECT_COMMANDS = /* @__PURE__ */ new Set([
|
|
7480
|
+
"goto",
|
|
7481
|
+
// 导航命令不需要检测
|
|
7482
|
+
"screenshot",
|
|
7483
|
+
// 截图不需要检测
|
|
7484
|
+
"snapshot",
|
|
7485
|
+
// snapshot 不需要检测
|
|
7486
|
+
"get",
|
|
7487
|
+
// get 命令不需要检测
|
|
7488
|
+
"detect",
|
|
7489
|
+
// detect 命令本身不需要检测
|
|
7490
|
+
"history",
|
|
7491
|
+
// history 命令不需要检测
|
|
7492
|
+
"viewer"
|
|
7493
|
+
// viewer 命令不需要检测
|
|
7494
|
+
]);
|
|
7495
|
+
var INTERACTION_COMMANDS = /* @__PURE__ */ new Set([
|
|
7496
|
+
"click",
|
|
7497
|
+
"fill",
|
|
7498
|
+
"type",
|
|
7499
|
+
"select",
|
|
7500
|
+
"check",
|
|
7501
|
+
"uncheck",
|
|
7502
|
+
"hover",
|
|
7503
|
+
"dblclick"
|
|
7504
|
+
]);
|
|
7505
|
+
var TipsManager = class {
|
|
7506
|
+
domWatcher = null;
|
|
7507
|
+
contextTracker = new ContextTracker();
|
|
7508
|
+
generator = new TipGenerator(this.contextTracker);
|
|
7509
|
+
beforeSnapshot = null;
|
|
7510
|
+
lastDetectionTime = 0;
|
|
7511
|
+
async beforeCommand(page, commandName, params) {
|
|
7512
|
+
this.contextTracker.record(commandName, params);
|
|
7513
|
+
if (!this.domWatcher) {
|
|
7514
|
+
this.domWatcher = new DomWatcher(page);
|
|
7515
|
+
}
|
|
7790
7516
|
try {
|
|
7791
|
-
|
|
7792
|
-
|
|
7793
|
-
|
|
7794
|
-
plugin: pluginName,
|
|
7795
|
-
command: commandName,
|
|
7796
|
-
reason: "config.isLogin returned false",
|
|
7797
|
-
sessionName,
|
|
7798
|
-
loginConfig
|
|
7799
|
-
});
|
|
7517
|
+
await this.domWatcher.inject();
|
|
7518
|
+
const elements = await this.domWatcher.scanOverlays();
|
|
7519
|
+
this.beforeSnapshot = buildSnapshot(elements);
|
|
7800
7520
|
} catch {
|
|
7521
|
+
this.beforeSnapshot = { timestamp: Date.now(), overlaySelectors: [] };
|
|
7522
|
+
}
|
|
7523
|
+
if (INTERACTION_COMMANDS.has(commandName) && !SKIP_DETECT_COMMANDS.has(commandName)) {
|
|
7524
|
+
await this.checkAntiBot(page, commandName);
|
|
7801
7525
|
}
|
|
7802
7526
|
}
|
|
7803
|
-
|
|
7527
|
+
/**
|
|
7528
|
+
* 检测反机器人机制
|
|
7529
|
+
*/
|
|
7530
|
+
async checkAntiBot(page, _commandName) {
|
|
7531
|
+
const now = Date.now();
|
|
7532
|
+
if (now - this.lastDetectionTime < 5e3) {
|
|
7533
|
+
return;
|
|
7534
|
+
}
|
|
7535
|
+
this.lastDetectionTime = now;
|
|
7536
|
+
const config = {
|
|
7537
|
+
checkCaptcha: true,
|
|
7538
|
+
checkWarning: true,
|
|
7539
|
+
checkBlocked: true,
|
|
7540
|
+
checkWebdriver: true
|
|
7541
|
+
};
|
|
7542
|
+
const result = await detectAntiBot(page, config);
|
|
7543
|
+
if (result.detected && result.severity === "high") {
|
|
7544
|
+
const message = formatDetectionMessage(result);
|
|
7545
|
+
console.error(`
|
|
7546
|
+
\u{1F6A8} ${message}
|
|
7547
|
+
`);
|
|
7548
|
+
console.log("\u{1F4A1} Action blocked. To continue:");
|
|
7549
|
+
console.log(" 1. Use viewer mode: xbrowser viewer --json");
|
|
7550
|
+
console.log(" 2. Or skip detection with --skip-detect flag\n");
|
|
7551
|
+
throw new Error(`Anti-bot detection blocked: ${result.message}`);
|
|
7552
|
+
}
|
|
7553
|
+
}
|
|
7554
|
+
async afterCommand() {
|
|
7555
|
+
if (!this.domWatcher || !this.beforeSnapshot) return [];
|
|
7556
|
+
await this.debounce();
|
|
7804
7557
|
try {
|
|
7805
|
-
const
|
|
7806
|
-
|
|
7807
|
-
|
|
7808
|
-
|
|
7809
|
-
|
|
7810
|
-
|
|
7811
|
-
sessionName,
|
|
7812
|
-
loginConfig
|
|
7813
|
-
});
|
|
7558
|
+
const currentElements = await this.domWatcher.scanOverlays();
|
|
7559
|
+
const afterSnapshot = buildSnapshot(currentElements);
|
|
7560
|
+
const newElements = this.generator.diff(this.beforeSnapshot, afterSnapshot, currentElements);
|
|
7561
|
+
const tips = this.generator.generate(newElements);
|
|
7562
|
+
this.beforeSnapshot = null;
|
|
7563
|
+
return tips;
|
|
7814
7564
|
} catch {
|
|
7565
|
+
this.beforeSnapshot = null;
|
|
7566
|
+
return [];
|
|
7815
7567
|
}
|
|
7816
7568
|
}
|
|
7817
|
-
|
|
7818
|
-
const
|
|
7819
|
-
if (
|
|
7820
|
-
|
|
7821
|
-
return buildLoginRequired({
|
|
7822
|
-
plugin: pluginName,
|
|
7823
|
-
command: commandName,
|
|
7824
|
-
reason: "generic loginConfig detected logged-out page",
|
|
7825
|
-
sessionName,
|
|
7826
|
-
loginConfig
|
|
7827
|
-
});
|
|
7828
|
-
}
|
|
7569
|
+
debounce() {
|
|
7570
|
+
const ms = tipsDebounceMs();
|
|
7571
|
+
if (ms <= 0) return Promise.resolve();
|
|
7572
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
7829
7573
|
}
|
|
7830
|
-
|
|
7831
|
-
|
|
7832
|
-
|
|
7833
|
-
|
|
7834
|
-
|
|
7835
|
-
const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
|
|
7836
|
-
const tips = [
|
|
7837
|
-
message,
|
|
7838
|
-
...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
|
|
7839
|
-
...loginUrl ? [`Login page: ${loginUrl}`] : [],
|
|
7840
|
-
`After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
|
|
7841
|
-
];
|
|
7842
|
-
return {
|
|
7843
|
-
ok: false,
|
|
7844
|
-
data: {
|
|
7845
|
-
code: "LOGIN_REQUIRED",
|
|
7846
|
-
plugin: options.plugin,
|
|
7847
|
-
command: options.command,
|
|
7848
|
-
reason: options.reason,
|
|
7849
|
-
...viewerUrl ? { viewerUrl } : {},
|
|
7850
|
-
...loginUrl ? { loginUrl } : {}
|
|
7851
|
-
},
|
|
7852
|
-
message,
|
|
7853
|
-
tips
|
|
7854
|
-
};
|
|
7855
|
-
}
|
|
7856
|
-
async function detectLoginFromPage(page, config) {
|
|
7857
|
-
const url = page.url();
|
|
7858
|
-
if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
|
|
7859
|
-
const result = await page.evaluate((cfg) => {
|
|
7860
|
-
const visible = (selector) => {
|
|
7861
|
-
try {
|
|
7862
|
-
const el = document.querySelector(selector);
|
|
7863
|
-
if (!el) return false;
|
|
7864
|
-
const rect = el.getBoundingClientRect();
|
|
7865
|
-
const style = window.getComputedStyle(el);
|
|
7866
|
-
return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
|
|
7867
|
-
} catch {
|
|
7868
|
-
return false;
|
|
7574
|
+
formatTips(tips) {
|
|
7575
|
+
return tips.map((tip) => {
|
|
7576
|
+
const lines = [tip.message];
|
|
7577
|
+
for (const s of tip.suggestions) {
|
|
7578
|
+
lines.push(` \u2192 ${s}`);
|
|
7869
7579
|
}
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
|
|
7878
|
-
|
|
7879
|
-
}
|
|
7880
|
-
|
|
7881
|
-
|
|
7882
|
-
|
|
7883
|
-
|
|
7884
|
-
|
|
7580
|
+
return lines.join("\n");
|
|
7581
|
+
});
|
|
7582
|
+
}
|
|
7583
|
+
reset() {
|
|
7584
|
+
this.beforeSnapshot = null;
|
|
7585
|
+
this.generator.resetDedup();
|
|
7586
|
+
this.contextTracker.clear();
|
|
7587
|
+
this.domWatcher = null;
|
|
7588
|
+
this.lastDetectionTime = 0;
|
|
7589
|
+
}
|
|
7590
|
+
};
|
|
7591
|
+
var globalTipsManager = null;
|
|
7592
|
+
function getTipsManager() {
|
|
7593
|
+
if (!globalTipsManager) {
|
|
7594
|
+
globalTipsManager = new TipsManager();
|
|
7595
|
+
}
|
|
7596
|
+
return globalTipsManager;
|
|
7885
7597
|
}
|
|
7886
7598
|
|
|
7887
|
-
// src/
|
|
7888
|
-
var
|
|
7889
|
-
|
|
7890
|
-
|
|
7891
|
-
|
|
7892
|
-
|
|
7893
|
-
|
|
7894
|
-
|
|
7895
|
-
|
|
7896
|
-
|
|
7897
|
-
|
|
7898
|
-
|
|
7599
|
+
// src/hooks/loader.ts
|
|
7600
|
+
var FAIL_KEYWORDS = [
|
|
7601
|
+
"\u767B\u5F55",
|
|
7602
|
+
"login",
|
|
7603
|
+
"Login",
|
|
7604
|
+
"\u672A\u767B\u5F55",
|
|
7605
|
+
"not logged in",
|
|
7606
|
+
"cdp",
|
|
7607
|
+
"CDP",
|
|
7608
|
+
"\u9A8C\u8BC1\u7801",
|
|
7609
|
+
"\u9A8C\u8BC1",
|
|
7610
|
+
"captcha",
|
|
7611
|
+
"\u9700\u8981\u767B\u5F55",
|
|
7612
|
+
"requires login",
|
|
7613
|
+
"blocked",
|
|
7614
|
+
"403",
|
|
7615
|
+
"404"
|
|
7616
|
+
];
|
|
7617
|
+
var HOOK_REGISTRY = {
|
|
7618
|
+
viewer: {
|
|
7619
|
+
name: "viewer",
|
|
7620
|
+
onAfterCommand: async (ctx) => {
|
|
7621
|
+
const result = ctx.result;
|
|
7622
|
+
if (!result || result.success !== false) return void 0;
|
|
7623
|
+
const msg = [
|
|
7624
|
+
result.message,
|
|
7625
|
+
...result.tips || []
|
|
7626
|
+
].filter(Boolean).join(" ").toLowerCase();
|
|
7627
|
+
if (!FAIL_KEYWORDS.some((k) => msg.includes(k))) return void 0;
|
|
7628
|
+
const viewerUrl = buildViewerUrl();
|
|
7629
|
+
if (!viewerUrl) return void 0;
|
|
7630
|
+
const tips = result.tips || [];
|
|
7631
|
+
if (!tips.some((t) => t.includes("viewer") || t.includes("Viewer"))) {
|
|
7632
|
+
tips.push(`Open viewer: ${viewerUrl}`);
|
|
7633
|
+
}
|
|
7634
|
+
result.tips = tips;
|
|
7635
|
+
result.viewerUrl = viewerUrl;
|
|
7636
|
+
return void 0;
|
|
7637
|
+
}
|
|
7638
|
+
},
|
|
7639
|
+
screenshot: {
|
|
7640
|
+
name: "screenshot",
|
|
7641
|
+
onAfterCommand: async (ctx) => {
|
|
7642
|
+
try {
|
|
7643
|
+
const buf = await ctx.page.screenshot({ type: "jpeg", quality: 40 }).catch(() => null);
|
|
7644
|
+
if (!buf) return;
|
|
7645
|
+
return { screenshot: { url: `data:image/jpeg;base64,${buf.toString("base64").slice(0, 50)}...` } };
|
|
7646
|
+
} catch {
|
|
7647
|
+
return;
|
|
7648
|
+
}
|
|
7649
|
+
}
|
|
7650
|
+
},
|
|
7651
|
+
recorder: {
|
|
7652
|
+
name: "recorder",
|
|
7653
|
+
onAfterCommand: async (ctx) => {
|
|
7654
|
+
const logs = ("__commandLogs" in ctx ? ctx.__commandLogs : void 0) || [];
|
|
7655
|
+
logs.push({
|
|
7656
|
+
timestamp: Date.now(),
|
|
7657
|
+
command: ctx.command,
|
|
7658
|
+
params: JSON.parse(JSON.stringify(ctx.params)),
|
|
7659
|
+
duration: ctx.duration
|
|
7660
|
+
});
|
|
7661
|
+
Reflect.set(ctx, "__commandLogs", logs);
|
|
7662
|
+
return void 0;
|
|
7899
7663
|
}
|
|
7900
|
-
const cls = el.className && typeof el.className === 'string'
|
|
7901
|
-
? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
|
|
7902
|
-
: '';
|
|
7903
|
-
if (cls) return el.tagName.toLowerCase() + '.' + cls;
|
|
7904
|
-
return el.tagName.toLowerCase();
|
|
7905
7664
|
}
|
|
7665
|
+
};
|
|
7666
|
+
var customHooks = {};
|
|
7667
|
+
async function loadHooks() {
|
|
7668
|
+
const env = process.env.XBROWSER_HOOKS;
|
|
7669
|
+
if (!env) return [];
|
|
7670
|
+
const names = env.split(",").map((n) => n.trim()).filter(Boolean);
|
|
7671
|
+
if (names.length === 0) return [];
|
|
7672
|
+
const hooks = [];
|
|
7673
|
+
for (const name of names) {
|
|
7674
|
+
const hook = HOOK_REGISTRY[name];
|
|
7675
|
+
if (hook) {
|
|
7676
|
+
hooks.push(hook);
|
|
7677
|
+
continue;
|
|
7678
|
+
}
|
|
7679
|
+
const customFactory = customHooks[name];
|
|
7680
|
+
if (customFactory) {
|
|
7681
|
+
const customHook = await customFactory();
|
|
7682
|
+
if (customHook) hooks.push(customHook);
|
|
7683
|
+
}
|
|
7684
|
+
}
|
|
7685
|
+
return hooks;
|
|
7686
|
+
}
|
|
7906
7687
|
|
|
7907
|
-
|
|
7908
|
-
|
|
7909
|
-
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
|
|
7914
|
-
|
|
7915
|
-
|
|
7916
|
-
|
|
7917
|
-
|
|
7688
|
+
// src/fail-codes.ts
|
|
7689
|
+
var FAIL_CODES = {
|
|
7690
|
+
selectorNotFound: "RETRYABLE: selector-not-found",
|
|
7691
|
+
pageNotReady: "RETRYABLE: page-not-ready",
|
|
7692
|
+
elementGone: "RETRYABLE: element-gone",
|
|
7693
|
+
inputNotRetained: "RETRYABLE: input-not-retained",
|
|
7694
|
+
captcha: "HUMAN: captcha",
|
|
7695
|
+
loginWall: "HUMAN: login-wall",
|
|
7696
|
+
permissionDenied: "FATAL: permission-denied",
|
|
7697
|
+
targetGone: "FATAL: target-gone",
|
|
7698
|
+
unknown: "FATAL: unknown"
|
|
7699
|
+
};
|
|
7700
|
+
function classifyFailure(message) {
|
|
7701
|
+
const msg = (message || "").toLowerCase();
|
|
7702
|
+
const pick = (code) => ({
|
|
7703
|
+
code,
|
|
7704
|
+
level: code.split(":")[0],
|
|
7705
|
+
message: message || code
|
|
7706
|
+
});
|
|
7707
|
+
if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
|
|
7708
|
+
if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
|
|
7709
|
+
if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
|
|
7710
|
+
if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
|
|
7711
|
+
return pick(FAIL_CODES.selectorNotFound);
|
|
7712
|
+
if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
|
|
7713
|
+
if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
|
|
7714
|
+
if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
|
|
7715
|
+
return pick(FAIL_CODES.targetGone);
|
|
7716
|
+
return pick(FAIL_CODES.unknown);
|
|
7717
|
+
}
|
|
7918
7718
|
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
|
|
7719
|
+
// src/lib/mistake-ledger.ts
|
|
7720
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
|
|
7721
|
+
import { homedir as homedir5 } from "os";
|
|
7722
|
+
import { join as join7 } from "path";
|
|
7723
|
+
var MISTAKE_THRESHOLD = 3;
|
|
7724
|
+
var MISTAKE_LEDGER_PATH = join7(
|
|
7725
|
+
homedir5(),
|
|
7726
|
+
".xbrowser",
|
|
7727
|
+
"knowledge",
|
|
7728
|
+
"mistakes.json"
|
|
7729
|
+
);
|
|
7730
|
+
function emptyLedger() {
|
|
7731
|
+
return { version: 1, entries: {} };
|
|
7732
|
+
}
|
|
7733
|
+
function normalizeMistakeText(value) {
|
|
7734
|
+
return value.replace(/\d{4}-\d{2}-\d{2}T[^'"\s]+/g, "<timestamp>").replace(/\d+(?:\.\d+)?\s*(?:ms|s)\b/gi, "<duration>").replace(/\b\d+\b/g, "<number>").replace(/\s+/g, " ").trim();
|
|
7735
|
+
}
|
|
7736
|
+
function mistakeFingerprint(category, message) {
|
|
7737
|
+
return `${category}::${normalizeMistakeText(message)}`;
|
|
7738
|
+
}
|
|
7739
|
+
function readMistakeLedger(path2 = MISTAKE_LEDGER_PATH) {
|
|
7740
|
+
try {
|
|
7741
|
+
const parsed = JSON.parse(readFileSync5(path2, "utf8"));
|
|
7742
|
+
if (parsed.version !== 1 || typeof parsed.entries !== "object") {
|
|
7743
|
+
return emptyLedger();
|
|
7923
7744
|
}
|
|
7745
|
+
return parsed;
|
|
7746
|
+
} catch {
|
|
7747
|
+
return emptyLedger();
|
|
7748
|
+
}
|
|
7749
|
+
}
|
|
7750
|
+
function writeMistakeLedger(ledger, path2 = MISTAKE_LEDGER_PATH) {
|
|
7751
|
+
mkdirSync4(join7(path2, ".."), { recursive: true });
|
|
7752
|
+
writeFileSync4(path2, JSON.stringify(ledger, null, 2), "utf8");
|
|
7753
|
+
}
|
|
7754
|
+
function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
|
|
7755
|
+
if (!input.category) throw new Error("mistake category is required");
|
|
7756
|
+
if (!input.command) throw new Error("mistake command is required");
|
|
7757
|
+
if (!input.message) throw new Error("mistake message is required");
|
|
7758
|
+
const ledger = readMistakeLedger(path2);
|
|
7759
|
+
const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
|
|
7760
|
+
const previous = ledger.entries[fingerprint];
|
|
7761
|
+
const occurrence = {
|
|
7762
|
+
timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
7763
|
+
command: input.command,
|
|
7764
|
+
message: input.message,
|
|
7765
|
+
...input.context ? { context: input.context } : {}
|
|
7766
|
+
};
|
|
7767
|
+
const entry = previous ? {
|
|
7768
|
+
...previous,
|
|
7769
|
+
lastSeen: occurrence.timestamp,
|
|
7770
|
+
occurrences: [...previous.occurrences, occurrence].slice(-100),
|
|
7771
|
+
constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
|
|
7772
|
+
} : {
|
|
7773
|
+
fingerprint,
|
|
7774
|
+
category: input.category,
|
|
7775
|
+
firstSeen: occurrence.timestamp,
|
|
7776
|
+
lastSeen: occurrence.timestamp,
|
|
7777
|
+
occurrences: [occurrence],
|
|
7778
|
+
constrained: false
|
|
7779
|
+
};
|
|
7780
|
+
ledger.entries[fingerprint] = entry;
|
|
7781
|
+
writeMistakeLedger(ledger, path2);
|
|
7782
|
+
return {
|
|
7783
|
+
entry,
|
|
7784
|
+
newlyConstrained: Boolean(previous && !previous.constrained && entry.constrained)
|
|
7785
|
+
};
|
|
7786
|
+
}
|
|
7924
7787
|
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7788
|
+
// src/executor/foundation.ts
|
|
7789
|
+
import { homedir as homedir7 } from "os";
|
|
7790
|
+
import { join as join9 } from "path";
|
|
7791
|
+
import {
|
|
7792
|
+
CompositeStorage as CompositeStorage2,
|
|
7793
|
+
configureArchiveStore,
|
|
7794
|
+
appendCommandToArchive,
|
|
7795
|
+
fail as fail17,
|
|
7796
|
+
checkGuard
|
|
7797
|
+
} from "@dyyz1993/xcli-core";
|
|
7932
7798
|
|
|
7933
|
-
|
|
7934
|
-
|
|
7935
|
-
|
|
7936
|
-
|
|
7937
|
-
|
|
7938
|
-
|
|
7939
|
-
|
|
7940
|
-
return 'unknown';
|
|
7941
|
-
}
|
|
7799
|
+
// src/plugin/loader.ts
|
|
7800
|
+
import {
|
|
7801
|
+
Core
|
|
7802
|
+
} from "@dyyz1993/xcli-core";
|
|
7803
|
+
import { resolve as resolve2, basename, dirname as dirname3 } from "path";
|
|
7804
|
+
import { existsSync as existsSync7, readdirSync } from "fs";
|
|
7805
|
+
import { homedir as homedir6 } from "os";
|
|
7942
7806
|
|
|
7943
|
-
|
|
7944
|
-
|
|
7945
|
-
|
|
7946
|
-
return {
|
|
7947
|
-
selector: getSelector(el),
|
|
7948
|
-
tag: el.tagName.toLowerCase(),
|
|
7949
|
-
role: el.getAttribute('role') || undefined,
|
|
7950
|
-
text: (el.textContent || '').trim().slice(0, 100) || undefined,
|
|
7951
|
-
ariaLabel: el.getAttribute('aria-label') || undefined,
|
|
7952
|
-
size: { width: Math.round(rect.width), height: Math.round(rect.height) },
|
|
7953
|
-
position: { x: Math.round(rect.x), y: Math.round(rect.y) },
|
|
7954
|
-
zIndex: parseInt(style.zIndex) || 0,
|
|
7955
|
-
category: categorize(el),
|
|
7956
|
-
};
|
|
7957
|
-
}
|
|
7807
|
+
// src/plugin/metadata-parser.ts
|
|
7808
|
+
import { existsSync as existsSync5 } from "fs";
|
|
7809
|
+
import { resolve } from "path";
|
|
7958
7810
|
|
|
7959
|
-
|
|
7960
|
-
|
|
7961
|
-
|
|
7962
|
-
|
|
7963
|
-
|
|
7964
|
-
|
|
7811
|
+
// src/utils/json-file.ts
|
|
7812
|
+
import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
|
|
7813
|
+
function readJsonFile(filePath, defaultValue) {
|
|
7814
|
+
try {
|
|
7815
|
+
const content = readFileSync6(filePath, "utf-8");
|
|
7816
|
+
return JSON.parse(content);
|
|
7817
|
+
} catch {
|
|
7818
|
+
return defaultValue;
|
|
7965
7819
|
}
|
|
7820
|
+
}
|
|
7966
7821
|
|
|
7967
|
-
|
|
7968
|
-
|
|
7969
|
-
|
|
7970
|
-
|
|
7971
|
-
|
|
7972
|
-
|
|
7973
|
-
|
|
7974
|
-
page;
|
|
7975
|
-
injected = false;
|
|
7976
|
-
constructor(page) {
|
|
7977
|
-
this.page = page;
|
|
7978
|
-
}
|
|
7979
|
-
async inject() {
|
|
7980
|
-
if (this.injected) return;
|
|
7981
|
-
try {
|
|
7982
|
-
await this.page.evaluate(DOM_WATCHER_SCRIPT);
|
|
7983
|
-
await this.page.addInitScript(DOM_WATCHER_SCRIPT);
|
|
7984
|
-
this.injected = true;
|
|
7985
|
-
} catch {
|
|
7822
|
+
// src/plugin/metadata-parser.ts
|
|
7823
|
+
var PluginMetadataParser = class {
|
|
7824
|
+
static XBROWSER_KEYWORDS = ["xbrowser", "xbrowser-plugin"];
|
|
7825
|
+
static parseFromPackageJson(pluginPath) {
|
|
7826
|
+
const packageJsonPath = resolve(pluginPath, "package.json");
|
|
7827
|
+
if (!existsSync5(packageJsonPath)) {
|
|
7828
|
+
return null;
|
|
7986
7829
|
}
|
|
7987
|
-
|
|
7988
|
-
|
|
7989
|
-
|
|
7990
|
-
|
|
7991
|
-
const result = await this.page.evaluate(
|
|
7992
|
-
"window.__xbrowserScanOverlays ? window.__xbrowserScanOverlays() : []"
|
|
7993
|
-
);
|
|
7994
|
-
return result || [];
|
|
7995
|
-
} catch {
|
|
7996
|
-
return [];
|
|
7830
|
+
const packageJson = readJsonFile(packageJsonPath, null);
|
|
7831
|
+
if (!packageJson) return null;
|
|
7832
|
+
if (!packageJson.xbrowser) {
|
|
7833
|
+
return null;
|
|
7997
7834
|
}
|
|
7998
|
-
|
|
7999
|
-
|
|
8000
|
-
|
|
8001
|
-
|
|
8002
|
-
|
|
8003
|
-
|
|
8004
|
-
|
|
8005
|
-
|
|
8006
|
-
|
|
8007
|
-
|
|
8008
|
-
|
|
8009
|
-
|
|
8010
|
-
|
|
8011
|
-
|
|
8012
|
-
// src/tips/context-tracker.ts
|
|
8013
|
-
var ContextTracker = class {
|
|
8014
|
-
history = [];
|
|
8015
|
-
maxHistory = 20;
|
|
8016
|
-
record(commandName, params) {
|
|
8017
|
-
const entry = {
|
|
8018
|
-
commandName,
|
|
8019
|
-
params,
|
|
8020
|
-
timestamp: Date.now(),
|
|
8021
|
-
targetSelector: params.selector || params.url || void 0
|
|
7835
|
+
const xbrowser = packageJson.xbrowser;
|
|
7836
|
+
const metadata = {
|
|
7837
|
+
id: xbrowser.id || packageJson.name,
|
|
7838
|
+
name: xbrowser.name || packageJson.name,
|
|
7839
|
+
description: xbrowser.description || packageJson.description || "",
|
|
7840
|
+
version: xbrowser.version || packageJson.version || "1.0.0",
|
|
7841
|
+
author: xbrowser.author || this.extractAuthor(packageJson.author),
|
|
7842
|
+
homepage: xbrowser.homepage || packageJson.homepage,
|
|
7843
|
+
commands: xbrowser.commands,
|
|
7844
|
+
sites: xbrowser.sites,
|
|
7845
|
+
tags: xbrowser.tags,
|
|
7846
|
+
screenshot: xbrowser.screenshot,
|
|
7847
|
+
license: xbrowser.license || packageJson.license
|
|
8022
7848
|
};
|
|
8023
|
-
|
|
8024
|
-
if (this.history.length > this.maxHistory) {
|
|
8025
|
-
this.history.shift();
|
|
8026
|
-
}
|
|
8027
|
-
}
|
|
8028
|
-
getLastCommand() {
|
|
8029
|
-
return this.history.length > 0 ? this.history[this.history.length - 1] : void 0;
|
|
7849
|
+
return metadata;
|
|
8030
7850
|
}
|
|
8031
|
-
|
|
8032
|
-
|
|
8033
|
-
|
|
8034
|
-
return this.history[i].targetSelector;
|
|
8035
|
-
}
|
|
7851
|
+
static isXBrowserPlugin(packageJson) {
|
|
7852
|
+
if (packageJson.xbrowser) {
|
|
7853
|
+
return true;
|
|
8036
7854
|
}
|
|
8037
|
-
|
|
7855
|
+
const keywords = packageJson.keywords;
|
|
7856
|
+
if (!keywords) return false;
|
|
7857
|
+
return this.XBROWSER_KEYWORDS.some((kw) => keywords.includes(kw));
|
|
8038
7858
|
}
|
|
8039
|
-
|
|
8040
|
-
const
|
|
8041
|
-
|
|
8042
|
-
|
|
8043
|
-
|
|
8044
|
-
|
|
8045
|
-
|
|
8046
|
-
|
|
8047
|
-
|
|
8048
|
-
|
|
8049
|
-
|
|
8050
|
-
|
|
7859
|
+
static fromNPMResult(result) {
|
|
7860
|
+
const author = typeof result.author === "string" ? result.author : result.author?.name || "Unknown";
|
|
7861
|
+
return {
|
|
7862
|
+
id: result.name,
|
|
7863
|
+
name: result.name.replace(/^xbrowser-plugin-/, "").replace(/^@[^/]+\//, ""),
|
|
7864
|
+
description: result.description || "",
|
|
7865
|
+
version: result.version,
|
|
7866
|
+
author,
|
|
7867
|
+
homepage: result.homepage || result.links?.homepage,
|
|
7868
|
+
tags: result.keywords,
|
|
7869
|
+
license: ""
|
|
7870
|
+
};
|
|
8051
7871
|
}
|
|
8052
|
-
|
|
8053
|
-
|
|
8054
|
-
if (
|
|
8055
|
-
|
|
7872
|
+
static extractAuthor(author) {
|
|
7873
|
+
if (typeof author === "string") return author;
|
|
7874
|
+
if (typeof author === "object" && author !== null) {
|
|
7875
|
+
const authorObj = author;
|
|
7876
|
+
return authorObj.name || "Unknown";
|
|
7877
|
+
}
|
|
7878
|
+
return "Unknown";
|
|
8056
7879
|
}
|
|
8057
|
-
|
|
8058
|
-
|
|
7880
|
+
static validateMetadata(metadata) {
|
|
7881
|
+
const errors = [];
|
|
7882
|
+
if (!metadata.id) errors.push("id is required");
|
|
7883
|
+
if (!metadata.name) errors.push("name is required");
|
|
7884
|
+
if (!metadata.description) errors.push("description is required");
|
|
7885
|
+
if (!metadata.version) errors.push("version is required");
|
|
7886
|
+
return errors;
|
|
8059
7887
|
}
|
|
8060
7888
|
};
|
|
8061
7889
|
|
|
8062
|
-
// src/
|
|
8063
|
-
|
|
8064
|
-
|
|
8065
|
-
|
|
8066
|
-
|
|
8067
|
-
|
|
8068
|
-
|
|
8069
|
-
|
|
8070
|
-
|
|
8071
|
-
|
|
8072
|
-
|
|
8073
|
-
|
|
8074
|
-
|
|
8075
|
-
|
|
8076
|
-
|
|
8077
|
-
|
|
8078
|
-
|
|
8079
|
-
|
|
8080
|
-
return currentElements.filter((el) => newSelectors.includes(el.selector));
|
|
8081
|
-
}
|
|
8082
|
-
generate(newElements) {
|
|
8083
|
-
const tips = [];
|
|
8084
|
-
for (const el of newElements) {
|
|
8085
|
-
if (this.contextTracker.isLikelyTriggered(el.selector)) continue;
|
|
8086
|
-
if (SILENT_CATEGORIES.has(el.category)) continue;
|
|
8087
|
-
if (NOTIFICATION_CATEGORIES.has(el.category) && el.text && /success|成功|done|完成|saved|已保存/i.test(el.text)) {
|
|
8088
|
-
continue;
|
|
8089
|
-
}
|
|
8090
|
-
if (this.isRecentlyReported(el.selector)) continue;
|
|
8091
|
-
const priority = classifyPriority(el.category, el);
|
|
8092
|
-
if (priority === "p3") continue;
|
|
8093
|
-
const message = this.buildMessage(el);
|
|
8094
|
-
const suggestions = this.buildSuggestions(el);
|
|
8095
|
-
tips.push({
|
|
8096
|
-
priority,
|
|
8097
|
-
category: el.category,
|
|
8098
|
-
element: el,
|
|
8099
|
-
message,
|
|
8100
|
-
suggestions
|
|
8101
|
-
});
|
|
8102
|
-
this.reportedSelectors.set(el.selector, Date.now());
|
|
8103
|
-
}
|
|
8104
|
-
tips.sort((a, b) => {
|
|
8105
|
-
const order = { p0: 0, p1: 1, p2: 2 };
|
|
8106
|
-
return (order[a.priority] ?? 3) - (order[b.priority] ?? 3);
|
|
8107
|
-
});
|
|
8108
|
-
return tips;
|
|
8109
|
-
}
|
|
8110
|
-
buildMessage(el) {
|
|
8111
|
-
const label = el.ariaLabel || el.text?.slice(0, 40) || "";
|
|
8112
|
-
const labelStr = label ? ` "${label}"` : "";
|
|
8113
|
-
const sizeStr = `${el.size.width}x${el.size.height}`;
|
|
8114
|
-
const typeLabel = this.categoryLabel(el.category);
|
|
8115
|
-
return `\u68C0\u6D4B\u5230\u65B0${typeLabel}${labelStr} (${sizeStr})\uFF0C\u9009\u62E9\u5668: ${el.selector}`;
|
|
8116
|
-
}
|
|
8117
|
-
buildSuggestions(el) {
|
|
8118
|
-
const suggestions = [];
|
|
8119
|
-
if (el.category === "dialog" || el.category === "modal") {
|
|
8120
|
-
const confirmBtn = this.guessButtonSelector(el, ["confirm", "ok", "yes", "\u786E\u5B9A", "\u786E\u8BA4", "\u540C\u610F"]);
|
|
8121
|
-
const cancelBtn = this.guessButtonSelector(el, ["cancel", "close", "no", "\u53D6\u6D88", "\u5173\u95ED", "\u62D2\u7EDD"]);
|
|
8122
|
-
if (confirmBtn) suggestions.push(`click "${confirmBtn}"`);
|
|
8123
|
-
if (cancelBtn) suggestions.push(`click "${cancelBtn}"`);
|
|
8124
|
-
}
|
|
8125
|
-
if (el.category === "popover" || el.category === "overlay") {
|
|
8126
|
-
suggestions.push(`click "${el.selector}"`);
|
|
8127
|
-
}
|
|
8128
|
-
if (el.category === "toast" || el.category === "notification") {
|
|
8129
|
-
suggestions.push(`text "${el.selector}"`);
|
|
8130
|
-
}
|
|
8131
|
-
if (suggestions.length === 0) {
|
|
8132
|
-
suggestions.push(`click "${el.selector}"`);
|
|
7890
|
+
// src/plugin/ensure-deps.ts
|
|
7891
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "fs";
|
|
7892
|
+
import { join as join8 } from "path";
|
|
7893
|
+
import { execSync } from "child_process";
|
|
7894
|
+
var SHARED_PLUGIN_DEPENDENCIES = {
|
|
7895
|
+
"zod": "^3.24.0",
|
|
7896
|
+
"@dyyz1993/xcli-core": "^0.19.0"
|
|
7897
|
+
};
|
|
7898
|
+
function ensurePluginDependencies(pluginsDir) {
|
|
7899
|
+
const zodPath = join8(pluginsDir, "node_modules", "zod");
|
|
7900
|
+
if (existsSync6(zodPath)) return;
|
|
7901
|
+
mkdirSync5(pluginsDir, { recursive: true });
|
|
7902
|
+
const pkgPath = join8(pluginsDir, "package.json");
|
|
7903
|
+
let pkg = {};
|
|
7904
|
+
if (existsSync6(pkgPath)) {
|
|
7905
|
+
try {
|
|
7906
|
+
pkg = readJsonFile(pkgPath, {});
|
|
7907
|
+
} catch {
|
|
8133
7908
|
}
|
|
8134
|
-
return suggestions;
|
|
8135
7909
|
}
|
|
8136
|
-
|
|
8137
|
-
|
|
8138
|
-
|
|
8139
|
-
|
|
7910
|
+
const existingDeps = pkg.dependencies || {};
|
|
7911
|
+
let needsInstall = false;
|
|
7912
|
+
for (const [dep, version] of Object.entries(SHARED_PLUGIN_DEPENDENCIES)) {
|
|
7913
|
+
if (!existingDeps[dep]) {
|
|
7914
|
+
existingDeps[dep] = version;
|
|
7915
|
+
needsInstall = true;
|
|
8140
7916
|
}
|
|
8141
|
-
return void 0;
|
|
8142
7917
|
}
|
|
8143
|
-
|
|
8144
|
-
|
|
8145
|
-
|
|
8146
|
-
|
|
8147
|
-
|
|
8148
|
-
|
|
8149
|
-
|
|
8150
|
-
|
|
8151
|
-
|
|
8152
|
-
|
|
8153
|
-
|
|
8154
|
-
};
|
|
8155
|
-
|
|
8156
|
-
}
|
|
8157
|
-
isRecentlyReported(selector) {
|
|
8158
|
-
const lastTime = this.reportedSelectors.get(selector);
|
|
8159
|
-
if (!lastTime) return false;
|
|
8160
|
-
return Date.now() - lastTime < this.dedupWindowMs;
|
|
8161
|
-
}
|
|
8162
|
-
resetDedup() {
|
|
8163
|
-
this.reportedSelectors.clear();
|
|
7918
|
+
if (!needsInstall && existsSync6(join8(pluginsDir, "node_modules"))) return;
|
|
7919
|
+
pkg.dependencies = existingDeps;
|
|
7920
|
+
pkg.private = true;
|
|
7921
|
+
pkg.description = pkg.description || "xbrowser plugins \u2014 shared dependencies";
|
|
7922
|
+
writeFileSync6(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
|
|
7923
|
+
try {
|
|
7924
|
+
execSync("npm install --production --no-package-lock --no-fund --no-audit", {
|
|
7925
|
+
cwd: pluginsDir,
|
|
7926
|
+
stdio: "pipe",
|
|
7927
|
+
timeout: 6e4,
|
|
7928
|
+
env: { ...process.env, NODE_ENV: "production" }
|
|
7929
|
+
});
|
|
7930
|
+
} catch (err) {
|
|
7931
|
+
console.warn(`\u26A0\uFE0F Failed to install shared plugin dependencies: ${err instanceof Error ? err.message : String(err)}`);
|
|
8164
7932
|
}
|
|
8165
|
-
};
|
|
8166
|
-
function buildSnapshot(elements) {
|
|
8167
|
-
return {
|
|
8168
|
-
timestamp: Date.now(),
|
|
8169
|
-
overlaySelectors: elements.map((el) => el.selector)
|
|
8170
|
-
};
|
|
8171
7933
|
}
|
|
8172
7934
|
|
|
8173
|
-
// src/
|
|
8174
|
-
|
|
8175
|
-
|
|
8176
|
-
|
|
7935
|
+
// src/plugin/contract.ts
|
|
7936
|
+
import {
|
|
7937
|
+
unwrapZod,
|
|
7938
|
+
fieldsFromZodObjectReflected,
|
|
7939
|
+
zodTypeToContractType
|
|
7940
|
+
} from "@dyyz1993/xcli-core";
|
|
7941
|
+
function buildPluginContract(site) {
|
|
7942
|
+
const commands = site.getAllCommands().map((command) => buildCommandContract(site.getCommand?.(command.name) || command, {
|
|
7943
|
+
siteRequiresLogin: site.config?.requiresLogin
|
|
7944
|
+
}));
|
|
7945
|
+
return {
|
|
7946
|
+
version: 2,
|
|
7947
|
+
plugin: {
|
|
7948
|
+
name: site.name,
|
|
7949
|
+
url: site.url,
|
|
7950
|
+
description: site.config?.description,
|
|
7951
|
+
requiresLogin: site.config?.requiresLogin
|
|
7952
|
+
},
|
|
7953
|
+
commands
|
|
7954
|
+
};
|
|
8177
7955
|
}
|
|
8178
|
-
|
|
8179
|
-
|
|
8180
|
-
|
|
8181
|
-
|
|
8182
|
-
|
|
8183
|
-
"
|
|
8184
|
-
|
|
8185
|
-
|
|
8186
|
-
|
|
8187
|
-
|
|
8188
|
-
|
|
8189
|
-
|
|
8190
|
-
|
|
8191
|
-
|
|
8192
|
-
|
|
8193
|
-
|
|
8194
|
-
|
|
8195
|
-
|
|
8196
|
-
|
|
8197
|
-
|
|
8198
|
-
|
|
8199
|
-
|
|
8200
|
-
|
|
8201
|
-
|
|
8202
|
-
|
|
8203
|
-
|
|
8204
|
-
|
|
8205
|
-
|
|
8206
|
-
|
|
8207
|
-
|
|
8208
|
-
|
|
8209
|
-
|
|
8210
|
-
|
|
8211
|
-
|
|
8212
|
-
|
|
8213
|
-
|
|
7956
|
+
function buildCommandContract(command, options = {}) {
|
|
7957
|
+
const extension = command.xbrowser || {};
|
|
7958
|
+
const inferredFields = fieldsFromZodObject(command.parameters);
|
|
7959
|
+
const fields = mergeFields(inferredFields, extension.form?.fields || []);
|
|
7960
|
+
const positional = extension.positional || fields.filter((field) => field.positional).map((field) => field.name);
|
|
7961
|
+
const requiresLogin = command.requiresLogin === true || options.siteRequiresLogin === true && command.name !== "login" && command.name !== "logout";
|
|
7962
|
+
const capabilities = extension.capabilities || inferCapabilities(command.scope || "project", requiresLogin);
|
|
7963
|
+
const outputSchema = command.result ? summarizeZod(command.result) : void 0;
|
|
7964
|
+
return {
|
|
7965
|
+
name: command.name,
|
|
7966
|
+
description: command.description || "",
|
|
7967
|
+
scope: command.scope || "project",
|
|
7968
|
+
requiresLogin,
|
|
7969
|
+
category: extension.category,
|
|
7970
|
+
capabilities,
|
|
7971
|
+
positional,
|
|
7972
|
+
form: {
|
|
7973
|
+
title: extension.form?.title || command.description || command.name,
|
|
7974
|
+
description: extension.form?.description,
|
|
7975
|
+
submitLabel: extension.form?.submitLabel || "Run",
|
|
7976
|
+
fields
|
|
7977
|
+
},
|
|
7978
|
+
output: extension.output || (outputSchema ? { schema: outputSchema } : void 0)
|
|
7979
|
+
};
|
|
7980
|
+
}
|
|
7981
|
+
function fieldsFromZodObject(schema) {
|
|
7982
|
+
const reflected = fieldsFromZodObjectReflected(schema);
|
|
7983
|
+
return reflected.map((field) => {
|
|
7984
|
+
const widget = widgetFor(field.type, field.enum);
|
|
7985
|
+
return {
|
|
7986
|
+
name: field.name,
|
|
7987
|
+
label: toLabel(field.name),
|
|
7988
|
+
type: field.type,
|
|
7989
|
+
widget,
|
|
7990
|
+
required: field.required,
|
|
7991
|
+
...field.description ? { description: field.description } : {},
|
|
7992
|
+
...field.default !== void 0 ? { default: field.default } : {},
|
|
7993
|
+
...field.enum ? { enum: field.enum } : {},
|
|
7994
|
+
...field.type === "array" ? { multiple: true } : {}
|
|
7995
|
+
};
|
|
7996
|
+
});
|
|
7997
|
+
}
|
|
7998
|
+
function mergeFields(inferred, overrides) {
|
|
7999
|
+
if (overrides.length === 0) return inferred;
|
|
8000
|
+
const byName = new Map(inferred.map((field) => [field.name, field]));
|
|
8001
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8002
|
+
const merged = [];
|
|
8003
|
+
for (const override of overrides) {
|
|
8004
|
+
if (!override.name) continue;
|
|
8005
|
+
const base = byName.get(override.name) || {
|
|
8006
|
+
name: override.name,
|
|
8007
|
+
label: toLabel(override.name),
|
|
8008
|
+
type: "string",
|
|
8009
|
+
widget: "text",
|
|
8010
|
+
required: false
|
|
8011
|
+
};
|
|
8012
|
+
merged.push({ ...base, ...override, name: override.name });
|
|
8013
|
+
seen.add(override.name);
|
|
8014
|
+
}
|
|
8015
|
+
for (const field of inferred) {
|
|
8016
|
+
if (!seen.has(field.name)) merged.push(field);
|
|
8017
|
+
}
|
|
8018
|
+
return merged;
|
|
8019
|
+
}
|
|
8020
|
+
function inferCapabilities(scope, requiresLogin) {
|
|
8021
|
+
const caps = [];
|
|
8022
|
+
if (scope === "page") caps.push("browser.page");
|
|
8023
|
+
if (scope === "browser") caps.push("browser.context");
|
|
8024
|
+
if (requiresLogin) caps.push("auth.login");
|
|
8025
|
+
return caps;
|
|
8026
|
+
}
|
|
8027
|
+
function widgetFor(type, enumValues) {
|
|
8028
|
+
if (enumValues) return "select";
|
|
8029
|
+
if (type === "boolean") return "checkbox";
|
|
8030
|
+
if (type === "number") return "number";
|
|
8031
|
+
if (type === "array") return "multi-select";
|
|
8032
|
+
if (type === "object") return "json";
|
|
8033
|
+
return "text";
|
|
8034
|
+
}
|
|
8035
|
+
function summarizeZod(schema) {
|
|
8036
|
+
const unwrapped = unwrapZod(schema);
|
|
8037
|
+
if (unwrapped.typeName === "ZodArray") {
|
|
8038
|
+
const def = unwrapped.schema?._def;
|
|
8039
|
+
return {
|
|
8040
|
+
type: "array",
|
|
8041
|
+
items: summarizeZod(def?.type || def?.innerType)
|
|
8042
|
+
};
|
|
8043
|
+
}
|
|
8044
|
+
const shape = getObjectShape(schema);
|
|
8045
|
+
if (!shape) {
|
|
8046
|
+
return {
|
|
8047
|
+
type: zodTypeToContractType(unwrapped.typeName),
|
|
8048
|
+
required: !unwrapped.optional,
|
|
8049
|
+
...unwrapped.description ? { description: unwrapped.description } : {}
|
|
8050
|
+
};
|
|
8051
|
+
}
|
|
8052
|
+
return Object.fromEntries(
|
|
8053
|
+
Object.entries(shape).map(([name, field]) => {
|
|
8054
|
+
const inner = unwrapZod(field);
|
|
8055
|
+
return [name, {
|
|
8056
|
+
type: zodTypeToContractType(inner.typeName),
|
|
8057
|
+
required: !inner.optional,
|
|
8058
|
+
...inner.description ? { description: inner.description } : {}
|
|
8059
|
+
}];
|
|
8060
|
+
})
|
|
8061
|
+
);
|
|
8062
|
+
}
|
|
8063
|
+
function getObjectShape(schema) {
|
|
8064
|
+
const zod = schema;
|
|
8065
|
+
const shapeOrFn = zod?.shape ?? zod?._def?.shape;
|
|
8066
|
+
if (!shapeOrFn) return void 0;
|
|
8067
|
+
return typeof shapeOrFn === "function" ? shapeOrFn() : shapeOrFn;
|
|
8068
|
+
}
|
|
8069
|
+
function toLabel(name) {
|
|
8070
|
+
return name.replace(/([A-Z])/g, " $1").replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim().replace(/^./, (char) => char.toUpperCase());
|
|
8071
|
+
}
|
|
8072
|
+
|
|
8073
|
+
// src/plugin/login-required-patch.ts
|
|
8074
|
+
import { SiteInstanceImpl } from "@dyyz1993/xcli-core";
|
|
8075
|
+
var patched = false;
|
|
8076
|
+
function patchLoginRequired() {
|
|
8077
|
+
if (patched) return;
|
|
8078
|
+
patched = true;
|
|
8079
|
+
const target = SiteInstanceImpl.prototype;
|
|
8080
|
+
const originalCommand = target.command;
|
|
8081
|
+
const wrapped = function(...args) {
|
|
8082
|
+
const result = originalCommand.apply(this, args);
|
|
8083
|
+
const [name, cmd] = args;
|
|
8084
|
+
const loginRequired = cmd.loginRequired;
|
|
8085
|
+
if (loginRequired) {
|
|
8086
|
+
const commands = this.commands;
|
|
8087
|
+
const entry = commands?.get(name);
|
|
8088
|
+
if (entry) {
|
|
8089
|
+
entry.loginRequired = loginRequired;
|
|
8090
|
+
}
|
|
8091
|
+
}
|
|
8092
|
+
return result;
|
|
8093
|
+
};
|
|
8094
|
+
Object.defineProperty(target, "command", {
|
|
8095
|
+
value: wrapped,
|
|
8096
|
+
writable: true,
|
|
8097
|
+
configurable: true
|
|
8098
|
+
});
|
|
8099
|
+
}
|
|
8100
|
+
|
|
8101
|
+
// src/plugin/loader.ts
|
|
8102
|
+
var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
|
|
8103
|
+
var XBrowserPluginLoader = class {
|
|
8104
|
+
core;
|
|
8105
|
+
loader;
|
|
8106
|
+
options;
|
|
8107
|
+
/** 目录名 → 该插件注册的 site 名(site.name ≠ 目录名时的命令别名兜底) */
|
|
8108
|
+
dirSiteAliases = /* @__PURE__ */ new Map();
|
|
8109
|
+
constructor(options) {
|
|
8110
|
+
patchLoginRequired();
|
|
8111
|
+
globalThis.__xbrowserRecordMistake = recordMistake;
|
|
8112
|
+
this.options = options ?? {};
|
|
8113
|
+
const cwd = this.options.cwd || process.cwd();
|
|
8114
|
+
const coreConfig = {
|
|
8115
|
+
name: "xbrowser",
|
|
8116
|
+
version: "0.1.0",
|
|
8117
|
+
description: "Browser automation CLI",
|
|
8118
|
+
configDirName: ".xbrowser",
|
|
8119
|
+
envPrefix: "XBROWSER",
|
|
8120
|
+
pluginDirs: [
|
|
8121
|
+
...DEFAULT_PLUGIN_DIRS,
|
|
8122
|
+
resolve2(cwd, ".xcli/plugins")
|
|
8123
|
+
]
|
|
8124
|
+
};
|
|
8125
|
+
this.core = new Core(coreConfig);
|
|
8126
|
+
this.loader = this.core.loader;
|
|
8127
|
+
}
|
|
8128
|
+
getAPI() {
|
|
8129
|
+
return this.loader.getAPI();
|
|
8130
|
+
}
|
|
8131
|
+
/**
|
|
8132
|
+
* Get the core instance for external use.
|
|
8133
|
+
* @returns The xcli-core Core instance.
|
|
8134
|
+
*/
|
|
8135
|
+
getCore() {
|
|
8136
|
+
return this.core;
|
|
8137
|
+
}
|
|
8138
|
+
getPlugin(id) {
|
|
8139
|
+
return this.loader.getPlugin(id);
|
|
8140
|
+
}
|
|
8141
|
+
getPluginStatus(id) {
|
|
8142
|
+
return this.loader.getPluginStatus(id);
|
|
8143
|
+
}
|
|
8144
|
+
getLoadedPlugins() {
|
|
8145
|
+
return this.loader.getLoadedPlugins();
|
|
8146
|
+
}
|
|
8147
|
+
/**
|
|
8148
|
+
* 目录名别名兜底(小白用户实测踩坑):`plugin list` 显示目录名,但命令路由
|
|
8149
|
+
* 按 site.name 匹配——两者不一致时(如目录 alibaba-1688、site 名 1688),
|
|
8150
|
+
* 用户按 list 显示的名字敲命令会 "Unknown command"。映射在 scanAndLoad/
|
|
8151
|
+
* loadPlugin 时通过加载前后 site 快照 diff 记录(instance.siteName 返回的是
|
|
8152
|
+
* 插件 id 而非 site 名,不可用)。
|
|
8153
|
+
*/
|
|
8154
|
+
resolveSiteName(name) {
|
|
8155
|
+
if (this.core.loader.getSite(name)) return name;
|
|
8156
|
+
const aliased = this.dirSiteAliases.get(name);
|
|
8157
|
+
if (aliased && this.core.loader.getSite(aliased)) return aliased;
|
|
8158
|
+
return void 0;
|
|
8159
|
+
}
|
|
8160
|
+
/** 记录一次插件加载引入的 site:加载前后快照 diff(同插件可注册多个 site) */
|
|
8161
|
+
recordSiteAliases(pluginDirName, before) {
|
|
8162
|
+
for (const site of this.core.loader.getSites()) {
|
|
8163
|
+
if (!before.has(site.name)) this.dirSiteAliases.set(pluginDirName, site.name);
|
|
8164
|
+
}
|
|
8165
|
+
}
|
|
8166
|
+
getPluginContract(siteName, commandName) {
|
|
8167
|
+
const resolved = this.resolveSiteName(siteName);
|
|
8168
|
+
if (!resolved) return void 0;
|
|
8169
|
+
const site = this.core.loader.getSite(resolved);
|
|
8170
|
+
if (!site) return void 0;
|
|
8171
|
+
const contract = buildPluginContract(site);
|
|
8172
|
+
if (!commandName) return contract;
|
|
8173
|
+
return contract.commands.find((command) => command.name === commandName);
|
|
8174
|
+
}
|
|
8175
|
+
async loadPlugin(pluginPath, id) {
|
|
8176
|
+
const before = new Set(this.core.loader.getSites().map((s) => s.name));
|
|
8177
|
+
const instance = await this.loader.loadPlugin(pluginPath, id);
|
|
8178
|
+
this.recordSiteAliases(basename(dirname3(pluginPath)), before);
|
|
8179
|
+
return instance;
|
|
8180
|
+
}
|
|
8181
|
+
async unloadPlugin(id) {
|
|
8182
|
+
return this.loader.unloadPlugin(id);
|
|
8183
|
+
}
|
|
8184
|
+
async reloadPlugin(id) {
|
|
8185
|
+
return this.loader.reloadPlugin(id);
|
|
8186
|
+
}
|
|
8187
|
+
async loadFromFunction(setup) {
|
|
8188
|
+
return this.loader.loadFromFunction(setup);
|
|
8189
|
+
}
|
|
8190
|
+
async scanAndLoad() {
|
|
8191
|
+
const cwd = this.options.cwd || process.cwd();
|
|
8192
|
+
const globalDir = this.options.globalDir || resolve2(homedir6(), ".xbrowser/plugins");
|
|
8193
|
+
ensurePluginDependencies(globalDir);
|
|
8194
|
+
const dirs = [
|
|
8195
|
+
resolve2(cwd, ".xcli/plugins"),
|
|
8196
|
+
resolve2(cwd, "../.xcli/plugins"),
|
|
8197
|
+
this.options.userDir || resolve2(homedir6(), ".xcli/plugins"),
|
|
8198
|
+
globalDir
|
|
8199
|
+
];
|
|
8200
|
+
const loaded = [];
|
|
8201
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8202
|
+
for (const dir of dirs) {
|
|
8203
|
+
if (!existsSync7(dir)) continue;
|
|
8204
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
8205
|
+
for (const entry of entries) {
|
|
8206
|
+
if (!entry.isDirectory()) continue;
|
|
8207
|
+
if (seen.has(entry.name)) continue;
|
|
8208
|
+
seen.add(entry.name);
|
|
8209
|
+
const pluginDir = resolve2(dir, entry.name);
|
|
8210
|
+
let indexPath = resolve2(pluginDir, "index.js");
|
|
8211
|
+
if (!existsSync7(indexPath)) {
|
|
8212
|
+
indexPath = resolve2(pluginDir, "index.ts");
|
|
8213
|
+
}
|
|
8214
|
+
if (!existsSync7(indexPath)) continue;
|
|
8215
|
+
try {
|
|
8216
|
+
if (!existsSync7(resolve2(pluginDir, "package.json"))) {
|
|
8217
|
+
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
|
|
8218
|
+
} else {
|
|
8219
|
+
const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
|
|
8220
|
+
if (!metadata) {
|
|
8221
|
+
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has package.json but no xbrowser metadata. Add { "xbrowser": { "description": "..." } } to package.json.`);
|
|
8222
|
+
}
|
|
8223
|
+
}
|
|
8224
|
+
const instance = await this.loadPlugin(indexPath, entry.name);
|
|
8225
|
+
loaded.push(instance);
|
|
8226
|
+
} catch (err) {
|
|
8227
|
+
const errMsg2 = err instanceof Error ? err.message : String(err);
|
|
8228
|
+
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" load failed: ${errMsg2}`);
|
|
8229
|
+
if (errMsg2.includes("Cannot find module") && errMsg2.includes("shared/")) {
|
|
8230
|
+
console.warn(` \u{1F4A1} This plugin needs shared/ dependencies. Try: xbrowser plugin install shared`);
|
|
8231
|
+
}
|
|
8232
|
+
}
|
|
8233
|
+
}
|
|
8214
8234
|
}
|
|
8235
|
+
return loaded;
|
|
8236
|
+
}
|
|
8237
|
+
async unload() {
|
|
8238
|
+
return this.loader.unload();
|
|
8239
|
+
}
|
|
8240
|
+
};
|
|
8241
|
+
|
|
8242
|
+
// src/utils/plugin-singleton.ts
|
|
8243
|
+
var pluginLoader = null;
|
|
8244
|
+
var pluginsScanned = false;
|
|
8245
|
+
function silenceSchemaWarnings(fn) {
|
|
8246
|
+
if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
|
|
8247
|
+
const originalWarn = console.warn;
|
|
8248
|
+
console.warn = (...args) => {
|
|
8249
|
+
const msg = typeof args[0] === "string" ? args[0] : "";
|
|
8250
|
+
if (msg.includes('has no "result" schema')) return;
|
|
8251
|
+
originalWarn(...args);
|
|
8252
|
+
};
|
|
8253
|
+
return fn().finally(() => {
|
|
8254
|
+
console.warn = originalWarn;
|
|
8255
|
+
});
|
|
8256
|
+
}
|
|
8257
|
+
async function getPluginLoader() {
|
|
8258
|
+
if (!pluginLoader) {
|
|
8259
|
+
pluginLoader = new XBrowserPluginLoader();
|
|
8260
|
+
}
|
|
8261
|
+
if (!pluginsScanned) {
|
|
8262
|
+
await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
|
|
8263
|
+
pluginsScanned = true;
|
|
8264
|
+
}
|
|
8265
|
+
return pluginLoader;
|
|
8266
|
+
}
|
|
8267
|
+
|
|
8268
|
+
// src/executor/foundation.ts
|
|
8269
|
+
var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
|
|
8270
|
+
var snapshotHintShown = /* @__PURE__ */ new WeakSet();
|
|
8271
|
+
var CONFIG_DIR2 = join9(homedir7(), ".xbrowser");
|
|
8272
|
+
var storageCache = /* @__PURE__ */ new Map();
|
|
8273
|
+
function getPluginStorage(pluginName) {
|
|
8274
|
+
if (!storageCache.has(pluginName)) {
|
|
8275
|
+
storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
|
|
8276
|
+
}
|
|
8277
|
+
return storageCache.get(pluginName);
|
|
8278
|
+
}
|
|
8279
|
+
var archiveInitialized = false;
|
|
8280
|
+
function ensureArchiveInit() {
|
|
8281
|
+
if (!archiveInitialized) {
|
|
8215
8282
|
try {
|
|
8216
|
-
|
|
8217
|
-
const elements = await this.domWatcher.scanOverlays();
|
|
8218
|
-
this.beforeSnapshot = buildSnapshot(elements);
|
|
8283
|
+
configureArchiveStore({ archiveDir: join9(homedir7(), ".xbrowser", "archives") });
|
|
8219
8284
|
} catch {
|
|
8220
|
-
this.beforeSnapshot = { timestamp: Date.now(), overlaySelectors: [] };
|
|
8221
8285
|
}
|
|
8222
|
-
|
|
8223
|
-
|
|
8286
|
+
archiveInitialized = true;
|
|
8287
|
+
}
|
|
8288
|
+
}
|
|
8289
|
+
function recordArchive(sessionId, sessionName, entry) {
|
|
8290
|
+
if (!sessionId) return;
|
|
8291
|
+
try {
|
|
8292
|
+
ensureArchiveInit();
|
|
8293
|
+
appendCommandToArchive(sessionId, sessionName, entry);
|
|
8294
|
+
} catch {
|
|
8295
|
+
}
|
|
8296
|
+
}
|
|
8297
|
+
async function guardCheck(commandName) {
|
|
8298
|
+
try {
|
|
8299
|
+
const loader = await getPluginLoader();
|
|
8300
|
+
return checkGuard(loader.getCore(), commandName, process.env);
|
|
8301
|
+
} catch {
|
|
8302
|
+
return null;
|
|
8303
|
+
}
|
|
8304
|
+
}
|
|
8305
|
+
function errorResult(message) {
|
|
8306
|
+
return { ...fail17(message), duration: 0 };
|
|
8307
|
+
}
|
|
8308
|
+
function tipsToMessages(tips) {
|
|
8309
|
+
if (!tips || tips.length === 0) return [];
|
|
8310
|
+
return tips.map((tip) => typeof tip === "string" ? tip : tip.message);
|
|
8311
|
+
}
|
|
8312
|
+
var wsServer = null;
|
|
8313
|
+
function streamCommandEvent(sessionId, message) {
|
|
8314
|
+
if (!wsServer || !wsServer.getRunning()) return;
|
|
8315
|
+
wsServer.broadcastToSession(sessionId, { type: "command", data: message });
|
|
8316
|
+
}
|
|
8317
|
+
|
|
8318
|
+
// src/executor/chain.ts
|
|
8319
|
+
import {
|
|
8320
|
+
fail as fail18,
|
|
8321
|
+
ok as ok32,
|
|
8322
|
+
TipCollector as TipCollector2,
|
|
8323
|
+
normalizeTips as normalizeTips7,
|
|
8324
|
+
unquote as unquote2
|
|
8325
|
+
} from "@dyyz1993/xcli-core";
|
|
8326
|
+
|
|
8327
|
+
// src/plugin/login-guard.ts
|
|
8328
|
+
async function checkPluginLoginRequired(options) {
|
|
8329
|
+
const { site, command, commandName, ctx, page, sessionName } = options;
|
|
8330
|
+
if (commandName === "login" || commandName === "logout") return { ok: true };
|
|
8331
|
+
const loginConfig = site.config?.loginConfig;
|
|
8332
|
+
const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
|
|
8333
|
+
if (!requiresLogin) return { ok: true };
|
|
8334
|
+
const pluginName = site.name || "plugin";
|
|
8335
|
+
const siteConfig = site.config;
|
|
8336
|
+
const configIsLogin = siteConfig?.isLogin;
|
|
8337
|
+
if (configIsLogin) {
|
|
8338
|
+
try {
|
|
8339
|
+
const loggedIn = await configIsLogin(ctx);
|
|
8340
|
+
if (loggedIn) return { ok: true };
|
|
8341
|
+
return buildLoginRequired({
|
|
8342
|
+
plugin: pluginName,
|
|
8343
|
+
command: commandName,
|
|
8344
|
+
reason: "config.isLogin returned false",
|
|
8345
|
+
sessionName,
|
|
8346
|
+
loginConfig
|
|
8347
|
+
});
|
|
8348
|
+
} catch {
|
|
8224
8349
|
}
|
|
8225
8350
|
}
|
|
8226
|
-
|
|
8227
|
-
|
|
8228
|
-
|
|
8229
|
-
|
|
8230
|
-
|
|
8231
|
-
|
|
8232
|
-
|
|
8351
|
+
if (typeof site.isLoggedIn === "function") {
|
|
8352
|
+
try {
|
|
8353
|
+
const loggedIn = await site.isLoggedIn(ctx);
|
|
8354
|
+
if (loggedIn) return { ok: true };
|
|
8355
|
+
return buildLoginRequired({
|
|
8356
|
+
plugin: pluginName,
|
|
8357
|
+
command: commandName,
|
|
8358
|
+
reason: "plugin isLoggedIn returned false",
|
|
8359
|
+
sessionName,
|
|
8360
|
+
loginConfig
|
|
8361
|
+
});
|
|
8362
|
+
} catch {
|
|
8233
8363
|
}
|
|
8234
|
-
|
|
8235
|
-
|
|
8236
|
-
|
|
8237
|
-
|
|
8238
|
-
|
|
8239
|
-
|
|
8364
|
+
}
|
|
8365
|
+
if (page && loginConfig) {
|
|
8366
|
+
const generic = await detectLoginFromPage(page, loginConfig);
|
|
8367
|
+
if (generic === "logged-in") return { ok: true };
|
|
8368
|
+
if (generic === "logged-out") {
|
|
8369
|
+
return buildLoginRequired({
|
|
8370
|
+
plugin: pluginName,
|
|
8371
|
+
command: commandName,
|
|
8372
|
+
reason: "generic loginConfig detected logged-out page",
|
|
8373
|
+
sessionName,
|
|
8374
|
+
loginConfig
|
|
8375
|
+
});
|
|
8376
|
+
}
|
|
8377
|
+
}
|
|
8378
|
+
return { ok: true };
|
|
8379
|
+
}
|
|
8380
|
+
function buildLoginRequired(options) {
|
|
8381
|
+
const viewerUrl = buildViewerUrl(options.sessionName);
|
|
8382
|
+
const loginUrl = options.loginConfig?.loginUrl;
|
|
8383
|
+
const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
|
|
8384
|
+
const tips = [
|
|
8385
|
+
message,
|
|
8386
|
+
...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
|
|
8387
|
+
...loginUrl ? [`Login page: ${loginUrl}`] : [],
|
|
8388
|
+
`After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
|
|
8389
|
+
];
|
|
8390
|
+
return {
|
|
8391
|
+
ok: false,
|
|
8392
|
+
data: {
|
|
8393
|
+
code: "LOGIN_REQUIRED",
|
|
8394
|
+
plugin: options.plugin,
|
|
8395
|
+
command: options.command,
|
|
8396
|
+
reason: options.reason,
|
|
8397
|
+
...viewerUrl ? { viewerUrl } : {},
|
|
8398
|
+
...loginUrl ? { loginUrl } : {}
|
|
8399
|
+
},
|
|
8400
|
+
message,
|
|
8401
|
+
tips
|
|
8402
|
+
};
|
|
8403
|
+
}
|
|
8404
|
+
async function detectLoginFromPage(page, config) {
|
|
8405
|
+
const url = page.url();
|
|
8406
|
+
if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
|
|
8407
|
+
const result = await page.evaluate((cfg) => {
|
|
8408
|
+
const visible = (selector) => {
|
|
8409
|
+
try {
|
|
8410
|
+
const el = document.querySelector(selector);
|
|
8411
|
+
if (!el) return false;
|
|
8412
|
+
const rect = el.getBoundingClientRect();
|
|
8413
|
+
const style = window.getComputedStyle(el);
|
|
8414
|
+
return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
|
|
8415
|
+
} catch {
|
|
8416
|
+
return false;
|
|
8417
|
+
}
|
|
8240
8418
|
};
|
|
8241
|
-
|
|
8242
|
-
if (
|
|
8243
|
-
|
|
8244
|
-
|
|
8245
|
-
|
|
8246
|
-
|
|
8247
|
-
console.log("\u{1F4A1} Action blocked. To continue:");
|
|
8248
|
-
console.log(" 1. Use viewer mode: xbrowser viewer --json");
|
|
8249
|
-
console.log(" 2. Or skip detection with --skip-detect flag\n");
|
|
8250
|
-
throw new Error(`Anti-bot detection blocked: ${result.message}`);
|
|
8419
|
+
if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
|
|
8420
|
+
if (cfg.loginSelectors?.some(visible)) return "logged-out";
|
|
8421
|
+
const bodyText = document.body?.innerText || "";
|
|
8422
|
+
const keywords = cfg.loginKeywords || [];
|
|
8423
|
+
if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
|
|
8424
|
+
return "logged-out";
|
|
8251
8425
|
}
|
|
8426
|
+
return "unknown";
|
|
8427
|
+
}, {
|
|
8428
|
+
loginSelectors: config.loginSelectors || [],
|
|
8429
|
+
loginKeywords: config.loginKeywords || [],
|
|
8430
|
+
loggedInSelectors: config.loggedInSelectors || []
|
|
8431
|
+
});
|
|
8432
|
+
return result;
|
|
8433
|
+
}
|
|
8434
|
+
|
|
8435
|
+
// src/utils/positional-params.ts
|
|
8436
|
+
import { unquote } from "@dyyz1993/xcli-core";
|
|
8437
|
+
function getTypeName(field) {
|
|
8438
|
+
return field?._def?.typeName;
|
|
8439
|
+
}
|
|
8440
|
+
function unwrapField(field) {
|
|
8441
|
+
const typeName = getTypeName(field);
|
|
8442
|
+
if (typeName === "ZodOptional" || typeName === "ZodDefault") {
|
|
8443
|
+
const innerType = field?._def?.innerType;
|
|
8444
|
+
return unwrapField(innerType);
|
|
8252
8445
|
}
|
|
8253
|
-
|
|
8254
|
-
|
|
8255
|
-
|
|
8256
|
-
|
|
8257
|
-
|
|
8258
|
-
|
|
8259
|
-
|
|
8260
|
-
|
|
8261
|
-
|
|
8262
|
-
|
|
8263
|
-
|
|
8264
|
-
|
|
8265
|
-
|
|
8446
|
+
return field;
|
|
8447
|
+
}
|
|
8448
|
+
function isOptionalNumber(field) {
|
|
8449
|
+
const typeName = getTypeName(field);
|
|
8450
|
+
return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
|
|
8451
|
+
}
|
|
8452
|
+
function coerceValue(raw, field) {
|
|
8453
|
+
const inner = unwrapField(field);
|
|
8454
|
+
const optionalNum = isOptionalNumber(field);
|
|
8455
|
+
const innerTypeName = getTypeName(inner);
|
|
8456
|
+
if (innerTypeName === "ZodString") {
|
|
8457
|
+
return { value: unquote(raw), skip: false };
|
|
8458
|
+
}
|
|
8459
|
+
if (innerTypeName === "ZodNumber") {
|
|
8460
|
+
const parsed = Number(raw);
|
|
8461
|
+
if (isNaN(parsed)) {
|
|
8462
|
+
if (optionalNum) return { value: void 0, skip: true };
|
|
8463
|
+
return { value: raw, skip: false };
|
|
8266
8464
|
}
|
|
8465
|
+
return { value: parsed, skip: false };
|
|
8267
8466
|
}
|
|
8268
|
-
|
|
8269
|
-
|
|
8270
|
-
if (
|
|
8271
|
-
return
|
|
8467
|
+
if (innerTypeName === "ZodBoolean") {
|
|
8468
|
+
if (raw === "true" || raw === "1") return { value: true, skip: false };
|
|
8469
|
+
if (raw === "false" || raw === "0") return { value: false, skip: false };
|
|
8470
|
+
return { value: raw, skip: false };
|
|
8272
8471
|
}
|
|
8273
|
-
|
|
8274
|
-
|
|
8275
|
-
|
|
8276
|
-
|
|
8277
|
-
|
|
8278
|
-
|
|
8279
|
-
|
|
8280
|
-
|
|
8472
|
+
return { value: unquote(raw), skip: false };
|
|
8473
|
+
}
|
|
8474
|
+
function mapPositionalValues(schema, positional, existing) {
|
|
8475
|
+
const result = { ...existing };
|
|
8476
|
+
if (!schema || typeof schema !== "object") return result;
|
|
8477
|
+
const shape = schema.shape;
|
|
8478
|
+
if (!shape || typeof shape !== "object") return result;
|
|
8479
|
+
const keys = Object.keys(shape);
|
|
8480
|
+
let pIdx = 0;
|
|
8481
|
+
for (const key of keys) {
|
|
8482
|
+
if (pIdx >= positional.length) break;
|
|
8483
|
+
if (result[key] !== void 0) {
|
|
8484
|
+
pIdx++;
|
|
8485
|
+
continue;
|
|
8486
|
+
}
|
|
8487
|
+
const field = shape[key];
|
|
8488
|
+
const raw = positional[pIdx];
|
|
8489
|
+
const { value, skip } = coerceValue(raw, field);
|
|
8490
|
+
if (skip) continue;
|
|
8491
|
+
result[key] = value;
|
|
8492
|
+
pIdx++;
|
|
8281
8493
|
}
|
|
8282
|
-
|
|
8283
|
-
|
|
8284
|
-
|
|
8285
|
-
|
|
8286
|
-
|
|
8287
|
-
|
|
8494
|
+
return result;
|
|
8495
|
+
}
|
|
8496
|
+
|
|
8497
|
+
// src/utils/plugin-params.ts
|
|
8498
|
+
function schemaFieldType(schema, key) {
|
|
8499
|
+
const shape = schema?.shape;
|
|
8500
|
+
const field = shape?.[key];
|
|
8501
|
+
let current = field;
|
|
8502
|
+
while (current) {
|
|
8503
|
+
const def = current._def;
|
|
8504
|
+
if (!def) return void 0;
|
|
8505
|
+
const type = def.typeName ?? def.type;
|
|
8506
|
+
if (type === "ZodOptional" || type === "ZodDefault" || type === "ZodNullable" || type === "optional" || type === "default" || type === "nullable") {
|
|
8507
|
+
current = def.innerType ?? def.inner;
|
|
8508
|
+
continue;
|
|
8509
|
+
}
|
|
8510
|
+
return type;
|
|
8288
8511
|
}
|
|
8289
|
-
|
|
8290
|
-
|
|
8291
|
-
function
|
|
8292
|
-
|
|
8293
|
-
|
|
8512
|
+
return void 0;
|
|
8513
|
+
}
|
|
8514
|
+
function parsePluginParams(args, schema, base = {}) {
|
|
8515
|
+
const params = { ...base };
|
|
8516
|
+
const positionalValues = [];
|
|
8517
|
+
for (let i = 0; i < args.length; i++) {
|
|
8518
|
+
if (args[i] === "--" && args[i + 1]) {
|
|
8519
|
+
try {
|
|
8520
|
+
Object.assign(params, JSON.parse(args[i + 1]));
|
|
8521
|
+
} catch {
|
|
8522
|
+
}
|
|
8523
|
+
break;
|
|
8524
|
+
}
|
|
8525
|
+
if (args[i].startsWith("--")) {
|
|
8526
|
+
const key = args[i].slice(2);
|
|
8527
|
+
const value = args[i + 1];
|
|
8528
|
+
if (value && !value.startsWith("-")) {
|
|
8529
|
+
const type = schemaFieldType(schema, key.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
|
|
8530
|
+
if (type === "ZodString" || type === "string") params[key] = value;
|
|
8531
|
+
else if (value === "true") params[key] = true;
|
|
8532
|
+
else if (value === "false") params[key] = false;
|
|
8533
|
+
else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
|
|
8534
|
+
else {
|
|
8535
|
+
try {
|
|
8536
|
+
const parsed = JSON.parse(value);
|
|
8537
|
+
if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
|
|
8538
|
+
params[key] = parsed;
|
|
8539
|
+
} else {
|
|
8540
|
+
params[key] = value;
|
|
8541
|
+
}
|
|
8542
|
+
} catch {
|
|
8543
|
+
params[key] = value;
|
|
8544
|
+
}
|
|
8545
|
+
}
|
|
8546
|
+
i++;
|
|
8547
|
+
} else {
|
|
8548
|
+
params[key] = true;
|
|
8549
|
+
}
|
|
8550
|
+
} else if (!args[i].startsWith("-")) {
|
|
8551
|
+
positionalValues.push(args[i]);
|
|
8552
|
+
}
|
|
8294
8553
|
}
|
|
8295
|
-
|
|
8554
|
+
Object.assign(params, mapPositionalValues(schema, positionalValues, params));
|
|
8555
|
+
const result = {};
|
|
8556
|
+
for (const [k, v] of Object.entries(params)) {
|
|
8557
|
+
const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
8558
|
+
result[camelKey] = v;
|
|
8559
|
+
}
|
|
8560
|
+
return result;
|
|
8296
8561
|
}
|
|
8297
8562
|
|
|
8298
|
-
// src/
|
|
8299
|
-
|
|
8300
|
-
|
|
8301
|
-
"
|
|
8302
|
-
|
|
8303
|
-
|
|
8304
|
-
|
|
8305
|
-
|
|
8306
|
-
|
|
8307
|
-
|
|
8308
|
-
|
|
8309
|
-
|
|
8310
|
-
|
|
8311
|
-
|
|
8312
|
-
|
|
8313
|
-
|
|
8314
|
-
|
|
8315
|
-
|
|
8316
|
-
|
|
8317
|
-
|
|
8318
|
-
|
|
8319
|
-
|
|
8320
|
-
const
|
|
8321
|
-
|
|
8322
|
-
|
|
8323
|
-
|
|
8324
|
-
|
|
8325
|
-
|
|
8326
|
-
|
|
8327
|
-
|
|
8328
|
-
|
|
8329
|
-
|
|
8330
|
-
|
|
8331
|
-
|
|
8563
|
+
// src/executor/chain.ts
|
|
8564
|
+
async function executeChain(input, options, executeCommand2) {
|
|
8565
|
+
const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
|
|
8566
|
+
const sessionName = options?.sessionName || "default";
|
|
8567
|
+
const results = [];
|
|
8568
|
+
const totalStart = Date.now();
|
|
8569
|
+
let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
8570
|
+
if (!session) {
|
|
8571
|
+
const launchOpts = {};
|
|
8572
|
+
if (options?.cdpEndpoint) launchOpts.cdpEndpoint = options.cdpEndpoint;
|
|
8573
|
+
session = await createSession(sessionName, void 0, launchOpts);
|
|
8574
|
+
saveSessionDiskMeta(sessionName, {
|
|
8575
|
+
id: session.id,
|
|
8576
|
+
name: sessionName,
|
|
8577
|
+
url: session.page.url(),
|
|
8578
|
+
createdAt: session.createdAt,
|
|
8579
|
+
cdpEndpoint: session.cdpEndpoint
|
|
8580
|
+
});
|
|
8581
|
+
}
|
|
8582
|
+
try {
|
|
8583
|
+
for (const pipeline of pipelines) {
|
|
8584
|
+
const { type, pipeline: commands } = pipeline;
|
|
8585
|
+
for (const cmdStr of commands) {
|
|
8586
|
+
if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
|
|
8587
|
+
await new Promise((resolve3) => setTimeout(resolve3, 800 + Math.random() * 1700));
|
|
8588
|
+
}
|
|
8589
|
+
const parts = splitCommand(cmdStr);
|
|
8590
|
+
if (parts.length === 0) continue;
|
|
8591
|
+
const cmdName = parts[0];
|
|
8592
|
+
const cmdArgs = parts.slice(1);
|
|
8593
|
+
const loader = await getPluginLoader();
|
|
8594
|
+
const internalLoader = loader.getCore().loader;
|
|
8595
|
+
const resolvedName = loader.resolveSiteName(cmdName);
|
|
8596
|
+
const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
|
|
8597
|
+
if (site) {
|
|
8598
|
+
const pluginHandled = await executePluginChainStep({
|
|
8599
|
+
site,
|
|
8600
|
+
cmdName,
|
|
8601
|
+
cmdArgs,
|
|
8602
|
+
cmdStr,
|
|
8603
|
+
type,
|
|
8604
|
+
results,
|
|
8605
|
+
totalStart,
|
|
8606
|
+
session,
|
|
8607
|
+
sessionName
|
|
8608
|
+
});
|
|
8609
|
+
if (pluginHandled) return pluginHandled;
|
|
8610
|
+
continue;
|
|
8611
|
+
}
|
|
8612
|
+
const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
|
|
8613
|
+
if (cmdName === "goto" && params.url) {
|
|
8614
|
+
const existing = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
8615
|
+
if (!existing) {
|
|
8616
|
+
session = await createSession(sessionName, params.url, {
|
|
8617
|
+
cdpEndpoint: options?.cdpEndpoint
|
|
8618
|
+
});
|
|
8619
|
+
}
|
|
8620
|
+
}
|
|
8621
|
+
const result = await executeCommand2(cmdName, params, sessionName, {
|
|
8622
|
+
cdpEndpoint: options?.cdpEndpoint,
|
|
8623
|
+
skipCleanup: true
|
|
8624
|
+
});
|
|
8625
|
+
results.push({
|
|
8626
|
+
command: cmdName,
|
|
8627
|
+
raw: cmdStr,
|
|
8628
|
+
success: result.success,
|
|
8629
|
+
data: result.data,
|
|
8630
|
+
message: result.message,
|
|
8631
|
+
duration: 0,
|
|
8632
|
+
tips: result.tips,
|
|
8633
|
+
...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
|
|
8634
|
+
});
|
|
8635
|
+
if (type === "and" && !result.success) {
|
|
8636
|
+
return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): ${result.message}`);
|
|
8637
|
+
}
|
|
8638
|
+
if (type === "or" && result.success) {
|
|
8639
|
+
return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName}' succeeded (|| chain)`);
|
|
8640
|
+
}
|
|
8332
8641
|
}
|
|
8333
|
-
result.tips = tips;
|
|
8334
|
-
result.viewerUrl = viewerUrl;
|
|
8335
|
-
return void 0;
|
|
8336
8642
|
}
|
|
8337
|
-
|
|
8338
|
-
|
|
8339
|
-
|
|
8340
|
-
|
|
8341
|
-
|
|
8342
|
-
|
|
8343
|
-
|
|
8344
|
-
|
|
8345
|
-
|
|
8346
|
-
|
|
8643
|
+
return {
|
|
8644
|
+
success: !results.some((result) => !result.success),
|
|
8645
|
+
steps: results,
|
|
8646
|
+
totalDuration: Date.now() - totalStart
|
|
8647
|
+
};
|
|
8648
|
+
} finally {
|
|
8649
|
+
}
|
|
8650
|
+
}
|
|
8651
|
+
function stoppedChain(success, steps, totalStart, stoppedAt, reason) {
|
|
8652
|
+
return {
|
|
8653
|
+
success,
|
|
8654
|
+
steps,
|
|
8655
|
+
totalDuration: Date.now() - totalStart,
|
|
8656
|
+
stoppedAt,
|
|
8657
|
+
stoppedReason: reason
|
|
8658
|
+
};
|
|
8659
|
+
}
|
|
8660
|
+
async function executePluginChainStep(context) {
|
|
8661
|
+
const { site, cmdName, cmdArgs, cmdStr, type, results, totalStart, session, sessionName } = context;
|
|
8662
|
+
const subCommand = cmdArgs[0];
|
|
8663
|
+
if (!subCommand) {
|
|
8664
|
+
results.push({ command: cmdName, raw: cmdStr, ...fail18(`Plugin "${cmdName}" requires a sub-command`), duration: 0 });
|
|
8665
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): no sub-command`);
|
|
8666
|
+
return void 0;
|
|
8667
|
+
}
|
|
8668
|
+
const cmdEntry = site.getCommand(subCommand);
|
|
8669
|
+
if (!cmdEntry) {
|
|
8670
|
+
results.push({ command: cmdName, raw: cmdStr, ...fail18(`Unknown command "${subCommand}" for plugin "${cmdName}"`), duration: 0 });
|
|
8671
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`);
|
|
8672
|
+
return void 0;
|
|
8673
|
+
}
|
|
8674
|
+
const pluginArgs = cmdArgs.slice(1);
|
|
8675
|
+
const pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
|
|
8676
|
+
if (cmdEntry.parameters) {
|
|
8677
|
+
const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
|
|
8678
|
+
if (schemaCheck.success) {
|
|
8679
|
+
for (const [key, value] of Object.entries(schemaCheck.data)) {
|
|
8680
|
+
if (!(key in pluginParams)) pluginParams[key] = value;
|
|
8347
8681
|
}
|
|
8348
8682
|
}
|
|
8349
|
-
}
|
|
8350
|
-
|
|
8351
|
-
|
|
8352
|
-
|
|
8353
|
-
|
|
8354
|
-
|
|
8355
|
-
|
|
8356
|
-
|
|
8357
|
-
|
|
8358
|
-
|
|
8683
|
+
}
|
|
8684
|
+
const pluginCtx = {
|
|
8685
|
+
args: pluginArgs,
|
|
8686
|
+
options: pluginParams,
|
|
8687
|
+
cwd: process.cwd(),
|
|
8688
|
+
page: session.page,
|
|
8689
|
+
browser: session.context.browser(),
|
|
8690
|
+
browserContext: session.context,
|
|
8691
|
+
sessionId: session.id,
|
|
8692
|
+
storage: getPluginStorage(cmdName),
|
|
8693
|
+
output: { mode: "text", showTips: false, color: false, emoji: false },
|
|
8694
|
+
error: (message) => {
|
|
8695
|
+
throw new Error(message);
|
|
8696
|
+
},
|
|
8697
|
+
config: {},
|
|
8698
|
+
site,
|
|
8699
|
+
cliName: "xbrowser",
|
|
8700
|
+
tips: new TipCollector2()
|
|
8701
|
+
};
|
|
8702
|
+
const start = Date.now();
|
|
8703
|
+
try {
|
|
8704
|
+
const loginGuard = await checkPluginLoginRequired({
|
|
8705
|
+
site,
|
|
8706
|
+
command: cmdEntry,
|
|
8707
|
+
commandName: subCommand,
|
|
8708
|
+
ctx: pluginCtx,
|
|
8709
|
+
page: session.page,
|
|
8710
|
+
sessionName
|
|
8711
|
+
});
|
|
8712
|
+
if (!loginGuard.ok) {
|
|
8713
|
+
const duration2 = Date.now() - start;
|
|
8714
|
+
const data2 = loginGuard.data ?? null;
|
|
8715
|
+
recordArchive(session.id, sessionName, {
|
|
8716
|
+
step: results.length,
|
|
8717
|
+
command: `${cmdName} ${subCommand}`,
|
|
8718
|
+
params: pluginParams,
|
|
8719
|
+
result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
|
|
8720
|
+
toolCalls: [],
|
|
8721
|
+
duration: duration2,
|
|
8722
|
+
timestamp: start
|
|
8359
8723
|
});
|
|
8360
|
-
|
|
8724
|
+
results.push({
|
|
8725
|
+
command: `${cmdName} ${subCommand}`,
|
|
8726
|
+
raw: cmdStr,
|
|
8727
|
+
success: false,
|
|
8728
|
+
data: data2,
|
|
8729
|
+
message: loginGuard.message,
|
|
8730
|
+
tips: normalizeTips7(loginGuard.tips),
|
|
8731
|
+
duration: duration2
|
|
8732
|
+
});
|
|
8733
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`);
|
|
8361
8734
|
return void 0;
|
|
8362
8735
|
}
|
|
8363
|
-
|
|
8364
|
-
|
|
8365
|
-
|
|
8366
|
-
async function loadHooks() {
|
|
8367
|
-
const env = process.env.XBROWSER_HOOKS;
|
|
8368
|
-
if (!env) return [];
|
|
8369
|
-
const names = env.split(",").map((n) => n.trim()).filter(Boolean);
|
|
8370
|
-
if (names.length === 0) return [];
|
|
8371
|
-
const hooks = [];
|
|
8372
|
-
for (const name of names) {
|
|
8373
|
-
const hook = HOOK_REGISTRY[name];
|
|
8374
|
-
if (hook) {
|
|
8375
|
-
hooks.push(hook);
|
|
8376
|
-
continue;
|
|
8736
|
+
const hooks = await loadHooks();
|
|
8737
|
+
if (hooks.length > 0) {
|
|
8738
|
+
await Promise.all(hooks.map((hook) => hook.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
|
|
8377
8739
|
}
|
|
8378
|
-
const
|
|
8379
|
-
|
|
8380
|
-
|
|
8381
|
-
|
|
8740
|
+
const raw = await cmdEntry.handler(pluginParams, pluginCtx);
|
|
8741
|
+
const duration = Date.now() - start;
|
|
8742
|
+
let hookOutputs;
|
|
8743
|
+
if (hooks.length > 0) {
|
|
8744
|
+
const outputs = [];
|
|
8745
|
+
for (const hook of hooks) {
|
|
8746
|
+
const output = await hook.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration });
|
|
8747
|
+
if (output) outputs.push({ _hook: hook.name, ...output });
|
|
8748
|
+
}
|
|
8749
|
+
if (outputs.length > 0) hookOutputs = outputs;
|
|
8382
8750
|
}
|
|
8751
|
+
const data = raw?.data ?? raw;
|
|
8752
|
+
recordArchive(session.id, sessionName, {
|
|
8753
|
+
step: results.length,
|
|
8754
|
+
command: `${cmdName} ${subCommand}`,
|
|
8755
|
+
params: pluginParams,
|
|
8756
|
+
result: { success: true, data, tips: tipsToMessages(raw?.tips) },
|
|
8757
|
+
toolCalls: [],
|
|
8758
|
+
duration,
|
|
8759
|
+
timestamp: start
|
|
8760
|
+
});
|
|
8761
|
+
results.push({
|
|
8762
|
+
command: `${cmdName} ${subCommand}`,
|
|
8763
|
+
raw: cmdStr,
|
|
8764
|
+
...ok32(data),
|
|
8765
|
+
duration,
|
|
8766
|
+
...hookOutputs ? { hookOutputs } : {}
|
|
8767
|
+
});
|
|
8768
|
+
if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
|
|
8769
|
+
} catch (error) {
|
|
8770
|
+
const duration = Date.now() - start;
|
|
8771
|
+
const message = errMsg(error);
|
|
8772
|
+
recordArchive(session.id, sessionName, {
|
|
8773
|
+
step: results.length,
|
|
8774
|
+
command: `${cmdName} ${subCommand}`,
|
|
8775
|
+
params: pluginParams,
|
|
8776
|
+
result: { success: false, data: null, message, tips: [] },
|
|
8777
|
+
toolCalls: [],
|
|
8778
|
+
duration,
|
|
8779
|
+
timestamp: start
|
|
8780
|
+
});
|
|
8781
|
+
results.push({ command: `${cmdName} ${subCommand}`, raw: cmdStr, ...fail18(message), duration });
|
|
8782
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${message}`);
|
|
8383
8783
|
}
|
|
8384
|
-
return
|
|
8784
|
+
return void 0;
|
|
8385
8785
|
}
|
|
8386
8786
|
|
|
8387
8787
|
// src/executor.ts
|
|
8388
|
-
import { homedir as homedir6 } from "os";
|
|
8389
|
-
import { join as join8 } from "path";
|
|
8390
8788
|
function levenshtein(a, b) {
|
|
8391
8789
|
const m = a.length, n = b.length;
|
|
8392
8790
|
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
|
|
@@ -8394,63 +8792,11 @@ function levenshtein(a, b) {
|
|
|
8394
8792
|
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
8395
8793
|
for (let i = 1; i <= m; i++) {
|
|
8396
8794
|
for (let j = 1; j <= n; j++) {
|
|
8397
|
-
dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j
|
|
8795
|
+
dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j - 1], dp[i - 1][j - 1]);
|
|
8398
8796
|
}
|
|
8399
8797
|
}
|
|
8400
8798
|
return dp[m][n];
|
|
8401
8799
|
}
|
|
8402
|
-
var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
|
|
8403
|
-
var snapshotHintShown = /* @__PURE__ */ new WeakSet();
|
|
8404
|
-
var CONFIG_DIR2 = join8(homedir6(), ".xbrowser");
|
|
8405
|
-
var storageCache = /* @__PURE__ */ new Map();
|
|
8406
|
-
function getPluginStorage(pluginName) {
|
|
8407
|
-
if (!storageCache.has(pluginName)) {
|
|
8408
|
-
storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
|
|
8409
|
-
}
|
|
8410
|
-
return storageCache.get(pluginName);
|
|
8411
|
-
}
|
|
8412
|
-
var archiveInitialized = false;
|
|
8413
|
-
function ensureArchiveInit() {
|
|
8414
|
-
if (!archiveInitialized) {
|
|
8415
|
-
try {
|
|
8416
|
-
configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
|
|
8417
|
-
} catch {
|
|
8418
|
-
}
|
|
8419
|
-
archiveInitialized = true;
|
|
8420
|
-
}
|
|
8421
|
-
}
|
|
8422
|
-
function recordArchive(sessionId, sessionName, entry) {
|
|
8423
|
-
if (!sessionId) return;
|
|
8424
|
-
try {
|
|
8425
|
-
ensureArchiveInit();
|
|
8426
|
-
appendCommandToArchive(sessionId, sessionName, entry);
|
|
8427
|
-
} catch {
|
|
8428
|
-
}
|
|
8429
|
-
}
|
|
8430
|
-
async function guardCheck(commandName) {
|
|
8431
|
-
try {
|
|
8432
|
-
const loader = await getPluginLoader();
|
|
8433
|
-
const core = loader.getCore();
|
|
8434
|
-
return checkGuard(core, commandName, process.env);
|
|
8435
|
-
} catch {
|
|
8436
|
-
return null;
|
|
8437
|
-
}
|
|
8438
|
-
}
|
|
8439
|
-
function errorResult(message) {
|
|
8440
|
-
return { ...fail17(message), duration: 0 };
|
|
8441
|
-
}
|
|
8442
|
-
function tipsToMessages(tips) {
|
|
8443
|
-
if (!tips || tips.length === 0) return [];
|
|
8444
|
-
return tips.map((t) => typeof t === "string" ? t : t.message);
|
|
8445
|
-
}
|
|
8446
|
-
var wsServer = null;
|
|
8447
|
-
function streamCommandEvent(sessionId, message) {
|
|
8448
|
-
if (!wsServer || !wsServer.getRunning()) return;
|
|
8449
|
-
wsServer.broadcastToSession(sessionId, {
|
|
8450
|
-
type: "command",
|
|
8451
|
-
data: message
|
|
8452
|
-
});
|
|
8453
|
-
}
|
|
8454
8800
|
async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
|
|
8455
8801
|
const guardResult = await guardCheck(commandName);
|
|
8456
8802
|
if (guardResult?.blocked) {
|
|
@@ -8498,8 +8844,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8498
8844
|
if (knownPlugins.includes(commandName)) {
|
|
8499
8845
|
hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
|
|
8500
8846
|
}
|
|
8847
|
+
const message = `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`;
|
|
8848
|
+
recordMistake({
|
|
8849
|
+
category: classifyFailure(message).code,
|
|
8850
|
+
command: commandName,
|
|
8851
|
+
message,
|
|
8852
|
+
context: { sessionName, params }
|
|
8853
|
+
});
|
|
8501
8854
|
return errorResult(
|
|
8502
|
-
|
|
8855
|
+
message
|
|
8503
8856
|
);
|
|
8504
8857
|
}
|
|
8505
8858
|
const _target = params._target;
|
|
@@ -8514,7 +8867,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8514
8867
|
}
|
|
8515
8868
|
let targetPageOverride = null;
|
|
8516
8869
|
if (_target && extraOpts?.cdpEndpoint) {
|
|
8517
|
-
const { findTargetPage } = await import("./browser-
|
|
8870
|
+
const { findTargetPage } = await import("./browser-2K3XYAKM.js");
|
|
8518
8871
|
targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
|
|
8519
8872
|
if (!targetPageOverride) {
|
|
8520
8873
|
return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
|
|
@@ -8532,7 +8885,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8532
8885
|
}
|
|
8533
8886
|
if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
|
|
8534
8887
|
const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
|
|
8535
|
-
const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
|
|
8888
|
+
const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
|
|
8536
8889
|
const result = await forwardExec(
|
|
8537
8890
|
commandName,
|
|
8538
8891
|
params,
|
|
@@ -8594,7 +8947,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8594
8947
|
config: {},
|
|
8595
8948
|
site: new NoopSiteInstance(),
|
|
8596
8949
|
cliName: "xbrowser",
|
|
8597
|
-
tips: new
|
|
8950
|
+
tips: new TipCollector3()
|
|
8598
8951
|
};
|
|
8599
8952
|
attachDetectAntiBot(ctx);
|
|
8600
8953
|
if (_tabIndex !== void 0 && session?.context) {
|
|
@@ -8626,7 +8979,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8626
8979
|
const cache = /* @__PURE__ */ new Map();
|
|
8627
8980
|
const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
|
|
8628
8981
|
if (resolved.tips.length > 0) {
|
|
8629
|
-
refTips =
|
|
8982
|
+
refTips = normalizeTips8(resolved.tips);
|
|
8630
8983
|
params = resolved.params;
|
|
8631
8984
|
}
|
|
8632
8985
|
}
|
|
@@ -8694,11 +9047,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8694
9047
|
}
|
|
8695
9048
|
const merged = [
|
|
8696
9049
|
...raw.tips || [],
|
|
8697
|
-
...
|
|
8698
|
-
...snapshotHint ?
|
|
9050
|
+
...normalizeTips8(smartTips),
|
|
9051
|
+
...snapshotHint ? normalizeTips8([snapshotHint]) : [],
|
|
8699
9052
|
...refTips
|
|
8700
9053
|
];
|
|
8701
9054
|
const isSuccess = raw.success !== false;
|
|
9055
|
+
if (!isSuccess) {
|
|
9056
|
+
recordMistake({
|
|
9057
|
+
category: classifyFailure(raw.message).code,
|
|
9058
|
+
command: commandName,
|
|
9059
|
+
message: raw.message ?? "unknown command failure",
|
|
9060
|
+
context: { sessionName, params }
|
|
9061
|
+
});
|
|
9062
|
+
}
|
|
8702
9063
|
const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
|
|
8703
9064
|
recordArchive(session?.id, sessionName, {
|
|
8704
9065
|
step: 0,
|
|
@@ -8710,7 +9071,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8710
9071
|
timestamp: start
|
|
8711
9072
|
});
|
|
8712
9073
|
if (isSuccess) {
|
|
8713
|
-
return { ...
|
|
9074
|
+
return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
|
|
8714
9075
|
}
|
|
8715
9076
|
const fc = classifyFailure(raw.message);
|
|
8716
9077
|
return {
|
|
@@ -8723,7 +9084,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8723
9084
|
...hookOutputs ? { hookOutputs } : {}
|
|
8724
9085
|
};
|
|
8725
9086
|
}
|
|
8726
|
-
const smartTipNormalized =
|
|
9087
|
+
const smartTipNormalized = normalizeTips8(smartTips);
|
|
8727
9088
|
recordArchive(session?.id, sessionName, {
|
|
8728
9089
|
step: 0,
|
|
8729
9090
|
command: commandName,
|
|
@@ -8733,11 +9094,17 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8733
9094
|
duration,
|
|
8734
9095
|
timestamp: start
|
|
8735
9096
|
});
|
|
8736
|
-
return { ...
|
|
9097
|
+
return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
|
|
8737
9098
|
} catch (err) {
|
|
8738
9099
|
const end = Date.now();
|
|
8739
9100
|
const duration = end - start;
|
|
8740
9101
|
const errorMessage = errMsg(err);
|
|
9102
|
+
recordMistake({
|
|
9103
|
+
category: classifyFailure(errorMessage).code,
|
|
9104
|
+
command: commandName,
|
|
9105
|
+
message: errorMessage,
|
|
9106
|
+
context: { sessionName, params }
|
|
9107
|
+
});
|
|
8741
9108
|
if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
|
|
8742
9109
|
try {
|
|
8743
9110
|
const { attemptRecovery } = await import("./recovery-EBKORYEU.js");
|
|
@@ -8778,301 +9145,33 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8778
9145
|
duration,
|
|
8779
9146
|
timestamp: start
|
|
8780
9147
|
});
|
|
8781
|
-
return { ...
|
|
9148
|
+
return { ...fail19(errorMessage), duration };
|
|
8782
9149
|
} finally {
|
|
8783
9150
|
}
|
|
8784
9151
|
}
|
|
8785
|
-
async function
|
|
8786
|
-
|
|
8787
|
-
const sessionName = options?.sessionName || "default";
|
|
8788
|
-
const results = [];
|
|
8789
|
-
const totalStart = Date.now();
|
|
8790
|
-
let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
8791
|
-
if (!session) {
|
|
8792
|
-
const launchOpts = {};
|
|
8793
|
-
if (options?.cdpEndpoint) {
|
|
8794
|
-
launchOpts.cdpEndpoint = options.cdpEndpoint;
|
|
8795
|
-
}
|
|
8796
|
-
session = await createSession(sessionName, void 0, launchOpts);
|
|
8797
|
-
saveSessionDiskMeta(sessionName, {
|
|
8798
|
-
id: session.id,
|
|
8799
|
-
name: sessionName,
|
|
8800
|
-
url: session.page.url(),
|
|
8801
|
-
createdAt: session.createdAt,
|
|
8802
|
-
cdpEndpoint: session.cdpEndpoint
|
|
8803
|
-
});
|
|
8804
|
-
}
|
|
8805
|
-
try {
|
|
8806
|
-
for (const pipeline of pipelines) {
|
|
8807
|
-
const { type, pipeline: commands } = pipeline;
|
|
8808
|
-
for (const cmdStr of commands) {
|
|
8809
|
-
if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
|
|
8810
|
-
await new Promise((r) => setTimeout(r, 800 + Math.random() * 1700));
|
|
8811
|
-
}
|
|
8812
|
-
const parts = splitCommand(cmdStr);
|
|
8813
|
-
if (parts.length === 0) continue;
|
|
8814
|
-
const cmdName = parts[0];
|
|
8815
|
-
const cmdArgs = parts.slice(1);
|
|
8816
|
-
const loader = await getPluginLoader();
|
|
8817
|
-
const internalLoader = loader.getCore().loader;
|
|
8818
|
-
const resolvedName = loader.resolveSiteName(cmdName);
|
|
8819
|
-
const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
|
|
8820
|
-
if (site) {
|
|
8821
|
-
const subCommand = cmdArgs[0];
|
|
8822
|
-
if (!subCommand) {
|
|
8823
|
-
results.push({
|
|
8824
|
-
command: cmdName,
|
|
8825
|
-
raw: cmdStr,
|
|
8826
|
-
...fail17(`Plugin "${cmdName}" requires a sub-command`),
|
|
8827
|
-
duration: 0
|
|
8828
|
-
});
|
|
8829
|
-
if (type === "and") {
|
|
8830
|
-
return {
|
|
8831
|
-
success: false,
|
|
8832
|
-
steps: results,
|
|
8833
|
-
totalDuration: Date.now() - totalStart,
|
|
8834
|
-
stoppedAt: results.length,
|
|
8835
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): no sub-command`
|
|
8836
|
-
};
|
|
8837
|
-
}
|
|
8838
|
-
continue;
|
|
8839
|
-
}
|
|
8840
|
-
const cmdEntry = site.getCommand(subCommand);
|
|
8841
|
-
if (!cmdEntry) {
|
|
8842
|
-
results.push({
|
|
8843
|
-
command: cmdName,
|
|
8844
|
-
raw: cmdStr,
|
|
8845
|
-
...fail17(`Unknown command "${subCommand}" for plugin "${cmdName}"`),
|
|
8846
|
-
duration: 0
|
|
8847
|
-
});
|
|
8848
|
-
if (type === "and") {
|
|
8849
|
-
return {
|
|
8850
|
-
success: false,
|
|
8851
|
-
steps: results,
|
|
8852
|
-
totalDuration: Date.now() - totalStart,
|
|
8853
|
-
stoppedAt: results.length,
|
|
8854
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`
|
|
8855
|
-
};
|
|
8856
|
-
}
|
|
8857
|
-
continue;
|
|
8858
|
-
}
|
|
8859
|
-
const pluginArgs = cmdArgs.slice(1);
|
|
8860
|
-
let pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
|
|
8861
|
-
if (cmdEntry.parameters) {
|
|
8862
|
-
const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
|
|
8863
|
-
if (schemaCheck.success) {
|
|
8864
|
-
for (const [k, v] of Object.entries(schemaCheck.data)) {
|
|
8865
|
-
if (!(k in pluginParams)) pluginParams[k] = v;
|
|
8866
|
-
}
|
|
8867
|
-
}
|
|
8868
|
-
}
|
|
8869
|
-
const pluginCtx = {
|
|
8870
|
-
args: pluginArgs,
|
|
8871
|
-
options: pluginParams,
|
|
8872
|
-
cwd: process.cwd(),
|
|
8873
|
-
page: session.page,
|
|
8874
|
-
browser: session.context.browser(),
|
|
8875
|
-
browserContext: session.context,
|
|
8876
|
-
sessionId: session.id,
|
|
8877
|
-
storage: getPluginStorage(cmdName),
|
|
8878
|
-
output: { mode: "text", showTips: false, color: false, emoji: false },
|
|
8879
|
-
error: (msg) => {
|
|
8880
|
-
throw new Error(msg);
|
|
8881
|
-
},
|
|
8882
|
-
config: {},
|
|
8883
|
-
site,
|
|
8884
|
-
cliName: "xbrowser",
|
|
8885
|
-
tips: new TipCollector2()
|
|
8886
|
-
};
|
|
8887
|
-
const start2 = Date.now();
|
|
8888
|
-
try {
|
|
8889
|
-
const loginGuard = await checkPluginLoginRequired({
|
|
8890
|
-
site,
|
|
8891
|
-
command: cmdEntry,
|
|
8892
|
-
commandName: subCommand,
|
|
8893
|
-
ctx: pluginCtx,
|
|
8894
|
-
page: session?.page,
|
|
8895
|
-
sessionName
|
|
8896
|
-
});
|
|
8897
|
-
if (!loginGuard.ok) {
|
|
8898
|
-
const duration3 = Date.now() - start2;
|
|
8899
|
-
const data2 = loginGuard.data ?? null;
|
|
8900
|
-
recordArchive(session.id, sessionName, {
|
|
8901
|
-
step: results.length,
|
|
8902
|
-
command: `${cmdName} ${subCommand}`,
|
|
8903
|
-
params: pluginParams,
|
|
8904
|
-
result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
|
|
8905
|
-
toolCalls: [],
|
|
8906
|
-
duration: duration3,
|
|
8907
|
-
timestamp: start2
|
|
8908
|
-
});
|
|
8909
|
-
results.push({
|
|
8910
|
-
command: `${cmdName} ${subCommand}`,
|
|
8911
|
-
raw: cmdStr,
|
|
8912
|
-
success: false,
|
|
8913
|
-
data: data2,
|
|
8914
|
-
message: loginGuard.message,
|
|
8915
|
-
tips: normalizeTips7(loginGuard.tips),
|
|
8916
|
-
duration: duration3
|
|
8917
|
-
});
|
|
8918
|
-
if (type === "and") {
|
|
8919
|
-
return {
|
|
8920
|
-
success: false,
|
|
8921
|
-
steps: results,
|
|
8922
|
-
totalDuration: Date.now() - totalStart,
|
|
8923
|
-
stoppedAt: results.length,
|
|
8924
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`
|
|
8925
|
-
};
|
|
8926
|
-
}
|
|
8927
|
-
continue;
|
|
8928
|
-
}
|
|
8929
|
-
const hooks = await loadHooks();
|
|
8930
|
-
if (hooks.length > 0) {
|
|
8931
|
-
await Promise.all(hooks.map((h) => h.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
|
|
8932
|
-
}
|
|
8933
|
-
const raw = await cmdEntry.handler(pluginParams, pluginCtx);
|
|
8934
|
-
const duration2 = Date.now() - start2;
|
|
8935
|
-
let hookOutputs;
|
|
8936
|
-
if (hooks.length > 0) {
|
|
8937
|
-
const outputs = [];
|
|
8938
|
-
for (const h of hooks) {
|
|
8939
|
-
const output = await h.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration: duration2 });
|
|
8940
|
-
if (output) outputs.push({ _hook: h.name, ...output });
|
|
8941
|
-
}
|
|
8942
|
-
if (outputs.length > 0) hookOutputs = outputs;
|
|
8943
|
-
}
|
|
8944
|
-
const data = raw?.data ?? raw;
|
|
8945
|
-
recordArchive(session.id, sessionName, {
|
|
8946
|
-
step: results.length,
|
|
8947
|
-
command: `${cmdName} ${subCommand}`,
|
|
8948
|
-
params: pluginParams,
|
|
8949
|
-
result: { success: true, data, tips: tipsToMessages(raw?.tips) },
|
|
8950
|
-
toolCalls: [],
|
|
8951
|
-
duration: duration2,
|
|
8952
|
-
timestamp: start2
|
|
8953
|
-
});
|
|
8954
|
-
results.push({
|
|
8955
|
-
command: `${cmdName} ${subCommand}`,
|
|
8956
|
-
raw: cmdStr,
|
|
8957
|
-
...ok32(data),
|
|
8958
|
-
duration: duration2,
|
|
8959
|
-
...hookOutputs ? { hookOutputs } : {}
|
|
8960
|
-
});
|
|
8961
|
-
if (type === "or") {
|
|
8962
|
-
return {
|
|
8963
|
-
success: true,
|
|
8964
|
-
steps: results,
|
|
8965
|
-
totalDuration: Date.now() - totalStart,
|
|
8966
|
-
stoppedAt: results.length,
|
|
8967
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' succeeded (|| chain)`
|
|
8968
|
-
};
|
|
8969
|
-
}
|
|
8970
|
-
} catch (err) {
|
|
8971
|
-
const duration2 = Date.now() - start2;
|
|
8972
|
-
const errorMessage = errMsg(err);
|
|
8973
|
-
recordArchive(session.id, sessionName, {
|
|
8974
|
-
step: results.length,
|
|
8975
|
-
command: `${cmdName} ${subCommand}`,
|
|
8976
|
-
params: pluginParams,
|
|
8977
|
-
result: { success: false, data: null, message: errorMessage, tips: [] },
|
|
8978
|
-
toolCalls: [],
|
|
8979
|
-
duration: duration2,
|
|
8980
|
-
timestamp: start2
|
|
8981
|
-
});
|
|
8982
|
-
results.push({
|
|
8983
|
-
command: `${cmdName} ${subCommand}`,
|
|
8984
|
-
raw: cmdStr,
|
|
8985
|
-
...fail17(errorMessage),
|
|
8986
|
-
duration: duration2
|
|
8987
|
-
});
|
|
8988
|
-
if (type === "and") {
|
|
8989
|
-
return {
|
|
8990
|
-
success: false,
|
|
8991
|
-
steps: results,
|
|
8992
|
-
totalDuration: Date.now() - totalStart,
|
|
8993
|
-
stoppedAt: results.length,
|
|
8994
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${errorMessage}`
|
|
8995
|
-
};
|
|
8996
|
-
}
|
|
8997
|
-
}
|
|
8998
|
-
continue;
|
|
8999
|
-
}
|
|
9000
|
-
const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
|
|
9001
|
-
if (cmdName === "goto" && params.url) {
|
|
9002
|
-
const existing2 = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
9003
|
-
if (!existing2) {
|
|
9004
|
-
session = await createSession(sessionName, params.url, {
|
|
9005
|
-
cdpEndpoint: options?.cdpEndpoint
|
|
9006
|
-
});
|
|
9007
|
-
}
|
|
9008
|
-
}
|
|
9009
|
-
const start = Date.now();
|
|
9010
|
-
const result = await executeCommand(cmdName, params, sessionName, {
|
|
9011
|
-
cdpEndpoint: options?.cdpEndpoint,
|
|
9012
|
-
skipCleanup: true
|
|
9013
|
-
// executeChain's finally handles cleanup
|
|
9014
|
-
});
|
|
9015
|
-
const duration = Date.now() - start;
|
|
9016
|
-
const stepResult = {
|
|
9017
|
-
command: cmdName,
|
|
9018
|
-
raw: cmdStr,
|
|
9019
|
-
success: result.success,
|
|
9020
|
-
data: result.data,
|
|
9021
|
-
message: result.message,
|
|
9022
|
-
duration,
|
|
9023
|
-
tips: result.tips,
|
|
9024
|
-
...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
|
|
9025
|
-
};
|
|
9026
|
-
results.push(stepResult);
|
|
9027
|
-
if (type === "and" && !result.success) {
|
|
9028
|
-
return {
|
|
9029
|
-
success: false,
|
|
9030
|
-
steps: results,
|
|
9031
|
-
totalDuration: Date.now() - totalStart,
|
|
9032
|
-
stoppedAt: results.length,
|
|
9033
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): ${result.message}`
|
|
9034
|
-
};
|
|
9035
|
-
}
|
|
9036
|
-
if (type === "or" && result.success) {
|
|
9037
|
-
return {
|
|
9038
|
-
success: true,
|
|
9039
|
-
steps: results,
|
|
9040
|
-
totalDuration: Date.now() - totalStart,
|
|
9041
|
-
stoppedAt: results.length,
|
|
9042
|
-
stoppedReason: `Command '${cmdName}' succeeded (|| chain)`
|
|
9043
|
-
};
|
|
9044
|
-
}
|
|
9045
|
-
}
|
|
9046
|
-
}
|
|
9047
|
-
const anyFailed = results.some((r) => !r.success);
|
|
9048
|
-
return {
|
|
9049
|
-
success: !anyFailed,
|
|
9050
|
-
steps: results,
|
|
9051
|
-
totalDuration: Date.now() - totalStart
|
|
9052
|
-
};
|
|
9053
|
-
} finally {
|
|
9054
|
-
}
|
|
9152
|
+
async function executeChain2(input, options) {
|
|
9153
|
+
return executeChain(input, options, executeCommand);
|
|
9055
9154
|
}
|
|
9056
9155
|
function isChainInput(input) {
|
|
9057
9156
|
return /\s&&\s|\|\|\s|\s;\s|;\s|\s,\s|\s\+\s|\s->\s/.test(input);
|
|
9058
9157
|
}
|
|
9059
9158
|
|
|
9060
9159
|
export {
|
|
9061
|
-
parsePluginParams,
|
|
9062
9160
|
createStubContext,
|
|
9063
9161
|
getCommand,
|
|
9064
9162
|
getAllCommands,
|
|
9065
9163
|
getCommandNames,
|
|
9066
9164
|
attachDetectAntiBot,
|
|
9165
|
+
loadHooks,
|
|
9067
9166
|
readJsonFile,
|
|
9068
9167
|
PluginMetadataParser,
|
|
9069
9168
|
ensurePluginDependencies,
|
|
9070
9169
|
XBrowserPluginLoader,
|
|
9071
9170
|
getPluginLoader,
|
|
9072
|
-
checkPluginLoginRequired,
|
|
9073
|
-
loadHooks,
|
|
9074
9171
|
getPluginStorage,
|
|
9172
|
+
checkPluginLoginRequired,
|
|
9173
|
+
parsePluginParams,
|
|
9075
9174
|
executeCommand,
|
|
9076
|
-
executeChain,
|
|
9175
|
+
executeChain2 as executeChain,
|
|
9077
9176
|
isChainInput
|
|
9078
9177
|
};
|