@xbrowser/cli 1.27.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-IDXOIXQR.js → chunk-GDKKVT2P.js} +773 -655
- 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-YITK42HZ.js → chunk-SCYBNSOG.js} +1596 -1478
- 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 +749 -700
- 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-YKMRFDEM.js → server-LNZTDAKT.js} +4 -4
- package/dist/{server-WDDGIV3C.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
|
@@ -1,18 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
launch
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-N5XTLNKS.js";
|
|
4
4
|
import {
|
|
5
5
|
errMsg
|
|
6
6
|
} from "./chunk-GDKLH7ZY.js";
|
|
7
7
|
import {
|
|
8
8
|
CDPInterceptorProxy
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-NEE6EMYA.js";
|
|
10
10
|
|
|
11
11
|
// src/browser.ts
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import { join } from "path";
|
|
15
|
-
import { homedir } from "os";
|
|
12
|
+
import { readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
|
|
13
|
+
import { join as join2 } from "path";
|
|
16
14
|
|
|
17
15
|
// src/utils/cdp.ts
|
|
18
16
|
async function fetchNoProxy(url) {
|
|
@@ -84,116 +82,39 @@ async function resolveCDPEndpoint(raw) {
|
|
|
84
82
|
return raw;
|
|
85
83
|
}
|
|
86
84
|
|
|
87
|
-
// src/browser.ts
|
|
88
|
-
import {
|
|
89
|
-
function logSessionEvent(event, details) {
|
|
90
|
-
const ts = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
91
|
-
const pid = process.pid;
|
|
92
|
-
console.error(`[SESSION] ${ts} [PID:${pid}] ${event} | ${details}`);
|
|
93
|
-
}
|
|
94
|
-
var SESSION_DIR = join(homedir(), ".xbrowser", "sessions");
|
|
95
|
-
function sessionFile(name) {
|
|
96
|
-
return join(SESSION_DIR, `${name}.json`);
|
|
97
|
-
}
|
|
98
|
-
function ensureSessionDir() {
|
|
99
|
-
mkdirSync(SESSION_DIR, { recursive: true });
|
|
100
|
-
}
|
|
101
|
-
var sessions = new SessionStore();
|
|
102
|
-
var _sharedBrowser = null;
|
|
103
|
-
var _sharedCdpProxy = null;
|
|
104
|
-
var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
|
|
105
|
-
var idleTimer = null;
|
|
106
|
-
function resetIdleTimer() {
|
|
107
|
-
if (idleTimer) clearTimeout(idleTimer);
|
|
108
|
-
idleTimer = setTimeout(async () => {
|
|
109
|
-
const now = Date.now();
|
|
110
|
-
let allIdle = true;
|
|
111
|
-
const idleSessions = [];
|
|
112
|
-
for (const s of sessions) {
|
|
113
|
-
if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
|
|
114
|
-
allIdle = false;
|
|
115
|
-
} else {
|
|
116
|
-
idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
if (allIdle && (sessions.size > 0 || _sharedBrowser)) {
|
|
120
|
-
logSessionEvent("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
|
|
121
|
-
await destroyBrowser().catch(() => {
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
}, IDLE_TIMEOUT_MS);
|
|
125
|
-
if (idleTimer && typeof idleTimer.unref === "function") {
|
|
126
|
-
idleTimer.unref();
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
function touchSession(id) {
|
|
130
|
-
const s = sessions.get(id);
|
|
131
|
-
if (s) s.lastActivityAt = Date.now();
|
|
132
|
-
resetIdleTimer();
|
|
133
|
-
}
|
|
134
|
-
process.on("exit", () => {
|
|
135
|
-
for (const session of sessions.list()) {
|
|
136
|
-
if (session.isCDP) {
|
|
137
|
-
logSessionEvent("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
|
|
138
|
-
} else {
|
|
139
|
-
logSessionEvent("process_exit", `Session "${session.name}": Closing self-launched browser.`);
|
|
140
|
-
try {
|
|
141
|
-
session.browser?.close();
|
|
142
|
-
} catch {
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
if (_sharedBrowser) {
|
|
147
|
-
logSessionEvent("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
|
|
148
|
-
try {
|
|
149
|
-
_sharedBrowser.close();
|
|
150
|
-
} catch {
|
|
151
|
-
}
|
|
152
|
-
_sharedBrowser = null;
|
|
153
|
-
}
|
|
154
|
-
if (_sharedCdpProxy) {
|
|
155
|
-
try {
|
|
156
|
-
_sharedCdpProxy.stop();
|
|
157
|
-
} catch {
|
|
158
|
-
}
|
|
159
|
-
_sharedCdpProxy = null;
|
|
160
|
-
}
|
|
161
|
-
sessions.clear();
|
|
162
|
-
});
|
|
85
|
+
// src/browser/connection.ts
|
|
86
|
+
import { existsSync } from "fs";
|
|
163
87
|
async function getCDPTargets(cdpEndpoint) {
|
|
164
88
|
try {
|
|
165
|
-
const
|
|
89
|
+
const endpoint = String(cdpEndpoint);
|
|
166
90
|
let url = "http://localhost:9222/json/list";
|
|
167
|
-
if (
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
url =
|
|
171
|
-
} else if (/^\d+$/.test(
|
|
172
|
-
url = `http://localhost:${
|
|
173
|
-
}
|
|
174
|
-
const
|
|
175
|
-
return await
|
|
91
|
+
if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
|
|
92
|
+
const parsed = new URL(endpoint);
|
|
93
|
+
parsed.pathname = (parsed.pathname.replace(/\/+$/, "") || "") + "/json/list";
|
|
94
|
+
url = parsed.toString();
|
|
95
|
+
} else if (/^\d+$/.test(endpoint)) {
|
|
96
|
+
url = `http://localhost:${endpoint}/json/list`;
|
|
97
|
+
}
|
|
98
|
+
const response = await fetch(url);
|
|
99
|
+
return await response.json();
|
|
176
100
|
} catch {
|
|
177
101
|
return [];
|
|
178
102
|
}
|
|
179
103
|
}
|
|
180
104
|
async function findTargetPage(cdpEndpoint, target) {
|
|
181
105
|
const targets = await getCDPTargets(cdpEndpoint);
|
|
182
|
-
const pages = targets.filter((
|
|
183
|
-
const byId = pages.find((
|
|
106
|
+
const pages = targets.filter((item) => item.url && !item.url.startsWith("about:blank") && !item.url.startsWith("chrome://") && !item.url.startsWith("chrome-untrusted://") && !item.url.startsWith("chrome-error://"));
|
|
107
|
+
const byId = pages.find((item) => item.id === target);
|
|
184
108
|
if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
|
|
185
109
|
const lowerTarget = target.toLowerCase();
|
|
186
|
-
const byTitle = pages.find((
|
|
110
|
+
const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
|
|
187
111
|
if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
|
|
188
|
-
const byUrl = pages.find((
|
|
112
|
+
const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
|
|
189
113
|
if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
|
|
190
114
|
return null;
|
|
191
115
|
}
|
|
192
116
|
function resolveLaunchOpts(ctx) {
|
|
193
|
-
|
|
194
|
-
return { cdpEndpoint: ctx.cdpEndpoint };
|
|
195
|
-
}
|
|
196
|
-
return { headless: true };
|
|
117
|
+
return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
|
|
197
118
|
}
|
|
198
119
|
var CHROMIUM_CANDIDATES = [
|
|
199
120
|
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
@@ -203,57 +124,58 @@ var CHROMIUM_CANDIDATES = [
|
|
|
203
124
|
"/usr/bin/google-chrome"
|
|
204
125
|
];
|
|
205
126
|
function discoverChromiumPath() {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
127
|
+
return CHROMIUM_CANDIDATES.find((path) => existsSync(path));
|
|
128
|
+
}
|
|
129
|
+
var browserPool = /* @__PURE__ */ new Map();
|
|
130
|
+
var sharedCdpProxy = null;
|
|
131
|
+
function getSharedCdpProxy() {
|
|
132
|
+
return sharedCdpProxy;
|
|
133
|
+
}
|
|
134
|
+
function setSharedCdpProxy(proxy) {
|
|
135
|
+
sharedCdpProxy = proxy;
|
|
210
136
|
}
|
|
211
|
-
var _browserPool = /* @__PURE__ */ new Map();
|
|
212
137
|
async function createBrowser(options) {
|
|
213
138
|
if (options?.cdpEndpoint) {
|
|
214
139
|
const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
|
|
215
140
|
if (!options.intercept) {
|
|
216
|
-
const pooled =
|
|
217
|
-
if (pooled && !pooled.disconnected)
|
|
218
|
-
|
|
219
|
-
}
|
|
220
|
-
if (pooled) _browserPool.delete(realEndpoint);
|
|
141
|
+
const pooled = browserPool.get(realEndpoint);
|
|
142
|
+
if (pooled && !pooled.disconnected) return pooled;
|
|
143
|
+
if (pooled) browserPool.delete(realEndpoint);
|
|
221
144
|
}
|
|
222
145
|
if (options.intercept) {
|
|
223
146
|
const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
|
|
224
|
-
|
|
225
|
-
const proxyPort = await
|
|
147
|
+
sharedCdpProxy = new CDPInterceptorProxy(config);
|
|
148
|
+
const proxyPort = await sharedCdpProxy.start();
|
|
226
149
|
console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
|
|
227
150
|
const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
|
|
228
151
|
return browser3;
|
|
229
152
|
}
|
|
230
153
|
const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
|
|
231
|
-
await browser2.discoverContexts().catch((
|
|
232
|
-
console.error(`[browser] discoverContexts failed: ${errMsg(
|
|
154
|
+
await browser2.discoverContexts().catch((error) => {
|
|
155
|
+
console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
|
|
233
156
|
});
|
|
234
|
-
|
|
157
|
+
browserPool.set(realEndpoint, browser2);
|
|
235
158
|
return browser2;
|
|
236
159
|
}
|
|
237
160
|
const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
|
|
238
161
|
const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
|
|
239
162
|
return browser;
|
|
240
163
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
}
|
|
251
|
-
function
|
|
252
|
-
return
|
|
164
|
+
|
|
165
|
+
// src/browser/state.ts
|
|
166
|
+
import { randomUUID } from "crypto";
|
|
167
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
|
|
168
|
+
import { join } from "path";
|
|
169
|
+
import { homedir } from "os";
|
|
170
|
+
import { SessionStore } from "@dyyz1993/xcli-core";
|
|
171
|
+
var SESSION_DIR = join(homedir(), ".xbrowser", "sessions");
|
|
172
|
+
var sessions = new SessionStore();
|
|
173
|
+
var sharedState = { browser: null, idleTimer: null };
|
|
174
|
+
function sessionFile(name) {
|
|
175
|
+
return join(SESSION_DIR, `${name}.json`);
|
|
253
176
|
}
|
|
254
|
-
function
|
|
255
|
-
|
|
256
|
-
session.lastActivityAt = Date.now();
|
|
177
|
+
function ensureSessionDir() {
|
|
178
|
+
mkdirSync(SESSION_DIR, { recursive: true });
|
|
257
179
|
}
|
|
258
180
|
function saveSessionDiskMeta(name, data) {
|
|
259
181
|
ensureSessionDir();
|
|
@@ -267,20 +189,40 @@ function saveSessionDiskMeta(name, data) {
|
|
|
267
189
|
writeFileSync(file, JSON.stringify(existing, null, 2));
|
|
268
190
|
}
|
|
269
191
|
function readSessionDiskMeta(name) {
|
|
270
|
-
const file = sessionFile(name);
|
|
271
192
|
try {
|
|
272
|
-
return JSON.parse(readFileSync(
|
|
193
|
+
return JSON.parse(readFileSync(sessionFile(name), "utf8"));
|
|
273
194
|
} catch {
|
|
274
195
|
return null;
|
|
275
196
|
}
|
|
276
197
|
}
|
|
277
198
|
function deleteSessionDiskMeta(name) {
|
|
278
|
-
const file = sessionFile(name);
|
|
279
199
|
try {
|
|
280
|
-
unlinkSync(
|
|
200
|
+
unlinkSync(sessionFile(name));
|
|
281
201
|
} catch {
|
|
282
202
|
}
|
|
283
203
|
}
|
|
204
|
+
function newSessionId() {
|
|
205
|
+
return randomUUID();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// src/browser/lifecycle.ts
|
|
209
|
+
function registerSession(session) {
|
|
210
|
+
const complete = {
|
|
211
|
+
id: session.id ?? newSessionId(),
|
|
212
|
+
createdAt: session.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
213
|
+
lastActivityAt: session.lastActivityAt ?? Date.now(),
|
|
214
|
+
...session
|
|
215
|
+
};
|
|
216
|
+
sessions.set(complete);
|
|
217
|
+
resetIdleTimer();
|
|
218
|
+
return complete;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/browser/restore.ts
|
|
222
|
+
function logSessionEvent(event, details) {
|
|
223
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
224
|
+
console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
|
|
225
|
+
}
|
|
284
226
|
async function isSessionPageAlive(session) {
|
|
285
227
|
const page = session.page;
|
|
286
228
|
if (!page || typeof page.evaluate !== "function") return false;
|
|
@@ -292,69 +234,65 @@ async function isSessionPageAlive(session) {
|
|
|
292
234
|
]);
|
|
293
235
|
return true;
|
|
294
236
|
} catch {
|
|
295
|
-
await new Promise((
|
|
237
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
296
238
|
}
|
|
297
239
|
}
|
|
298
240
|
return false;
|
|
299
241
|
}
|
|
300
|
-
async function findOrRestoreSession(name, cdpEndpoint) {
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
242
|
+
async function findOrRestoreSession(name, cdpEndpoint, cleanup = async () => false, installNetworkCapture2 = async () => {
|
|
243
|
+
}) {
|
|
244
|
+
const inMemory = findSession(name);
|
|
245
|
+
if (inMemory) {
|
|
246
|
+
if (await isSessionPageAlive(inMemory)) return inMemory;
|
|
247
|
+
logSessionEvent("stale_session", `name="${name}" \u2014 page probe failed; rebuilding`);
|
|
305
248
|
try {
|
|
306
|
-
await
|
|
249
|
+
await cleanup(name);
|
|
307
250
|
} catch {
|
|
308
251
|
}
|
|
309
252
|
}
|
|
310
253
|
const meta = readSessionDiskMeta(name);
|
|
311
254
|
if (!meta) return void 0;
|
|
312
|
-
const
|
|
313
|
-
if (!
|
|
255
|
+
const endpoint = cdpEndpoint || meta.cdpEndpoint;
|
|
256
|
+
if (!endpoint) return void 0;
|
|
314
257
|
try {
|
|
315
|
-
const
|
|
316
|
-
await new Promise((
|
|
317
|
-
let contexts =
|
|
258
|
+
const browser = await createBrowser({ cdpEndpoint: endpoint });
|
|
259
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
260
|
+
let contexts = browser.contexts();
|
|
318
261
|
if (contexts.length === 0) {
|
|
319
|
-
await new Promise((
|
|
320
|
-
contexts =
|
|
262
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
263
|
+
contexts = browser.contexts();
|
|
321
264
|
}
|
|
322
|
-
const context = contexts[0] || await
|
|
265
|
+
const context = contexts[0] || await browser.newContext();
|
|
323
266
|
const savedUrl = meta.conversationUrl || meta.url;
|
|
324
|
-
|
|
267
|
+
let targetHostname = "";
|
|
268
|
+
if (savedUrl) {
|
|
325
269
|
try {
|
|
326
|
-
|
|
270
|
+
targetHostname = new URL(savedUrl).hostname;
|
|
327
271
|
} catch {
|
|
328
|
-
|
|
272
|
+
targetHostname = "";
|
|
329
273
|
}
|
|
330
|
-
}
|
|
274
|
+
}
|
|
331
275
|
let page = null;
|
|
332
276
|
let fallbackPage = null;
|
|
333
|
-
for (const
|
|
334
|
-
const
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
if (
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
break;
|
|
341
|
-
}
|
|
342
|
-
if (!fallbackPage) {
|
|
343
|
-
fallbackPage = p;
|
|
344
|
-
}
|
|
277
|
+
for (const browserContext of contexts) {
|
|
278
|
+
for (const candidate of browserContext.pages()) {
|
|
279
|
+
const url = candidate.url();
|
|
280
|
+
if (!url || url === "about:blank" || url.startsWith("chrome://") || url.startsWith("chrome-untrusted://") || url.startsWith("chrome-error://")) continue;
|
|
281
|
+
if (targetHostname && url.includes(targetHostname)) {
|
|
282
|
+
page = candidate;
|
|
283
|
+
break;
|
|
345
284
|
}
|
|
285
|
+
fallbackPage ??= candidate;
|
|
346
286
|
}
|
|
347
287
|
if (page) break;
|
|
348
288
|
}
|
|
349
|
-
page
|
|
289
|
+
page ??= fallbackPage;
|
|
350
290
|
if (!page) {
|
|
351
|
-
const targets = await getCDPTargets(
|
|
352
|
-
const
|
|
353
|
-
|
|
354
|
-
);
|
|
355
|
-
if (matchTarget && matchTarget.url) {
|
|
291
|
+
const targets = await getCDPTargets(endpoint);
|
|
292
|
+
const match = targets.find((target) => target.url && target.url !== "about:blank" && !target.url.startsWith("chrome://") && !target.url.startsWith("chrome-untrusted://") && !target.url.startsWith("chrome-error://") && (!targetHostname || target.url.includes(targetHostname)));
|
|
293
|
+
if (match?.url) {
|
|
356
294
|
page = await context.newPage();
|
|
357
|
-
await page.goto(
|
|
295
|
+
await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
|
|
358
296
|
});
|
|
359
297
|
}
|
|
360
298
|
}
|
|
@@ -368,7 +306,6 @@ async function findOrRestoreSession(name, cdpEndpoint) {
|
|
|
368
306
|
new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
|
|
369
307
|
]);
|
|
370
308
|
} catch {
|
|
371
|
-
console.log(`[Session] "${name}" restored page unresponsive, creating fresh session`);
|
|
372
309
|
deleteSessionDiskMeta(name);
|
|
373
310
|
return void 0;
|
|
374
311
|
}
|
|
@@ -383,186 +320,35 @@ async function findOrRestoreSession(name, cdpEndpoint) {
|
|
|
383
320
|
}
|
|
384
321
|
}
|
|
385
322
|
const session = {
|
|
386
|
-
id: meta.id
|
|
323
|
+
id: meta.id,
|
|
387
324
|
name,
|
|
388
325
|
context,
|
|
389
326
|
page,
|
|
390
|
-
browser
|
|
391
|
-
createdAt: meta.createdAt
|
|
327
|
+
browser,
|
|
328
|
+
createdAt: meta.createdAt,
|
|
392
329
|
lastActivityAt: Date.now(),
|
|
393
330
|
isCDP: true,
|
|
394
|
-
cdpEndpoint:
|
|
331
|
+
cdpEndpoint: endpoint
|
|
395
332
|
};
|
|
396
|
-
for (const
|
|
397
|
-
if (
|
|
398
|
-
logSessionEvent("remove_stale", `Removing stale session name="${name}" id="${existingSession.id}" during restore`);
|
|
399
|
-
sessions.removeById(existingSession.id);
|
|
400
|
-
}
|
|
333
|
+
for (const existing of sessions.list()) {
|
|
334
|
+
if (existing.name === name) sessions.removeById(existing.id);
|
|
401
335
|
}
|
|
402
336
|
sessions.set(session);
|
|
403
|
-
|
|
404
|
-
await installNetworkCapture(page, name);
|
|
337
|
+
await installNetworkCapture2(session.page, name);
|
|
405
338
|
return session;
|
|
406
|
-
} catch (
|
|
407
|
-
console.error(`[Session Restore] Failed for "${name}":`, errMsg(
|
|
339
|
+
} catch (error) {
|
|
340
|
+
console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
|
|
408
341
|
deleteSessionDiskMeta(name);
|
|
409
342
|
return void 0;
|
|
410
343
|
}
|
|
411
344
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
|
|
416
|
-
const contexts = b2.contexts();
|
|
417
|
-
const ctx = contexts[0] || await b2.newContext();
|
|
418
|
-
const allPages = ctx.pages();
|
|
419
|
-
const existingPages = allPages.filter((p) => {
|
|
420
|
-
const url = p.url();
|
|
421
|
-
return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
|
|
422
|
-
});
|
|
423
|
-
const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
|
|
424
|
-
resetIdleTimer();
|
|
425
|
-
ephemeralConnections.set(page2, b2);
|
|
426
|
-
return { context: ctx, page: page2 };
|
|
427
|
-
}
|
|
428
|
-
const b = await getBrowser(options);
|
|
429
|
-
const context = await b.newContext();
|
|
430
|
-
const page = await context.newPage();
|
|
431
|
-
resetIdleTimer();
|
|
432
|
-
return { context, page };
|
|
433
|
-
}
|
|
434
|
-
var ephemeralConnections = /* @__PURE__ */ new WeakMap();
|
|
435
|
-
async function closeEphemeralContext(context) {
|
|
436
|
-
try {
|
|
437
|
-
const pages = context.pages();
|
|
438
|
-
for (const p of pages) {
|
|
439
|
-
const conn = ephemeralConnections.get(p);
|
|
440
|
-
if (conn) {
|
|
441
|
-
ephemeralConnections.delete(p);
|
|
442
|
-
await conn.close();
|
|
443
|
-
break;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
await context.close();
|
|
447
|
-
} catch {
|
|
448
|
-
}
|
|
449
|
-
if (sessions.size === 0 && idleTimer) {
|
|
450
|
-
clearTimeout(idleTimer);
|
|
451
|
-
idleTimer = null;
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
function getAllSessions() {
|
|
455
|
-
return sessions.list();
|
|
456
|
-
}
|
|
457
|
-
async function installNetworkCapture(page, sessionName) {
|
|
458
|
-
if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
|
|
459
|
-
const { networkStore } = await import("./network-store-YVDNUREI.js");
|
|
460
|
-
const requestData = /* @__PURE__ */ new Map();
|
|
461
|
-
const responseMeta = /* @__PURE__ */ new Map();
|
|
462
|
-
const xbPage = page;
|
|
463
|
-
xbPage.on("request", (params) => {
|
|
464
|
-
try {
|
|
465
|
-
const p = params;
|
|
466
|
-
requestData.set(p.requestId, {
|
|
467
|
-
method: p.request.method,
|
|
468
|
-
headers: p.request.headers,
|
|
469
|
-
postData: p.request.postData ?? null,
|
|
470
|
-
resourceType: p.type
|
|
471
|
-
});
|
|
472
|
-
} catch {
|
|
473
|
-
}
|
|
474
|
-
});
|
|
475
|
-
xbPage.on("response", (params) => {
|
|
476
|
-
try {
|
|
477
|
-
const p = params;
|
|
478
|
-
responseMeta.set(p.requestId, {
|
|
479
|
-
status: p.response.status,
|
|
480
|
-
url: p.response.url,
|
|
481
|
-
headers: p.response.headers,
|
|
482
|
-
mimeType: p.response.mimeType,
|
|
483
|
-
type: p.type
|
|
484
|
-
});
|
|
485
|
-
} catch {
|
|
486
|
-
}
|
|
487
|
-
});
|
|
488
|
-
xbPage.on("requestfinished", async (params) => {
|
|
489
|
-
try {
|
|
490
|
-
const p = params;
|
|
491
|
-
const meta = responseMeta.get(p.requestId);
|
|
492
|
-
if (!meta) return;
|
|
493
|
-
const req = requestData.get(p.requestId);
|
|
494
|
-
const method = req?.method ?? "GET";
|
|
495
|
-
const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
|
|
496
|
-
const resourceType = req?.resourceType ?? meta.type;
|
|
497
|
-
const requestHeaders = req?.headers ?? {};
|
|
498
|
-
let requestBody = void 0;
|
|
499
|
-
const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
|
|
500
|
-
if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
|
|
501
|
-
const postData = req?.postData;
|
|
502
|
-
if (postData) {
|
|
503
|
-
try {
|
|
504
|
-
requestBody = JSON.parse(postData);
|
|
505
|
-
} catch {
|
|
506
|
-
requestBody = postData;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
let responseBody = void 0;
|
|
511
|
-
let size = 0;
|
|
512
|
-
const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
|
|
513
|
-
if (isJsonish) {
|
|
514
|
-
try {
|
|
515
|
-
const bodyResult = await xbPage._cdpSend(
|
|
516
|
-
"Network.getResponseBody",
|
|
517
|
-
{ requestId: p.requestId }
|
|
518
|
-
);
|
|
519
|
-
const text = bodyResult.body ?? "";
|
|
520
|
-
size = text.length;
|
|
521
|
-
if (size <= 10240) {
|
|
522
|
-
try {
|
|
523
|
-
responseBody = JSON.parse(text);
|
|
524
|
-
} catch {
|
|
525
|
-
responseBody = text.slice(0, 200);
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
} catch {
|
|
529
|
-
}
|
|
530
|
-
} else {
|
|
531
|
-
try {
|
|
532
|
-
const bodyResult = await xbPage._cdpSend(
|
|
533
|
-
"Network.getResponseBody",
|
|
534
|
-
{ requestId: p.requestId }
|
|
535
|
-
);
|
|
536
|
-
size = bodyResult.body?.length ?? 0;
|
|
537
|
-
} catch {
|
|
538
|
-
size = 0;
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
networkStore.add(sessionName, {
|
|
542
|
-
timestamp: Date.now(),
|
|
543
|
-
method,
|
|
544
|
-
url: meta.url,
|
|
545
|
-
path: new URL(meta.url).pathname,
|
|
546
|
-
status: meta.status,
|
|
547
|
-
contentType,
|
|
548
|
-
size,
|
|
549
|
-
headers: meta.headers,
|
|
550
|
-
body: responseBody,
|
|
551
|
-
requestHeaders,
|
|
552
|
-
requestBody,
|
|
553
|
-
resourceType
|
|
554
|
-
});
|
|
555
|
-
requestData.delete(p.requestId);
|
|
556
|
-
responseMeta.delete(p.requestId);
|
|
557
|
-
} catch {
|
|
558
|
-
}
|
|
559
|
-
});
|
|
560
|
-
}
|
|
561
|
-
async function createSession(name, url, options) {
|
|
345
|
+
|
|
346
|
+
// src/browser/create-session.ts
|
|
347
|
+
async function createSessionImpl(name, url, options, deps) {
|
|
562
348
|
const existing = findSession(name);
|
|
563
349
|
if (existing) {
|
|
564
|
-
logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
|
|
565
|
-
await closeSessionByName(name);
|
|
350
|
+
deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
|
|
351
|
+
await deps.closeSessionByName(name);
|
|
566
352
|
}
|
|
567
353
|
const b = await createBrowser(options);
|
|
568
354
|
const isCDP = !!options?.cdpEndpoint;
|
|
@@ -673,7 +459,7 @@ async function createSession(name, url, options) {
|
|
|
673
459
|
}
|
|
674
460
|
}
|
|
675
461
|
if (!targetPage && options?.cdpEndpoint) {
|
|
676
|
-
const targets = await getCDPTargets(options.cdpEndpoint);
|
|
462
|
+
const targets = await deps.getCDPTargets(options.cdpEndpoint);
|
|
677
463
|
const ownedUrlsT = /* @__PURE__ */ new Set();
|
|
678
464
|
for (const ssn of sessions.list()) {
|
|
679
465
|
try {
|
|
@@ -754,27 +540,270 @@ async function createSession(name, url, options) {
|
|
|
754
540
|
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
|
|
755
541
|
});
|
|
756
542
|
}
|
|
757
|
-
const session = {
|
|
758
|
-
id: randomUUID(),
|
|
543
|
+
const session = deps.registerSession({
|
|
759
544
|
name,
|
|
760
545
|
context,
|
|
761
546
|
page,
|
|
762
547
|
browser: b,
|
|
763
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
764
|
-
lastActivityAt: Date.now(),
|
|
765
548
|
isCDP,
|
|
766
549
|
cdpEndpoint: options?.cdpEndpoint
|
|
767
|
-
};
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
resetIdleTimer();
|
|
771
|
-
await installNetworkCapture(page, name);
|
|
550
|
+
});
|
|
551
|
+
deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
|
|
552
|
+
await deps.installNetworkCapture(page, name);
|
|
772
553
|
return session;
|
|
773
554
|
}
|
|
555
|
+
|
|
556
|
+
// src/browser.ts
|
|
557
|
+
function logSessionEvent2(event, details) {
|
|
558
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
559
|
+
console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
|
|
560
|
+
}
|
|
561
|
+
var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
|
|
562
|
+
function resetIdleTimer() {
|
|
563
|
+
if (sharedState.idleTimer) clearTimeout(sharedState.idleTimer);
|
|
564
|
+
sharedState.idleTimer = setTimeout(async () => {
|
|
565
|
+
const now = Date.now();
|
|
566
|
+
let allIdle = true;
|
|
567
|
+
const idleSessions = [];
|
|
568
|
+
for (const s of sessions) {
|
|
569
|
+
if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
|
|
570
|
+
allIdle = false;
|
|
571
|
+
} else {
|
|
572
|
+
idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
if (allIdle && (sessions.size > 0 || sharedState.browser)) {
|
|
576
|
+
logSessionEvent2("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
|
|
577
|
+
await destroyBrowser().catch(() => {
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
}, IDLE_TIMEOUT_MS);
|
|
581
|
+
if (sharedState.idleTimer && typeof sharedState.idleTimer.unref === "function") {
|
|
582
|
+
sharedState.idleTimer.unref();
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
async function findOrRestoreSession2(name, cdpEndpoint) {
|
|
586
|
+
return findOrRestoreSession(
|
|
587
|
+
name,
|
|
588
|
+
cdpEndpoint,
|
|
589
|
+
closeSessionByName,
|
|
590
|
+
installNetworkCapture
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
function touchSession(id) {
|
|
594
|
+
const s = sessions.get(id);
|
|
595
|
+
if (s) s.lastActivityAt = Date.now();
|
|
596
|
+
resetIdleTimer();
|
|
597
|
+
}
|
|
598
|
+
process.on("exit", () => {
|
|
599
|
+
for (const session of sessions.list()) {
|
|
600
|
+
if (session.isCDP) {
|
|
601
|
+
logSessionEvent2("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
|
|
602
|
+
} else {
|
|
603
|
+
logSessionEvent2("process_exit", `Session "${session.name}": Closing self-launched browser.`);
|
|
604
|
+
try {
|
|
605
|
+
session.browser?.close();
|
|
606
|
+
} catch {
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
if (sharedState.browser) {
|
|
611
|
+
logSessionEvent2("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
|
|
612
|
+
try {
|
|
613
|
+
sharedState.browser.close();
|
|
614
|
+
} catch {
|
|
615
|
+
}
|
|
616
|
+
sharedState.browser = null;
|
|
617
|
+
}
|
|
618
|
+
const cdpProxy = getSharedCdpProxy();
|
|
619
|
+
if (cdpProxy) {
|
|
620
|
+
try {
|
|
621
|
+
cdpProxy.stop();
|
|
622
|
+
} catch {
|
|
623
|
+
}
|
|
624
|
+
setSharedCdpProxy(null);
|
|
625
|
+
}
|
|
626
|
+
sessions.clear();
|
|
627
|
+
});
|
|
628
|
+
async function getBrowser(options) {
|
|
629
|
+
if (sharedState.browser) return sharedState.browser;
|
|
630
|
+
sharedState.browser = await createBrowser(options);
|
|
631
|
+
if (options?.cdpEndpoint && options.intercept) {
|
|
632
|
+
}
|
|
633
|
+
return sharedState.browser;
|
|
634
|
+
}
|
|
635
|
+
function findSession(name) {
|
|
636
|
+
return sessions.find(name);
|
|
637
|
+
}
|
|
638
|
+
function getSessionById2(id) {
|
|
639
|
+
return sessions.get(id);
|
|
640
|
+
}
|
|
641
|
+
function setActivePage2(session, page) {
|
|
642
|
+
session.page = page;
|
|
643
|
+
session.lastActivityAt = Date.now();
|
|
644
|
+
}
|
|
645
|
+
async function createEphemeralContext(options) {
|
|
646
|
+
if (options?.cdpEndpoint) {
|
|
647
|
+
const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
|
|
648
|
+
const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
|
|
649
|
+
const contexts = b2.contexts();
|
|
650
|
+
const ctx = contexts[0] || await b2.newContext();
|
|
651
|
+
const allPages = ctx.pages();
|
|
652
|
+
const existingPages = allPages.filter((p) => {
|
|
653
|
+
const url = p.url();
|
|
654
|
+
return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
|
|
655
|
+
});
|
|
656
|
+
const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
|
|
657
|
+
resetIdleTimer();
|
|
658
|
+
ephemeralConnections.set(page2, b2);
|
|
659
|
+
return { context: ctx, page: page2 };
|
|
660
|
+
}
|
|
661
|
+
const b = await getBrowser(options);
|
|
662
|
+
const context = await b.newContext();
|
|
663
|
+
const page = await context.newPage();
|
|
664
|
+
resetIdleTimer();
|
|
665
|
+
return { context, page };
|
|
666
|
+
}
|
|
667
|
+
var ephemeralConnections = /* @__PURE__ */ new WeakMap();
|
|
668
|
+
async function closeEphemeralContext(context) {
|
|
669
|
+
try {
|
|
670
|
+
const pages = context.pages();
|
|
671
|
+
for (const p of pages) {
|
|
672
|
+
const conn = ephemeralConnections.get(p);
|
|
673
|
+
if (conn) {
|
|
674
|
+
ephemeralConnections.delete(p);
|
|
675
|
+
await conn.close();
|
|
676
|
+
break;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
await context.close();
|
|
680
|
+
} catch {
|
|
681
|
+
}
|
|
682
|
+
if (sessions.size === 0 && sharedState.idleTimer) {
|
|
683
|
+
clearTimeout(sharedState.idleTimer);
|
|
684
|
+
sharedState.idleTimer = null;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
function getAllSessions2() {
|
|
688
|
+
return sessions.list();
|
|
689
|
+
}
|
|
690
|
+
async function installNetworkCapture(page, sessionName) {
|
|
691
|
+
if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
|
|
692
|
+
const { networkStore } = await import("./network-store-YVDNUREI.js");
|
|
693
|
+
const requestData = /* @__PURE__ */ new Map();
|
|
694
|
+
const responseMeta = /* @__PURE__ */ new Map();
|
|
695
|
+
const xbPage = page;
|
|
696
|
+
xbPage.on("request", (params) => {
|
|
697
|
+
try {
|
|
698
|
+
const p = params;
|
|
699
|
+
requestData.set(p.requestId, {
|
|
700
|
+
method: p.request.method,
|
|
701
|
+
headers: p.request.headers,
|
|
702
|
+
postData: p.request.postData ?? null,
|
|
703
|
+
resourceType: p.type
|
|
704
|
+
});
|
|
705
|
+
} catch {
|
|
706
|
+
}
|
|
707
|
+
});
|
|
708
|
+
xbPage.on("response", (params) => {
|
|
709
|
+
try {
|
|
710
|
+
const p = params;
|
|
711
|
+
responseMeta.set(p.requestId, {
|
|
712
|
+
status: p.response.status,
|
|
713
|
+
url: p.response.url,
|
|
714
|
+
headers: p.response.headers,
|
|
715
|
+
mimeType: p.response.mimeType,
|
|
716
|
+
type: p.type
|
|
717
|
+
});
|
|
718
|
+
} catch {
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
xbPage.on("requestfinished", async (params) => {
|
|
722
|
+
try {
|
|
723
|
+
const p = params;
|
|
724
|
+
const meta = responseMeta.get(p.requestId);
|
|
725
|
+
if (!meta) return;
|
|
726
|
+
const req = requestData.get(p.requestId);
|
|
727
|
+
const method = req?.method ?? "GET";
|
|
728
|
+
const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
|
|
729
|
+
const resourceType = req?.resourceType ?? meta.type;
|
|
730
|
+
const requestHeaders = req?.headers ?? {};
|
|
731
|
+
let requestBody = void 0;
|
|
732
|
+
const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
|
|
733
|
+
if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
|
|
734
|
+
const postData = req?.postData;
|
|
735
|
+
if (postData) {
|
|
736
|
+
try {
|
|
737
|
+
requestBody = JSON.parse(postData);
|
|
738
|
+
} catch {
|
|
739
|
+
requestBody = postData;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
let responseBody = void 0;
|
|
744
|
+
let size = 0;
|
|
745
|
+
const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
|
|
746
|
+
if (isJsonish) {
|
|
747
|
+
try {
|
|
748
|
+
const bodyResult = await xbPage._cdpSend(
|
|
749
|
+
"Network.getResponseBody",
|
|
750
|
+
{ requestId: p.requestId }
|
|
751
|
+
);
|
|
752
|
+
const text = bodyResult.body ?? "";
|
|
753
|
+
size = text.length;
|
|
754
|
+
if (size <= 10240) {
|
|
755
|
+
try {
|
|
756
|
+
responseBody = JSON.parse(text);
|
|
757
|
+
} catch {
|
|
758
|
+
responseBody = text.slice(0, 200);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
} catch {
|
|
762
|
+
}
|
|
763
|
+
} else {
|
|
764
|
+
try {
|
|
765
|
+
const bodyResult = await xbPage._cdpSend(
|
|
766
|
+
"Network.getResponseBody",
|
|
767
|
+
{ requestId: p.requestId }
|
|
768
|
+
);
|
|
769
|
+
size = bodyResult.body?.length ?? 0;
|
|
770
|
+
} catch {
|
|
771
|
+
size = 0;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
networkStore.add(sessionName, {
|
|
775
|
+
timestamp: Date.now(),
|
|
776
|
+
method,
|
|
777
|
+
url: meta.url,
|
|
778
|
+
path: new URL(meta.url).pathname,
|
|
779
|
+
status: meta.status,
|
|
780
|
+
contentType,
|
|
781
|
+
size,
|
|
782
|
+
headers: meta.headers,
|
|
783
|
+
body: responseBody,
|
|
784
|
+
requestHeaders,
|
|
785
|
+
requestBody,
|
|
786
|
+
resourceType
|
|
787
|
+
});
|
|
788
|
+
requestData.delete(p.requestId);
|
|
789
|
+
responseMeta.delete(p.requestId);
|
|
790
|
+
} catch {
|
|
791
|
+
}
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
async function createSession(name, url, options) {
|
|
795
|
+
return createSessionImpl(name, url, options, {
|
|
796
|
+
closeSessionByName,
|
|
797
|
+
installNetworkCapture,
|
|
798
|
+
registerSession,
|
|
799
|
+
logSessionEvent: logSessionEvent2,
|
|
800
|
+
getCDPTargets
|
|
801
|
+
});
|
|
802
|
+
}
|
|
774
803
|
async function closeSessionByName(name) {
|
|
775
804
|
for (const session of sessions) {
|
|
776
805
|
if (session.name === name || session.id === name) {
|
|
777
|
-
|
|
806
|
+
logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
|
|
778
807
|
if (session.isCDP) {
|
|
779
808
|
if (session.browser) {
|
|
780
809
|
await session.browser.close().catch(() => {
|
|
@@ -790,7 +819,7 @@ async function closeSessionByName(name) {
|
|
|
790
819
|
sessions.removeById(session.id);
|
|
791
820
|
const file2 = sessionFile(session.name);
|
|
792
821
|
try {
|
|
793
|
-
|
|
822
|
+
unlinkSync2(file2);
|
|
794
823
|
} catch {
|
|
795
824
|
}
|
|
796
825
|
try {
|
|
@@ -800,7 +829,7 @@ async function closeSessionByName(name) {
|
|
|
800
829
|
} catch {
|
|
801
830
|
}
|
|
802
831
|
try {
|
|
803
|
-
const { SessionRecorder } = await import("./session-recorder-
|
|
832
|
+
const { SessionRecorder } = await import("./session-recorder-R3GDGXLJ.js");
|
|
804
833
|
SessionRecorder.cleanup(session.name);
|
|
805
834
|
} catch {
|
|
806
835
|
}
|
|
@@ -809,14 +838,14 @@ async function closeSessionByName(name) {
|
|
|
809
838
|
}
|
|
810
839
|
const file = sessionFile(name);
|
|
811
840
|
try {
|
|
812
|
-
|
|
841
|
+
unlinkSync2(file);
|
|
813
842
|
} catch {
|
|
814
843
|
}
|
|
815
844
|
return false;
|
|
816
845
|
}
|
|
817
846
|
async function closeAllSessions() {
|
|
818
847
|
const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
|
|
819
|
-
if (names)
|
|
848
|
+
if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
|
|
820
849
|
for (const session of sessions.list()) {
|
|
821
850
|
try {
|
|
822
851
|
if (session.isCDP) {
|
|
@@ -838,38 +867,37 @@ async function closeAllSessions() {
|
|
|
838
867
|
}
|
|
839
868
|
}
|
|
840
869
|
async function destroyBrowser() {
|
|
841
|
-
|
|
842
|
-
if (idleTimer) {
|
|
843
|
-
clearTimeout(idleTimer);
|
|
844
|
-
idleTimer = null;
|
|
870
|
+
logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
|
|
871
|
+
if (sharedState.idleTimer) {
|
|
872
|
+
clearTimeout(sharedState.idleTimer);
|
|
873
|
+
sharedState.idleTimer = null;
|
|
845
874
|
}
|
|
846
875
|
await closeAllSessions();
|
|
847
|
-
if (
|
|
848
|
-
await
|
|
876
|
+
if (sharedState.browser) {
|
|
877
|
+
await sharedState.browser.close().catch(() => {
|
|
849
878
|
});
|
|
850
|
-
|
|
879
|
+
sharedState.browser = null;
|
|
851
880
|
}
|
|
852
|
-
if (
|
|
853
|
-
await
|
|
881
|
+
if (getSharedCdpProxy()) {
|
|
882
|
+
await getSharedCdpProxy().stop().catch(() => {
|
|
854
883
|
});
|
|
855
|
-
|
|
884
|
+
setSharedCdpProxy(null);
|
|
856
885
|
}
|
|
857
886
|
}
|
|
858
887
|
function resetForTesting() {
|
|
859
888
|
sessions.clear();
|
|
860
|
-
|
|
861
|
-
|
|
889
|
+
sharedState.browser = null;
|
|
890
|
+
sharedState.idleTimer = null;
|
|
891
|
+
setSharedCdpProxy(null);
|
|
862
892
|
try {
|
|
863
|
-
for (const
|
|
864
|
-
unlinkSync(join(SESSION_DIR, f));
|
|
865
|
-
}
|
|
893
|
+
for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join2(SESSION_DIR, file));
|
|
866
894
|
} catch {
|
|
867
895
|
}
|
|
868
896
|
}
|
|
869
897
|
async function ensureProcessCanExit() {
|
|
870
|
-
if (idleTimer) {
|
|
871
|
-
clearTimeout(idleTimer);
|
|
872
|
-
idleTimer = null;
|
|
898
|
+
if (sharedState.idleTimer) {
|
|
899
|
+
clearTimeout(sharedState.idleTimer);
|
|
900
|
+
sharedState.idleTimer = null;
|
|
873
901
|
}
|
|
874
902
|
for (const session of sessions.list()) {
|
|
875
903
|
if (session.browser) {
|
|
@@ -881,34 +909,35 @@ async function ensureProcessCanExit() {
|
|
|
881
909
|
}
|
|
882
910
|
}
|
|
883
911
|
sessions.clear();
|
|
884
|
-
if (
|
|
885
|
-
await
|
|
912
|
+
if (sharedState.browser) {
|
|
913
|
+
await sharedState.browser.close().catch(() => {
|
|
886
914
|
});
|
|
887
|
-
|
|
915
|
+
sharedState.browser = null;
|
|
888
916
|
}
|
|
889
|
-
if (
|
|
890
|
-
await
|
|
917
|
+
if (getSharedCdpProxy()) {
|
|
918
|
+
await getSharedCdpProxy().stop().catch(() => {
|
|
891
919
|
});
|
|
892
|
-
|
|
920
|
+
setSharedCdpProxy(null);
|
|
893
921
|
}
|
|
894
922
|
}
|
|
895
923
|
|
|
896
924
|
export {
|
|
897
|
-
touchSession,
|
|
898
925
|
findTargetPage,
|
|
899
926
|
resolveLaunchOpts,
|
|
900
927
|
createBrowser,
|
|
901
|
-
getBrowser,
|
|
902
|
-
findSession,
|
|
903
|
-
getSessionById,
|
|
904
|
-
setActivePage,
|
|
905
928
|
saveSessionDiskMeta,
|
|
906
929
|
readSessionDiskMeta,
|
|
907
930
|
deleteSessionDiskMeta,
|
|
908
|
-
|
|
931
|
+
resetIdleTimer,
|
|
932
|
+
findOrRestoreSession2 as findOrRestoreSession,
|
|
933
|
+
touchSession,
|
|
934
|
+
getBrowser,
|
|
935
|
+
findSession,
|
|
936
|
+
getSessionById2 as getSessionById,
|
|
937
|
+
setActivePage2 as setActivePage,
|
|
909
938
|
createEphemeralContext,
|
|
910
939
|
closeEphemeralContext,
|
|
911
|
-
getAllSessions,
|
|
940
|
+
getAllSessions2 as getAllSessions,
|
|
912
941
|
createSession,
|
|
913
942
|
closeSessionByName,
|
|
914
943
|
closeAllSessions,
|