@querying/sneaky 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +159 -2
- package/bin/sneaky-mcp.mjs +36 -0
- package/bin/sneaky.mjs +36 -0
- package/dist/agent/index.d.ts +275 -0
- package/dist/agent/index.js +319 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/browser/index.d.ts +69 -0
- package/dist/browser/index.js +326 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/cli/index.d.ts +51 -0
- package/dist/cli/index.js +189 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/driver/cdp.d.ts +36 -0
- package/dist/driver/cdp.js +240 -0
- package/dist/driver/cdp.js.map +1 -0
- package/dist/driver/frame.d.ts +229 -0
- package/dist/driver/frame.js +794 -0
- package/dist/driver/frame.js.map +1 -0
- package/dist/driver/index.d.ts +13 -0
- package/dist/driver/index.js +6 -0
- package/dist/driver/index.js.map +1 -0
- package/dist/driver/keys.d.ts +9 -0
- package/dist/driver/keys.js +65 -0
- package/dist/driver/keys.js.map +1 -0
- package/dist/driver/launcher.d.ts +49 -0
- package/dist/driver/launcher.js +251 -0
- package/dist/driver/launcher.js.map +1 -0
- package/dist/driver/page.d.ts +391 -0
- package/dist/driver/page.js +1594 -0
- package/dist/driver/page.js.map +1 -0
- package/dist/index.d.ts +319 -0
- package/dist/index.js +511 -0
- package/dist/index.js.map +1 -0
- package/dist/request/index.d.ts +265 -0
- package/dist/request/index.js +898 -0
- package/dist/request/index.js.map +1 -0
- package/package.json +79 -4
|
@@ -0,0 +1,898 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
/** A request that Chromium could not complete. `code` is Chromium's name, such as `net::ERR_TIMED_OUT`. */
|
|
5
|
+
export class RequestError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
netError;
|
|
8
|
+
/** True when the failure came after the response head, in the middle of the body. */
|
|
9
|
+
headSent;
|
|
10
|
+
/** The session's wire totals when the request failed. */
|
|
11
|
+
session;
|
|
12
|
+
/**
|
|
13
|
+
* The status an `http://` proxy answered CONNECT with, when the request failed before its response
|
|
14
|
+
* head. A proxy reached over TLS or SOCKS5 reports none.
|
|
15
|
+
*/
|
|
16
|
+
proxyStatus;
|
|
17
|
+
/** True when a connection to the proxy was closed for `proxyDialTimeoutMs` or `proxyAnswerTimeoutMs`. */
|
|
18
|
+
proxyTimedOut;
|
|
19
|
+
/** The status the server answered a WebSocket handshake with, when it refused the socket. */
|
|
20
|
+
status;
|
|
21
|
+
constructor(detail) {
|
|
22
|
+
super(detail.message ? `${detail.code}: ${detail.message}` : detail.code);
|
|
23
|
+
this.name = "RequestError";
|
|
24
|
+
this.code = detail.code;
|
|
25
|
+
this.netError = detail.netError;
|
|
26
|
+
this.headSent = detail.headSent ?? false;
|
|
27
|
+
this.session = detail.session;
|
|
28
|
+
this.proxyStatus = detail.proxyStatus;
|
|
29
|
+
this.proxyTimedOut = detail.proxyTimedOut ?? false;
|
|
30
|
+
this.status = detail.status;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export class Response {
|
|
34
|
+
status;
|
|
35
|
+
statusText;
|
|
36
|
+
/** Response headers in the order the server sent them. */
|
|
37
|
+
rawHeaders;
|
|
38
|
+
#headers;
|
|
39
|
+
/** The URL that answered, after redirects. */
|
|
40
|
+
url;
|
|
41
|
+
/** "h2", "h3" or "http/1.1". */
|
|
42
|
+
protocol;
|
|
43
|
+
/** Address the response came from: the proxy's when the session has one. */
|
|
44
|
+
remote;
|
|
45
|
+
/** The body with Content-Encoding already undone. */
|
|
46
|
+
body;
|
|
47
|
+
/** Resolves when the body has been received in full. It rejects when the body fails. */
|
|
48
|
+
finished;
|
|
49
|
+
/** @internal */
|
|
50
|
+
constructor(head, body, finished) {
|
|
51
|
+
this.status = head.status;
|
|
52
|
+
this.statusText = head.statusText;
|
|
53
|
+
this.rawHeaders = head.headers;
|
|
54
|
+
this.url = head.url;
|
|
55
|
+
this.protocol = head.protocol;
|
|
56
|
+
this.remote = head.remote;
|
|
57
|
+
this.body = body;
|
|
58
|
+
this.finished = finished;
|
|
59
|
+
}
|
|
60
|
+
get headers() {
|
|
61
|
+
if (this.#headers === undefined) {
|
|
62
|
+
const headers = new Headers();
|
|
63
|
+
for (const [name, value] of this.rawHeaders)
|
|
64
|
+
headers.append(name, value);
|
|
65
|
+
this.#headers = headers;
|
|
66
|
+
}
|
|
67
|
+
return this.#headers;
|
|
68
|
+
}
|
|
69
|
+
get ok() {
|
|
70
|
+
return this.status >= 200 && this.status < 300;
|
|
71
|
+
}
|
|
72
|
+
async bytes() {
|
|
73
|
+
const chunks = [];
|
|
74
|
+
let total = 0;
|
|
75
|
+
for await (const chunk of this.body) {
|
|
76
|
+
chunks.push(chunk);
|
|
77
|
+
total += chunk.byteLength;
|
|
78
|
+
}
|
|
79
|
+
if (chunks.length === 0)
|
|
80
|
+
return Buffer.alloc(0);
|
|
81
|
+
if (chunks.length === 1) {
|
|
82
|
+
const only = chunks[0];
|
|
83
|
+
return Buffer.isBuffer(only) ? only : Buffer.from(only.buffer, only.byteOffset, only.byteLength);
|
|
84
|
+
}
|
|
85
|
+
return Buffer.concat(chunks, total);
|
|
86
|
+
}
|
|
87
|
+
async text() {
|
|
88
|
+
const data = await this.bytes();
|
|
89
|
+
if (Buffer.isBuffer(data))
|
|
90
|
+
return data.toString("utf8");
|
|
91
|
+
return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8");
|
|
92
|
+
}
|
|
93
|
+
async json() {
|
|
94
|
+
return JSON.parse(await this.text());
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** An open WebSocket. Messages arrive whole: a text message as a string, a binary one as bytes. */
|
|
98
|
+
export class WebSocketConnection {
|
|
99
|
+
/** 101 over HTTP/1.1, 200 over HTTP/2. */
|
|
100
|
+
status;
|
|
101
|
+
/** Headers of the server's answer to the handshake, in the order it sent them. */
|
|
102
|
+
rawHeaders;
|
|
103
|
+
#headers;
|
|
104
|
+
url;
|
|
105
|
+
/** The subprotocol the server chose, or "". */
|
|
106
|
+
subprotocol;
|
|
107
|
+
/** The extensions in use, such as "permessage-deflate". */
|
|
108
|
+
extensions;
|
|
109
|
+
remote;
|
|
110
|
+
/** Resolves when the socket has ended with a closing handshake or a dropped connection. Rejects when it failed. */
|
|
111
|
+
closed;
|
|
112
|
+
#socket;
|
|
113
|
+
#queue = [];
|
|
114
|
+
#queueHead = 0;
|
|
115
|
+
#queuedBytes = 0;
|
|
116
|
+
#waiter;
|
|
117
|
+
#ended = false;
|
|
118
|
+
#error;
|
|
119
|
+
/** @internal */
|
|
120
|
+
constructor(head, socket, closed) {
|
|
121
|
+
this.status = head.status;
|
|
122
|
+
this.rawHeaders = head.headers;
|
|
123
|
+
this.url = head.url;
|
|
124
|
+
this.subprotocol = head.subprotocol;
|
|
125
|
+
this.extensions = head.extensions;
|
|
126
|
+
this.remote = head.remote;
|
|
127
|
+
this.#socket = socket;
|
|
128
|
+
this.closed = closed;
|
|
129
|
+
}
|
|
130
|
+
get headers() {
|
|
131
|
+
if (this.#headers === undefined) {
|
|
132
|
+
const headers = new Headers();
|
|
133
|
+
for (const [name, value] of this.rawHeaders)
|
|
134
|
+
headers.append(name, value);
|
|
135
|
+
this.#headers = headers;
|
|
136
|
+
}
|
|
137
|
+
return this.#headers;
|
|
138
|
+
}
|
|
139
|
+
/** Sends one message: a string as text, bytes as binary. A message sent after the socket has ended is dropped. */
|
|
140
|
+
send(data) {
|
|
141
|
+
if (this.#ended)
|
|
142
|
+
return;
|
|
143
|
+
if (typeof data === "string") {
|
|
144
|
+
const byteLength = Buffer.byteLength(data, "utf8");
|
|
145
|
+
const payloadLength = 1 + byteLength;
|
|
146
|
+
const frame = Buffer.allocUnsafe(5 + payloadLength);
|
|
147
|
+
frame[0] = FRAME_M;
|
|
148
|
+
frame.writeUInt32BE(payloadLength, 1);
|
|
149
|
+
frame[5] = 1;
|
|
150
|
+
if (byteLength > 0)
|
|
151
|
+
frame.write(data, 6, byteLength, "utf8");
|
|
152
|
+
this.#socket.write(frame);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const payloadLength = 1 + data.byteLength;
|
|
156
|
+
const frame = Buffer.allocUnsafe(5 + payloadLength);
|
|
157
|
+
frame[0] = FRAME_M;
|
|
158
|
+
frame.writeUInt32BE(payloadLength, 1);
|
|
159
|
+
frame[5] = 2;
|
|
160
|
+
frame.set(data, 6);
|
|
161
|
+
this.#socket.write(frame);
|
|
162
|
+
}
|
|
163
|
+
/** The next message, or undefined when the socket has ended. Rejects when the socket failed. */
|
|
164
|
+
receive() {
|
|
165
|
+
if (this.#queueHead < this.#queue.length) {
|
|
166
|
+
const message = this.#queue[this.#queueHead];
|
|
167
|
+
this.#queue[this.#queueHead] = undefined;
|
|
168
|
+
this.#queueHead++;
|
|
169
|
+
if (this.#queueHead === this.#queue.length) {
|
|
170
|
+
this.#queue.length = 0;
|
|
171
|
+
this.#queueHead = 0;
|
|
172
|
+
}
|
|
173
|
+
else if (this.#queueHead >= 64 && this.#queueHead * 2 >= this.#queue.length) {
|
|
174
|
+
this.#queue = this.#queue.slice(this.#queueHead);
|
|
175
|
+
this.#queueHead = 0;
|
|
176
|
+
}
|
|
177
|
+
this.#queuedBytes -= message.length;
|
|
178
|
+
if (!this.#ended && this.#queuedBytes < WEBSOCKET_QUEUE_BYTES)
|
|
179
|
+
this.#socket.resume();
|
|
180
|
+
return Promise.resolve(message);
|
|
181
|
+
}
|
|
182
|
+
if (this.#error !== undefined)
|
|
183
|
+
return Promise.reject(this.#error);
|
|
184
|
+
if (this.#ended)
|
|
185
|
+
return Promise.resolve(undefined);
|
|
186
|
+
this.#waiter ??= Promise.withResolvers();
|
|
187
|
+
return this.#waiter.promise;
|
|
188
|
+
}
|
|
189
|
+
async *[Symbol.asyncIterator]() {
|
|
190
|
+
for (;;) {
|
|
191
|
+
const message = await this.receive();
|
|
192
|
+
if (message === undefined)
|
|
193
|
+
return;
|
|
194
|
+
yield message;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/** Starts the closing handshake. Resolves, as "closed" does, when the socket has ended. */
|
|
198
|
+
close(code = 1000, reason = "") {
|
|
199
|
+
if (!this.#ended)
|
|
200
|
+
this.#socket.write(encodeStringFrame(FRAME_C, JSON.stringify({ code, reason })));
|
|
201
|
+
return this.closed;
|
|
202
|
+
}
|
|
203
|
+
/** Drops the socket without a closing handshake. */
|
|
204
|
+
abort() {
|
|
205
|
+
this.#socket.destroy();
|
|
206
|
+
}
|
|
207
|
+
/** @internal */
|
|
208
|
+
push(message) {
|
|
209
|
+
if (this.#waiter) {
|
|
210
|
+
const waiter = this.#waiter;
|
|
211
|
+
this.#waiter = undefined;
|
|
212
|
+
waiter.resolve(message);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.#queue.push(message);
|
|
216
|
+
this.#queuedBytes += message.length;
|
|
217
|
+
// The daemon stops reading the socket when this connection does not take what it has.
|
|
218
|
+
if (this.#queuedBytes >= WEBSOCKET_QUEUE_BYTES)
|
|
219
|
+
this.#socket.pause();
|
|
220
|
+
}
|
|
221
|
+
/** @internal */
|
|
222
|
+
end(error) {
|
|
223
|
+
if (this.#ended)
|
|
224
|
+
return;
|
|
225
|
+
this.#ended = true;
|
|
226
|
+
this.#error = error;
|
|
227
|
+
const waiter = this.#waiter;
|
|
228
|
+
this.#waiter = undefined;
|
|
229
|
+
if (error !== undefined)
|
|
230
|
+
waiter?.reject(error);
|
|
231
|
+
else
|
|
232
|
+
waiter?.resolve(undefined);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const WEBSOCKET_QUEUE_BYTES = 1024 * 1024;
|
|
236
|
+
const MAX_IDLE_SOCKETS = 64;
|
|
237
|
+
const EMPTY_BUFFER = Buffer.alloc(0);
|
|
238
|
+
const EMPTY_HEADERS = [];
|
|
239
|
+
const FRAME_A = 0x41; // 'A'
|
|
240
|
+
const FRAME_B = 0x42; // 'B'
|
|
241
|
+
const FRAME_C = 0x43; // 'C'
|
|
242
|
+
const FRAME_E = 0x45; // 'E'
|
|
243
|
+
const FRAME_M = 0x4d; // 'M'
|
|
244
|
+
const FRAME_Q = 0x51; // 'Q'
|
|
245
|
+
const END_BODY_FRAME = Buffer.from([FRAME_E, 0, 0, 0, 0]);
|
|
246
|
+
function encodeFrame(typeCode, payload) {
|
|
247
|
+
const frame = Buffer.allocUnsafe(5 + payload.byteLength);
|
|
248
|
+
frame[0] = typeCode;
|
|
249
|
+
frame.writeUInt32BE(payload.byteLength, 1);
|
|
250
|
+
frame.set(payload, 5);
|
|
251
|
+
return frame;
|
|
252
|
+
}
|
|
253
|
+
function encodeStringFrame(typeCode, text) {
|
|
254
|
+
const byteLength = Buffer.byteLength(text, "utf8");
|
|
255
|
+
const frame = Buffer.allocUnsafe(5 + byteLength);
|
|
256
|
+
frame[0] = typeCode;
|
|
257
|
+
frame.writeUInt32BE(byteLength, 1);
|
|
258
|
+
if (byteLength > 0)
|
|
259
|
+
frame.write(text, 5, byteLength, "utf8");
|
|
260
|
+
return frame;
|
|
261
|
+
}
|
|
262
|
+
/** Splits the daemon's byte stream into frames without quadratic concatenation. */
|
|
263
|
+
class FrameReader {
|
|
264
|
+
#chunks = [];
|
|
265
|
+
#head = 0;
|
|
266
|
+
#offset = 0;
|
|
267
|
+
#length = 0;
|
|
268
|
+
#headerBuf = Buffer.allocUnsafe(5);
|
|
269
|
+
hasPending() {
|
|
270
|
+
return this.#length > 0;
|
|
271
|
+
}
|
|
272
|
+
#advance(n) {
|
|
273
|
+
this.#length -= n;
|
|
274
|
+
let remaining = n;
|
|
275
|
+
while (remaining > 0) {
|
|
276
|
+
const first = this.#chunks[this.#head];
|
|
277
|
+
const avail = first.length - this.#offset;
|
|
278
|
+
if (remaining < avail) {
|
|
279
|
+
this.#offset += remaining;
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
remaining -= avail;
|
|
283
|
+
this.#chunks[this.#head] = EMPTY_BUFFER;
|
|
284
|
+
this.#head++;
|
|
285
|
+
this.#offset = 0;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
push(chunk) {
|
|
289
|
+
if (chunk.length === 0)
|
|
290
|
+
return [];
|
|
291
|
+
const frames = [];
|
|
292
|
+
// Fast path: no buffered bytes from earlier chunks.
|
|
293
|
+
if (this.#length === 0) {
|
|
294
|
+
let offset = 0;
|
|
295
|
+
const len = chunk.length;
|
|
296
|
+
while (len - offset >= 5) {
|
|
297
|
+
const frameLen = chunk.readUInt32BE(offset + 1);
|
|
298
|
+
if (len - offset - 5 < frameLen)
|
|
299
|
+
break;
|
|
300
|
+
frames.push({
|
|
301
|
+
type: String.fromCharCode(chunk[offset]),
|
|
302
|
+
payload: chunk.subarray(offset + 5, offset + 5 + frameLen),
|
|
303
|
+
});
|
|
304
|
+
offset += 5 + frameLen;
|
|
305
|
+
}
|
|
306
|
+
if (offset < len) {
|
|
307
|
+
this.#chunks.push(chunk);
|
|
308
|
+
this.#head = 0;
|
|
309
|
+
this.#offset = offset;
|
|
310
|
+
this.#length = len - offset;
|
|
311
|
+
}
|
|
312
|
+
return frames;
|
|
313
|
+
}
|
|
314
|
+
this.#chunks.push(chunk);
|
|
315
|
+
this.#length += chunk.length;
|
|
316
|
+
while (this.#length >= 5) {
|
|
317
|
+
const first = this.#chunks[this.#head];
|
|
318
|
+
const avail = first.length - this.#offset;
|
|
319
|
+
let typeCode;
|
|
320
|
+
let frameLen;
|
|
321
|
+
if (avail >= 5) {
|
|
322
|
+
typeCode = first[this.#offset];
|
|
323
|
+
frameLen = first.readUInt32BE(this.#offset + 1);
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
let cIdx = this.#head;
|
|
327
|
+
let cOff = this.#offset;
|
|
328
|
+
for (let i = 0; i < 5; i++) {
|
|
329
|
+
let cur = this.#chunks[cIdx];
|
|
330
|
+
while (cOff >= cur.length) {
|
|
331
|
+
cIdx++;
|
|
332
|
+
cOff = 0;
|
|
333
|
+
cur = this.#chunks[cIdx];
|
|
334
|
+
}
|
|
335
|
+
this.#headerBuf[i] = cur[cOff++];
|
|
336
|
+
}
|
|
337
|
+
typeCode = this.#headerBuf[0];
|
|
338
|
+
frameLen = this.#headerBuf.readUInt32BE(1);
|
|
339
|
+
}
|
|
340
|
+
if (this.#length - 5 < frameLen)
|
|
341
|
+
break;
|
|
342
|
+
this.#advance(5);
|
|
343
|
+
let payload;
|
|
344
|
+
if (frameLen === 0) {
|
|
345
|
+
payload = EMPTY_BUFFER;
|
|
346
|
+
}
|
|
347
|
+
else {
|
|
348
|
+
const headChunk = this.#chunks[this.#head];
|
|
349
|
+
const headAvail = headChunk.length - this.#offset;
|
|
350
|
+
if (headAvail >= frameLen) {
|
|
351
|
+
payload = headChunk.subarray(this.#offset, this.#offset + frameLen);
|
|
352
|
+
this.#length -= frameLen;
|
|
353
|
+
this.#offset += frameLen;
|
|
354
|
+
if (this.#offset === headChunk.length) {
|
|
355
|
+
this.#chunks[this.#head] = EMPTY_BUFFER;
|
|
356
|
+
this.#head++;
|
|
357
|
+
this.#offset = 0;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
else {
|
|
361
|
+
const out = Buffer.allocUnsafe(frameLen);
|
|
362
|
+
let copied = 0;
|
|
363
|
+
while (copied < frameLen) {
|
|
364
|
+
const cur = this.#chunks[this.#head];
|
|
365
|
+
const curAvail = cur.length - this.#offset;
|
|
366
|
+
const take = Math.min(curAvail, frameLen - copied);
|
|
367
|
+
cur.copy(out, copied, this.#offset, this.#offset + take);
|
|
368
|
+
copied += take;
|
|
369
|
+
this.#offset += take;
|
|
370
|
+
if (this.#offset === cur.length) {
|
|
371
|
+
this.#chunks[this.#head] = EMPTY_BUFFER;
|
|
372
|
+
this.#head++;
|
|
373
|
+
this.#offset = 0;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
this.#length -= frameLen;
|
|
377
|
+
payload = out;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
frames.push({
|
|
381
|
+
type: String.fromCharCode(typeCode),
|
|
382
|
+
payload,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
if (this.#length === 0) {
|
|
386
|
+
this.#chunks.length = 0;
|
|
387
|
+
this.#head = 0;
|
|
388
|
+
this.#offset = 0;
|
|
389
|
+
}
|
|
390
|
+
else if (this.#head >= 64 && this.#head * 2 >= this.#chunks.length) {
|
|
391
|
+
this.#chunks = this.#chunks.slice(this.#head);
|
|
392
|
+
this.#head = 0;
|
|
393
|
+
}
|
|
394
|
+
return frames;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
function parseAddress(address) {
|
|
398
|
+
if (address.startsWith("unix:"))
|
|
399
|
+
return { path: address.slice(5) };
|
|
400
|
+
if (address.startsWith("tcp:")) {
|
|
401
|
+
const colon = address.lastIndexOf(":");
|
|
402
|
+
return { host: address.slice(4, colon), port: Number(address.slice(colon + 1)) };
|
|
403
|
+
}
|
|
404
|
+
throw new TypeError(`daemon address must be unix:<path> or tcp:<host>:<port>, got ${address}`);
|
|
405
|
+
}
|
|
406
|
+
const DAEMON_GONE = "TFR_DAEMON_CLOSED";
|
|
407
|
+
export class Daemon {
|
|
408
|
+
address;
|
|
409
|
+
#connect;
|
|
410
|
+
#isTcp;
|
|
411
|
+
#child;
|
|
412
|
+
#idleSockets = [];
|
|
413
|
+
#closed = false;
|
|
414
|
+
constructor(address, child) {
|
|
415
|
+
this.address = address;
|
|
416
|
+
this.#connect = parseAddress(address);
|
|
417
|
+
this.#isTcp = "port" in this.#connect;
|
|
418
|
+
this.#child = child;
|
|
419
|
+
}
|
|
420
|
+
/** Uses a daemon that is already running. */
|
|
421
|
+
static connect(address) {
|
|
422
|
+
return new Daemon(address);
|
|
423
|
+
}
|
|
424
|
+
/** Starts a daemon and resolves when it accepts connections. `close()` stops it. */
|
|
425
|
+
static async spawn(options) {
|
|
426
|
+
parseAddress(options.listen);
|
|
427
|
+
const child = spawn(options.binary, [`--listen=${options.listen}`, ...(options.args ?? [])], {
|
|
428
|
+
stdio: ["ignore", "pipe", options.stderr ?? "inherit"],
|
|
429
|
+
});
|
|
430
|
+
await new Promise((resolve, reject) => {
|
|
431
|
+
let output = "";
|
|
432
|
+
child.once("error", reject);
|
|
433
|
+
child.once("exit", (code, signal) => reject(new Error(`tfrd exited before it listened (${signal ?? code})`)));
|
|
434
|
+
child.stdout?.on("data", (chunk) => {
|
|
435
|
+
output += chunk.toString("utf8");
|
|
436
|
+
if (output.includes("listening "))
|
|
437
|
+
resolve();
|
|
438
|
+
});
|
|
439
|
+
});
|
|
440
|
+
child.removeAllListeners("exit");
|
|
441
|
+
child.removeAllListeners("error");
|
|
442
|
+
return new Daemon(options.listen, child);
|
|
443
|
+
}
|
|
444
|
+
async createSession(options = {}) {
|
|
445
|
+
const id = options.id ?? randomUUID();
|
|
446
|
+
await this.#command({ ...options, op: "session.create", id });
|
|
447
|
+
return new Session(this, id);
|
|
448
|
+
}
|
|
449
|
+
/** Counts of every session, or of session `id` only. */
|
|
450
|
+
async stats(id) {
|
|
451
|
+
return (await this.#command(id === undefined ? { op: "stats" } : { op: "stats", id }));
|
|
452
|
+
}
|
|
453
|
+
/** The Chromium version the daemon is built from, such as "157.0.8103.78". */
|
|
454
|
+
async chromiumVersion() {
|
|
455
|
+
return (await this.#command({ op: "version" })).chromium;
|
|
456
|
+
}
|
|
457
|
+
/** Stops the daemon when this object started it, and closes idle pooled connections. */
|
|
458
|
+
async close() {
|
|
459
|
+
this.#closed = true;
|
|
460
|
+
this.#closePool();
|
|
461
|
+
const child = this.#child;
|
|
462
|
+
if (!child || child.exitCode !== null || child.signalCode !== null)
|
|
463
|
+
return;
|
|
464
|
+
await new Promise((resolve) => {
|
|
465
|
+
child.once("exit", () => resolve());
|
|
466
|
+
child.kill("SIGTERM");
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
/** @internal */
|
|
470
|
+
async closeSession(id) {
|
|
471
|
+
return (await this.#command({ op: "session.close", id }));
|
|
472
|
+
}
|
|
473
|
+
#acquireSocket() {
|
|
474
|
+
while (this.#idleSockets.length > 0) {
|
|
475
|
+
const entry = this.#idleSockets.pop();
|
|
476
|
+
const { socket, onIdleDrop } = entry;
|
|
477
|
+
socket.off("data", onIdleDrop);
|
|
478
|
+
socket.off("error", onIdleDrop);
|
|
479
|
+
socket.off("end", onIdleDrop);
|
|
480
|
+
socket.off("close", onIdleDrop);
|
|
481
|
+
if (!socket.destroyed && socket.readable && socket.writable && !socket.readableEnded && !socket.writableEnded) {
|
|
482
|
+
socket.ref();
|
|
483
|
+
return socket;
|
|
484
|
+
}
|
|
485
|
+
socket.destroy();
|
|
486
|
+
}
|
|
487
|
+
const socket = net.connect(this.#connect);
|
|
488
|
+
if (this.#isTcp)
|
|
489
|
+
socket.setNoDelay(true);
|
|
490
|
+
return socket;
|
|
491
|
+
}
|
|
492
|
+
#releaseSocket(socket) {
|
|
493
|
+
if (this.#closed ||
|
|
494
|
+
socket.destroyed ||
|
|
495
|
+
!socket.readable ||
|
|
496
|
+
!socket.writable ||
|
|
497
|
+
socket.readableEnded ||
|
|
498
|
+
socket.writableEnded ||
|
|
499
|
+
this.#idleSockets.length >= MAX_IDLE_SOCKETS) {
|
|
500
|
+
socket.destroy();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
const onIdleDrop = () => {
|
|
504
|
+
this.#removeIdleSocket(socket);
|
|
505
|
+
socket.destroy();
|
|
506
|
+
};
|
|
507
|
+
const entry = { socket, onIdleDrop };
|
|
508
|
+
socket.on("data", onIdleDrop);
|
|
509
|
+
socket.on("error", onIdleDrop);
|
|
510
|
+
socket.on("end", onIdleDrop);
|
|
511
|
+
socket.on("close", onIdleDrop);
|
|
512
|
+
socket.unref();
|
|
513
|
+
this.#idleSockets.push(entry);
|
|
514
|
+
}
|
|
515
|
+
#removeIdleSocket(socket) {
|
|
516
|
+
const idx = this.#idleSockets.findIndex((entry) => entry.socket === socket);
|
|
517
|
+
if (idx !== -1) {
|
|
518
|
+
const entry = this.#idleSockets[idx];
|
|
519
|
+
socket.off("data", entry.onIdleDrop);
|
|
520
|
+
socket.off("error", entry.onIdleDrop);
|
|
521
|
+
socket.off("end", entry.onIdleDrop);
|
|
522
|
+
socket.off("close", entry.onIdleDrop);
|
|
523
|
+
this.#idleSockets.splice(idx, 1);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
#closePool() {
|
|
527
|
+
while (this.#idleSockets.length > 0) {
|
|
528
|
+
const entry = this.#idleSockets.pop();
|
|
529
|
+
entry.socket.off("data", entry.onIdleDrop);
|
|
530
|
+
entry.socket.off("error", entry.onIdleDrop);
|
|
531
|
+
entry.socket.off("end", entry.onIdleDrop);
|
|
532
|
+
entry.socket.off("close", entry.onIdleDrop);
|
|
533
|
+
entry.socket.destroy();
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
/** Runs a command that has a single reply. */
|
|
537
|
+
#command(command) {
|
|
538
|
+
return new Promise((resolve, reject) => {
|
|
539
|
+
const socket = this.#acquireSocket();
|
|
540
|
+
const reader = new FrameReader();
|
|
541
|
+
let settled = false;
|
|
542
|
+
const send = () => {
|
|
543
|
+
socket.write(encodeStringFrame(FRAME_Q, JSON.stringify(command)));
|
|
544
|
+
};
|
|
545
|
+
const detach = () => {
|
|
546
|
+
socket.off("connect", send);
|
|
547
|
+
socket.off("data", onData);
|
|
548
|
+
socket.off("error", onError);
|
|
549
|
+
socket.off("close", onClose);
|
|
550
|
+
};
|
|
551
|
+
const settle = (reusable, act) => {
|
|
552
|
+
if (settled)
|
|
553
|
+
return;
|
|
554
|
+
settled = true;
|
|
555
|
+
detach();
|
|
556
|
+
if (reusable)
|
|
557
|
+
this.#releaseSocket(socket);
|
|
558
|
+
else
|
|
559
|
+
socket.destroy();
|
|
560
|
+
act();
|
|
561
|
+
};
|
|
562
|
+
const onData = (chunk) => {
|
|
563
|
+
const frames = reader.push(chunk);
|
|
564
|
+
for (let i = 0; i < frames.length; i++) {
|
|
565
|
+
const frame = frames[i];
|
|
566
|
+
const payload = JSON.parse(frame.payload.toString("utf8"));
|
|
567
|
+
if (frame.type === "R") {
|
|
568
|
+
const reusable = i === frames.length - 1 && !reader.hasPending();
|
|
569
|
+
settle(reusable, () => resolve(payload));
|
|
570
|
+
}
|
|
571
|
+
else {
|
|
572
|
+
settle(false, () => reject(new RequestError(payload)));
|
|
573
|
+
}
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
const onError = (error) => settle(false, () => reject(error));
|
|
578
|
+
const onClose = () => settle(false, () => reject(new RequestError({ code: DAEMON_GONE, message: "the daemon closed the connection" })));
|
|
579
|
+
socket.on("data", onData);
|
|
580
|
+
socket.once("error", onError);
|
|
581
|
+
socket.once("close", onClose);
|
|
582
|
+
if (socket.connecting)
|
|
583
|
+
socket.once("connect", send);
|
|
584
|
+
else
|
|
585
|
+
send();
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
/** @internal */
|
|
589
|
+
request(session, url, options) {
|
|
590
|
+
const { signal } = options;
|
|
591
|
+
const headers = options.headers === undefined
|
|
592
|
+
? EMPTY_HEADERS
|
|
593
|
+
: Array.isArray(options.headers)
|
|
594
|
+
? options.headers
|
|
595
|
+
: Object.entries(options.headers);
|
|
596
|
+
const body = options.body === undefined
|
|
597
|
+
? undefined
|
|
598
|
+
: typeof options.body === "string"
|
|
599
|
+
? Buffer.from(options.body, "utf8")
|
|
600
|
+
: options.body;
|
|
601
|
+
const command = {
|
|
602
|
+
op: "request",
|
|
603
|
+
session,
|
|
604
|
+
url,
|
|
605
|
+
method: options.method ?? (body ? "POST" : "GET"),
|
|
606
|
+
headers,
|
|
607
|
+
priority: options.priority,
|
|
608
|
+
timeoutMs: options.timeoutMs,
|
|
609
|
+
followRedirects: options.followRedirects,
|
|
610
|
+
bodyWindow: options.bodyWindow,
|
|
611
|
+
body: body !== undefined && body.byteLength > 0,
|
|
612
|
+
};
|
|
613
|
+
// With a body window the stream holds nothing: a chunk goes to the caller when the caller reads,
|
|
614
|
+
// and only then does the daemon learn that it may read more.
|
|
615
|
+
const windowed = (options.bodyWindow ?? 0) > 0;
|
|
616
|
+
return new Promise((resolveHead, rejectHead) => {
|
|
617
|
+
if (signal?.aborted) {
|
|
618
|
+
rejectHead(signal.reason);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
const socket = this.#acquireSocket();
|
|
622
|
+
const reader = new FrameReader();
|
|
623
|
+
let stream;
|
|
624
|
+
let headSeen = false;
|
|
625
|
+
let done = false;
|
|
626
|
+
let held = [];
|
|
627
|
+
let heldHead = 0;
|
|
628
|
+
let wanted = false;
|
|
629
|
+
let ended = false;
|
|
630
|
+
const finished = Promise.withResolvers();
|
|
631
|
+
// A caller that reads only the body learns of a failure from the stream.
|
|
632
|
+
finished.promise.catch(() => { });
|
|
633
|
+
const send = () => {
|
|
634
|
+
const qFrame = encodeStringFrame(FRAME_Q, JSON.stringify(command));
|
|
635
|
+
if (command.body && body) {
|
|
636
|
+
socket.cork();
|
|
637
|
+
socket.write(qFrame);
|
|
638
|
+
socket.write(encodeFrame(FRAME_B, body));
|
|
639
|
+
socket.write(END_BODY_FRAME);
|
|
640
|
+
socket.uncork();
|
|
641
|
+
}
|
|
642
|
+
else {
|
|
643
|
+
socket.write(qFrame);
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
const detach = () => {
|
|
647
|
+
socket.off("connect", send);
|
|
648
|
+
socket.off("data", onData);
|
|
649
|
+
socket.off("error", fail);
|
|
650
|
+
socket.off("close", onClose);
|
|
651
|
+
};
|
|
652
|
+
const fail = (error) => {
|
|
653
|
+
if (done)
|
|
654
|
+
return;
|
|
655
|
+
done = true;
|
|
656
|
+
signal?.removeEventListener("abort", onAbort);
|
|
657
|
+
detach();
|
|
658
|
+
socket.destroy();
|
|
659
|
+
if (headSeen) {
|
|
660
|
+
finished.reject(error);
|
|
661
|
+
try {
|
|
662
|
+
stream?.error(error);
|
|
663
|
+
}
|
|
664
|
+
catch { }
|
|
665
|
+
}
|
|
666
|
+
else {
|
|
667
|
+
rejectHead(error);
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
const onAbort = () => fail(signal?.reason);
|
|
671
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
672
|
+
const deliver = () => {
|
|
673
|
+
if (wanted && heldHead < held.length) {
|
|
674
|
+
wanted = false;
|
|
675
|
+
const chunk = held[heldHead];
|
|
676
|
+
held[heldHead] = undefined;
|
|
677
|
+
heldHead++;
|
|
678
|
+
if (heldHead === held.length) {
|
|
679
|
+
held.length = 0;
|
|
680
|
+
heldHead = 0;
|
|
681
|
+
}
|
|
682
|
+
else if (heldHead >= 64 && heldHead * 2 >= held.length) {
|
|
683
|
+
held = held.slice(heldHead);
|
|
684
|
+
heldHead = 0;
|
|
685
|
+
}
|
|
686
|
+
stream?.enqueue(chunk);
|
|
687
|
+
if (!ended)
|
|
688
|
+
socket.write(encodeStringFrame(FRAME_A, String(chunk.byteLength)));
|
|
689
|
+
}
|
|
690
|
+
if (ended && heldHead === held.length)
|
|
691
|
+
stream?.close();
|
|
692
|
+
};
|
|
693
|
+
const body_stream = new ReadableStream({
|
|
694
|
+
start(controller) {
|
|
695
|
+
stream = controller;
|
|
696
|
+
},
|
|
697
|
+
pull() {
|
|
698
|
+
if (windowed) {
|
|
699
|
+
wanted = true;
|
|
700
|
+
deliver();
|
|
701
|
+
}
|
|
702
|
+
else if (!done) {
|
|
703
|
+
socket.resume();
|
|
704
|
+
}
|
|
705
|
+
},
|
|
706
|
+
cancel() {
|
|
707
|
+
if (done) {
|
|
708
|
+
held.length = 0;
|
|
709
|
+
heldHead = 0;
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
// Closing the connection cancels the request in the daemon.
|
|
713
|
+
done = true;
|
|
714
|
+
signal?.removeEventListener("abort", onAbort);
|
|
715
|
+
detach();
|
|
716
|
+
socket.destroy();
|
|
717
|
+
finished.reject(new RequestError({ code: "TFR_BODY_CANCELLED", headSent: true }));
|
|
718
|
+
},
|
|
719
|
+
}, new ByteLengthQueuingStrategy({ highWaterMark: windowed ? 0 : 1024 * 1024 }));
|
|
720
|
+
const onData = (chunk) => {
|
|
721
|
+
const frames = reader.push(chunk);
|
|
722
|
+
for (let i = 0; i < frames.length; i++) {
|
|
723
|
+
if (done)
|
|
724
|
+
return;
|
|
725
|
+
const frame = frames[i];
|
|
726
|
+
switch (frame.type) {
|
|
727
|
+
case "H":
|
|
728
|
+
headSeen = true;
|
|
729
|
+
resolveHead(new Response(JSON.parse(frame.payload.toString("utf8")), body_stream, finished.promise));
|
|
730
|
+
break;
|
|
731
|
+
case "D": {
|
|
732
|
+
const data = new Uint8Array(frame.payload.buffer, frame.payload.byteOffset, frame.payload.byteLength);
|
|
733
|
+
if (windowed) {
|
|
734
|
+
held.push(data);
|
|
735
|
+
deliver();
|
|
736
|
+
}
|
|
737
|
+
else {
|
|
738
|
+
stream?.enqueue(data);
|
|
739
|
+
}
|
|
740
|
+
break;
|
|
741
|
+
}
|
|
742
|
+
case "T": {
|
|
743
|
+
done = true;
|
|
744
|
+
signal?.removeEventListener("abort", onAbort);
|
|
745
|
+
detach();
|
|
746
|
+
const reusable = i === frames.length - 1 && !reader.hasPending();
|
|
747
|
+
if (reusable)
|
|
748
|
+
this.#releaseSocket(socket);
|
|
749
|
+
else
|
|
750
|
+
socket.destroy();
|
|
751
|
+
if (windowed) {
|
|
752
|
+
ended = true;
|
|
753
|
+
deliver();
|
|
754
|
+
}
|
|
755
|
+
else {
|
|
756
|
+
stream?.close();
|
|
757
|
+
}
|
|
758
|
+
finished.resolve(JSON.parse(frame.payload.toString("utf8")));
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
default:
|
|
762
|
+
fail(new RequestError(JSON.parse(frame.payload.toString("utf8"))));
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
if (!done && !windowed && stream && (stream.desiredSize ?? 1) <= 0)
|
|
767
|
+
socket.pause();
|
|
768
|
+
};
|
|
769
|
+
const onClose = () => fail(new RequestError({ code: DAEMON_GONE, message: "the daemon closed the connection", headSent: headSeen }));
|
|
770
|
+
socket.on("data", onData);
|
|
771
|
+
socket.once("error", fail);
|
|
772
|
+
socket.once("close", onClose);
|
|
773
|
+
if (socket.connecting)
|
|
774
|
+
socket.once("connect", send);
|
|
775
|
+
else
|
|
776
|
+
send();
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
/** @internal */
|
|
780
|
+
webSocket(session, url, options) {
|
|
781
|
+
const { signal } = options;
|
|
782
|
+
const headers = options.headers === undefined
|
|
783
|
+
? EMPTY_HEADERS
|
|
784
|
+
: Array.isArray(options.headers)
|
|
785
|
+
? options.headers
|
|
786
|
+
: Object.entries(options.headers);
|
|
787
|
+
const command = {
|
|
788
|
+
op: "ws.open",
|
|
789
|
+
session,
|
|
790
|
+
url,
|
|
791
|
+
headers,
|
|
792
|
+
protocols: options.protocols ?? [],
|
|
793
|
+
timeoutMs: options.timeoutMs,
|
|
794
|
+
};
|
|
795
|
+
return new Promise((resolveOpen, rejectOpen) => {
|
|
796
|
+
if (signal?.aborted) {
|
|
797
|
+
rejectOpen(signal.reason);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
const socket = this.#acquireSocket();
|
|
801
|
+
const reader = new FrameReader();
|
|
802
|
+
let connection;
|
|
803
|
+
let done = false;
|
|
804
|
+
const closed = Promise.withResolvers();
|
|
805
|
+
closed.promise.catch(() => { });
|
|
806
|
+
const send = () => {
|
|
807
|
+
socket.write(encodeStringFrame(FRAME_Q, JSON.stringify(command)));
|
|
808
|
+
};
|
|
809
|
+
const detach = () => {
|
|
810
|
+
socket.off("connect", send);
|
|
811
|
+
socket.off("data", onData);
|
|
812
|
+
socket.off("error", fail);
|
|
813
|
+
socket.off("close", onClose);
|
|
814
|
+
};
|
|
815
|
+
const fail = (error) => {
|
|
816
|
+
if (done)
|
|
817
|
+
return;
|
|
818
|
+
done = true;
|
|
819
|
+
signal?.removeEventListener("abort", onAbort);
|
|
820
|
+
detach();
|
|
821
|
+
socket.destroy();
|
|
822
|
+
if (connection) {
|
|
823
|
+
connection.end(error);
|
|
824
|
+
closed.reject(error);
|
|
825
|
+
}
|
|
826
|
+
else {
|
|
827
|
+
rejectOpen(error);
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
const onAbort = () => fail(signal?.reason);
|
|
831
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
832
|
+
const onData = (chunk) => {
|
|
833
|
+
for (const frame of reader.push(chunk)) {
|
|
834
|
+
if (done)
|
|
835
|
+
return;
|
|
836
|
+
switch (frame.type) {
|
|
837
|
+
case "H":
|
|
838
|
+
connection = new WebSocketConnection(JSON.parse(frame.payload.toString("utf8")), socket, closed.promise);
|
|
839
|
+
resolveOpen(connection);
|
|
840
|
+
break;
|
|
841
|
+
case "M":
|
|
842
|
+
connection?.push(frame.payload[0] === 1
|
|
843
|
+
? frame.payload.toString("utf8", 1)
|
|
844
|
+
: new Uint8Array(frame.payload.buffer, frame.payload.byteOffset + 1, Math.max(0, frame.payload.byteLength - 1)));
|
|
845
|
+
break;
|
|
846
|
+
case "T": {
|
|
847
|
+
done = true;
|
|
848
|
+
signal?.removeEventListener("abort", onAbort);
|
|
849
|
+
detach();
|
|
850
|
+
socket.destroy();
|
|
851
|
+
const trailer = JSON.parse(frame.payload.toString("utf8"));
|
|
852
|
+
connection?.end();
|
|
853
|
+
closed.resolve({ ...trailer.closed, session: trailer.session });
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
default:
|
|
857
|
+
fail(new RequestError(JSON.parse(frame.payload.toString("utf8"))));
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
const onClose = () => fail(new RequestError({
|
|
863
|
+
code: DAEMON_GONE,
|
|
864
|
+
message: "the daemon closed the connection",
|
|
865
|
+
headSent: connection !== undefined,
|
|
866
|
+
}));
|
|
867
|
+
socket.on("data", onData);
|
|
868
|
+
socket.once("error", fail);
|
|
869
|
+
socket.once("close", onClose);
|
|
870
|
+
if (socket.connecting)
|
|
871
|
+
socket.once("connect", send);
|
|
872
|
+
else
|
|
873
|
+
send();
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
export class Session {
|
|
878
|
+
id;
|
|
879
|
+
#daemon;
|
|
880
|
+
/** @internal */
|
|
881
|
+
constructor(daemon, id) {
|
|
882
|
+
this.#daemon = daemon;
|
|
883
|
+
this.id = id;
|
|
884
|
+
}
|
|
885
|
+
/** Resolves with the response head; the body streams. Rejects with RequestError when Chromium fails. */
|
|
886
|
+
fetch(url, options = {}) {
|
|
887
|
+
return this.#daemon.request(this.id, String(url), options);
|
|
888
|
+
}
|
|
889
|
+
/** Opens a WebSocket with the session's connections, proxy and cookies. Rejects with RequestError when the handshake fails. */
|
|
890
|
+
webSocket(url, options = {}) {
|
|
891
|
+
return this.#daemon.webSocket(this.id, String(url), options);
|
|
892
|
+
}
|
|
893
|
+
/** Drops the session's connections and cookies, and returns its final wire totals. */
|
|
894
|
+
close() {
|
|
895
|
+
return this.#daemon.closeSession(this.id);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
//# sourceMappingURL=index.js.map
|