-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdriver-api.ts
More file actions
78 lines (73 loc) · 1.89 KB
/
Copy pathdriver-api.ts
File metadata and controls
78 lines (73 loc) · 1.89 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
const DEFAULT_SESSION_URL =
process.env.DRIVER_SESSION_URL?.trim() ||
"https://api.browser.cash/v1/browser/session";
export interface DriverSessionConfig {
country?: string;
type?: string;
captchaSolver?: boolean;
}
export interface DriverSession {
sessionId: string;
cdpUrl: string;
servedBy?: string;
status?: string;
}
async function requestWithTimeout(
input: string,
init: RequestInit,
timeoutMs: number,
): Promise<Response> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(input, { ...init, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
export async function createDriverSession(
apiKey: string,
config: DriverSessionConfig,
): Promise<DriverSession> {
const response = await requestWithTimeout(
DEFAULT_SESSION_URL,
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(config),
},
120_000,
);
if (!response.ok) {
throw new Error(
`Driver session create failed: ${response.status} ${await response.text()}`,
);
}
const data = (await response.json()) as DriverSession;
if (!data.sessionId || !data.cdpUrl) {
throw new Error("Driver session create response missing sessionId or cdpUrl");
}
return data;
}
export async function stopDriverSession(apiKey: string, sessionId: string): Promise<void> {
const url = new URL(DEFAULT_SESSION_URL);
url.searchParams.set("sessionId", sessionId);
const response = await requestWithTimeout(
url.toString(),
{
method: "DELETE",
headers: {
Authorization: `Bearer ${apiKey}`,
},
},
30_000,
);
if (!response.ok) {
throw new Error(
`Driver session stop failed: ${response.status} ${await response.text()}`,
);
}
}