-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb.ts
More file actions
180 lines (154 loc) · 5.27 KB
/
Copy pathweb.ts
File metadata and controls
180 lines (154 loc) · 5.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import type { Device, ScreenInfo, DeviceConfig, SampleConfig } from '.';
import puppeteer, { type Browser, type Page, type Cookie } from 'puppeteer';
import { PuppeteerAgent } from '@midscene/web/puppeteer';
import { overrideAIConfig } from '@midscene/web/puppeteer';
import type { Sample } from '../blackbox';
interface Snapshot {
url: string;
html: string;
cookies: Cookie[];
localStorage: Record<string, string>;
sessionStorage: Record<string, string>;
scroll: { x: number; y: number };
}
function canonicalizeUrl(inputUrl: string): string {
try {
const url = new URL(inputUrl);
// Remove fragment
url.hash = '';
// Normalize pathname (e.g., remove duplicate slashes)
url.pathname = url.pathname.replace(/\/{2,}/g, '/');
// Remove trailing '?' if no search parameters exist
if (!url.searchParams.toString()) {
url.search = '';
}
// Optionally, remove trailing slash from pathname (except root)
if (url.pathname.length > 1 && url.pathname.endsWith('/')) {
url.pathname = url.pathname.slice(0, -1);
}
return url.toString();
} catch (error) {
throw new Error(`Invalid URL: ${inputUrl}`);
}
}
export class WebBrowser implements Device {
private browser!: Browser;
private page!: Page;
private agent!: PuppeteerAgent;
private readonly snapshots: Map<string, Snapshot> = new Map();
async start(config: DeviceConfig) {
const args = [];
if (config.proxyUrl && config.proxyCertFingerprint) {
args.push(
`--proxy-server=${config.proxyUrl}`,
// '--ignore-certificate-errors',
'--ignore-certificate-errors-spki-list=' + config.proxyCertFingerprint
);
}
this.browser = await puppeteer.launch({
headless: false,
args
});
}
async stop() {
if (this.browser) {
await this.browser.close();
}
}
async setup(sample: Sample) {
this.page = await this.browser.newPage();
overrideAIConfig({
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
OPENAI_BASE_URL: process.env.OPENAI_BASE_URL,
MIDSCENE_MODEL_NAME: process.env.MIDSCENE_MODEL_NAME,
MIDSCENE_USE_QWEN_VL: process.env.MIDSCENE_USE_QWEN_VL
});
this.agent = new PuppeteerAgent(this.page, {
forceSameTabNavigation: true,
// generateReport: false,
aiActionContext: undefined
});
await this.page.setViewport({
width: 1280,
height: 800,
deviceScaleFactor: 1
});
}
async cleanup() {
if (this.page) {
await this.page.close();
}
}
async open(sample: Sample) {
await this.page.goto(sample.target, {
waitUntil: 'networkidle2'
});
}
async extractUI(): Promise<ScreenInfo> {
const prompt = `Identify all interactive elements on the page. For each, provide:
- Type (e.g., button, link, input, dropdown, etc.)
- Name (a short, human-readable label)
- Description (a clear explanation of its function or purpose)
If there are many similar elements (e.g., category links, product cards), group them and describe their shared purpose in a single entry.;
The structure of your response should be {type, name, description}[]`;
const elements = await this.agent.aiQuery(prompt);
const screenshotBase64 = await this.page.screenshot({
encoding: 'base64'
});
return {
id: this.page.url(),
screenshotBase64: `data:image/png;base64,${screenshotBase64}`,
elements
};
}
async takeSnapshot(id: string): Promise<void> {
if (this.snapshots.has(id)) return;
const snapshot: Snapshot = {
url: this.page.url(),
html: await this.page.content(),
cookies: await this.browser.cookies(),
localStorage: await this.page.evaluate(() =>
Object.fromEntries(Object.entries(localStorage))
),
sessionStorage: await this.page.evaluate(() =>
Object.fromEntries(Object.entries(sessionStorage))
),
scroll: await this.page.evaluate(() => ({ x: window.scrollX, y: window.scrollY }))
};
this.snapshots.set(id, snapshot);
}
async restoreSnapshot(id: string): Promise<void> {
const snap = this.snapshots.get(id);
if (!snap) throw new Error('Snapshot not found');
await this.page.goto(snap.url);
// Set cookies
await this.browser.deleteCookie(...snap.cookies);
await this.browser.setCookie(...snap.cookies);
// Restore localStorage
await this.page.evaluate(() => localStorage.clear());
await this.page.evaluate((data) => {
for (const [k, v] of Object.entries(data)) localStorage.setItem(k, v);
}, snap.localStorage);
// Restore sessionStorage
await this.page.evaluate(() => sessionStorage.clear());
await this.page.evaluate((data) => {
for (const [k, v] of Object.entries(data)) sessionStorage.setItem(k, v);
}, snap.sessionStorage);
// Refresh to apply cookies
await this.page.reload({ waitUntil: 'networkidle2' });
await this.page.evaluate(({ x, y }) => window.scrollTo(x, y), snap.scroll);
}
async removeSnapshot(id: string): Promise<void> {
this.snapshots.delete(id);
}
async takeScreenshot(): Promise<Uint8Array> {
return await this.page.screenshot();
}
async executeAction(action: string): Promise<void> {
await this.agent.aiAction(action);
}
// Getters and setters
async getUrl(): Promise<string> {
return this.page.url();
}
}