wreq-js 2.2.1 → 2.3.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/wreq-js.js CHANGED
@@ -1,2693 +1,2186 @@
1
- // src/wreq-js.ts
2
- import { randomUUID } from "crypto";
3
- import { STATUS_CODES } from "http";
4
- import { createRequire } from "module";
5
- import { Readable } from "stream";
6
- import { ReadableStream } from "stream/web";
7
-
8
- // src/types.ts
1
+ import { createRequire } from "node:module";
2
+ import { randomUUID } from "node:crypto";
3
+ import { STATUS_CODES } from "node:http";
4
+ import { Readable } from "node:stream";
5
+ import { ReadableStream } from "node:stream/web";
6
+ //#region src/native-require.ts
7
+ const nativeRequire = createRequire(import.meta.url);
8
+ //#endregion
9
+ //#region src/types.ts
10
+ /**
11
+ * Error thrown when a request fails. This can occur due to network errors,
12
+ * timeouts, invalid URLs, or other request-related issues.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * try {
17
+ * const response = await fetch('https://api.example.com');
18
+ * } catch (error) {
19
+ * if (error instanceof RequestError) {
20
+ * console.error('Request failed:', error.message);
21
+ * }
22
+ * }
23
+ * ```
24
+ */
9
25
  var RequestError = class extends TypeError {
10
- constructor(message) {
11
- super(message);
12
- this.name = "RequestError";
13
- }
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = "RequestError";
29
+ }
14
30
  };
15
-
16
- // src/wreq-js.ts
17
- var nativeBinding;
18
- var cachedProfiles;
19
- var cachedProfileSet;
20
- var cachedOperatingSystems;
21
- var cachedOperatingSystemSet;
31
+ //#endregion
32
+ //#region src/wreq-js.ts
33
+ let nativeBinding;
34
+ let cachedProfiles;
35
+ let cachedProfileSet;
36
+ let cachedOperatingSystems;
37
+ let cachedOperatingSystemSet;
22
38
  function detectLibc() {
23
- if (process.platform !== "linux") {
24
- return void 0;
25
- }
26
- const envLibc = process.env.LIBC ?? process.env.npm_config_libc;
27
- if (envLibc) {
28
- return envLibc.toLowerCase().includes("musl") ? "musl" : "gnu";
29
- }
30
- try {
31
- const report = process.report?.getReport?.();
32
- const glibcVersion = report?.header?.glibcVersionRuntime;
33
- if (glibcVersion) {
34
- return "gnu";
35
- }
36
- return "musl";
37
- } catch {
38
- return "gnu";
39
- }
40
- }
41
- var require2 = typeof import.meta !== "undefined" && import.meta.url ? createRequire(import.meta.url) : createRequire(__filename);
42
- function requirePlatformBinary(platformArch) {
43
- switch (platformArch) {
44
- case "darwin-x64":
45
- return require2("../rust/wreq-js.darwin-x64.node");
46
- case "darwin-arm64":
47
- return require2("../rust/wreq-js.darwin-arm64.node");
48
- case "linux-x64-gnu":
49
- return require2("../rust/wreq-js.linux-x64-gnu.node");
50
- case "linux-x64-musl":
51
- return require2("../rust/wreq-js.linux-x64-musl.node");
52
- case "linux-arm64-gnu":
53
- return require2("../rust/wreq-js.linux-arm64-gnu.node");
54
- case "win32-x64-msvc":
55
- return require2("../rust/wreq-js.win32-x64-msvc.node");
56
- default:
57
- return void 0;
58
- }
39
+ if (process.platform !== "linux") return;
40
+ const envLibc = process.env.LIBC ?? process.env.npm_config_libc;
41
+ if (envLibc) return envLibc.toLowerCase().includes("musl") ? "musl" : "gnu";
42
+ try {
43
+ if ((process.report?.getReport?.())?.header?.glibcVersionRuntime) return "gnu";
44
+ return "musl";
45
+ } catch {
46
+ return "gnu";
47
+ }
59
48
  }
60
49
  function loadNativeBinding() {
61
- const platform = process.platform;
62
- const arch = process.arch;
63
- const libc = detectLibc();
64
- const platformArchMap = {
65
- darwin: { x64: "darwin-x64", arm64: "darwin-arm64" },
66
- linux: {
67
- x64: { gnu: "linux-x64-gnu", musl: "linux-x64-musl" },
68
- arm64: "linux-arm64-gnu"
69
- },
70
- win32: { x64: "win32-x64-msvc" }
71
- };
72
- const platformArchMapEntry = platformArchMap[platform]?.[arch];
73
- const platformArch = typeof platformArchMapEntry === "string" ? platformArchMapEntry : platformArchMapEntry?.[libc ?? "gnu"];
74
- if (!platformArch) {
75
- throw new Error(
76
- `Unsupported platform: ${platform}-${arch}${libc ? `-${libc}` : ""}. Supported platforms: darwin-x64, darwin-arm64, linux-x64-gnu, linux-x64-musl, linux-arm64-gnu, win32-x64-msvc`
77
- );
78
- }
79
- const binaryName = `wreq-js.${platformArch}.node`;
80
- try {
81
- const platformBinding = requirePlatformBinary(platformArch);
82
- if (platformBinding) {
83
- return platformBinding;
84
- }
85
- } catch {
86
- }
87
- try {
88
- return require2("../rust/wreq-js.node");
89
- } catch {
90
- throw new Error(
91
- `Failed to load native module for ${platform}-${arch}. Tried: ../rust/${binaryName} and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.`
92
- );
93
- }
50
+ const platform = process.platform;
51
+ const arch = process.arch;
52
+ const libc = detectLibc();
53
+ if (platform === "darwin" && arch === "x64") try {
54
+ return nativeRequire("../rust/wreq-js.darwin-x64.node");
55
+ } catch {
56
+ try {
57
+ return nativeRequire("../rust/wreq-js.node");
58
+ } catch {
59
+ throw new Error("Failed to load native module for darwin-x64. Tried: ../rust/wreq-js.darwin-x64.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
60
+ }
61
+ }
62
+ if (platform === "darwin" && arch === "arm64") try {
63
+ return nativeRequire("../rust/wreq-js.darwin-arm64.node");
64
+ } catch {
65
+ try {
66
+ return nativeRequire("../rust/wreq-js.node");
67
+ } catch {
68
+ throw new Error("Failed to load native module for darwin-arm64. Tried: ../rust/wreq-js.darwin-arm64.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
69
+ }
70
+ }
71
+ if (platform === "linux" && arch === "x64") {
72
+ if (libc === "musl") try {
73
+ return nativeRequire("../rust/wreq-js.linux-x64-musl.node");
74
+ } catch {
75
+ try {
76
+ return nativeRequire("../rust/wreq-js.node");
77
+ } catch {
78
+ throw new Error("Failed to load native module for linux-x64-musl. Tried: ../rust/wreq-js.linux-x64-musl.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
79
+ }
80
+ }
81
+ try {
82
+ return nativeRequire("../rust/wreq-js.linux-x64-gnu.node");
83
+ } catch {
84
+ try {
85
+ return nativeRequire("../rust/wreq-js.node");
86
+ } catch {
87
+ throw new Error("Failed to load native module for linux-x64-gnu. Tried: ../rust/wreq-js.linux-x64-gnu.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
88
+ }
89
+ }
90
+ }
91
+ if (platform === "linux" && arch === "arm64") try {
92
+ return nativeRequire("../rust/wreq-js.linux-arm64-gnu.node");
93
+ } catch {
94
+ try {
95
+ return nativeRequire("../rust/wreq-js.node");
96
+ } catch {
97
+ throw new Error("Failed to load native module for linux-arm64-gnu. Tried: ../rust/wreq-js.linux-arm64-gnu.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
98
+ }
99
+ }
100
+ if (platform === "win32" && arch === "x64") try {
101
+ return nativeRequire("../rust/wreq-js.win32-x64-msvc.node");
102
+ } catch {
103
+ try {
104
+ return nativeRequire("../rust/wreq-js.node");
105
+ } catch {
106
+ throw new Error("Failed to load native module for win32-x64-msvc. Tried: ../rust/wreq-js.win32-x64-msvc.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
107
+ }
108
+ }
109
+ throw new Error(`Unsupported platform: ${platform}-${arch}${libc ? `-${libc}` : ""}. Supported platforms: darwin-x64, darwin-arm64, linux-x64-gnu, linux-x64-musl, linux-arm64-gnu, win32-x64-msvc`);
94
110
  }
95
111
  nativeBinding = loadNativeBinding();
96
- var websocketFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((connection) => {
97
- void nativeBinding.websocketClose(connection).catch(() => void 0);
112
+ const websocketFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((connection) => {
113
+ nativeBinding.websocketClose(connection).catch(() => void 0);
98
114
  }) : void 0;
99
- var bodyHandleFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((handle) => {
100
- if (handle.released) {
101
- return;
102
- }
103
- handle.released = true;
104
- try {
105
- nativeBinding.cancelBody(handle.id);
106
- } catch {
107
- }
115
+ const bodyHandleFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((handle) => {
116
+ if (handle.released) return;
117
+ handle.released = true;
118
+ try {
119
+ nativeBinding.cancelBody(handle.id);
120
+ } catch {}
108
121
  }) : void 0;
109
- var DEFAULT_BROWSER = "chrome_142";
110
- var DEFAULT_OS = "macos";
111
- var DEFAULT_REQUEST_TIMEOUT_MS = 3e5;
112
- var SUPPORTED_OSES = ["windows", "macos", "linux", "android", "ios"];
113
- var UTF8_DECODER = new TextDecoder("utf-8");
114
- var ephemeralIdCounter = 0;
122
+ const DEFAULT_BROWSER = "chrome_142";
123
+ const DEFAULT_OS = "macos";
124
+ const DEFAULT_REQUEST_TIMEOUT_MS = 3e5;
125
+ const DEFAULT_TRUST_STORE = "combined";
126
+ const SUPPORTED_OSES = [
127
+ "windows",
128
+ "macos",
129
+ "linux",
130
+ "android",
131
+ "ios"
132
+ ];
133
+ const UTF8_DECODER = new TextDecoder("utf-8");
134
+ let ephemeralIdCounter = 0;
115
135
  function generateEphemeralSessionId() {
116
- return `_e${++ephemeralIdCounter}`;
136
+ return `_e${++ephemeralIdCounter}`;
117
137
  }
118
138
  function generateSessionId() {
119
- return randomUUID();
139
+ return randomUUID();
120
140
  }
121
141
  function normalizeSessionOptions(options) {
122
- const sessionId = options?.sessionId ?? generateSessionId();
123
- const defaults = {
124
- transportMode: resolveEmulationMode(options?.browser, options?.os, options?.emulation)
125
- };
126
- if (options?.proxy !== void 0) {
127
- defaults.proxy = options.proxy;
128
- }
129
- if (options?.timeout !== void 0) {
130
- validateTimeout(options.timeout);
131
- defaults.timeout = options.timeout;
132
- }
133
- if (options?.insecure !== void 0) {
134
- defaults.insecure = options.insecure;
135
- }
136
- if (options?.defaultHeaders !== void 0) {
137
- defaults.defaultHeaders = headersToTuples(options.defaultHeaders);
138
- }
139
- return { sessionId, defaults };
142
+ const sessionId = options?.sessionId ?? generateSessionId();
143
+ const defaults = {
144
+ transportMode: resolveEmulationMode(options?.browser, options?.os, options?.emulation),
145
+ trustStore: DEFAULT_TRUST_STORE
146
+ };
147
+ if (options?.proxy !== void 0) defaults.proxy = options.proxy;
148
+ if (options?.timeout !== void 0) {
149
+ validateTimeout(options.timeout);
150
+ defaults.timeout = options.timeout;
151
+ }
152
+ if (options?.insecure !== void 0) defaults.insecure = options.insecure;
153
+ if (options?.trustStore !== void 0) {
154
+ validateTrustStore(options.trustStore);
155
+ defaults.trustStore = options.trustStore;
156
+ }
157
+ if (options?.defaultHeaders !== void 0) defaults.defaultHeaders = headersToTuples(options.defaultHeaders);
158
+ if (options?.captureDiagnostics !== void 0) defaults.captureDiagnostics = options.captureDiagnostics;
159
+ return {
160
+ sessionId,
161
+ defaults
162
+ };
140
163
  }
141
164
  function isIterable(value) {
142
- return Boolean(value) && typeof value[Symbol.iterator] === "function";
165
+ return Boolean(value) && typeof value[Symbol.iterator] === "function";
143
166
  }
144
167
  function isPlainObject(value) {
145
- if (typeof value !== "object" || value === null) {
146
- return false;
147
- }
148
- const proto = Object.getPrototypeOf(value);
149
- return proto === Object.prototype || proto === null;
168
+ if (typeof value !== "object" || value === null) return false;
169
+ const proto = Object.getPrototypeOf(value);
170
+ return proto === Object.prototype || proto === null;
150
171
  }
151
172
  function coerceHeaderValue(value) {
152
- return String(value);
153
- }
154
- var Headers = class _Headers {
155
- store = /* @__PURE__ */ new Map();
156
- constructor(init) {
157
- if (init) {
158
- this.applyInit(init);
159
- }
160
- }
161
- applyInit(init) {
162
- if (init instanceof _Headers) {
163
- for (const [name, value] of init) {
164
- this.append(name, value);
165
- }
166
- return;
167
- }
168
- if (Array.isArray(init) || isIterable(init)) {
169
- for (const tuple of init) {
170
- if (!tuple) {
171
- continue;
172
- }
173
- const [name, value] = tuple;
174
- this.append(name, value);
175
- }
176
- return;
177
- }
178
- if (isPlainObject(init)) {
179
- for (const [name, value] of Object.entries(init)) {
180
- if (value === void 0 || value === null) {
181
- continue;
182
- }
183
- this.set(name, coerceHeaderValue(value));
184
- }
185
- }
186
- }
187
- normalizeName(name) {
188
- if (typeof name !== "string") {
189
- throw new TypeError("Header name must be a string");
190
- }
191
- const trimmed = name.trim();
192
- if (!trimmed) {
193
- throw new TypeError("Header name must not be empty");
194
- }
195
- return { key: trimmed.toLowerCase(), display: trimmed };
196
- }
197
- assertValue(value) {
198
- if (value === void 0 || value === null) {
199
- throw new TypeError("Header value must not be null or undefined");
200
- }
201
- return coerceHeaderValue(value);
202
- }
203
- append(name, value) {
204
- const normalized = this.normalizeName(name);
205
- const existing = this.store.get(normalized.key);
206
- const coercedValue = this.assertValue(value);
207
- if (existing) {
208
- existing.values.push(coercedValue);
209
- return;
210
- }
211
- this.store.set(normalized.key, {
212
- name: normalized.display,
213
- values: [coercedValue]
214
- });
215
- }
216
- set(name, value) {
217
- const normalized = this.normalizeName(name);
218
- const coercedValue = this.assertValue(value);
219
- this.store.set(normalized.key, {
220
- name: normalized.display,
221
- values: [coercedValue]
222
- });
223
- }
224
- get(name) {
225
- const normalized = this.normalizeName(name);
226
- const entry = this.store.get(normalized.key);
227
- return entry ? entry.values.join(", ") : null;
228
- }
229
- has(name) {
230
- const normalized = this.normalizeName(name);
231
- return this.store.has(normalized.key);
232
- }
233
- delete(name) {
234
- const normalized = this.normalizeName(name);
235
- this.store.delete(normalized.key);
236
- }
237
- entries() {
238
- return this[Symbol.iterator]();
239
- }
240
- *keys() {
241
- for (const [name] of this) {
242
- yield name;
243
- }
244
- }
245
- *values() {
246
- for (const [, value] of this) {
247
- yield value;
248
- }
249
- }
250
- forEach(callback, thisArg) {
251
- for (const [name, value] of this) {
252
- callback.call(thisArg, value, name, this);
253
- }
254
- }
255
- [Symbol.iterator]() {
256
- const generator = function* (store) {
257
- for (const entry of store.values()) {
258
- yield [entry.name, entry.values.join(", ")];
259
- }
260
- };
261
- return generator(this.store);
262
- }
263
- toObject() {
264
- const result = {};
265
- for (const [name, value] of this) {
266
- result[name] = value;
267
- }
268
- return result;
269
- }
270
- toTuples() {
271
- const result = [];
272
- for (const [name, value] of this) {
273
- result.push([name, value]);
274
- }
275
- return result;
276
- }
173
+ return String(value);
174
+ }
175
+ var Headers = class Headers {
176
+ store = /* @__PURE__ */ new Map();
177
+ constructor(init) {
178
+ if (init) this.applyInit(init);
179
+ }
180
+ applyInit(init) {
181
+ if (init instanceof Headers) {
182
+ for (const [name, value] of init) this.append(name, value);
183
+ return;
184
+ }
185
+ if (Array.isArray(init) || isIterable(init)) {
186
+ for (const tuple of init) {
187
+ if (!tuple) continue;
188
+ const [name, value] = tuple;
189
+ this.append(name, value);
190
+ }
191
+ return;
192
+ }
193
+ if (isPlainObject(init)) for (const [name, value] of Object.entries(init)) {
194
+ if (value === void 0 || value === null) continue;
195
+ this.set(name, coerceHeaderValue(value));
196
+ }
197
+ }
198
+ normalizeName(name) {
199
+ if (typeof name !== "string") throw new TypeError("Header name must be a string");
200
+ const trimmed = name.trim();
201
+ if (!trimmed) throw new TypeError("Header name must not be empty");
202
+ return {
203
+ key: trimmed.toLowerCase(),
204
+ display: trimmed
205
+ };
206
+ }
207
+ assertValue(value) {
208
+ if (value === void 0 || value === null) throw new TypeError("Header value must not be null or undefined");
209
+ return coerceHeaderValue(value);
210
+ }
211
+ append(name, value) {
212
+ const normalized = this.normalizeName(name);
213
+ const existing = this.store.get(normalized.key);
214
+ const coercedValue = this.assertValue(value);
215
+ if (existing) {
216
+ existing.values.push(coercedValue);
217
+ return;
218
+ }
219
+ this.store.set(normalized.key, {
220
+ name: normalized.display,
221
+ values: [coercedValue]
222
+ });
223
+ }
224
+ set(name, value) {
225
+ const normalized = this.normalizeName(name);
226
+ const coercedValue = this.assertValue(value);
227
+ this.store.set(normalized.key, {
228
+ name: normalized.display,
229
+ values: [coercedValue]
230
+ });
231
+ }
232
+ get(name) {
233
+ const normalized = this.normalizeName(name);
234
+ const entry = this.store.get(normalized.key);
235
+ return entry ? entry.values.join(", ") : null;
236
+ }
237
+ has(name) {
238
+ const normalized = this.normalizeName(name);
239
+ return this.store.has(normalized.key);
240
+ }
241
+ delete(name) {
242
+ const normalized = this.normalizeName(name);
243
+ this.store.delete(normalized.key);
244
+ }
245
+ entries() {
246
+ return this[Symbol.iterator]();
247
+ }
248
+ *keys() {
249
+ for (const [name] of this) yield name;
250
+ }
251
+ *values() {
252
+ for (const [, value] of this) yield value;
253
+ }
254
+ forEach(callback, thisArg) {
255
+ for (const [name, value] of this) callback.call(thisArg, value, name, this);
256
+ }
257
+ [Symbol.iterator]() {
258
+ const generator = function* (store) {
259
+ for (const entry of store.values()) yield [entry.name, entry.values.join(", ")];
260
+ };
261
+ return generator(this.store);
262
+ }
263
+ toObject() {
264
+ const result = {};
265
+ for (const [name, value] of this) result[name] = value;
266
+ return result;
267
+ }
268
+ toTuples() {
269
+ const result = [];
270
+ for (const [name, value] of this) result.push([name, value]);
271
+ return result;
272
+ }
277
273
  };
278
274
  function headersToTuples(init) {
279
- return new Headers(init).toTuples();
275
+ return new Headers(init).toTuples();
280
276
  }
281
277
  function hasHeaderName(tuples, name) {
282
- if (!tuples) {
283
- return false;
284
- }
285
- const target = name.toLowerCase();
286
- for (const [headerName] of tuples) {
287
- if (headerName.toLowerCase() === target) {
288
- return true;
289
- }
290
- }
291
- return false;
278
+ if (!tuples) return false;
279
+ const target = name.toLowerCase();
280
+ for (const [headerName] of tuples) if (headerName.toLowerCase() === target) return true;
281
+ return false;
292
282
  }
293
283
  function hasWebSocketProtocolHeader(headers) {
294
- const protocolHeaderName = "Sec-WebSocket-Protocol";
295
- if (!headers) {
296
- return false;
297
- }
298
- return hasHeaderName(headersToTuples(headers), protocolHeaderName);
284
+ const protocolHeaderName = "Sec-WebSocket-Protocol";
285
+ if (!headers) return false;
286
+ return hasHeaderName(headersToTuples(headers), protocolHeaderName);
299
287
  }
300
288
  function assertNoManualWebSocketProtocolHeader(headers) {
301
- if (hasWebSocketProtocolHeader(headers)) {
302
- throw new RequestError("Do not set `Sec-WebSocket-Protocol` header manually; use the `protocols` option instead.");
303
- }
289
+ if (hasWebSocketProtocolHeader(headers)) throw new RequestError("Do not set `Sec-WebSocket-Protocol` header manually; use the `protocols` option instead.");
304
290
  }
305
291
  function normalizeWebSocketProtocolList(protocols) {
306
- if (protocols === void 0) {
307
- return void 0;
308
- }
309
- return typeof protocols === "string" ? [protocols] : [...protocols];
292
+ if (protocols === void 0) return;
293
+ return typeof protocols === "string" ? [protocols] : [...protocols];
310
294
  }
311
295
  function mergeHeaderTuples(defaults, overrides) {
312
- if (!defaults) {
313
- return overrides === void 0 ? void 0 : headersToTuples(overrides);
314
- }
315
- if (overrides === void 0) {
316
- return defaults;
317
- }
318
- const overrideTuples = headersToTuples(overrides);
319
- if (overrideTuples.length === 0) {
320
- return defaults;
321
- }
322
- const overrideKeys = /* @__PURE__ */ new Set();
323
- for (const tuple of overrideTuples) {
324
- overrideKeys.add(tuple[0].toLowerCase());
325
- }
326
- const merged = [];
327
- for (const tuple of defaults) {
328
- if (!overrideKeys.has(tuple[0].toLowerCase())) {
329
- merged.push(tuple);
330
- }
331
- }
332
- for (const tuple of overrideTuples) {
333
- merged.push(tuple);
334
- }
335
- return merged;
296
+ if (!defaults) return overrides === void 0 ? void 0 : headersToTuples(overrides);
297
+ if (overrides === void 0) return defaults;
298
+ const overrideTuples = headersToTuples(overrides);
299
+ if (overrideTuples.length === 0) return defaults;
300
+ const overrideKeys = /* @__PURE__ */ new Set();
301
+ for (const tuple of overrideTuples) overrideKeys.add(tuple[0].toLowerCase());
302
+ const merged = [];
303
+ for (const tuple of defaults) if (!overrideKeys.has(tuple[0].toLowerCase())) merged.push(tuple);
304
+ for (const tuple of overrideTuples) merged.push(tuple);
305
+ return merged;
336
306
  }
337
307
  function cloneNativeResponse(payload) {
338
- return {
339
- status: payload.status,
340
- headers: payload.headers.map(([name, value]) => [name, value]),
341
- bodyHandle: payload.bodyHandle,
342
- bodyBytes: payload.bodyBytes,
343
- contentLength: payload.contentLength,
344
- cookies: payload.cookies.map(([name, value]) => [name, value]),
345
- url: payload.url
346
- };
308
+ return {
309
+ status: payload.status,
310
+ headers: payload.headers.map(([name, value]) => [name, value]),
311
+ bodyHandle: payload.bodyHandle,
312
+ bodyBytes: payload.bodyBytes,
313
+ contentLength: payload.contentLength,
314
+ cookies: payload.cookies.map(([name, value]) => [name, value]),
315
+ url: payload.url,
316
+ diagnostics: payload.diagnostics ? { ...payload.diagnostics } : null
317
+ };
347
318
  }
348
319
  function releaseNativeBody(handle) {
349
- if (handle.released) {
350
- return;
351
- }
352
- handle.released = true;
353
- try {
354
- nativeBinding.cancelBody(handle.id);
355
- } catch {
356
- }
357
- bodyHandleFinalizer?.unregister(handle);
320
+ if (handle.released) return;
321
+ handle.released = true;
322
+ try {
323
+ nativeBinding.cancelBody(handle.id);
324
+ } catch {}
325
+ bodyHandleFinalizer?.unregister(handle);
358
326
  }
359
327
  function markNativeBodyReleased(handle) {
360
- if (handle.released) {
361
- return;
362
- }
363
- handle.released = true;
364
- bodyHandleFinalizer?.unregister(handle);
328
+ if (handle.released) return;
329
+ handle.released = true;
330
+ bodyHandleFinalizer?.unregister(handle);
365
331
  }
366
332
  function createNativeBodyStream(handle) {
367
- const stream = new ReadableStream({
368
- async pull(controller) {
369
- try {
370
- const chunk = await nativeBinding.readBodyChunk(handle.id);
371
- if (chunk === null) {
372
- releaseNativeBody(handle);
373
- controller.close();
374
- return;
375
- }
376
- controller.enqueue(chunk);
377
- } catch (error) {
378
- releaseNativeBody(handle);
379
- controller.error(error);
380
- }
381
- },
382
- cancel() {
383
- releaseNativeBody(handle);
384
- }
385
- });
386
- bodyHandleFinalizer?.register(stream, handle, handle);
387
- return stream;
333
+ const stream = new ReadableStream({
334
+ async pull(controller) {
335
+ try {
336
+ const chunk = await nativeBinding.readBodyChunk(handle.id);
337
+ if (chunk === null) {
338
+ releaseNativeBody(handle);
339
+ controller.close();
340
+ return;
341
+ }
342
+ controller.enqueue(chunk);
343
+ } catch (error) {
344
+ releaseNativeBody(handle);
345
+ controller.error(error);
346
+ }
347
+ },
348
+ cancel() {
349
+ releaseNativeBody(handle);
350
+ }
351
+ });
352
+ bodyHandleFinalizer?.register(stream, handle, handle);
353
+ return stream;
388
354
  }
389
355
  function wrapBodyStream(source, onFirstUse) {
390
- let started = false;
391
- let reader = null;
392
- return new ReadableStream({
393
- async pull(controller) {
394
- if (!started) {
395
- started = true;
396
- onFirstUse();
397
- }
398
- if (!reader) {
399
- reader = source.getReader();
400
- }
401
- try {
402
- const { done, value } = await reader.read();
403
- if (done) {
404
- controller.close();
405
- return;
406
- }
407
- controller.enqueue(value);
408
- } catch (error) {
409
- controller.error(error);
410
- }
411
- },
412
- cancel(reason) {
413
- if (!reader) {
414
- return source.cancel(reason);
415
- }
416
- return reader.cancel(reason);
417
- }
418
- });
419
- }
420
- var Response = class _Response {
421
- status;
422
- ok;
423
- contentLength;
424
- url;
425
- type = "basic";
426
- bodyUsed = false;
427
- payload;
428
- requestUrl;
429
- redirectedMemo;
430
- headersInit;
431
- headersInstance;
432
- cookiesInit;
433
- cookiesRecord;
434
- inlineBody;
435
- bodySource;
436
- bodyStream;
437
- // Track if we can use the fast path (native handle not yet wrapped in a stream)
438
- nativeHandleAvailable;
439
- nativeHandle;
440
- constructor(payload, requestUrl, bodySource) {
441
- this.payload = payload;
442
- this.requestUrl = requestUrl;
443
- this.status = this.payload.status;
444
- this.ok = this.status >= 200 && this.status < 300;
445
- this.headersInit = this.payload.headers;
446
- this.headersInstance = null;
447
- this.url = this.payload.url;
448
- this.cookiesInit = this.payload.cookies;
449
- this.cookiesRecord = null;
450
- this.contentLength = this.payload.contentLength ?? null;
451
- this.inlineBody = this.payload.bodyBytes ?? null;
452
- this.nativeHandle = null;
453
- if (typeof bodySource !== "undefined") {
454
- this.bodySource = bodySource;
455
- this.nativeHandleAvailable = false;
456
- } else if (this.inlineBody !== null) {
457
- this.bodySource = null;
458
- this.nativeHandleAvailable = false;
459
- } else if (this.payload.bodyHandle !== null) {
460
- this.bodySource = null;
461
- this.nativeHandleAvailable = true;
462
- this.nativeHandle = { id: this.payload.bodyHandle, released: false };
463
- bodyHandleFinalizer?.register(this, this.nativeHandle, this.nativeHandle);
464
- } else {
465
- this.bodySource = null;
466
- this.nativeHandleAvailable = false;
467
- }
468
- this.bodyStream = void 0;
469
- }
470
- get redirected() {
471
- if (this.redirectedMemo !== void 0) {
472
- return this.redirectedMemo;
473
- }
474
- if (this.url === this.requestUrl) {
475
- this.redirectedMemo = false;
476
- return false;
477
- }
478
- const normalizedRequestUrl = normalizeUrlForComparison(this.requestUrl);
479
- this.redirectedMemo = normalizedRequestUrl ? this.url !== normalizedRequestUrl : true;
480
- return this.redirectedMemo;
481
- }
482
- get statusText() {
483
- return STATUS_CODES[this.status] ?? "";
484
- }
485
- get headers() {
486
- if (!this.headersInstance) {
487
- this.headersInstance = new Headers(this.headersInit);
488
- }
489
- return this.headersInstance;
490
- }
491
- get cookies() {
492
- if (!this.cookiesRecord) {
493
- const record = /* @__PURE__ */ Object.create(null);
494
- for (const [name, value] of this.cookiesInit) {
495
- const existing = record[name];
496
- if (existing === void 0) {
497
- record[name] = value;
498
- } else if (Array.isArray(existing)) {
499
- existing.push(value);
500
- } else {
501
- record[name] = [existing, value];
502
- }
503
- }
504
- this.cookiesRecord = record;
505
- }
506
- return this.cookiesRecord;
507
- }
508
- get body() {
509
- if (this.inlineBody && this.bodySource === null) {
510
- const bytes = this.inlineBody;
511
- this.inlineBody = null;
512
- this.bodySource = new ReadableStream({
513
- start(controller) {
514
- controller.enqueue(bytes);
515
- controller.close();
516
- }
517
- });
518
- }
519
- if (this.inlineBody === null && this.payload.bodyHandle === null && this.bodySource === null) {
520
- return null;
521
- }
522
- if (this.bodySource === null && this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
523
- if (this.nativeHandle) {
524
- bodyHandleFinalizer?.unregister(this.nativeHandle);
525
- }
526
- const handle = this.nativeHandle ?? { id: this.payload.bodyHandle, released: false };
527
- this.nativeHandle = handle;
528
- this.bodySource = createNativeBodyStream(handle);
529
- this.nativeHandleAvailable = false;
530
- }
531
- if (this.bodySource === null) {
532
- return null;
533
- }
534
- if (this.bodyStream === void 0) {
535
- this.bodyStream = wrapBodyStream(this.bodySource, () => {
536
- this.bodyUsed = true;
537
- });
538
- }
539
- return this.bodyStream;
540
- }
541
- async json() {
542
- const text = await this.text();
543
- return JSON.parse(text);
544
- }
545
- async arrayBuffer() {
546
- const bytes = await this.consumeBody();
547
- const { buffer, byteOffset, byteLength } = bytes;
548
- if (buffer instanceof ArrayBuffer) {
549
- if (byteOffset === 0 && byteLength === buffer.byteLength) {
550
- return buffer;
551
- }
552
- return buffer.slice(byteOffset, byteOffset + byteLength);
553
- }
554
- const view = new Uint8Array(byteLength);
555
- view.set(bytes);
556
- return view.buffer;
557
- }
558
- async text() {
559
- const bytes = await this.consumeBody();
560
- return UTF8_DECODER.decode(bytes);
561
- }
562
- async blob() {
563
- const bytes = await this.consumeBody();
564
- const contentType = this.headers.get("content-type") ?? "";
565
- return new Blob([bytes], contentType ? { type: contentType } : void 0);
566
- }
567
- async formData() {
568
- const bytes = await this.consumeBody();
569
- const contentType = this.headers.get("content-type");
570
- const response = new globalThis.Response(
571
- bytes,
572
- contentType ? { headers: { "content-type": contentType } } : void 0
573
- );
574
- return response.formData();
575
- }
576
- readable() {
577
- this.assertBodyAvailable();
578
- this.bodyUsed = true;
579
- const stream = this.body;
580
- if (stream === null) {
581
- return Readable.from([]);
582
- }
583
- return Readable.fromWeb(stream);
584
- }
585
- clone() {
586
- if (this.bodyUsed) {
587
- throw new TypeError("Cannot clone a Response whose body is already used");
588
- }
589
- if (this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
590
- if (this.nativeHandle) {
591
- bodyHandleFinalizer?.unregister(this.nativeHandle);
592
- }
593
- const handle = this.nativeHandle ?? { id: this.payload.bodyHandle, released: false };
594
- this.nativeHandle = handle;
595
- this.bodySource = createNativeBodyStream(handle);
596
- this.nativeHandleAvailable = false;
597
- }
598
- if (this.bodySource === null) {
599
- return new _Response(cloneNativeResponse(this.payload), this.requestUrl, null);
600
- }
601
- const [branchA, branchB] = this.bodySource.tee();
602
- this.bodySource = branchA;
603
- this.bodyStream = void 0;
604
- return new _Response(cloneNativeResponse(this.payload), this.requestUrl, branchB);
605
- }
606
- assertBodyAvailable() {
607
- if (this.bodyUsed) {
608
- throw new TypeError("Response body is already used");
609
- }
610
- }
611
- async consumeBody() {
612
- this.assertBodyAvailable();
613
- this.bodyUsed = true;
614
- if (this.inlineBody) {
615
- const bytes = this.inlineBody;
616
- this.inlineBody = null;
617
- return bytes;
618
- }
619
- if (this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
620
- this.nativeHandleAvailable = false;
621
- try {
622
- return await nativeBinding.readBodyAll(this.payload.bodyHandle);
623
- } catch (error) {
624
- if (String(error).includes("Body handle") && String(error).includes("not found")) {
625
- return Buffer.alloc(0);
626
- }
627
- throw error;
628
- } finally {
629
- if (this.nativeHandle) {
630
- markNativeBodyReleased(this.nativeHandle);
631
- }
632
- }
633
- }
634
- const stream = this.body;
635
- if (!stream) {
636
- return Buffer.alloc(0);
637
- }
638
- const reader = stream.getReader();
639
- const chunks = [];
640
- try {
641
- while (true) {
642
- const { done, value } = await reader.read();
643
- if (done) {
644
- break;
645
- }
646
- if (value && value.byteLength > 0) {
647
- if (Buffer.isBuffer(value)) {
648
- chunks.push(value);
649
- } else {
650
- chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
651
- }
652
- }
653
- }
654
- } finally {
655
- }
656
- return chunks.length === 0 ? Buffer.alloc(0) : Buffer.concat(chunks);
657
- }
356
+ let started = false;
357
+ let reader = null;
358
+ return new ReadableStream({
359
+ async pull(controller) {
360
+ if (!started) {
361
+ started = true;
362
+ onFirstUse();
363
+ }
364
+ if (!reader) reader = source.getReader();
365
+ try {
366
+ const { done, value } = await reader.read();
367
+ if (done) {
368
+ controller.close();
369
+ return;
370
+ }
371
+ controller.enqueue(value);
372
+ } catch (error) {
373
+ controller.error(error);
374
+ }
375
+ },
376
+ cancel(reason) {
377
+ if (!reader) return source.cancel(reason);
378
+ return reader.cancel(reason);
379
+ }
380
+ });
381
+ }
382
+ var Response = class Response {
383
+ status;
384
+ ok;
385
+ contentLength;
386
+ url;
387
+ diagnostics;
388
+ type = "basic";
389
+ bodyUsed = false;
390
+ payload;
391
+ requestUrl;
392
+ redirectedMemo;
393
+ headersInit;
394
+ headersInstance;
395
+ cookiesInit;
396
+ cookiesRecord;
397
+ inlineBody;
398
+ bodySource;
399
+ bodyStream;
400
+ nativeHandleAvailable;
401
+ nativeHandle;
402
+ constructor(payload, requestUrl, bodySource) {
403
+ this.payload = payload;
404
+ this.requestUrl = requestUrl;
405
+ this.status = this.payload.status;
406
+ this.ok = this.status >= 200 && this.status < 300;
407
+ this.headersInit = this.payload.headers;
408
+ this.headersInstance = null;
409
+ this.url = this.payload.url;
410
+ this.diagnostics = this.payload.diagnostics ?? null;
411
+ this.cookiesInit = this.payload.cookies;
412
+ this.cookiesRecord = null;
413
+ this.contentLength = this.payload.contentLength ?? null;
414
+ this.inlineBody = this.payload.bodyBytes ?? null;
415
+ this.nativeHandle = null;
416
+ if (typeof bodySource !== "undefined") {
417
+ this.bodySource = bodySource;
418
+ this.nativeHandleAvailable = false;
419
+ } else if (this.inlineBody !== null) {
420
+ this.bodySource = null;
421
+ this.nativeHandleAvailable = false;
422
+ } else if (this.payload.bodyHandle !== null) {
423
+ this.bodySource = null;
424
+ this.nativeHandleAvailable = true;
425
+ this.nativeHandle = {
426
+ id: this.payload.bodyHandle,
427
+ released: false
428
+ };
429
+ bodyHandleFinalizer?.register(this, this.nativeHandle, this.nativeHandle);
430
+ } else {
431
+ this.bodySource = null;
432
+ this.nativeHandleAvailable = false;
433
+ }
434
+ this.bodyStream = void 0;
435
+ }
436
+ get redirected() {
437
+ if (this.redirectedMemo !== void 0) return this.redirectedMemo;
438
+ if (this.url === this.requestUrl) {
439
+ this.redirectedMemo = false;
440
+ return false;
441
+ }
442
+ const normalizedRequestUrl = normalizeUrlForComparison(this.requestUrl);
443
+ this.redirectedMemo = normalizedRequestUrl ? this.url !== normalizedRequestUrl : true;
444
+ return this.redirectedMemo;
445
+ }
446
+ get statusText() {
447
+ return STATUS_CODES[this.status] ?? "";
448
+ }
449
+ get headers() {
450
+ if (!this.headersInstance) this.headersInstance = new Headers(this.headersInit);
451
+ return this.headersInstance;
452
+ }
453
+ get cookies() {
454
+ if (!this.cookiesRecord) {
455
+ const record = Object.create(null);
456
+ for (const [name, value] of this.cookiesInit) {
457
+ const existing = record[name];
458
+ if (existing === void 0) record[name] = value;
459
+ else if (Array.isArray(existing)) existing.push(value);
460
+ else record[name] = [existing, value];
461
+ }
462
+ this.cookiesRecord = record;
463
+ }
464
+ return this.cookiesRecord;
465
+ }
466
+ get body() {
467
+ if (this.inlineBody && this.bodySource === null) {
468
+ const bytes = this.inlineBody;
469
+ this.inlineBody = null;
470
+ this.bodySource = new ReadableStream({ start(controller) {
471
+ controller.enqueue(bytes);
472
+ controller.close();
473
+ } });
474
+ }
475
+ if (this.inlineBody === null && this.payload.bodyHandle === null && this.bodySource === null) return null;
476
+ if (this.bodySource === null && this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
477
+ if (this.nativeHandle) bodyHandleFinalizer?.unregister(this.nativeHandle);
478
+ const handle = this.nativeHandle ?? {
479
+ id: this.payload.bodyHandle,
480
+ released: false
481
+ };
482
+ this.nativeHandle = handle;
483
+ this.bodySource = createNativeBodyStream(handle);
484
+ this.nativeHandleAvailable = false;
485
+ }
486
+ if (this.bodySource === null) return null;
487
+ if (this.bodyStream === void 0) this.bodyStream = wrapBodyStream(this.bodySource, () => {
488
+ this.bodyUsed = true;
489
+ });
490
+ return this.bodyStream;
491
+ }
492
+ async json() {
493
+ const text = await this.text();
494
+ return JSON.parse(text);
495
+ }
496
+ async arrayBuffer() {
497
+ const bytes = await this.consumeBody();
498
+ const { buffer, byteOffset, byteLength } = bytes;
499
+ if (buffer instanceof ArrayBuffer) {
500
+ if (byteOffset === 0 && byteLength === buffer.byteLength) return buffer;
501
+ return buffer.slice(byteOffset, byteOffset + byteLength);
502
+ }
503
+ const view = new Uint8Array(byteLength);
504
+ view.set(bytes);
505
+ return view.buffer;
506
+ }
507
+ async text() {
508
+ const bytes = await this.consumeBody();
509
+ return UTF8_DECODER.decode(bytes);
510
+ }
511
+ async blob() {
512
+ const bytes = await this.consumeBody();
513
+ const contentType = this.headers.get("content-type") ?? "";
514
+ return new Blob([bytes], contentType ? { type: contentType } : void 0);
515
+ }
516
+ async formData() {
517
+ const bytes = await this.consumeBody();
518
+ const contentType = this.headers.get("content-type");
519
+ return new globalThis.Response(bytes, contentType ? { headers: { "content-type": contentType } } : void 0).formData();
520
+ }
521
+ readable() {
522
+ this.assertBodyAvailable();
523
+ this.bodyUsed = true;
524
+ const stream = this.body;
525
+ if (stream === null) return Readable.from([]);
526
+ return Readable.fromWeb(stream);
527
+ }
528
+ clone() {
529
+ if (this.bodyUsed) throw new TypeError("Cannot clone a Response whose body is already used");
530
+ if (this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
531
+ if (this.nativeHandle) bodyHandleFinalizer?.unregister(this.nativeHandle);
532
+ const handle = this.nativeHandle ?? {
533
+ id: this.payload.bodyHandle,
534
+ released: false
535
+ };
536
+ this.nativeHandle = handle;
537
+ this.bodySource = createNativeBodyStream(handle);
538
+ this.nativeHandleAvailable = false;
539
+ }
540
+ if (this.bodySource === null) return new Response(cloneNativeResponse(this.payload), this.requestUrl, null);
541
+ const [branchA, branchB] = this.bodySource.tee();
542
+ this.bodySource = branchA;
543
+ this.bodyStream = void 0;
544
+ return new Response(cloneNativeResponse(this.payload), this.requestUrl, branchB);
545
+ }
546
+ assertBodyAvailable() {
547
+ if (this.bodyUsed) throw new TypeError("Response body is already used");
548
+ }
549
+ async consumeBody() {
550
+ this.assertBodyAvailable();
551
+ this.bodyUsed = true;
552
+ if (this.inlineBody) {
553
+ const bytes = this.inlineBody;
554
+ this.inlineBody = null;
555
+ return bytes;
556
+ }
557
+ if (this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
558
+ this.nativeHandleAvailable = false;
559
+ try {
560
+ return await nativeBinding.readBodyAll(this.payload.bodyHandle);
561
+ } catch (error) {
562
+ if (String(error).includes("Body handle") && String(error).includes("not found")) return Buffer.alloc(0);
563
+ throw error;
564
+ } finally {
565
+ if (this.nativeHandle) markNativeBodyReleased(this.nativeHandle);
566
+ }
567
+ }
568
+ const stream = this.body;
569
+ if (!stream) return Buffer.alloc(0);
570
+ const reader = stream.getReader();
571
+ const chunks = [];
572
+ try {
573
+ while (true) {
574
+ const { done, value } = await reader.read();
575
+ if (done) break;
576
+ if (value && value.byteLength > 0) if (Buffer.isBuffer(value)) chunks.push(value);
577
+ else chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
578
+ }
579
+ } finally {}
580
+ return chunks.length === 0 ? Buffer.alloc(0) : Buffer.concat(chunks);
581
+ }
658
582
  };
659
583
  var Transport = class {
660
- id;
661
- disposed = false;
662
- constructor(id) {
663
- this.id = id;
664
- }
665
- get closed() {
666
- return this.disposed;
667
- }
668
- async close() {
669
- if (this.disposed) {
670
- return;
671
- }
672
- this.disposed = true;
673
- try {
674
- nativeBinding.dropTransport(this.id);
675
- } catch (error) {
676
- throw new RequestError(String(error));
677
- }
678
- }
584
+ id;
585
+ disposed = false;
586
+ constructor(id) {
587
+ this.id = id;
588
+ }
589
+ get closed() {
590
+ return this.disposed;
591
+ }
592
+ async close() {
593
+ if (this.disposed) return;
594
+ this.disposed = true;
595
+ try {
596
+ nativeBinding.dropTransport(this.id);
597
+ } catch (error) {
598
+ throw new RequestError(String(error));
599
+ }
600
+ }
679
601
  };
680
602
  var Session = class {
681
- id;
682
- disposed = false;
683
- defaults;
684
- constructor(id, defaults) {
685
- this.id = id;
686
- this.defaults = defaults;
687
- }
688
- get closed() {
689
- return this.disposed;
690
- }
691
- ensureActive() {
692
- if (this.disposed) {
693
- throw new RequestError("Session has been closed");
694
- }
695
- }
696
- /** @internal */
697
- getDefaults() {
698
- const snapshot = { ...this.defaults };
699
- if (this.defaults.defaultHeaders) {
700
- snapshot.defaultHeaders = [...this.defaults.defaultHeaders];
701
- }
702
- return snapshot;
703
- }
704
- /** @internal */
705
- _defaultsRef() {
706
- return this.defaults;
707
- }
708
- async fetch(input, init) {
709
- this.ensureActive();
710
- const config = init ? { ...init, session: this } : { session: this };
711
- return fetch(input, config);
712
- }
713
- async clearCookies() {
714
- this.ensureActive();
715
- try {
716
- nativeBinding.clearSession(this.id);
717
- } catch (error) {
718
- throw new RequestError(String(error));
719
- }
720
- }
721
- getCookies(url) {
722
- this.ensureActive();
723
- try {
724
- return nativeBinding.getCookies(this.id, String(url));
725
- } catch (error) {
726
- throw new RequestError(String(error));
727
- }
728
- }
729
- setCookie(name, value, url) {
730
- this.ensureActive();
731
- try {
732
- nativeBinding.setCookie(this.id, name, value, String(url));
733
- } catch (error) {
734
- throw new RequestError(String(error));
735
- }
736
- }
737
- async websocket(urlOrOptions, options) {
738
- this.ensureActive();
739
- const normalized = normalizeSessionWebSocketArgs(urlOrOptions, options);
740
- validateWebSocketProtocols(normalized.options.protocols);
741
- assertNoManualWebSocketProtocolHeader(normalized.options.headers);
742
- const protocols = normalizeWebSocketProtocolList(normalized.options.protocols);
743
- const transportId = this.defaults.transportId;
744
- if (!transportId) {
745
- throw new RequestError(
746
- "Session has no transport. Create the session with browser/os options or pass a transport to use session.websocket()."
747
- );
748
- }
749
- return WebSocket._connectWithInit({
750
- _internal: true,
751
- url: normalized.url,
752
- options: normalized.options,
753
- openDispatchMode: "deferred",
754
- connect: (callbacks) => nativeBinding.websocketConnectSession({
755
- url: normalized.url,
756
- sessionId: this.id,
757
- transportId,
758
- headers: headersToTuples(normalized.options.headers ?? {}),
759
- ...protocols && protocols.length > 0 && { protocols },
760
- onMessage: callbacks.onMessage,
761
- onClose: callbacks.onClose,
762
- onError: callbacks.onError
763
- }),
764
- legacyCallbacks: normalized.legacyCallbacks
765
- });
766
- }
767
- async close() {
768
- if (this.disposed) {
769
- return;
770
- }
771
- this.disposed = true;
772
- const transportId = this.defaults.transportId;
773
- const ownsTransport = this.defaults.ownsTransport;
774
- try {
775
- nativeBinding.dropSession(this.id);
776
- } catch (error) {
777
- if (!ownsTransport || !transportId) {
778
- throw new RequestError(String(error));
779
- }
780
- const originalError = error;
781
- try {
782
- nativeBinding.dropTransport(transportId);
783
- } catch {
784
- }
785
- throw new RequestError(String(originalError));
786
- }
787
- if (ownsTransport && transportId) {
788
- try {
789
- nativeBinding.dropTransport(transportId);
790
- } catch (error) {
791
- throw new RequestError(String(error));
792
- }
793
- }
794
- }
603
+ id;
604
+ disposed = false;
605
+ defaults;
606
+ constructor(id, defaults) {
607
+ this.id = id;
608
+ this.defaults = defaults;
609
+ }
610
+ get closed() {
611
+ return this.disposed;
612
+ }
613
+ ensureActive() {
614
+ if (this.disposed) throw new RequestError("Session has been closed");
615
+ }
616
+ /** @internal */
617
+ getDefaults() {
618
+ const snapshot = { ...this.defaults };
619
+ if (this.defaults.defaultHeaders) snapshot.defaultHeaders = [...this.defaults.defaultHeaders];
620
+ return snapshot;
621
+ }
622
+ /** @internal */
623
+ _defaultsRef() {
624
+ return this.defaults;
625
+ }
626
+ async fetch(input, init) {
627
+ this.ensureActive();
628
+ return fetch(input, init ? {
629
+ ...init,
630
+ session: this
631
+ } : { session: this });
632
+ }
633
+ async clearCookies() {
634
+ this.ensureActive();
635
+ try {
636
+ nativeBinding.clearSession(this.id);
637
+ } catch (error) {
638
+ throw new RequestError(String(error));
639
+ }
640
+ }
641
+ getCookies(url) {
642
+ this.ensureActive();
643
+ try {
644
+ return nativeBinding.getCookies(this.id, String(url));
645
+ } catch (error) {
646
+ throw new RequestError(String(error));
647
+ }
648
+ }
649
+ getAllCookies() {
650
+ this.ensureActive();
651
+ try {
652
+ return nativeBinding.getAllCookies(this.id);
653
+ } catch (error) {
654
+ throw new RequestError(String(error));
655
+ }
656
+ }
657
+ setCookie(name, value, url) {
658
+ this.ensureActive();
659
+ try {
660
+ nativeBinding.setCookie(this.id, name, value, String(url));
661
+ } catch (error) {
662
+ throw new RequestError(String(error));
663
+ }
664
+ }
665
+ async websocket(urlOrOptions, options) {
666
+ this.ensureActive();
667
+ const normalized = normalizeSessionWebSocketArgs(urlOrOptions, options);
668
+ validateWebSocketProtocols(normalized.options.protocols);
669
+ assertNoManualWebSocketProtocolHeader(normalized.options.headers);
670
+ const protocols = normalizeWebSocketProtocolList(normalized.options.protocols);
671
+ const transportId = this.defaults.transportId;
672
+ if (!transportId) throw new RequestError("Session has no transport. Create the session with browser/os options or pass a transport to use session.websocket().");
673
+ return WebSocket._connectWithInit({
674
+ _internal: true,
675
+ url: normalized.url,
676
+ options: normalized.options,
677
+ openDispatchMode: "deferred",
678
+ connect: (callbacks) => nativeBinding.websocketConnectSession({
679
+ url: normalized.url,
680
+ sessionId: this.id,
681
+ transportId,
682
+ headers: headersToTuples(normalized.options.headers ?? {}),
683
+ ...protocols && protocols.length > 0 && { protocols },
684
+ ...normalized.options.maxFrameSize !== void 0 && { maxFrameSize: normalized.options.maxFrameSize },
685
+ ...normalized.options.maxMessageSize !== void 0 && { maxMessageSize: normalized.options.maxMessageSize },
686
+ onMessage: callbacks.onMessage,
687
+ onClose: callbacks.onClose,
688
+ onError: callbacks.onError
689
+ }),
690
+ legacyCallbacks: normalized.legacyCallbacks
691
+ });
692
+ }
693
+ async close() {
694
+ if (this.disposed) return;
695
+ this.disposed = true;
696
+ const transportId = this.defaults.transportId;
697
+ const ownsTransport = this.defaults.ownsTransport;
698
+ try {
699
+ nativeBinding.dropSession(this.id);
700
+ } catch (error) {
701
+ if (!ownsTransport || !transportId) throw new RequestError(String(error));
702
+ const originalError = error;
703
+ try {
704
+ nativeBinding.dropTransport(transportId);
705
+ } catch {}
706
+ throw new RequestError(String(originalError));
707
+ }
708
+ if (ownsTransport && transportId) try {
709
+ nativeBinding.dropTransport(transportId);
710
+ } catch (error) {
711
+ throw new RequestError(String(error));
712
+ }
713
+ }
795
714
  };
796
715
  function resolveSessionContext(config) {
797
- const requestedMode = config.cookieMode ?? "ephemeral";
798
- const sessionCandidate = config.session;
799
- const providedSessionId = typeof config.sessionId === "string" ? config.sessionId.trim() : void 0;
800
- if (sessionCandidate && providedSessionId) {
801
- throw new RequestError("Provide either `session` or `sessionId`, not both.");
802
- }
803
- if (sessionCandidate) {
804
- if (!(sessionCandidate instanceof Session)) {
805
- throw new RequestError("`session` must be created via createSession()");
806
- }
807
- if (sessionCandidate.closed) {
808
- throw new RequestError("Session has been closed");
809
- }
810
- return {
811
- sessionId: sessionCandidate.id,
812
- cookieMode: "session",
813
- dropAfterRequest: false,
814
- defaults: sessionCandidate._defaultsRef()
815
- };
816
- }
817
- if (providedSessionId) {
818
- if (!providedSessionId) {
819
- throw new RequestError("sessionId must not be empty");
820
- }
821
- if (requestedMode === "ephemeral") {
822
- throw new RequestError("cookieMode 'ephemeral' cannot be combined with sessionId");
823
- }
824
- return {
825
- sessionId: providedSessionId,
826
- cookieMode: "session",
827
- dropAfterRequest: false
828
- };
829
- }
830
- if (requestedMode === "session") {
831
- throw new RequestError("cookieMode 'session' requires a session or sessionId");
832
- }
833
- return {
834
- sessionId: generateEphemeralSessionId(),
835
- cookieMode: "ephemeral",
836
- dropAfterRequest: true
837
- };
716
+ const requestedMode = config.cookieMode ?? "ephemeral";
717
+ const sessionCandidate = config.session;
718
+ const providedSessionId = typeof config.sessionId === "string" ? config.sessionId.trim() : void 0;
719
+ if (sessionCandidate && providedSessionId) throw new RequestError("Provide either `session` or `sessionId`, not both.");
720
+ if (sessionCandidate) {
721
+ if (!(sessionCandidate instanceof Session)) throw new RequestError("`session` must be created via createSession()");
722
+ if (sessionCandidate.closed) throw new RequestError("Session has been closed");
723
+ return {
724
+ sessionId: sessionCandidate.id,
725
+ cookieMode: "session",
726
+ dropAfterRequest: false,
727
+ defaults: sessionCandidate._defaultsRef()
728
+ };
729
+ }
730
+ if (providedSessionId) {
731
+ if (!providedSessionId) throw new RequestError("sessionId must not be empty");
732
+ if (requestedMode === "ephemeral") throw new RequestError("cookieMode 'ephemeral' cannot be combined with sessionId");
733
+ return {
734
+ sessionId: providedSessionId,
735
+ cookieMode: "session",
736
+ dropAfterRequest: false
737
+ };
738
+ }
739
+ if (requestedMode === "session") throw new RequestError("cookieMode 'session' requires a session or sessionId");
740
+ return {
741
+ sessionId: generateEphemeralSessionId(),
742
+ cookieMode: "ephemeral",
743
+ dropAfterRequest: true
744
+ };
838
745
  }
839
746
  function resolveTransportContext(config, sessionDefaults) {
840
- if (config.transport !== void 0) {
841
- if (!(config.transport instanceof Transport)) {
842
- throw new RequestError("`transport` must be created via createTransport()");
843
- }
844
- if (config.transport.closed) {
845
- throw new RequestError("Transport has been closed");
846
- }
847
- const hasProxy = config.proxy !== void 0;
848
- if (config.browser !== void 0 || config.os !== void 0 || config.emulation !== void 0 || hasProxy || config.insecure !== void 0) {
849
- throw new RequestError("`transport` cannot be combined with browser/os/emulation/proxy/insecure options");
850
- }
851
- return { transportId: config.transport.id };
852
- }
853
- if (sessionDefaults?.transportId) {
854
- if (config.emulation !== void 0) {
855
- throw new RequestError("Session emulation cannot be changed after creation");
856
- }
857
- if (config.browser !== void 0) {
858
- validateBrowserProfile(config.browser);
859
- const lockedBrowser = sessionDefaults.transportMode.kind === "custom" ? void 0 : sessionDefaults.transportMode.browser;
860
- if (config.browser !== lockedBrowser) {
861
- throw new RequestError("Session browser cannot be changed after creation");
862
- }
863
- }
864
- if (config.os !== void 0) {
865
- validateOperatingSystem(config.os);
866
- const lockedOs = sessionDefaults.transportMode.kind === "custom" ? void 0 : sessionDefaults.transportMode.os;
867
- if (config.os !== lockedOs) {
868
- throw new RequestError("Session operating system cannot be changed after creation");
869
- }
870
- }
871
- const initHasProxy = Object.hasOwn(config, "proxy");
872
- const requestedProxy = initHasProxy ? config.proxy : void 0;
873
- if (initHasProxy && requestedProxy !== void 0 && (sessionDefaults.proxy ?? null) !== (requestedProxy ?? null)) {
874
- throw new RequestError("Session proxy cannot be changed after creation");
875
- }
876
- if (config.insecure !== void 0) {
877
- const lockedInsecure = sessionDefaults.insecure ?? false;
878
- if (config.insecure !== lockedInsecure) {
879
- throw new RequestError("Session insecure setting cannot be changed after creation");
880
- }
881
- }
882
- return { transportId: sessionDefaults.transportId };
883
- }
884
- const resolved = {
885
- mode: resolveEmulationMode(config.browser, config.os, config.emulation)
886
- };
887
- if (config.proxy !== void 0) {
888
- resolved.proxy = config.proxy;
889
- }
890
- if (config.insecure !== void 0) {
891
- resolved.insecure = config.insecure;
892
- }
893
- return resolved;
747
+ if (config.transport !== void 0) {
748
+ if (!(config.transport instanceof Transport)) throw new RequestError("`transport` must be created via createTransport()");
749
+ if (config.transport.closed) throw new RequestError("Transport has been closed");
750
+ const hasProxy = config.proxy !== void 0;
751
+ if (config.browser !== void 0 || config.os !== void 0 || config.emulation !== void 0 || hasProxy || config.insecure !== void 0 || config.trustStore !== void 0) throw new RequestError("`transport` cannot be combined with browser/os/emulation/proxy/insecure/trustStore options");
752
+ return {
753
+ transportId: config.transport.id,
754
+ ...config.captureDiagnostics !== void 0 && { captureDiagnostics: config.captureDiagnostics }
755
+ };
756
+ }
757
+ if (sessionDefaults?.transportId) {
758
+ if (config.emulation !== void 0) throw new RequestError("Session emulation cannot be changed after creation");
759
+ if (config.browser !== void 0) {
760
+ validateBrowserProfile(config.browser);
761
+ const lockedBrowser = sessionDefaults.transportMode.kind === "custom" ? void 0 : sessionDefaults.transportMode.browser;
762
+ if (config.browser !== lockedBrowser) throw new RequestError("Session browser cannot be changed after creation");
763
+ }
764
+ if (config.os !== void 0) {
765
+ validateOperatingSystem(config.os);
766
+ const lockedOs = sessionDefaults.transportMode.kind === "custom" ? void 0 : sessionDefaults.transportMode.os;
767
+ if (config.os !== lockedOs) throw new RequestError("Session operating system cannot be changed after creation");
768
+ }
769
+ const initHasProxy = Object.hasOwn(config, "proxy");
770
+ const requestedProxy = initHasProxy ? config.proxy : void 0;
771
+ if (initHasProxy && requestedProxy !== void 0 && (sessionDefaults.proxy ?? null) !== (requestedProxy ?? null)) throw new RequestError("Session proxy cannot be changed after creation");
772
+ if (config.insecure !== void 0) {
773
+ const lockedInsecure = sessionDefaults.insecure ?? false;
774
+ if (config.insecure !== lockedInsecure) throw new RequestError("Session insecure setting cannot be changed after creation");
775
+ }
776
+ if (config.trustStore !== void 0) {
777
+ const lockedTrustStore = sessionDefaults.trustStore ?? DEFAULT_TRUST_STORE;
778
+ if (config.trustStore !== lockedTrustStore) throw new RequestError("Session trustStore setting cannot be changed after creation");
779
+ }
780
+ const captureDiagnostics = config.captureDiagnostics ?? sessionDefaults.captureDiagnostics;
781
+ return {
782
+ transportId: sessionDefaults.transportId,
783
+ ...captureDiagnostics !== void 0 && { captureDiagnostics }
784
+ };
785
+ }
786
+ const resolved = { mode: resolveEmulationMode(config.browser, config.os, config.emulation) };
787
+ if (config.proxy !== void 0) resolved.proxy = config.proxy;
788
+ if (config.insecure !== void 0) resolved.insecure = config.insecure;
789
+ resolved.trustStore = config.trustStore ?? DEFAULT_TRUST_STORE;
790
+ if (config.captureDiagnostics !== void 0) resolved.captureDiagnostics = config.captureDiagnostics;
791
+ return resolved;
894
792
  }
895
793
  function createAbortError(reason) {
896
- const fallbackMessage = typeof reason === "string" ? reason : "The operation was aborted";
897
- if (typeof DOMException !== "undefined" && reason instanceof DOMException) {
898
- return reason.name === "AbortError" ? reason : new DOMException(reason.message || fallbackMessage, "AbortError");
899
- }
900
- if (reason instanceof Error) {
901
- const error2 = new Error(reason.message);
902
- error2.name = "AbortError";
903
- error2.cause = reason;
904
- return error2;
905
- }
906
- if (typeof DOMException !== "undefined") {
907
- return new DOMException(fallbackMessage, "AbortError");
908
- }
909
- const error = new Error(fallbackMessage);
910
- error.name = "AbortError";
911
- return error;
794
+ const fallbackMessage = typeof reason === "string" ? reason : "The operation was aborted";
795
+ if (typeof DOMException !== "undefined" && reason instanceof DOMException) return reason.name === "AbortError" ? reason : new DOMException(reason.message || fallbackMessage, "AbortError");
796
+ if (reason instanceof Error) {
797
+ const error = new Error(reason.message);
798
+ error.name = "AbortError";
799
+ error.cause = reason;
800
+ return error;
801
+ }
802
+ if (typeof DOMException !== "undefined") return new DOMException(fallbackMessage, "AbortError");
803
+ const error = new Error(fallbackMessage);
804
+ error.name = "AbortError";
805
+ return error;
912
806
  }
913
807
  function isAbortError(error) {
914
- return Boolean(error) && typeof error.name === "string" && error.name === "AbortError";
808
+ return Boolean(error) && typeof error.name === "string" && error.name === "AbortError";
915
809
  }
916
- var REQUEST_ID_MAX = 2 ** 48;
917
- var requestIdCounter = Math.trunc(Number(process.hrtime.bigint() % BigInt(REQUEST_ID_MAX - 1))) + 1;
810
+ const REQUEST_ID_MAX = 2 ** 48;
811
+ let requestIdCounter = Math.trunc(Number(process.hrtime.bigint() % BigInt(REQUEST_ID_MAX - 1))) + 1;
918
812
  function generateRequestId() {
919
- requestIdCounter += 1;
920
- if (requestIdCounter >= REQUEST_ID_MAX) {
921
- requestIdCounter = 1;
922
- }
923
- return requestIdCounter;
813
+ requestIdCounter += 1;
814
+ if (requestIdCounter >= REQUEST_ID_MAX) requestIdCounter = 1;
815
+ return requestIdCounter;
924
816
  }
925
817
  function setupAbort(signal, cancelNative) {
926
- if (!signal) {
927
- return null;
928
- }
929
- if (signal.aborted) {
930
- cancelNative();
931
- throw createAbortError(signal.reason);
932
- }
933
- let onAbortListener;
934
- const promise = new Promise((_, reject) => {
935
- onAbortListener = () => {
936
- cancelNative();
937
- reject(createAbortError(signal.reason));
938
- };
939
- signal.addEventListener("abort", onAbortListener, { once: true });
940
- });
941
- const cleanup = () => {
942
- if (onAbortListener) {
943
- signal.removeEventListener("abort", onAbortListener);
944
- onAbortListener = void 0;
945
- }
946
- };
947
- return { promise, cleanup };
818
+ if (!signal) return null;
819
+ if (signal.aborted) {
820
+ cancelNative();
821
+ throw createAbortError(signal.reason);
822
+ }
823
+ let onAbortListener;
824
+ const promise = new Promise((_, reject) => {
825
+ onAbortListener = () => {
826
+ cancelNative();
827
+ reject(createAbortError(signal.reason));
828
+ };
829
+ signal.addEventListener("abort", onAbortListener, { once: true });
830
+ });
831
+ const cleanup = () => {
832
+ if (onAbortListener) {
833
+ signal.removeEventListener("abort", onAbortListener);
834
+ onAbortListener = void 0;
835
+ }
836
+ };
837
+ return {
838
+ promise,
839
+ cleanup
840
+ };
948
841
  }
949
842
  function coerceUrlInput(input) {
950
- if (input instanceof URL) {
951
- return input.href;
952
- }
953
- if (input.length === 0) {
954
- throw new RequestError("URL is required");
955
- }
956
- if (input.charCodeAt(0) > 32 && input.charCodeAt(input.length - 1) > 32) {
957
- return input;
958
- }
959
- const trimmed = input.trim();
960
- if (trimmed.length === 0) {
961
- throw new RequestError("URL is required");
962
- }
963
- return trimmed;
843
+ if (input instanceof URL) return input.href;
844
+ if (input.length === 0) throw new RequestError("URL is required");
845
+ if (input.charCodeAt(0) > 32 && input.charCodeAt(input.length - 1) > 32) return input;
846
+ const trimmed = input.trim();
847
+ if (trimmed.length === 0) throw new RequestError("URL is required");
848
+ return trimmed;
964
849
  }
965
850
  function isRequestLike(input) {
966
- if (!input || typeof input !== "object") {
967
- return false;
968
- }
969
- if (typeof Request !== "undefined" && input instanceof Request) {
970
- return true;
971
- }
972
- const candidate = input;
973
- return typeof candidate.url === "string" && typeof candidate.method === "string" && typeof candidate.arrayBuffer === "function" && typeof candidate.redirect === "string";
851
+ if (!input || typeof input !== "object") return false;
852
+ if (typeof Request !== "undefined" && input instanceof Request) return true;
853
+ const candidate = input;
854
+ return typeof candidate.url === "string" && typeof candidate.method === "string" && typeof candidate.arrayBuffer === "function" && typeof candidate.redirect === "string";
974
855
  }
975
856
  async function resolveFetchArgs(input, init) {
976
- if (!isRequestLike(input)) {
977
- return { url: coerceUrlInput(input), init: init ?? {} };
978
- }
979
- const mergedInit = init ? { ...init } : {};
980
- if (mergedInit.method === void 0) {
981
- mergedInit.method = input.method;
982
- }
983
- if (mergedInit.headers === void 0) {
984
- mergedInit.headers = input.headers;
985
- }
986
- if (mergedInit.redirect === void 0 && (input.redirect === "follow" || input.redirect === "manual" || input.redirect === "error")) {
987
- mergedInit.redirect = input.redirect;
988
- }
989
- if (mergedInit.signal === void 0) {
990
- mergedInit.signal = input.signal;
991
- }
992
- if (mergedInit.body === void 0 && input.body !== null) {
993
- if (input.bodyUsed) {
994
- throw new TypeError("Request body is already used");
995
- }
996
- mergedInit.body = Buffer.from(await input.arrayBuffer());
997
- }
998
- return { url: coerceUrlInput(input.url), init: mergedInit };
857
+ if (!isRequestLike(input)) return {
858
+ url: coerceUrlInput(input),
859
+ init: init ?? {}
860
+ };
861
+ const mergedInit = init ? { ...init } : {};
862
+ if (mergedInit.method === void 0) mergedInit.method = input.method;
863
+ if (mergedInit.headers === void 0) mergedInit.headers = input.headers;
864
+ if (mergedInit.redirect === void 0 && (input.redirect === "follow" || input.redirect === "manual" || input.redirect === "error")) mergedInit.redirect = input.redirect;
865
+ if (mergedInit.signal === void 0) mergedInit.signal = input.signal;
866
+ if (mergedInit.body === void 0 && input.body !== null) {
867
+ if (input.bodyUsed) throw new TypeError("Request body is already used");
868
+ mergedInit.body = Buffer.from(await input.arrayBuffer());
869
+ }
870
+ return {
871
+ url: coerceUrlInput(input.url),
872
+ init: mergedInit
873
+ };
999
874
  }
1000
875
  function normalizeUrlForComparison(value) {
1001
- try {
1002
- return new URL(value).toString();
1003
- } catch {
1004
- return null;
1005
- }
876
+ try {
877
+ return new URL(value).toString();
878
+ } catch {
879
+ return null;
880
+ }
1006
881
  }
1007
882
  function validateRedirectMode(mode) {
1008
- if (mode === void 0 || mode === "follow" || mode === "manual" || mode === "error") {
1009
- return;
1010
- }
1011
- throw new RequestError(`Redirect mode '${mode}' is not supported`);
883
+ if (mode === void 0 || mode === "follow" || mode === "manual" || mode === "error") return;
884
+ throw new RequestError(`Redirect mode '${mode}' is not supported`);
1012
885
  }
1013
886
  async function serializeBody(body) {
1014
- if (body === null || body === void 0) {
1015
- return {};
1016
- }
1017
- if (typeof body === "string") {
1018
- return { body: Buffer.from(body, "utf8") };
1019
- }
1020
- if (Buffer.isBuffer(body)) {
1021
- return { body };
1022
- }
1023
- if (body instanceof URLSearchParams) {
1024
- return {
1025
- body: Buffer.from(body.toString(), "utf8"),
1026
- contentType: "application/x-www-form-urlencoded;charset=UTF-8"
1027
- };
1028
- }
1029
- if (body instanceof ArrayBuffer) {
1030
- return { body: Buffer.from(body) };
1031
- }
1032
- if (ArrayBuffer.isView(body)) {
1033
- return { body: Buffer.from(body.buffer, body.byteOffset, body.byteLength) };
1034
- }
1035
- if (typeof Blob !== "undefined" && body instanceof Blob) {
1036
- const buffer = Buffer.from(await body.arrayBuffer());
1037
- return { body: buffer, ...body.type ? { contentType: body.type } : {} };
1038
- }
1039
- if (typeof FormData !== "undefined" && body instanceof FormData) {
1040
- const encoded = new globalThis.Response(body);
1041
- const contentType = encoded.headers.get("content-type") ?? void 0;
1042
- const buffer = Buffer.from(await encoded.arrayBuffer());
1043
- return { body: buffer, ...contentType ? { contentType } : {} };
1044
- }
1045
- throw new TypeError(
1046
- "Unsupported body type; expected string, Buffer, ArrayBuffer, ArrayBufferView, URLSearchParams, Blob, or FormData"
1047
- );
887
+ if (body === null || body === void 0) return {};
888
+ if (typeof body === "string") return { body: Buffer.from(body, "utf8") };
889
+ if (Buffer.isBuffer(body)) return { body };
890
+ if (body instanceof URLSearchParams) return {
891
+ body: Buffer.from(body.toString(), "utf8"),
892
+ contentType: "application/x-www-form-urlencoded;charset=UTF-8"
893
+ };
894
+ if (body instanceof ArrayBuffer) return { body: Buffer.from(body) };
895
+ if (ArrayBuffer.isView(body)) return { body: Buffer.from(body.buffer, body.byteOffset, body.byteLength) };
896
+ if (typeof Blob !== "undefined" && body instanceof Blob) return {
897
+ body: Buffer.from(await body.arrayBuffer()),
898
+ ...body.type ? { contentType: body.type } : {}
899
+ };
900
+ if (typeof FormData !== "undefined" && body instanceof FormData) {
901
+ const encoded = new globalThis.Response(body);
902
+ const contentType = encoded.headers.get("content-type") ?? void 0;
903
+ return {
904
+ body: Buffer.from(await encoded.arrayBuffer()),
905
+ ...contentType ? { contentType } : {}
906
+ };
907
+ }
908
+ throw new TypeError("Unsupported body type; expected string, Buffer, ArrayBuffer, ArrayBufferView, URLSearchParams, Blob, or FormData");
1048
909
  }
1049
910
  function ensureMethod(method) {
1050
- if (method === void 0 || method.length === 0) {
1051
- return "GET";
1052
- }
1053
- switch (method) {
1054
- case "GET":
1055
- case "POST":
1056
- case "PUT":
1057
- case "DELETE":
1058
- case "PATCH":
1059
- case "HEAD":
1060
- case "OPTIONS":
1061
- return method;
1062
- }
1063
- const normalized = method.trim().toUpperCase();
1064
- return normalized.length > 0 ? normalized : "GET";
911
+ if (method === void 0 || method.length === 0) return "GET";
912
+ switch (method) {
913
+ case "GET":
914
+ case "POST":
915
+ case "PUT":
916
+ case "DELETE":
917
+ case "PATCH":
918
+ case "HEAD":
919
+ case "OPTIONS": return method;
920
+ }
921
+ const normalized = method.trim().toUpperCase();
922
+ return normalized.length > 0 ? normalized : "GET";
1065
923
  }
1066
924
  function ensureBodyAllowed(method, body) {
1067
- if (body === void 0) {
1068
- return;
1069
- }
1070
- if (method === "GET" || method === "HEAD") {
1071
- throw new RequestError(`Request with ${method} method cannot have a body`);
1072
- }
925
+ if (body === void 0) return;
926
+ if (method === "GET" || method === "HEAD") throw new RequestError(`Request with ${method} method cannot have a body`);
1073
927
  }
1074
928
  function validateBrowserProfile(browser) {
1075
- if (browser === void 0) {
1076
- return;
1077
- }
1078
- if (typeof browser !== "string" || browser.trim().length === 0) {
1079
- throw new RequestError("Browser profile must not be empty");
1080
- }
1081
- if (!getProfileSet().has(browser)) {
1082
- throw new RequestError(`Invalid browser profile: ${browser}. Available profiles: ${getProfiles().join(", ")}`);
1083
- }
929
+ if (browser === void 0) return;
930
+ if (typeof browser !== "string" || browser.trim().length === 0) throw new RequestError("Browser profile must not be empty");
931
+ if (!getProfileSet().has(browser)) throw new RequestError(`Invalid browser profile: ${browser}. Available profiles: ${getProfiles().join(", ")}`);
1084
932
  }
1085
933
  function validateOperatingSystem(os) {
1086
- if (os === void 0) {
1087
- return;
1088
- }
1089
- if (typeof os !== "string" || os.trim().length === 0) {
1090
- throw new RequestError("Operating system must not be empty");
1091
- }
1092
- if (!getOperatingSystemSet().has(os)) {
1093
- throw new RequestError(`Invalid operating system: ${os}. Available options: ${getOperatingSystems().join(", ")}`);
1094
- }
934
+ if (os === void 0) return;
935
+ if (typeof os !== "string" || os.trim().length === 0) throw new RequestError("Operating system must not be empty");
936
+ if (!getOperatingSystemSet().has(os)) throw new RequestError(`Invalid operating system: ${os}. Available options: ${getOperatingSystems().join(", ")}`);
1095
937
  }
1096
938
  function validateTimeout(timeout) {
1097
- if (timeout === void 0) {
1098
- return;
1099
- }
1100
- if (typeof timeout !== "number" || !Number.isFinite(timeout)) {
1101
- throw new RequestError("Timeout must be a finite number");
1102
- }
1103
- if (timeout < 0) {
1104
- throw new RequestError("Timeout must be 0 (no timeout) or a positive number");
1105
- }
939
+ if (timeout === void 0) return;
940
+ if (typeof timeout !== "number" || !Number.isFinite(timeout)) throw new RequestError("Timeout must be a finite number");
941
+ if (timeout < 0) throw new RequestError("Timeout must be 0 (no timeout) or a positive number");
942
+ }
943
+ function validateTrustStore(trustStore) {
944
+ if (trustStore === void 0) return;
945
+ if (trustStore !== "combined" && trustStore !== "mozilla" && trustStore !== "defaultPaths") throw new RequestError("trustStore must be one of: combined, mozilla, defaultPaths");
1106
946
  }
1107
947
  function validatePositiveNumber(value, label) {
1108
- if (typeof value !== "number" || !Number.isFinite(value)) {
1109
- throw new RequestError(`${label} must be a finite number`);
1110
- }
1111
- if (value <= 0) {
1112
- throw new RequestError(`${label} must be greater than 0`);
1113
- }
948
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new RequestError(`${label} must be a finite number`);
949
+ if (value <= 0) throw new RequestError(`${label} must be greater than 0`);
1114
950
  }
1115
951
  function validateNonNegativeInteger(value, label) {
1116
- if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
1117
- throw new RequestError(`${label} must be an integer`);
1118
- }
1119
- if (value < 0) {
1120
- throw new RequestError(`${label} must be greater than or equal to 0`);
1121
- }
952
+ if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) throw new RequestError(`${label} must be an integer`);
953
+ if (value < 0) throw new RequestError(`${label} must be greater than or equal to 0`);
1122
954
  }
1123
955
  function validatePositiveInteger(value, label) {
1124
- if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
1125
- throw new RequestError(`${label} must be an integer`);
1126
- }
1127
- if (value <= 0) {
1128
- throw new RequestError(`${label} must be greater than 0`);
1129
- }
956
+ if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) throw new RequestError(`${label} must be an integer`);
957
+ if (value <= 0) throw new RequestError(`${label} must be greater than 0`);
1130
958
  }
1131
959
  function validateIntegerInRange(value, min, max, label) {
1132
- validateNonNegativeInteger(value, label);
1133
- if (value < min || value > max) {
1134
- throw new RequestError(`${label} must be between ${min} and ${max}`);
1135
- }
1136
- }
1137
- var SUPPORTED_ALPN_PROTOCOLS = /* @__PURE__ */ new Set(["HTTP1", "HTTP2", "HTTP3"]);
1138
- var SUPPORTED_ALPS_PROTOCOLS = /* @__PURE__ */ new Set(["HTTP1", "HTTP2", "HTTP3"]);
1139
- var SUPPORTED_CERTIFICATE_COMPRESSION_ALGORITHMS = /* @__PURE__ */ new Set(["zlib", "brotli", "zstd"]);
1140
- var HTTP2_SETTING_IDS = /* @__PURE__ */ new Set([
1141
- "HeaderTableSize",
1142
- "EnablePush",
1143
- "MaxConcurrentStreams",
1144
- "InitialWindowSize",
1145
- "MaxFrameSize",
1146
- "MaxHeaderListSize",
1147
- "EnableConnectProtocol",
1148
- "NoRfc7540Priorities"
960
+ validateNonNegativeInteger(value, label);
961
+ if (value < min || value > max) throw new RequestError(`${label} must be between ${min} and ${max}`);
962
+ }
963
+ const SUPPORTED_ALPN_PROTOCOLS = new Set([
964
+ "HTTP1",
965
+ "HTTP2",
966
+ "HTTP3"
967
+ ]);
968
+ const SUPPORTED_ALPS_PROTOCOLS = new Set([
969
+ "HTTP1",
970
+ "HTTP2",
971
+ "HTTP3"
972
+ ]);
973
+ const SUPPORTED_CERTIFICATE_COMPRESSION_ALGORITHMS = new Set([
974
+ "zlib",
975
+ "brotli",
976
+ "zstd"
977
+ ]);
978
+ const HTTP2_SETTING_IDS = new Set([
979
+ "HeaderTableSize",
980
+ "EnablePush",
981
+ "MaxConcurrentStreams",
982
+ "InitialWindowSize",
983
+ "MaxFrameSize",
984
+ "MaxHeaderListSize",
985
+ "EnableConnectProtocol",
986
+ "NoRfc7540Priorities"
987
+ ]);
988
+ const HTTP2_PSEUDO_HEADER_IDS = new Set([
989
+ "Method",
990
+ "Scheme",
991
+ "Authority",
992
+ "Path",
993
+ "Protocol"
1149
994
  ]);
1150
- var HTTP2_PSEUDO_HEADER_IDS = /* @__PURE__ */ new Set(["Method", "Scheme", "Authority", "Path", "Protocol"]);
1151
- var STANDARD_HTTP2_SETTING_ID_VALUES = /* @__PURE__ */ new Set([1, 2, 3, 4, 5, 6, 8, 9]);
1152
- var MAX_HTTP2_EXPERIMENTAL_SETTING_ID = 15;
1153
- var TLS_VERSION_ALIASES = /* @__PURE__ */ new Map([
1154
- ["1.0", "1.0"],
1155
- ["1.1", "1.1"],
1156
- ["1.2", "1.2"],
1157
- ["1.3", "1.3"],
1158
- ["tls1.0", "1.0"],
1159
- ["tls1.1", "1.1"],
1160
- ["tls1.2", "1.2"],
1161
- ["tls1.3", "1.3"]
995
+ const STANDARD_HTTP2_SETTING_ID_VALUES = new Set([
996
+ 1,
997
+ 2,
998
+ 3,
999
+ 4,
1000
+ 5,
1001
+ 6,
1002
+ 8,
1003
+ 9
1004
+ ]);
1005
+ const MAX_HTTP2_EXPERIMENTAL_SETTING_ID = 15;
1006
+ const TLS_VERSION_ALIASES = new Map([
1007
+ ["1.0", "1.0"],
1008
+ ["1.1", "1.1"],
1009
+ ["1.2", "1.2"],
1010
+ ["1.3", "1.3"],
1011
+ ["tls1.0", "1.0"],
1012
+ ["tls1.1", "1.1"],
1013
+ ["tls1.2", "1.2"],
1014
+ ["tls1.3", "1.3"]
1162
1015
  ]);
1163
1016
  function isNonEmpty(value) {
1164
- for (const _ in value) return true;
1165
- return false;
1017
+ for (const _ in value) return true;
1018
+ return false;
1166
1019
  }
1167
1020
  function normalizeProtocolList(value, label, allowed) {
1168
- if (value === void 0) {
1169
- return void 0;
1170
- }
1171
- if (!Array.isArray(value)) {
1172
- throw new RequestError(`${label} must be an array`);
1173
- }
1174
- for (const protocol of value) {
1175
- if (!allowed.has(protocol)) {
1176
- throw new RequestError(`${label} values must be one of: HTTP1, HTTP2, HTTP3`);
1177
- }
1178
- }
1179
- return [...value];
1021
+ if (value === void 0) return;
1022
+ if (!Array.isArray(value)) throw new RequestError(`${label} must be an array`);
1023
+ for (const protocol of value) if (!allowed.has(protocol)) throw new RequestError(`${label} values must be one of: HTTP1, HTTP2, HTTP3`);
1024
+ return [...value];
1180
1025
  }
1181
1026
  function normalizeTlsVersion(value, label) {
1182
- if (value === void 0) {
1183
- return void 0;
1184
- }
1185
- if (typeof value !== "string") {
1186
- throw new RequestError(`${label} must be a string`);
1187
- }
1188
- const normalized = TLS_VERSION_ALIASES.get(value.trim().toLowerCase());
1189
- if (!normalized) {
1190
- throw new RequestError(`${label} must be one of: 1.0, 1.1, 1.2, 1.3`);
1191
- }
1192
- return normalized;
1027
+ if (value === void 0) return;
1028
+ if (typeof value !== "string") throw new RequestError(`${label} must be a string`);
1029
+ const normalized = TLS_VERSION_ALIASES.get(value.trim().toLowerCase());
1030
+ if (!normalized) throw new RequestError(`${label} must be one of: 1.0, 1.1, 1.2, 1.3`);
1031
+ return normalized;
1193
1032
  }
1194
1033
  function normalizeOrigHeaders(origHeaders) {
1195
- if (origHeaders === void 0) {
1196
- return void 0;
1197
- }
1198
- if (!Array.isArray(origHeaders)) {
1199
- throw new RequestError("emulation.origHeaders must be an array of strings");
1200
- }
1201
- const normalized = [];
1202
- const seen = /* @__PURE__ */ new Set();
1203
- for (const entry of origHeaders) {
1204
- if (typeof entry !== "string" || entry.trim().length === 0) {
1205
- throw new RequestError("emulation.origHeaders entries must be non-empty strings");
1206
- }
1207
- const trimmed = entry.trim();
1208
- const duplicateKey = trimmed.toLowerCase();
1209
- if (seen.has(duplicateKey)) {
1210
- throw new RequestError(`Duplicate emulation.origHeaders entry: ${trimmed}`);
1211
- }
1212
- seen.add(duplicateKey);
1213
- normalized.push(trimmed);
1214
- }
1215
- return normalized.length > 0 ? normalized : void 0;
1034
+ if (origHeaders === void 0) return;
1035
+ if (!Array.isArray(origHeaders)) throw new RequestError("emulation.origHeaders must be an array of strings");
1036
+ const normalized = [];
1037
+ const seen = /* @__PURE__ */ new Set();
1038
+ for (const entry of origHeaders) {
1039
+ if (typeof entry !== "string" || entry.trim().length === 0) throw new RequestError("emulation.origHeaders entries must be non-empty strings");
1040
+ const trimmed = entry.trim();
1041
+ const duplicateKey = trimmed.toLowerCase();
1042
+ if (seen.has(duplicateKey)) throw new RequestError(`Duplicate emulation.origHeaders entry: ${trimmed}`);
1043
+ seen.add(duplicateKey);
1044
+ normalized.push(trimmed);
1045
+ }
1046
+ return normalized.length > 0 ? normalized : void 0;
1216
1047
  }
1217
1048
  function normalizeCustomTlsOptions(options) {
1218
- if (options === void 0) {
1219
- return void 0;
1220
- }
1221
- const normalized = {};
1222
- const alpnProtocols = normalizeProtocolList(
1223
- options.alpnProtocols,
1224
- "emulation.tlsOptions.alpnProtocols",
1225
- SUPPORTED_ALPN_PROTOCOLS
1226
- );
1227
- if (alpnProtocols !== void 0) {
1228
- normalized.alpnProtocols = alpnProtocols;
1229
- }
1230
- const alpsProtocols = normalizeProtocolList(
1231
- options.alpsProtocols,
1232
- "emulation.tlsOptions.alpsProtocols",
1233
- SUPPORTED_ALPS_PROTOCOLS
1234
- );
1235
- if (alpsProtocols !== void 0) {
1236
- normalized.alpsProtocols = alpsProtocols;
1237
- }
1238
- const minTlsVersion = normalizeTlsVersion(options.minTlsVersion, "emulation.tlsOptions.minTlsVersion");
1239
- if (minTlsVersion !== void 0) {
1240
- normalized.minTlsVersion = minTlsVersion;
1241
- }
1242
- const maxTlsVersion = normalizeTlsVersion(options.maxTlsVersion, "emulation.tlsOptions.maxTlsVersion");
1243
- if (maxTlsVersion !== void 0) {
1244
- normalized.maxTlsVersion = maxTlsVersion;
1245
- }
1246
- if (options.alpsUseNewCodepoint !== void 0) {
1247
- normalized.alpsUseNewCodepoint = options.alpsUseNewCodepoint;
1248
- }
1249
- if (options.sessionTicket !== void 0) {
1250
- normalized.sessionTicket = options.sessionTicket;
1251
- }
1252
- if (options.preSharedKey !== void 0) {
1253
- normalized.preSharedKey = options.preSharedKey;
1254
- }
1255
- if (options.enableEchGrease !== void 0) {
1256
- normalized.enableEchGrease = options.enableEchGrease;
1257
- }
1258
- if (options.permuteExtensions !== void 0) {
1259
- normalized.permuteExtensions = options.permuteExtensions;
1260
- }
1261
- if (options.greaseEnabled !== void 0) {
1262
- normalized.greaseEnabled = options.greaseEnabled;
1263
- }
1264
- if (options.enableOcspStapling !== void 0) {
1265
- normalized.enableOcspStapling = options.enableOcspStapling;
1266
- }
1267
- if (options.enableSignedCertTimestamps !== void 0) {
1268
- normalized.enableSignedCertTimestamps = options.enableSignedCertTimestamps;
1269
- }
1270
- if (options.pskSkipSessionTicket !== void 0) {
1271
- normalized.pskSkipSessionTicket = options.pskSkipSessionTicket;
1272
- }
1273
- if (options.pskDheKe !== void 0) {
1274
- normalized.pskDheKe = options.pskDheKe;
1275
- }
1276
- if (options.renegotiation !== void 0) {
1277
- normalized.renegotiation = options.renegotiation;
1278
- }
1279
- if (options.aesHwOverride !== void 0) {
1280
- normalized.aesHwOverride = options.aesHwOverride;
1281
- }
1282
- if (options.preserveTls13CipherList !== void 0) {
1283
- normalized.preserveTls13CipherList = options.preserveTls13CipherList;
1284
- }
1285
- if (options.randomAesHwOverride !== void 0) {
1286
- normalized.randomAesHwOverride = options.randomAesHwOverride;
1287
- }
1288
- if (options.delegatedCredentials !== void 0) {
1289
- normalized.delegatedCredentials = options.delegatedCredentials;
1290
- }
1291
- if (options.curvesList !== void 0) {
1292
- normalized.curvesList = options.curvesList;
1293
- }
1294
- if (options.cipherList !== void 0) {
1295
- normalized.cipherList = options.cipherList;
1296
- }
1297
- if (options.sigalgsList !== void 0) {
1298
- normalized.sigalgsList = options.sigalgsList;
1299
- }
1300
- if (options.recordSizeLimit !== void 0) {
1301
- validateIntegerInRange(options.recordSizeLimit, 0, 65535, "emulation.tlsOptions.recordSizeLimit");
1302
- normalized.recordSizeLimit = options.recordSizeLimit;
1303
- }
1304
- if (options.keySharesLimit !== void 0) {
1305
- validateIntegerInRange(options.keySharesLimit, 0, 255, "emulation.tlsOptions.keySharesLimit");
1306
- normalized.keySharesLimit = options.keySharesLimit;
1307
- }
1308
- if (options.certificateCompressionAlgorithms !== void 0) {
1309
- if (!Array.isArray(options.certificateCompressionAlgorithms)) {
1310
- throw new RequestError("emulation.tlsOptions.certificateCompressionAlgorithms must be an array");
1311
- }
1312
- const algorithms = [];
1313
- const seen = /* @__PURE__ */ new Set();
1314
- for (const algorithm of options.certificateCompressionAlgorithms) {
1315
- if (!SUPPORTED_CERTIFICATE_COMPRESSION_ALGORITHMS.has(algorithm)) {
1316
- throw new RequestError(
1317
- "emulation.tlsOptions.certificateCompressionAlgorithms values must be one of: zlib, brotli, zstd"
1318
- );
1319
- }
1320
- if (seen.has(algorithm)) {
1321
- throw new RequestError(`Duplicate emulation.tlsOptions.certificateCompressionAlgorithms entry: ${algorithm}`);
1322
- }
1323
- seen.add(algorithm);
1324
- algorithms.push(algorithm);
1325
- }
1326
- normalized.certificateCompressionAlgorithms = algorithms;
1327
- }
1328
- if (options.extensionPermutation !== void 0) {
1329
- if (!Array.isArray(options.extensionPermutation)) {
1330
- throw new RequestError("emulation.tlsOptions.extensionPermutation must be an array");
1331
- }
1332
- const permutation = [];
1333
- const seen = /* @__PURE__ */ new Set();
1334
- for (const extensionId of options.extensionPermutation) {
1335
- validateIntegerInRange(extensionId, 0, 65535, "emulation.tlsOptions.extensionPermutation");
1336
- if (seen.has(extensionId)) {
1337
- throw new RequestError(`Duplicate emulation.tlsOptions.extensionPermutation entry: ${extensionId}`);
1338
- }
1339
- seen.add(extensionId);
1340
- permutation.push(extensionId);
1341
- }
1342
- normalized.extensionPermutation = permutation;
1343
- }
1344
- return isNonEmpty(normalized) ? normalized : void 0;
1049
+ if (options === void 0) return;
1050
+ const normalized = {};
1051
+ const alpnProtocols = normalizeProtocolList(options.alpnProtocols, "emulation.tlsOptions.alpnProtocols", SUPPORTED_ALPN_PROTOCOLS);
1052
+ if (alpnProtocols !== void 0) normalized.alpnProtocols = alpnProtocols;
1053
+ const alpsProtocols = normalizeProtocolList(options.alpsProtocols, "emulation.tlsOptions.alpsProtocols", SUPPORTED_ALPS_PROTOCOLS);
1054
+ if (alpsProtocols !== void 0) normalized.alpsProtocols = alpsProtocols;
1055
+ const minTlsVersion = normalizeTlsVersion(options.minTlsVersion, "emulation.tlsOptions.minTlsVersion");
1056
+ if (minTlsVersion !== void 0) normalized.minTlsVersion = minTlsVersion;
1057
+ const maxTlsVersion = normalizeTlsVersion(options.maxTlsVersion, "emulation.tlsOptions.maxTlsVersion");
1058
+ if (maxTlsVersion !== void 0) normalized.maxTlsVersion = maxTlsVersion;
1059
+ if (options.alpsUseNewCodepoint !== void 0) normalized.alpsUseNewCodepoint = options.alpsUseNewCodepoint;
1060
+ if (options.sessionTicket !== void 0) normalized.sessionTicket = options.sessionTicket;
1061
+ if (options.preSharedKey !== void 0) normalized.preSharedKey = options.preSharedKey;
1062
+ if (options.enableEchGrease !== void 0) normalized.enableEchGrease = options.enableEchGrease;
1063
+ if (options.permuteExtensions !== void 0) normalized.permuteExtensions = options.permuteExtensions;
1064
+ if (options.greaseEnabled !== void 0) normalized.greaseEnabled = options.greaseEnabled;
1065
+ if (options.enableOcspStapling !== void 0) normalized.enableOcspStapling = options.enableOcspStapling;
1066
+ if (options.enableSignedCertTimestamps !== void 0) normalized.enableSignedCertTimestamps = options.enableSignedCertTimestamps;
1067
+ if (options.pskSkipSessionTicket !== void 0) normalized.pskSkipSessionTicket = options.pskSkipSessionTicket;
1068
+ if (options.pskDheKe !== void 0) normalized.pskDheKe = options.pskDheKe;
1069
+ if (options.renegotiation !== void 0) normalized.renegotiation = options.renegotiation;
1070
+ if (options.aesHwOverride !== void 0) normalized.aesHwOverride = options.aesHwOverride;
1071
+ if (options.preserveTls13CipherList !== void 0) normalized.preserveTls13CipherList = options.preserveTls13CipherList;
1072
+ if (options.randomAesHwOverride !== void 0) normalized.randomAesHwOverride = options.randomAesHwOverride;
1073
+ if (options.delegatedCredentials !== void 0) normalized.delegatedCredentials = options.delegatedCredentials;
1074
+ if (options.curvesList !== void 0) normalized.curvesList = options.curvesList;
1075
+ if (options.cipherList !== void 0) normalized.cipherList = options.cipherList;
1076
+ if (options.sigalgsList !== void 0) normalized.sigalgsList = options.sigalgsList;
1077
+ if (options.recordSizeLimit !== void 0) {
1078
+ validateIntegerInRange(options.recordSizeLimit, 0, 65535, "emulation.tlsOptions.recordSizeLimit");
1079
+ normalized.recordSizeLimit = options.recordSizeLimit;
1080
+ }
1081
+ if (options.keySharesLimit !== void 0) {
1082
+ validateIntegerInRange(options.keySharesLimit, 0, 255, "emulation.tlsOptions.keySharesLimit");
1083
+ normalized.keySharesLimit = options.keySharesLimit;
1084
+ }
1085
+ if (options.certificateCompressionAlgorithms !== void 0) {
1086
+ if (!Array.isArray(options.certificateCompressionAlgorithms)) throw new RequestError("emulation.tlsOptions.certificateCompressionAlgorithms must be an array");
1087
+ const algorithms = [];
1088
+ const seen = /* @__PURE__ */ new Set();
1089
+ for (const algorithm of options.certificateCompressionAlgorithms) {
1090
+ if (!SUPPORTED_CERTIFICATE_COMPRESSION_ALGORITHMS.has(algorithm)) throw new RequestError("emulation.tlsOptions.certificateCompressionAlgorithms values must be one of: zlib, brotli, zstd");
1091
+ if (seen.has(algorithm)) throw new RequestError(`Duplicate emulation.tlsOptions.certificateCompressionAlgorithms entry: ${algorithm}`);
1092
+ seen.add(algorithm);
1093
+ algorithms.push(algorithm);
1094
+ }
1095
+ normalized.certificateCompressionAlgorithms = algorithms;
1096
+ }
1097
+ if (options.extensionPermutation !== void 0) {
1098
+ if (!Array.isArray(options.extensionPermutation)) throw new RequestError("emulation.tlsOptions.extensionPermutation must be an array");
1099
+ const permutation = [];
1100
+ const seen = /* @__PURE__ */ new Set();
1101
+ for (const extensionId of options.extensionPermutation) {
1102
+ validateIntegerInRange(extensionId, 0, 65535, "emulation.tlsOptions.extensionPermutation");
1103
+ if (seen.has(extensionId)) throw new RequestError(`Duplicate emulation.tlsOptions.extensionPermutation entry: ${extensionId}`);
1104
+ seen.add(extensionId);
1105
+ permutation.push(extensionId);
1106
+ }
1107
+ normalized.extensionPermutation = permutation;
1108
+ }
1109
+ return isNonEmpty(normalized) ? normalized : void 0;
1345
1110
  }
1346
1111
  function normalizeCustomHttp1Options(options) {
1347
- if (options === void 0) {
1348
- return void 0;
1349
- }
1350
- const normalized = {};
1351
- if (options.http09Responses !== void 0) {
1352
- normalized.http09Responses = options.http09Responses;
1353
- }
1354
- if (options.writev !== void 0) {
1355
- normalized.writev = options.writev;
1356
- }
1357
- if (options.ignoreInvalidHeadersInResponses !== void 0) {
1358
- normalized.ignoreInvalidHeadersInResponses = options.ignoreInvalidHeadersInResponses;
1359
- }
1360
- if (options.allowSpacesAfterHeaderNameInResponses !== void 0) {
1361
- normalized.allowSpacesAfterHeaderNameInResponses = options.allowSpacesAfterHeaderNameInResponses;
1362
- }
1363
- if (options.allowObsoleteMultilineHeadersInResponses !== void 0) {
1364
- normalized.allowObsoleteMultilineHeadersInResponses = options.allowObsoleteMultilineHeadersInResponses;
1365
- }
1366
- if (options.maxHeaders !== void 0) {
1367
- validateNonNegativeInteger(options.maxHeaders, "emulation.http1Options.maxHeaders");
1368
- normalized.maxHeaders = options.maxHeaders;
1369
- }
1370
- if (options.readBufExactSize !== void 0) {
1371
- validateNonNegativeInteger(options.readBufExactSize, "emulation.http1Options.readBufExactSize");
1372
- normalized.readBufExactSize = options.readBufExactSize;
1373
- }
1374
- if (options.maxBufSize !== void 0) {
1375
- validateNonNegativeInteger(options.maxBufSize, "emulation.http1Options.maxBufSize");
1376
- if (options.maxBufSize < 8192) {
1377
- throw new RequestError("emulation.http1Options.maxBufSize must be greater than or equal to 8192");
1378
- }
1379
- normalized.maxBufSize = options.maxBufSize;
1380
- }
1381
- if (normalized.readBufExactSize !== void 0 && normalized.maxBufSize !== void 0) {
1382
- throw new RequestError("emulation.http1Options.readBufExactSize and maxBufSize cannot both be set");
1383
- }
1384
- return isNonEmpty(normalized) ? normalized : void 0;
1112
+ if (options === void 0) return;
1113
+ const normalized = {};
1114
+ if (options.http09Responses !== void 0) normalized.http09Responses = options.http09Responses;
1115
+ if (options.writev !== void 0) normalized.writev = options.writev;
1116
+ if (options.ignoreInvalidHeadersInResponses !== void 0) normalized.ignoreInvalidHeadersInResponses = options.ignoreInvalidHeadersInResponses;
1117
+ if (options.allowSpacesAfterHeaderNameInResponses !== void 0) normalized.allowSpacesAfterHeaderNameInResponses = options.allowSpacesAfterHeaderNameInResponses;
1118
+ if (options.allowObsoleteMultilineHeadersInResponses !== void 0) normalized.allowObsoleteMultilineHeadersInResponses = options.allowObsoleteMultilineHeadersInResponses;
1119
+ if (options.maxHeaders !== void 0) {
1120
+ validateNonNegativeInteger(options.maxHeaders, "emulation.http1Options.maxHeaders");
1121
+ normalized.maxHeaders = options.maxHeaders;
1122
+ }
1123
+ if (options.readBufExactSize !== void 0) {
1124
+ validateNonNegativeInteger(options.readBufExactSize, "emulation.http1Options.readBufExactSize");
1125
+ normalized.readBufExactSize = options.readBufExactSize;
1126
+ }
1127
+ if (options.maxBufSize !== void 0) {
1128
+ validateNonNegativeInteger(options.maxBufSize, "emulation.http1Options.maxBufSize");
1129
+ if (options.maxBufSize < 8192) throw new RequestError("emulation.http1Options.maxBufSize must be greater than or equal to 8192");
1130
+ normalized.maxBufSize = options.maxBufSize;
1131
+ }
1132
+ if (normalized.readBufExactSize !== void 0 && normalized.maxBufSize !== void 0) throw new RequestError("emulation.http1Options.readBufExactSize and maxBufSize cannot both be set");
1133
+ return isNonEmpty(normalized) ? normalized : void 0;
1385
1134
  }
1386
1135
  function normalizeHttp2StreamDependency(dependency, label) {
1387
- if (!isPlainObject(dependency)) {
1388
- throw new RequestError(`${label} must be an object`);
1389
- }
1390
- validateIntegerInRange(dependency.dependencyId, 0, 2147483647, `${label}.dependencyId`);
1391
- validateIntegerInRange(dependency.weight, 0, 255, `${label}.weight`);
1392
- const normalized = {
1393
- dependencyId: dependency.dependencyId,
1394
- weight: dependency.weight
1395
- };
1396
- if (dependency.exclusive !== void 0) {
1397
- normalized.exclusive = dependency.exclusive;
1398
- }
1399
- return normalized;
1136
+ if (!isPlainObject(dependency)) throw new RequestError(`${label} must be an object`);
1137
+ validateIntegerInRange(dependency.dependencyId, 0, 2147483647, `${label}.dependencyId`);
1138
+ validateIntegerInRange(dependency.weight, 0, 255, `${label}.weight`);
1139
+ const normalized = {
1140
+ dependencyId: dependency.dependencyId,
1141
+ weight: dependency.weight
1142
+ };
1143
+ if (dependency.exclusive !== void 0) normalized.exclusive = dependency.exclusive;
1144
+ return normalized;
1400
1145
  }
1401
1146
  function normalizeCustomHttp2Options(options) {
1402
- if (options === void 0) {
1403
- return void 0;
1404
- }
1405
- const normalized = {};
1406
- if (options.adaptiveWindow !== void 0) {
1407
- normalized.adaptiveWindow = options.adaptiveWindow;
1408
- }
1409
- if (options.keepAliveWhileIdle !== void 0) {
1410
- normalized.keepAliveWhileIdle = options.keepAliveWhileIdle;
1411
- }
1412
- if (options.enablePush !== void 0) {
1413
- normalized.enablePush = options.enablePush;
1414
- }
1415
- if (options.enableConnectProtocol !== void 0) {
1416
- normalized.enableConnectProtocol = options.enableConnectProtocol;
1417
- }
1418
- if (options.noRfc7540Priorities !== void 0) {
1419
- normalized.noRfc7540Priorities = options.noRfc7540Priorities;
1420
- }
1421
- if (options.initialStreamId !== void 0) {
1422
- validateNonNegativeInteger(options.initialStreamId, "emulation.http2Options.initialStreamId");
1423
- normalized.initialStreamId = options.initialStreamId;
1424
- }
1425
- if (options.initialConnectionWindowSize !== void 0) {
1426
- validateNonNegativeInteger(
1427
- options.initialConnectionWindowSize,
1428
- "emulation.http2Options.initialConnectionWindowSize"
1429
- );
1430
- normalized.initialConnectionWindowSize = options.initialConnectionWindowSize;
1431
- }
1432
- if (options.initialWindowSize !== void 0) {
1433
- validateNonNegativeInteger(options.initialWindowSize, "emulation.http2Options.initialWindowSize");
1434
- normalized.initialWindowSize = options.initialWindowSize;
1435
- }
1436
- if (options.initialMaxSendStreams !== void 0) {
1437
- validateNonNegativeInteger(options.initialMaxSendStreams, "emulation.http2Options.initialMaxSendStreams");
1438
- normalized.initialMaxSendStreams = options.initialMaxSendStreams;
1439
- }
1440
- if (options.maxFrameSize !== void 0) {
1441
- validateNonNegativeInteger(options.maxFrameSize, "emulation.http2Options.maxFrameSize");
1442
- normalized.maxFrameSize = options.maxFrameSize;
1443
- }
1444
- if (options.keepAliveInterval !== void 0) {
1445
- validateNonNegativeInteger(options.keepAliveInterval, "emulation.http2Options.keepAliveInterval");
1446
- normalized.keepAliveInterval = options.keepAliveInterval;
1447
- }
1448
- if (options.keepAliveTimeout !== void 0) {
1449
- validateNonNegativeInteger(options.keepAliveTimeout, "emulation.http2Options.keepAliveTimeout");
1450
- normalized.keepAliveTimeout = options.keepAliveTimeout;
1451
- }
1452
- if (options.maxConcurrentResetStreams !== void 0) {
1453
- validateNonNegativeInteger(options.maxConcurrentResetStreams, "emulation.http2Options.maxConcurrentResetStreams");
1454
- normalized.maxConcurrentResetStreams = options.maxConcurrentResetStreams;
1455
- }
1456
- if (options.maxSendBufferSize !== void 0) {
1457
- validateNonNegativeInteger(options.maxSendBufferSize, "emulation.http2Options.maxSendBufferSize");
1458
- normalized.maxSendBufferSize = options.maxSendBufferSize;
1459
- }
1460
- if (options.maxConcurrentStreams !== void 0) {
1461
- validateNonNegativeInteger(options.maxConcurrentStreams, "emulation.http2Options.maxConcurrentStreams");
1462
- normalized.maxConcurrentStreams = options.maxConcurrentStreams;
1463
- }
1464
- if (options.maxHeaderListSize !== void 0) {
1465
- validateNonNegativeInteger(options.maxHeaderListSize, "emulation.http2Options.maxHeaderListSize");
1466
- normalized.maxHeaderListSize = options.maxHeaderListSize;
1467
- }
1468
- if (options.maxPendingAcceptResetStreams !== void 0) {
1469
- validateNonNegativeInteger(
1470
- options.maxPendingAcceptResetStreams,
1471
- "emulation.http2Options.maxPendingAcceptResetStreams"
1472
- );
1473
- normalized.maxPendingAcceptResetStreams = options.maxPendingAcceptResetStreams;
1474
- }
1475
- if (options.headerTableSize !== void 0) {
1476
- validateNonNegativeInteger(options.headerTableSize, "emulation.http2Options.headerTableSize");
1477
- normalized.headerTableSize = options.headerTableSize;
1478
- }
1479
- if (options.settingsOrder !== void 0) {
1480
- if (!Array.isArray(options.settingsOrder)) {
1481
- throw new RequestError("emulation.http2Options.settingsOrder must be an array");
1482
- }
1483
- const settingsOrder = [];
1484
- const seen = /* @__PURE__ */ new Set();
1485
- for (const settingId of options.settingsOrder) {
1486
- if (!HTTP2_SETTING_IDS.has(settingId)) {
1487
- throw new RequestError("emulation.http2Options.settingsOrder contains an unsupported setting id");
1488
- }
1489
- if (seen.has(settingId)) {
1490
- throw new RequestError(`Duplicate emulation.http2Options.settingsOrder entry: ${settingId}`);
1491
- }
1492
- seen.add(settingId);
1493
- settingsOrder.push(settingId);
1494
- }
1495
- normalized.settingsOrder = settingsOrder;
1496
- }
1497
- if (options.headersPseudoOrder !== void 0) {
1498
- if (!Array.isArray(options.headersPseudoOrder)) {
1499
- throw new RequestError("emulation.http2Options.headersPseudoOrder must be an array");
1500
- }
1501
- const headersPseudoOrder = [];
1502
- const seenPseudo = /* @__PURE__ */ new Set();
1503
- for (const pseudoId of options.headersPseudoOrder) {
1504
- if (!HTTP2_PSEUDO_HEADER_IDS.has(pseudoId)) {
1505
- throw new RequestError("emulation.http2Options.headersPseudoOrder contains an unsupported pseudo-header id");
1506
- }
1507
- if (seenPseudo.has(pseudoId)) {
1508
- throw new RequestError(`Duplicate emulation.http2Options.headersPseudoOrder entry: ${pseudoId}`);
1509
- }
1510
- seenPseudo.add(pseudoId);
1511
- headersPseudoOrder.push(pseudoId);
1512
- }
1513
- normalized.headersPseudoOrder = headersPseudoOrder;
1514
- }
1515
- if (options.headersStreamDependency !== void 0) {
1516
- normalized.headersStreamDependency = normalizeHttp2StreamDependency(
1517
- options.headersStreamDependency,
1518
- "emulation.http2Options.headersStreamDependency"
1519
- );
1520
- }
1521
- if (options.priorities !== void 0) {
1522
- if (!Array.isArray(options.priorities)) {
1523
- throw new RequestError("emulation.http2Options.priorities must be an array");
1524
- }
1525
- const priorities = [];
1526
- const seenStreamIds = /* @__PURE__ */ new Set();
1527
- for (const [index, priority] of options.priorities.entries()) {
1528
- if (!isPlainObject(priority)) {
1529
- throw new RequestError(`emulation.http2Options.priorities[${index}] must be an object`);
1530
- }
1531
- validatePositiveInteger(priority.streamId, `emulation.http2Options.priorities[${index}].streamId`);
1532
- if (seenStreamIds.has(priority.streamId)) {
1533
- throw new RequestError(`Duplicate emulation.http2Options.priorities streamId: ${priority.streamId}`);
1534
- }
1535
- seenStreamIds.add(priority.streamId);
1536
- priorities.push({
1537
- streamId: priority.streamId,
1538
- dependency: normalizeHttp2StreamDependency(
1539
- priority.dependency,
1540
- `emulation.http2Options.priorities[${index}].dependency`
1541
- )
1542
- });
1543
- }
1544
- normalized.priorities = priorities;
1545
- }
1546
- if (options.experimentalSettings !== void 0) {
1547
- if (!Array.isArray(options.experimentalSettings)) {
1548
- throw new RequestError("emulation.http2Options.experimentalSettings must be an array");
1549
- }
1550
- const experimentalSettings = [];
1551
- const seenIds = /* @__PURE__ */ new Set();
1552
- for (const [index, setting] of options.experimentalSettings.entries()) {
1553
- if (!isPlainObject(setting)) {
1554
- throw new RequestError(`emulation.http2Options.experimentalSettings[${index}] must be an object`);
1555
- }
1556
- validateIntegerInRange(
1557
- setting.id,
1558
- 1,
1559
- MAX_HTTP2_EXPERIMENTAL_SETTING_ID,
1560
- `emulation.http2Options.experimentalSettings[${index}].id`
1561
- );
1562
- if (STANDARD_HTTP2_SETTING_ID_VALUES.has(setting.id)) {
1563
- throw new RequestError(
1564
- `emulation.http2Options.experimentalSettings[${index}].id must not be a standard HTTP/2 setting id`
1565
- );
1566
- }
1567
- if (seenIds.has(setting.id)) {
1568
- throw new RequestError(`Duplicate emulation.http2Options.experimentalSettings id: ${setting.id}`);
1569
- }
1570
- seenIds.add(setting.id);
1571
- validateIntegerInRange(
1572
- setting.value,
1573
- 0,
1574
- 4294967295,
1575
- `emulation.http2Options.experimentalSettings[${index}].value`
1576
- );
1577
- experimentalSettings.push({
1578
- id: setting.id,
1579
- value: setting.value
1580
- });
1581
- }
1582
- normalized.experimentalSettings = experimentalSettings;
1583
- }
1584
- return isNonEmpty(normalized) ? normalized : void 0;
1147
+ if (options === void 0) return;
1148
+ const normalized = {};
1149
+ if (options.adaptiveWindow !== void 0) normalized.adaptiveWindow = options.adaptiveWindow;
1150
+ if (options.keepAliveWhileIdle !== void 0) normalized.keepAliveWhileIdle = options.keepAliveWhileIdle;
1151
+ if (options.enablePush !== void 0) normalized.enablePush = options.enablePush;
1152
+ if (options.enableConnectProtocol !== void 0) normalized.enableConnectProtocol = options.enableConnectProtocol;
1153
+ if (options.noRfc7540Priorities !== void 0) normalized.noRfc7540Priorities = options.noRfc7540Priorities;
1154
+ if (options.initialStreamId !== void 0) {
1155
+ validateNonNegativeInteger(options.initialStreamId, "emulation.http2Options.initialStreamId");
1156
+ normalized.initialStreamId = options.initialStreamId;
1157
+ }
1158
+ if (options.initialConnectionWindowSize !== void 0) {
1159
+ validateNonNegativeInteger(options.initialConnectionWindowSize, "emulation.http2Options.initialConnectionWindowSize");
1160
+ normalized.initialConnectionWindowSize = options.initialConnectionWindowSize;
1161
+ }
1162
+ if (options.initialWindowSize !== void 0) {
1163
+ validateNonNegativeInteger(options.initialWindowSize, "emulation.http2Options.initialWindowSize");
1164
+ normalized.initialWindowSize = options.initialWindowSize;
1165
+ }
1166
+ if (options.initialMaxSendStreams !== void 0) {
1167
+ validateNonNegativeInteger(options.initialMaxSendStreams, "emulation.http2Options.initialMaxSendStreams");
1168
+ normalized.initialMaxSendStreams = options.initialMaxSendStreams;
1169
+ }
1170
+ if (options.maxFrameSize !== void 0) {
1171
+ validateNonNegativeInteger(options.maxFrameSize, "emulation.http2Options.maxFrameSize");
1172
+ normalized.maxFrameSize = options.maxFrameSize;
1173
+ }
1174
+ if (options.keepAliveInterval !== void 0) {
1175
+ validateNonNegativeInteger(options.keepAliveInterval, "emulation.http2Options.keepAliveInterval");
1176
+ normalized.keepAliveInterval = options.keepAliveInterval;
1177
+ }
1178
+ if (options.keepAliveTimeout !== void 0) {
1179
+ validateNonNegativeInteger(options.keepAliveTimeout, "emulation.http2Options.keepAliveTimeout");
1180
+ normalized.keepAliveTimeout = options.keepAliveTimeout;
1181
+ }
1182
+ if (options.maxConcurrentResetStreams !== void 0) {
1183
+ validateNonNegativeInteger(options.maxConcurrentResetStreams, "emulation.http2Options.maxConcurrentResetStreams");
1184
+ normalized.maxConcurrentResetStreams = options.maxConcurrentResetStreams;
1185
+ }
1186
+ if (options.maxSendBufferSize !== void 0) {
1187
+ validateNonNegativeInteger(options.maxSendBufferSize, "emulation.http2Options.maxSendBufferSize");
1188
+ normalized.maxSendBufferSize = options.maxSendBufferSize;
1189
+ }
1190
+ if (options.maxConcurrentStreams !== void 0) {
1191
+ validateNonNegativeInteger(options.maxConcurrentStreams, "emulation.http2Options.maxConcurrentStreams");
1192
+ normalized.maxConcurrentStreams = options.maxConcurrentStreams;
1193
+ }
1194
+ if (options.maxHeaderListSize !== void 0) {
1195
+ validateNonNegativeInteger(options.maxHeaderListSize, "emulation.http2Options.maxHeaderListSize");
1196
+ normalized.maxHeaderListSize = options.maxHeaderListSize;
1197
+ }
1198
+ if (options.maxPendingAcceptResetStreams !== void 0) {
1199
+ validateNonNegativeInteger(options.maxPendingAcceptResetStreams, "emulation.http2Options.maxPendingAcceptResetStreams");
1200
+ normalized.maxPendingAcceptResetStreams = options.maxPendingAcceptResetStreams;
1201
+ }
1202
+ if (options.headerTableSize !== void 0) {
1203
+ validateNonNegativeInteger(options.headerTableSize, "emulation.http2Options.headerTableSize");
1204
+ normalized.headerTableSize = options.headerTableSize;
1205
+ }
1206
+ if (options.settingsOrder !== void 0) {
1207
+ if (!Array.isArray(options.settingsOrder)) throw new RequestError("emulation.http2Options.settingsOrder must be an array");
1208
+ const settingsOrder = [];
1209
+ const seen = /* @__PURE__ */ new Set();
1210
+ for (const settingId of options.settingsOrder) {
1211
+ if (!HTTP2_SETTING_IDS.has(settingId)) throw new RequestError("emulation.http2Options.settingsOrder contains an unsupported setting id");
1212
+ if (seen.has(settingId)) throw new RequestError(`Duplicate emulation.http2Options.settingsOrder entry: ${settingId}`);
1213
+ seen.add(settingId);
1214
+ settingsOrder.push(settingId);
1215
+ }
1216
+ normalized.settingsOrder = settingsOrder;
1217
+ }
1218
+ if (options.headersPseudoOrder !== void 0) {
1219
+ if (!Array.isArray(options.headersPseudoOrder)) throw new RequestError("emulation.http2Options.headersPseudoOrder must be an array");
1220
+ const headersPseudoOrder = [];
1221
+ const seenPseudo = /* @__PURE__ */ new Set();
1222
+ for (const pseudoId of options.headersPseudoOrder) {
1223
+ if (!HTTP2_PSEUDO_HEADER_IDS.has(pseudoId)) throw new RequestError("emulation.http2Options.headersPseudoOrder contains an unsupported pseudo-header id");
1224
+ if (seenPseudo.has(pseudoId)) throw new RequestError(`Duplicate emulation.http2Options.headersPseudoOrder entry: ${pseudoId}`);
1225
+ seenPseudo.add(pseudoId);
1226
+ headersPseudoOrder.push(pseudoId);
1227
+ }
1228
+ normalized.headersPseudoOrder = headersPseudoOrder;
1229
+ }
1230
+ if (options.headersStreamDependency !== void 0) normalized.headersStreamDependency = normalizeHttp2StreamDependency(options.headersStreamDependency, "emulation.http2Options.headersStreamDependency");
1231
+ if (options.priorities !== void 0) {
1232
+ if (!Array.isArray(options.priorities)) throw new RequestError("emulation.http2Options.priorities must be an array");
1233
+ const priorities = [];
1234
+ const seenStreamIds = /* @__PURE__ */ new Set();
1235
+ for (const [index, priority] of options.priorities.entries()) {
1236
+ if (!isPlainObject(priority)) throw new RequestError(`emulation.http2Options.priorities[${index}] must be an object`);
1237
+ validatePositiveInteger(priority.streamId, `emulation.http2Options.priorities[${index}].streamId`);
1238
+ if (seenStreamIds.has(priority.streamId)) throw new RequestError(`Duplicate emulation.http2Options.priorities streamId: ${priority.streamId}`);
1239
+ seenStreamIds.add(priority.streamId);
1240
+ priorities.push({
1241
+ streamId: priority.streamId,
1242
+ dependency: normalizeHttp2StreamDependency(priority.dependency, `emulation.http2Options.priorities[${index}].dependency`)
1243
+ });
1244
+ }
1245
+ normalized.priorities = priorities;
1246
+ }
1247
+ if (options.experimentalSettings !== void 0) {
1248
+ if (!Array.isArray(options.experimentalSettings)) throw new RequestError("emulation.http2Options.experimentalSettings must be an array");
1249
+ const experimentalSettings = [];
1250
+ const seenIds = /* @__PURE__ */ new Set();
1251
+ for (const [index, setting] of options.experimentalSettings.entries()) {
1252
+ if (!isPlainObject(setting)) throw new RequestError(`emulation.http2Options.experimentalSettings[${index}] must be an object`);
1253
+ validateIntegerInRange(setting.id, 1, MAX_HTTP2_EXPERIMENTAL_SETTING_ID, `emulation.http2Options.experimentalSettings[${index}].id`);
1254
+ if (STANDARD_HTTP2_SETTING_ID_VALUES.has(setting.id)) throw new RequestError(`emulation.http2Options.experimentalSettings[${index}].id must not be a standard HTTP/2 setting id`);
1255
+ if (seenIds.has(setting.id)) throw new RequestError(`Duplicate emulation.http2Options.experimentalSettings id: ${setting.id}`);
1256
+ seenIds.add(setting.id);
1257
+ validateIntegerInRange(setting.value, 0, 4294967295, `emulation.http2Options.experimentalSettings[${index}].value`);
1258
+ experimentalSettings.push({
1259
+ id: setting.id,
1260
+ value: setting.value
1261
+ });
1262
+ }
1263
+ normalized.experimentalSettings = experimentalSettings;
1264
+ }
1265
+ return isNonEmpty(normalized) ? normalized : void 0;
1585
1266
  }
1586
1267
  function normalizeCustomEmulationOptions(emulation, allowEmpty) {
1587
- if (emulation === void 0) {
1588
- return void 0;
1589
- }
1590
- if (!isPlainObject(emulation)) {
1591
- throw new RequestError("emulation must be an object");
1592
- }
1593
- const source = emulation;
1594
- const normalized = {};
1595
- const tlsOptions = normalizeCustomTlsOptions(source.tlsOptions);
1596
- if (tlsOptions !== void 0) {
1597
- normalized.tlsOptions = tlsOptions;
1598
- }
1599
- const http1Options = normalizeCustomHttp1Options(source.http1Options);
1600
- if (http1Options !== void 0) {
1601
- normalized.http1Options = http1Options;
1602
- }
1603
- const http2Options = normalizeCustomHttp2Options(source.http2Options);
1604
- if (http2Options !== void 0) {
1605
- normalized.http2Options = http2Options;
1606
- }
1607
- if (source.headers !== void 0) {
1608
- const headers = headersToTuples(source.headers);
1609
- if (headers.length > 0) {
1610
- normalized.headers = headers;
1611
- }
1612
- }
1613
- const origHeaders = normalizeOrigHeaders(source.origHeaders);
1614
- if (origHeaders !== void 0) {
1615
- normalized.origHeaders = origHeaders;
1616
- }
1617
- if (!allowEmpty && !isNonEmpty(normalized)) {
1618
- throw new RequestError(
1619
- "Standalone custom emulation requires at least one of tlsOptions, http1Options, http2Options, headers, or origHeaders"
1620
- );
1621
- }
1622
- return isNonEmpty(normalized) ? normalized : void 0;
1268
+ if (emulation === void 0) return;
1269
+ if (!isPlainObject(emulation)) throw new RequestError("emulation must be an object");
1270
+ const source = emulation;
1271
+ const normalized = {};
1272
+ const tlsOptions = normalizeCustomTlsOptions(source.tlsOptions);
1273
+ if (tlsOptions !== void 0) normalized.tlsOptions = tlsOptions;
1274
+ const http1Options = normalizeCustomHttp1Options(source.http1Options);
1275
+ if (http1Options !== void 0) normalized.http1Options = http1Options;
1276
+ const http2Options = normalizeCustomHttp2Options(source.http2Options);
1277
+ if (http2Options !== void 0) normalized.http2Options = http2Options;
1278
+ if (source.headers !== void 0) {
1279
+ const headers = headersToTuples(source.headers);
1280
+ if (headers.length > 0) normalized.headers = headers;
1281
+ }
1282
+ const origHeaders = normalizeOrigHeaders(source.origHeaders);
1283
+ if (origHeaders !== void 0) normalized.origHeaders = origHeaders;
1284
+ if (!allowEmpty && !isNonEmpty(normalized)) throw new RequestError("Standalone custom emulation requires at least one of tlsOptions, http1Options, http2Options, headers, or origHeaders");
1285
+ return isNonEmpty(normalized) ? normalized : void 0;
1623
1286
  }
1624
1287
  function serializeCustomEmulationOptions(emulation, allowEmpty) {
1625
- const normalized = normalizeCustomEmulationOptions(emulation, allowEmpty);
1626
- return normalized ? JSON.stringify(normalized) : void 0;
1288
+ const normalized = normalizeCustomEmulationOptions(emulation, allowEmpty);
1289
+ return normalized ? JSON.stringify(normalized) : void 0;
1627
1290
  }
1628
1291
  function resolveEmulationMode(browser, os, emulation) {
1629
- if (browser !== void 0) {
1630
- validateBrowserProfile(browser);
1631
- if (os !== void 0) {
1632
- validateOperatingSystem(os);
1633
- }
1634
- const emulationJson = serializeCustomEmulationOptions(emulation, true);
1635
- return {
1636
- kind: "preset",
1637
- browser,
1638
- os: os ?? DEFAULT_OS,
1639
- ...emulationJson !== void 0 && { emulationJson }
1640
- };
1641
- }
1642
- if (os !== void 0) {
1643
- validateOperatingSystem(os);
1644
- const emulationJson = serializeCustomEmulationOptions(emulation, true);
1645
- return {
1646
- kind: "preset",
1647
- browser: DEFAULT_BROWSER,
1648
- os,
1649
- ...emulationJson !== void 0 && { emulationJson }
1650
- };
1651
- }
1652
- if (emulation !== void 0) {
1653
- const emulationJson = serializeCustomEmulationOptions(emulation, false);
1654
- if (emulationJson === void 0) {
1655
- throw new RequestError(
1656
- "Standalone custom emulation requires at least one of tlsOptions, http1Options, http2Options, headers, or origHeaders"
1657
- );
1658
- }
1659
- return { kind: "custom", emulationJson };
1660
- }
1661
- return {
1662
- kind: "preset",
1663
- browser: DEFAULT_BROWSER,
1664
- os: DEFAULT_OS
1665
- };
1292
+ if (browser !== void 0) {
1293
+ validateBrowserProfile(browser);
1294
+ if (os !== void 0) validateOperatingSystem(os);
1295
+ const emulationJson = serializeCustomEmulationOptions(emulation, true);
1296
+ return {
1297
+ kind: "preset",
1298
+ browser,
1299
+ os: os ?? DEFAULT_OS,
1300
+ ...emulationJson !== void 0 && { emulationJson }
1301
+ };
1302
+ }
1303
+ if (os !== void 0) {
1304
+ validateOperatingSystem(os);
1305
+ const emulationJson = serializeCustomEmulationOptions(emulation, true);
1306
+ return {
1307
+ kind: "preset",
1308
+ browser: DEFAULT_BROWSER,
1309
+ os,
1310
+ ...emulationJson !== void 0 && { emulationJson }
1311
+ };
1312
+ }
1313
+ if (emulation !== void 0) {
1314
+ const emulationJson = serializeCustomEmulationOptions(emulation, false);
1315
+ if (emulationJson === void 0) throw new RequestError("Standalone custom emulation requires at least one of tlsOptions, http1Options, http2Options, headers, or origHeaders");
1316
+ return {
1317
+ kind: "custom",
1318
+ emulationJson
1319
+ };
1320
+ }
1321
+ return {
1322
+ kind: "preset",
1323
+ browser: DEFAULT_BROWSER,
1324
+ os: DEFAULT_OS
1325
+ };
1666
1326
  }
1667
1327
  function applyNativeEmulationMode(target, mode) {
1668
- if (mode.kind === "custom") {
1669
- target.emulationJson = mode.emulationJson;
1670
- return;
1671
- }
1672
- target.browser = mode.browser;
1673
- target.os = mode.os;
1674
- if (mode.emulationJson !== void 0) {
1675
- target.emulationJson = mode.emulationJson;
1676
- }
1328
+ if (mode.kind === "custom") {
1329
+ target.emulationJson = mode.emulationJson;
1330
+ return;
1331
+ }
1332
+ target.browser = mode.browser;
1333
+ target.os = mode.os;
1334
+ if (mode.emulationJson !== void 0) target.emulationJson = mode.emulationJson;
1677
1335
  }
1678
1336
  async function dispatchRequest(options, requestUrl, signal) {
1679
- if (!signal) {
1680
- const requestId2 = generateRequestId();
1681
- let payload2;
1682
- try {
1683
- payload2 = await nativeBinding.request(options, requestId2, false);
1684
- } catch (error) {
1685
- if (error instanceof RequestError) {
1686
- throw error;
1687
- }
1688
- throw new RequestError(String(error));
1689
- }
1690
- return new Response(payload2, requestUrl);
1691
- }
1692
- const requestId = generateRequestId();
1693
- const cancelNative = () => {
1694
- try {
1695
- nativeBinding.cancelRequest(requestId);
1696
- } catch {
1697
- }
1698
- };
1699
- const abortHandler = setupAbort(signal, cancelNative);
1700
- const pending = Promise.race([nativeBinding.request(options, requestId, true), abortHandler.promise]);
1701
- let payload;
1702
- try {
1703
- payload = await pending;
1704
- } catch (error) {
1705
- if (isAbortError(error)) {
1706
- throw error;
1707
- }
1708
- if (error instanceof RequestError) {
1709
- throw error;
1710
- }
1711
- throw new RequestError(String(error));
1712
- } finally {
1713
- abortHandler.cleanup();
1714
- }
1715
- return new Response(payload, requestUrl);
1716
- }
1337
+ if (!signal) {
1338
+ const requestId = generateRequestId();
1339
+ let payload;
1340
+ try {
1341
+ payload = await nativeBinding.request(options, requestId, false);
1342
+ } catch (error) {
1343
+ if (error instanceof RequestError) throw error;
1344
+ throw new RequestError(String(error));
1345
+ }
1346
+ return new Response(payload, requestUrl);
1347
+ }
1348
+ const requestId = generateRequestId();
1349
+ const cancelNative = () => {
1350
+ try {
1351
+ nativeBinding.cancelRequest(requestId);
1352
+ } catch {}
1353
+ };
1354
+ const abortHandler = setupAbort(signal, cancelNative);
1355
+ const pending = Promise.race([nativeBinding.request(options, requestId, true), abortHandler.promise]);
1356
+ let payload;
1357
+ try {
1358
+ payload = await pending;
1359
+ } catch (error) {
1360
+ if (isAbortError(error)) throw error;
1361
+ if (error instanceof RequestError) throw error;
1362
+ throw new RequestError(String(error));
1363
+ } finally {
1364
+ abortHandler.cleanup();
1365
+ }
1366
+ return new Response(payload, requestUrl);
1367
+ }
1368
+ /**
1369
+ * Fetch-compatible entry point that adds browser impersonation controls.
1370
+ *
1371
+ * **Important:** The default fetch path is isolated and non-persistent by design.
1372
+ * Each call uses an isolated request context, so cookies are not shared across calls.
1373
+ * Connection and TLS reuse behavior is handled by the native layer.
1374
+ *
1375
+ * **Use {@link createSession} or {@link withSession} if you need:**
1376
+ * - Cookie persistence across requests
1377
+ * - Shared session defaults across requests
1378
+ * - A single session context for multi-step flows
1379
+ *
1380
+ * **Concurrency:** The core is unthrottled by design. Callers are expected to implement
1381
+ * their own concurrency control (e.g., p-limit) if needed. Built-in throttling would
1382
+ * reduce performance for high-throughput workloads.
1383
+ *
1384
+ * @param input - Request URL (string or URL) or a Request object
1385
+ * @param init - Fetch-compatible init options
1386
+ *
1387
+ * @example
1388
+ * ```typescript
1389
+ * // Isolated request (no state persistence)
1390
+ * const response = await fetch('https://example.com');
1391
+ *
1392
+ * // For persistent cookies and connection reuse, use a session:
1393
+ * await withSession(async (session) => {
1394
+ * await session.fetch('https://example.com/login', { method: 'POST', body: loginData });
1395
+ * await session.fetch('https://example.com/protected'); // Cookies from login are sent
1396
+ * });
1397
+ * ```
1398
+ */
1717
1399
  async function fetch(input, init) {
1718
- const resolved = await resolveFetchArgs(input, init);
1719
- const url = resolved.url;
1720
- const config = resolved.init;
1721
- const sessionContext = resolveSessionContext(config);
1722
- const sessionDefaults = sessionContext.defaults;
1723
- validateRedirectMode(config.redirect);
1724
- if (config.timeout !== void 0) {
1725
- validateTimeout(config.timeout);
1726
- }
1727
- const method = ensureMethod(config.method);
1728
- const serializedBody = await serializeBody(config.body ?? null);
1729
- const body = serializedBody.body;
1730
- ensureBodyAllowed(method, body);
1731
- let headerTuples = mergeHeaderTuples(sessionDefaults?.defaultHeaders, config.headers);
1732
- if (serializedBody.contentType && !hasHeaderName(headerTuples, "content-type")) {
1733
- if (!headerTuples) {
1734
- headerTuples = [];
1735
- }
1736
- headerTuples.push(["Content-Type", serializedBody.contentType]);
1737
- }
1738
- const transport = resolveTransportContext(config, sessionDefaults);
1739
- const timeout = config.timeout ?? sessionDefaults?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS;
1740
- const requestOptions = {
1741
- url,
1742
- method,
1743
- sessionId: sessionContext.sessionId,
1744
- ephemeral: sessionContext.dropAfterRequest
1745
- };
1746
- if (body !== void 0) {
1747
- requestOptions.body = body;
1748
- }
1749
- if (transport.transportId) {
1750
- requestOptions.transportId = transport.transportId;
1751
- } else {
1752
- if (transport.mode !== void 0) {
1753
- applyNativeEmulationMode(requestOptions, transport.mode);
1754
- }
1755
- if (transport.proxy !== void 0) {
1756
- requestOptions.proxy = transport.proxy;
1757
- }
1758
- if (transport.insecure !== void 0) {
1759
- requestOptions.insecure = transport.insecure;
1760
- }
1761
- }
1762
- requestOptions.timeout = timeout;
1763
- if (config.redirect !== void 0) {
1764
- requestOptions.redirect = config.redirect;
1765
- }
1766
- if (config.disableDefaultHeaders !== void 0) {
1767
- requestOptions.disableDefaultHeaders = config.disableDefaultHeaders;
1768
- }
1769
- if (config.compress !== void 0) {
1770
- requestOptions.compress = config.compress;
1771
- }
1772
- if (headerTuples && headerTuples.length > 0) {
1773
- requestOptions.headers = headerTuples;
1774
- }
1775
- return dispatchRequest(requestOptions, url, config.signal ?? null);
1400
+ const resolved = await resolveFetchArgs(input, init);
1401
+ const url = resolved.url;
1402
+ const config = resolved.init;
1403
+ const sessionContext = resolveSessionContext(config);
1404
+ const sessionDefaults = sessionContext.defaults;
1405
+ validateRedirectMode(config.redirect);
1406
+ if (config.timeout !== void 0) validateTimeout(config.timeout);
1407
+ validateTrustStore(config.trustStore);
1408
+ const method = ensureMethod(config.method);
1409
+ const serializedBody = await serializeBody(config.body ?? null);
1410
+ const body = serializedBody.body;
1411
+ ensureBodyAllowed(method, body);
1412
+ let headerTuples = mergeHeaderTuples(sessionDefaults?.defaultHeaders, config.headers);
1413
+ if (serializedBody.contentType && !hasHeaderName(headerTuples, "content-type")) {
1414
+ if (!headerTuples) headerTuples = [];
1415
+ headerTuples.push(["Content-Type", serializedBody.contentType]);
1416
+ }
1417
+ const transport = resolveTransportContext(config, sessionDefaults);
1418
+ const timeout = config.timeout ?? sessionDefaults?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS;
1419
+ const requestOptions = {
1420
+ url,
1421
+ method,
1422
+ sessionId: sessionContext.sessionId,
1423
+ ephemeral: sessionContext.dropAfterRequest
1424
+ };
1425
+ if (body !== void 0) requestOptions.body = body;
1426
+ if (transport.captureDiagnostics !== void 0) requestOptions.captureDiagnostics = transport.captureDiagnostics;
1427
+ if (config.onRequestEvent !== void 0) requestOptions.onRequestEvent = config.onRequestEvent;
1428
+ if (transport.transportId) requestOptions.transportId = transport.transportId;
1429
+ else {
1430
+ if (transport.mode !== void 0) applyNativeEmulationMode(requestOptions, transport.mode);
1431
+ if (transport.proxy !== void 0) requestOptions.proxy = transport.proxy;
1432
+ if (transport.insecure !== void 0) requestOptions.insecure = transport.insecure;
1433
+ if (transport.trustStore !== void 0) requestOptions.trustStore = transport.trustStore;
1434
+ }
1435
+ requestOptions.timeout = timeout;
1436
+ if (config.redirect !== void 0) requestOptions.redirect = config.redirect;
1437
+ if (config.disableDefaultHeaders !== void 0) requestOptions.disableDefaultHeaders = config.disableDefaultHeaders;
1438
+ if (config.compress !== void 0) requestOptions.compress = config.compress;
1439
+ if (headerTuples && headerTuples.length > 0) requestOptions.headers = headerTuples;
1440
+ return dispatchRequest(requestOptions, url, config.signal ?? null);
1776
1441
  }
1777
1442
  async function createTransport(options) {
1778
- const mode = resolveEmulationMode(options?.browser, options?.os, options?.emulation);
1779
- if (options?.poolIdleTimeout !== void 0) {
1780
- validatePositiveNumber(options.poolIdleTimeout, "poolIdleTimeout");
1781
- }
1782
- if (options?.poolMaxIdlePerHost !== void 0) {
1783
- validateNonNegativeInteger(options.poolMaxIdlePerHost, "poolMaxIdlePerHost");
1784
- }
1785
- if (options?.poolMaxSize !== void 0) {
1786
- validatePositiveInteger(options.poolMaxSize, "poolMaxSize");
1787
- }
1788
- if (options?.connectTimeout !== void 0) {
1789
- validatePositiveNumber(options.connectTimeout, "connectTimeout");
1790
- }
1791
- if (options?.readTimeout !== void 0) {
1792
- validatePositiveNumber(options.readTimeout, "readTimeout");
1793
- }
1794
- try {
1795
- const transportOptions = {
1796
- ...options?.proxy !== void 0 && { proxy: options.proxy },
1797
- ...options?.insecure !== void 0 && { insecure: options.insecure },
1798
- ...options?.poolIdleTimeout !== void 0 && { poolIdleTimeout: options.poolIdleTimeout },
1799
- ...options?.poolMaxIdlePerHost !== void 0 && { poolMaxIdlePerHost: options.poolMaxIdlePerHost },
1800
- ...options?.poolMaxSize !== void 0 && { poolMaxSize: options.poolMaxSize },
1801
- ...options?.connectTimeout !== void 0 && { connectTimeout: options.connectTimeout },
1802
- ...options?.readTimeout !== void 0 && { readTimeout: options.readTimeout }
1803
- };
1804
- applyNativeEmulationMode(transportOptions, mode);
1805
- const id = nativeBinding.createTransport(transportOptions);
1806
- return new Transport(id);
1807
- } catch (error) {
1808
- throw new RequestError(String(error));
1809
- }
1443
+ const mode = resolveEmulationMode(options?.browser, options?.os, options?.emulation);
1444
+ validateTrustStore(options?.trustStore);
1445
+ if (options?.poolIdleTimeout !== void 0) validatePositiveNumber(options.poolIdleTimeout, "poolIdleTimeout");
1446
+ if (options?.poolMaxIdlePerHost !== void 0) validateNonNegativeInteger(options.poolMaxIdlePerHost, "poolMaxIdlePerHost");
1447
+ if (options?.poolMaxSize !== void 0) validatePositiveInteger(options.poolMaxSize, "poolMaxSize");
1448
+ if (options?.connectTimeout !== void 0) validatePositiveNumber(options.connectTimeout, "connectTimeout");
1449
+ if (options?.readTimeout !== void 0) validatePositiveNumber(options.readTimeout, "readTimeout");
1450
+ try {
1451
+ const transportOptions = {
1452
+ ...options?.proxy !== void 0 && { proxy: options.proxy },
1453
+ ...options?.insecure !== void 0 && { insecure: options.insecure },
1454
+ trustStore: options?.trustStore ?? DEFAULT_TRUST_STORE,
1455
+ ...options?.poolIdleTimeout !== void 0 && { poolIdleTimeout: options.poolIdleTimeout },
1456
+ ...options?.poolMaxIdlePerHost !== void 0 && { poolMaxIdlePerHost: options.poolMaxIdlePerHost },
1457
+ ...options?.poolMaxSize !== void 0 && { poolMaxSize: options.poolMaxSize },
1458
+ ...options?.connectTimeout !== void 0 && { connectTimeout: options.connectTimeout },
1459
+ ...options?.readTimeout !== void 0 && { readTimeout: options.readTimeout },
1460
+ ...options?.captureDiagnostics !== void 0 && { captureDiagnostics: options.captureDiagnostics }
1461
+ };
1462
+ applyNativeEmulationMode(transportOptions, mode);
1463
+ return new Transport(nativeBinding.createTransport(transportOptions));
1464
+ } catch (error) {
1465
+ throw new RequestError(String(error));
1466
+ }
1810
1467
  }
1811
1468
  async function createSession(options) {
1812
- const { sessionId, defaults } = normalizeSessionOptions(options);
1813
- let createdId;
1814
- let transportId;
1815
- try {
1816
- const transportOptions = {
1817
- ...defaults.proxy !== void 0 && { proxy: defaults.proxy },
1818
- ...defaults.insecure !== void 0 && { insecure: defaults.insecure }
1819
- };
1820
- applyNativeEmulationMode(transportOptions, defaults.transportMode);
1821
- transportId = nativeBinding.createTransport(transportOptions);
1822
- } catch (error) {
1823
- throw new RequestError(String(error));
1824
- }
1825
- try {
1826
- createdId = nativeBinding.createSession({
1827
- sessionId
1828
- });
1829
- } catch (error) {
1830
- try {
1831
- nativeBinding.dropTransport(transportId);
1832
- } catch {
1833
- }
1834
- throw new RequestError(String(error));
1835
- }
1836
- defaults.transportId = transportId;
1837
- defaults.ownsTransport = true;
1838
- return new Session(createdId, defaults);
1469
+ const { sessionId, defaults } = normalizeSessionOptions(options);
1470
+ let createdId;
1471
+ let transportId;
1472
+ try {
1473
+ const transportOptions = {
1474
+ ...defaults.proxy !== void 0 && { proxy: defaults.proxy },
1475
+ ...defaults.insecure !== void 0 && { insecure: defaults.insecure },
1476
+ trustStore: defaults.trustStore ?? DEFAULT_TRUST_STORE,
1477
+ ...defaults.captureDiagnostics !== void 0 && { captureDiagnostics: defaults.captureDiagnostics }
1478
+ };
1479
+ applyNativeEmulationMode(transportOptions, defaults.transportMode);
1480
+ transportId = nativeBinding.createTransport(transportOptions);
1481
+ } catch (error) {
1482
+ throw new RequestError(String(error));
1483
+ }
1484
+ try {
1485
+ createdId = nativeBinding.createSession({ sessionId });
1486
+ } catch (error) {
1487
+ try {
1488
+ nativeBinding.dropTransport(transportId);
1489
+ } catch {}
1490
+ throw new RequestError(String(error));
1491
+ }
1492
+ defaults.transportId = transportId;
1493
+ defaults.ownsTransport = true;
1494
+ return new Session(createdId, defaults);
1839
1495
  }
1840
1496
  async function withSession(fn, options) {
1841
- const session = await createSession(options);
1842
- try {
1843
- return await fn(session);
1844
- } finally {
1845
- await session.close();
1846
- }
1847
- }
1497
+ const session = await createSession(options);
1498
+ try {
1499
+ return await fn(session);
1500
+ } finally {
1501
+ await session.close();
1502
+ }
1503
+ }
1504
+ /**
1505
+ * @deprecated Use {@link fetch} instead.
1506
+ */
1848
1507
  async function request(options) {
1849
- if (!options.url) {
1850
- throw new RequestError("URL is required");
1851
- }
1852
- const { url, ...rest } = options;
1853
- const init = {};
1854
- const legacy = rest;
1855
- if (rest.method !== void 0) {
1856
- init.method = rest.method;
1857
- }
1858
- if (rest.headers !== void 0) {
1859
- init.headers = rest.headers;
1860
- }
1861
- if (rest.body !== void 0) {
1862
- init.body = rest.body;
1863
- }
1864
- if (rest.browser !== void 0) {
1865
- init.browser = rest.browser;
1866
- }
1867
- if (rest.os !== void 0) {
1868
- init.os = rest.os;
1869
- }
1870
- if (rest.emulation !== void 0) {
1871
- init.emulation = rest.emulation;
1872
- }
1873
- if (rest.proxy !== void 0) {
1874
- init.proxy = rest.proxy;
1875
- }
1876
- if (rest.timeout !== void 0) {
1877
- init.timeout = rest.timeout;
1878
- }
1879
- if (rest.sessionId !== void 0) {
1880
- init.sessionId = rest.sessionId;
1881
- }
1882
- if (rest.transport !== void 0) {
1883
- init.transport = rest.transport;
1884
- }
1885
- if (rest.insecure !== void 0) {
1886
- init.insecure = rest.insecure;
1887
- }
1888
- if (rest.disableDefaultHeaders !== void 0) {
1889
- init.disableDefaultHeaders = rest.disableDefaultHeaders;
1890
- }
1891
- if (rest.redirect !== void 0) {
1892
- init.redirect = rest.redirect;
1893
- }
1894
- if (legacy.signal !== void 0) {
1895
- init.signal = legacy.signal;
1896
- }
1897
- if (legacy.session !== void 0) {
1898
- init.session = legacy.session;
1899
- }
1900
- if (legacy.cookieMode !== void 0) {
1901
- init.cookieMode = legacy.cookieMode;
1902
- } else if (legacy.ephemeral === true) {
1903
- init.cookieMode = "ephemeral";
1904
- }
1905
- return fetch(url, init);
1906
- }
1508
+ if (!options.url) throw new RequestError("URL is required");
1509
+ const { url, ...rest } = options;
1510
+ const init = {};
1511
+ const legacy = rest;
1512
+ if (rest.method !== void 0) init.method = rest.method;
1513
+ if (rest.headers !== void 0) init.headers = rest.headers;
1514
+ if (rest.body !== void 0) init.body = rest.body;
1515
+ if (rest.browser !== void 0) init.browser = rest.browser;
1516
+ if (rest.os !== void 0) init.os = rest.os;
1517
+ if (rest.emulation !== void 0) init.emulation = rest.emulation;
1518
+ if (rest.proxy !== void 0) init.proxy = rest.proxy;
1519
+ if (rest.timeout !== void 0) init.timeout = rest.timeout;
1520
+ if (rest.sessionId !== void 0) init.sessionId = rest.sessionId;
1521
+ if (rest.transport !== void 0) init.transport = rest.transport;
1522
+ if (rest.insecure !== void 0) init.insecure = rest.insecure;
1523
+ if (rest.trustStore !== void 0) init.trustStore = rest.trustStore;
1524
+ if (rest.disableDefaultHeaders !== void 0) init.disableDefaultHeaders = rest.disableDefaultHeaders;
1525
+ if (rest.redirect !== void 0) init.redirect = rest.redirect;
1526
+ if (legacy.signal !== void 0) init.signal = legacy.signal;
1527
+ if (legacy.session !== void 0) init.session = legacy.session;
1528
+ if (legacy.cookieMode !== void 0) init.cookieMode = legacy.cookieMode;
1529
+ else if (legacy.ephemeral === true) init.cookieMode = "ephemeral";
1530
+ if (legacy.onRequestEvent !== void 0) init.onRequestEvent = legacy.onRequestEvent;
1531
+ if (legacy.captureDiagnostics !== void 0) init.captureDiagnostics = legacy.captureDiagnostics;
1532
+ return fetch(url, init);
1533
+ }
1534
+ /**
1535
+ * Get list of available browser profiles
1536
+ *
1537
+ * @returns Array of browser profile names
1538
+ *
1539
+ * @example
1540
+ * ```typescript
1541
+ * import { getProfiles } from 'wreq-js';
1542
+ *
1543
+ * const profiles = getProfiles();
1544
+ * console.log(profiles); // ['chrome_131', 'chrome_142', 'firefox_135', 'safari_18', ...]
1545
+ * ```
1546
+ */
1907
1547
  function getProfiles() {
1908
- if (!cachedProfiles) {
1909
- cachedProfiles = nativeBinding.getProfiles();
1910
- }
1911
- return cachedProfiles;
1548
+ if (!cachedProfiles) cachedProfiles = nativeBinding.getProfiles();
1549
+ return cachedProfiles;
1912
1550
  }
1913
1551
  function getProfileSet() {
1914
- if (!cachedProfileSet) {
1915
- cachedProfileSet = new Set(getProfiles());
1916
- }
1917
- return cachedProfileSet;
1918
- }
1552
+ if (!cachedProfileSet) cachedProfileSet = new Set(getProfiles());
1553
+ return cachedProfileSet;
1554
+ }
1555
+ /**
1556
+ * Get list of supported operating systems for emulation.
1557
+ *
1558
+ * @returns Array of operating system identifiers
1559
+ */
1919
1560
  function getOperatingSystems() {
1920
- if (!cachedOperatingSystems) {
1921
- const fromNative = nativeBinding.getOperatingSystems?.();
1922
- cachedOperatingSystems = fromNative && fromNative.length > 0 ? fromNative : [...SUPPORTED_OSES];
1923
- }
1924
- return cachedOperatingSystems;
1561
+ if (!cachedOperatingSystems) {
1562
+ const fromNative = nativeBinding.getOperatingSystems?.();
1563
+ cachedOperatingSystems = fromNative && fromNative.length > 0 ? fromNative : [...SUPPORTED_OSES];
1564
+ }
1565
+ return cachedOperatingSystems;
1925
1566
  }
1926
1567
  function getOperatingSystemSet() {
1927
- if (!cachedOperatingSystemSet) {
1928
- cachedOperatingSystemSet = new Set(getOperatingSystems());
1929
- }
1930
- return cachedOperatingSystemSet;
1568
+ if (!cachedOperatingSystemSet) cachedOperatingSystemSet = new Set(getOperatingSystems());
1569
+ return cachedOperatingSystemSet;
1931
1570
  }
1571
+ /**
1572
+ * Convenience helper for GET requests using {@link fetch}.
1573
+ */
1932
1574
  async function get(url, init) {
1933
- const config = {};
1934
- if (init) {
1935
- Object.assign(config, init);
1936
- }
1937
- config.method = "GET";
1938
- return fetch(url, config);
1939
- }
1575
+ const config = {};
1576
+ if (init) Object.assign(config, init);
1577
+ config.method = "GET";
1578
+ return fetch(url, config);
1579
+ }
1580
+ /**
1581
+ * Convenience helper for POST requests using {@link fetch}.
1582
+ */
1940
1583
  async function post(url, body, init) {
1941
- const config = {};
1942
- if (init) {
1943
- Object.assign(config, init);
1944
- }
1945
- config.method = "POST";
1946
- if (body !== void 0) {
1947
- config.body = body;
1948
- }
1949
- return fetch(url, config);
1584
+ const config = {};
1585
+ if (init) Object.assign(config, init);
1586
+ config.method = "POST";
1587
+ if (body !== void 0) config.body = body;
1588
+ return fetch(url, config);
1950
1589
  }
1951
1590
  function normalizeWebSocketUrl(url) {
1952
- const normalized = String(url).trim();
1953
- if (!normalized) {
1954
- throw new RequestError("URL is required");
1955
- }
1956
- let parsed;
1957
- try {
1958
- parsed = new URL(normalized);
1959
- } catch (error) {
1960
- throw new RequestError(String(error));
1961
- }
1962
- if (parsed.hash) {
1963
- throw new RequestError("WebSocket URL must not include a hash fragment");
1964
- }
1965
- if (parsed.protocol === "http:") {
1966
- parsed.protocol = "ws:";
1967
- } else if (parsed.protocol === "https:") {
1968
- parsed.protocol = "wss:";
1969
- }
1970
- if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
1971
- throw new RequestError("expected a ws: or wss: url");
1972
- }
1973
- return parsed.toString();
1591
+ const normalized = String(url).trim();
1592
+ if (!normalized) throw new RequestError("URL is required");
1593
+ let parsed;
1594
+ try {
1595
+ parsed = new URL(normalized);
1596
+ } catch (error) {
1597
+ throw new RequestError(String(error));
1598
+ }
1599
+ if (parsed.hash) throw new RequestError("WebSocket URL must not include a hash fragment");
1600
+ if (parsed.protocol === "http:") parsed.protocol = "ws:";
1601
+ else if (parsed.protocol === "https:") parsed.protocol = "wss:";
1602
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") throw new RequestError("expected a ws: or wss: url");
1603
+ return parsed.toString();
1974
1604
  }
1975
1605
  function validateWebSocketProtocols(protocols) {
1976
- if (protocols === void 0) {
1977
- return;
1978
- }
1979
- const protocolList = typeof protocols === "string" ? [protocols] : protocols;
1980
- const seen = /* @__PURE__ */ new Set();
1981
- const validToken = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
1982
- for (const protocol of protocolList) {
1983
- if (typeof protocol !== "string" || protocol.length === 0) {
1984
- throw new RequestError("WebSocket protocol values must be non-empty strings");
1985
- }
1986
- if (!validToken.test(protocol)) {
1987
- throw new RequestError(`Invalid WebSocket protocol value: ${protocol}`);
1988
- }
1989
- if (seen.has(protocol)) {
1990
- throw new RequestError(`Duplicate WebSocket protocol: ${protocol}`);
1991
- }
1992
- seen.add(protocol);
1993
- }
1606
+ if (protocols === void 0) return;
1607
+ const protocolList = typeof protocols === "string" ? [protocols] : protocols;
1608
+ const seen = /* @__PURE__ */ new Set();
1609
+ const validToken = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
1610
+ for (const protocol of protocolList) {
1611
+ if (typeof protocol !== "string" || protocol.length === 0) throw new RequestError("WebSocket protocol values must be non-empty strings");
1612
+ if (!validToken.test(protocol)) throw new RequestError(`Invalid WebSocket protocol value: ${protocol}`);
1613
+ if (seen.has(protocol)) throw new RequestError(`Duplicate WebSocket protocol: ${protocol}`);
1614
+ seen.add(protocol);
1615
+ }
1616
+ }
1617
+ function normalizeWebSocketSizeOption(value, label) {
1618
+ if (value === void 0) return;
1619
+ if (!Number.isSafeInteger(value) || value <= 0) throw new RequestError(`${label} must be a positive safe integer`);
1620
+ return value;
1994
1621
  }
1995
1622
  function normalizeStandaloneWebSocketOptions(options) {
1996
- const normalized = {};
1997
- if (!options) {
1998
- return normalized;
1999
- }
2000
- if (options.browser !== void 0) {
2001
- normalized.browser = options.browser;
2002
- }
2003
- if (options.os !== void 0) {
2004
- normalized.os = options.os;
2005
- }
2006
- if (options.emulation !== void 0) {
2007
- normalized.emulation = options.emulation;
2008
- }
2009
- if (options.headers !== void 0) {
2010
- normalized.headers = options.headers;
2011
- }
2012
- if (options.proxy !== void 0) {
2013
- normalized.proxy = options.proxy;
2014
- }
2015
- if (options.protocols !== void 0) {
2016
- normalized.protocols = options.protocols;
2017
- }
2018
- if (options.binaryType !== void 0) {
2019
- if (options.binaryType !== "nodebuffer" && options.binaryType !== "arraybuffer" && options.binaryType !== "blob") {
2020
- throw new RequestError("binaryType must be one of: 'nodebuffer', 'arraybuffer', 'blob'");
2021
- }
2022
- normalized.binaryType = options.binaryType;
2023
- }
2024
- return normalized;
1623
+ const normalized = {};
1624
+ if (!options) return normalized;
1625
+ if (options.browser !== void 0) normalized.browser = options.browser;
1626
+ if (options.os !== void 0) normalized.os = options.os;
1627
+ if (options.emulation !== void 0) normalized.emulation = options.emulation;
1628
+ if (options.headers !== void 0) normalized.headers = options.headers;
1629
+ if (options.proxy !== void 0) normalized.proxy = options.proxy;
1630
+ if (options.protocols !== void 0) normalized.protocols = options.protocols;
1631
+ if (options.maxFrameSize !== void 0) {
1632
+ const maxFrameSize = normalizeWebSocketSizeOption(options.maxFrameSize, "maxFrameSize");
1633
+ if (maxFrameSize !== void 0) normalized.maxFrameSize = maxFrameSize;
1634
+ }
1635
+ if (options.maxMessageSize !== void 0) {
1636
+ const maxMessageSize = normalizeWebSocketSizeOption(options.maxMessageSize, "maxMessageSize");
1637
+ if (maxMessageSize !== void 0) normalized.maxMessageSize = maxMessageSize;
1638
+ }
1639
+ if (options.binaryType !== void 0) {
1640
+ if (options.binaryType !== "nodebuffer" && options.binaryType !== "arraybuffer" && options.binaryType !== "blob") throw new RequestError("binaryType must be one of: 'nodebuffer', 'arraybuffer', 'blob'");
1641
+ normalized.binaryType = options.binaryType;
1642
+ }
1643
+ return normalized;
2025
1644
  }
2026
1645
  function normalizeSessionWebSocketOptions(options) {
2027
- const normalized = {};
2028
- if (!options) {
2029
- return normalized;
2030
- }
2031
- const optionsWithOverrides = options;
2032
- if (optionsWithOverrides.browser !== void 0) {
2033
- throw new RequestError(
2034
- "`browser` is not supported in session.websocket(); the session controls browser emulation."
2035
- );
2036
- }
2037
- if (optionsWithOverrides.os !== void 0) {
2038
- throw new RequestError("`os` is not supported in session.websocket(); the session controls OS emulation.");
2039
- }
2040
- if (optionsWithOverrides.emulation !== void 0) {
2041
- throw new RequestError(
2042
- "`emulation` is not supported in session.websocket(); the session transport controls emulation."
2043
- );
2044
- }
2045
- if (optionsWithOverrides.proxy !== void 0) {
2046
- throw new RequestError("`proxy` is not supported in session.websocket(); the session transport controls proxying.");
2047
- }
2048
- if (options.headers !== void 0) {
2049
- normalized.headers = options.headers;
2050
- }
2051
- if (options.protocols !== void 0) {
2052
- normalized.protocols = options.protocols;
2053
- }
2054
- if (options.binaryType !== void 0) {
2055
- if (options.binaryType !== "nodebuffer" && options.binaryType !== "arraybuffer" && options.binaryType !== "blob") {
2056
- throw new RequestError("binaryType must be one of: 'nodebuffer', 'arraybuffer', 'blob'");
2057
- }
2058
- normalized.binaryType = options.binaryType;
2059
- }
2060
- return normalized;
1646
+ const normalized = {};
1647
+ if (!options) return normalized;
1648
+ const optionsWithOverrides = options;
1649
+ if (optionsWithOverrides.browser !== void 0) throw new RequestError("`browser` is not supported in session.websocket(); the session controls browser emulation.");
1650
+ if (optionsWithOverrides.os !== void 0) throw new RequestError("`os` is not supported in session.websocket(); the session controls OS emulation.");
1651
+ if (optionsWithOverrides.emulation !== void 0) throw new RequestError("`emulation` is not supported in session.websocket(); the session transport controls emulation.");
1652
+ if (optionsWithOverrides.proxy !== void 0) throw new RequestError("`proxy` is not supported in session.websocket(); the session transport controls proxying.");
1653
+ if (options.headers !== void 0) normalized.headers = options.headers;
1654
+ if (options.protocols !== void 0) normalized.protocols = options.protocols;
1655
+ if (options.maxFrameSize !== void 0) {
1656
+ const maxFrameSize = normalizeWebSocketSizeOption(options.maxFrameSize, "maxFrameSize");
1657
+ if (maxFrameSize !== void 0) normalized.maxFrameSize = maxFrameSize;
1658
+ }
1659
+ if (options.maxMessageSize !== void 0) {
1660
+ const maxMessageSize = normalizeWebSocketSizeOption(options.maxMessageSize, "maxMessageSize");
1661
+ if (maxMessageSize !== void 0) normalized.maxMessageSize = maxMessageSize;
1662
+ }
1663
+ if (options.binaryType !== void 0) {
1664
+ if (options.binaryType !== "nodebuffer" && options.binaryType !== "arraybuffer" && options.binaryType !== "blob") throw new RequestError("binaryType must be one of: 'nodebuffer', 'arraybuffer', 'blob'");
1665
+ normalized.binaryType = options.binaryType;
1666
+ }
1667
+ return normalized;
2061
1668
  }
2062
1669
  function extractLegacyWebSocketCallbacks(options) {
2063
- if (!isPlainObject(options)) {
2064
- return void 0;
2065
- }
2066
- const maybeCallbacks = options;
2067
- const callbacks = {};
2068
- if (typeof maybeCallbacks.onMessage === "function") {
2069
- callbacks.onMessage = maybeCallbacks.onMessage;
2070
- }
2071
- if (typeof maybeCallbacks.onClose === "function") {
2072
- callbacks.onClose = maybeCallbacks.onClose;
2073
- }
2074
- if (typeof maybeCallbacks.onError === "function") {
2075
- callbacks.onError = maybeCallbacks.onError;
2076
- }
2077
- return Object.keys(callbacks).length > 0 ? callbacks : void 0;
1670
+ if (!isPlainObject(options)) return;
1671
+ const maybeCallbacks = options;
1672
+ const callbacks = {};
1673
+ if (typeof maybeCallbacks.onMessage === "function") callbacks.onMessage = maybeCallbacks.onMessage;
1674
+ if (typeof maybeCallbacks.onClose === "function") callbacks.onClose = maybeCallbacks.onClose;
1675
+ if (typeof maybeCallbacks.onError === "function") callbacks.onError = maybeCallbacks.onError;
1676
+ return Object.keys(callbacks).length > 0 ? callbacks : void 0;
2078
1677
  }
2079
1678
  function normalizeWebSocketCloseOptions(code, reason) {
2080
- if (code === void 0 && reason === void 0) {
2081
- return void 0;
2082
- }
2083
- if (code === void 0) {
2084
- throw new RequestError("A close code is required when providing a close reason");
2085
- }
2086
- if (!Number.isInteger(code)) {
2087
- throw new RequestError("Close code must be an integer");
2088
- }
2089
- if (code !== 1e3 && (code < 3e3 || code > 4999)) {
2090
- throw new RequestError("Close code must be 1000 or in range 3000-4999");
2091
- }
2092
- const normalizedReason = reason ?? "";
2093
- if (Buffer.byteLength(normalizedReason, "utf8") > 123) {
2094
- throw new RequestError("Close reason must be 123 bytes or fewer");
2095
- }
2096
- return {
2097
- code,
2098
- reason: normalizedReason
2099
- };
1679
+ if (code === void 0 && reason === void 0) return;
1680
+ if (code === void 0) throw new RequestError("A close code is required when providing a close reason");
1681
+ if (!Number.isInteger(code)) throw new RequestError("Close code must be an integer");
1682
+ if (code !== 1e3 && (code < 3e3 || code > 4999)) throw new RequestError("Close code must be 1000 or in range 3000-4999");
1683
+ const normalizedReason = reason ?? "";
1684
+ if (Buffer.byteLength(normalizedReason, "utf8") > 123) throw new RequestError("Close reason must be 123 bytes or fewer");
1685
+ return {
1686
+ code,
1687
+ reason: normalizedReason
1688
+ };
2100
1689
  }
2101
1690
  function isWebSocketListenerType(type) {
2102
- return type === "open" || type === "message" || type === "close" || type === "error";
2103
- }
2104
- var WebSocket = class _WebSocket {
2105
- static CONNECTING = 0;
2106
- static OPEN = 1;
2107
- static CLOSING = 2;
2108
- static CLOSED = 3;
2109
- url;
2110
- protocol = "";
2111
- extensions = "";
2112
- readyState = _WebSocket.CONNECTING;
2113
- _binaryType = "nodebuffer";
2114
- _bufferedAmount = 0;
2115
- _onopen = null;
2116
- _onmessage = null;
2117
- _onclose = null;
2118
- _onerror = null;
2119
- _onHandlerOrder = {
2120
- open: -1,
2121
- message: -1,
2122
- close: -1,
2123
- error: -1
2124
- };
2125
- _listenerOrderCounter = 0;
2126
- _listeners = {
2127
- open: /* @__PURE__ */ new Map(),
2128
- message: /* @__PURE__ */ new Map(),
2129
- close: /* @__PURE__ */ new Map(),
2130
- error: /* @__PURE__ */ new Map()
2131
- };
2132
- _legacyCallbacks;
2133
- _openDispatchMode;
2134
- _connection;
2135
- _connectPromise;
2136
- _closeOptions;
2137
- _finalizerToken;
2138
- _openEventDispatched = false;
2139
- _openEventQueued = false;
2140
- _closeEventDispatched = false;
2141
- _nativeCloseStarted = false;
2142
- _pendingMessages = [];
2143
- _sendChain = Promise.resolve();
2144
- constructor(urlOrInit, protocolsOrOptions, maybeOptions) {
2145
- let init;
2146
- if (isInternalWebSocketInit(urlOrInit)) {
2147
- init = urlOrInit;
2148
- } else {
2149
- init = _WebSocket.buildStandaloneInit(urlOrInit, protocolsOrOptions, maybeOptions);
2150
- }
2151
- this.url = init.url;
2152
- this.binaryType = init.options.binaryType ?? "nodebuffer";
2153
- this._legacyCallbacks = init.legacyCallbacks;
2154
- this._openDispatchMode = init.openDispatchMode;
2155
- this._connectPromise = this.connect(init.connect);
2156
- void this._connectPromise.catch(() => void 0);
2157
- }
2158
- get binaryType() {
2159
- return this._binaryType;
2160
- }
2161
- set binaryType(value) {
2162
- if (value === "arraybuffer" || value === "blob" || value === "nodebuffer") {
2163
- this._binaryType = value;
2164
- }
2165
- }
2166
- get bufferedAmount() {
2167
- return this._bufferedAmount;
2168
- }
2169
- get onopen() {
2170
- return this._onopen;
2171
- }
2172
- set onopen(listener) {
2173
- this._onopen = listener;
2174
- this._onHandlerOrder.open = listener ? ++this._listenerOrderCounter : -1;
2175
- }
2176
- get onmessage() {
2177
- return this._onmessage;
2178
- }
2179
- set onmessage(listener) {
2180
- this._onmessage = listener;
2181
- this._onHandlerOrder.message = listener ? ++this._listenerOrderCounter : -1;
2182
- }
2183
- get onclose() {
2184
- return this._onclose;
2185
- }
2186
- set onclose(listener) {
2187
- this._onclose = listener;
2188
- this._onHandlerOrder.close = listener ? ++this._listenerOrderCounter : -1;
2189
- }
2190
- get onerror() {
2191
- return this._onerror;
2192
- }
2193
- set onerror(listener) {
2194
- this._onerror = listener;
2195
- this._onHandlerOrder.error = listener ? ++this._listenerOrderCounter : -1;
2196
- }
2197
- static async _connectWithInit(init) {
2198
- const ws = new _WebSocket(init);
2199
- await ws._waitUntilConnected();
2200
- ws.scheduleOpenEventAfterAwait();
2201
- return ws;
2202
- }
2203
- static buildStandaloneInit(url, protocolsOrOptions, maybeOptions) {
2204
- const optionsCandidate = typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? maybeOptions : protocolsOrOptions ?? maybeOptions;
2205
- const normalizedOptions = normalizeStandaloneWebSocketOptions(optionsCandidate);
2206
- validateWebSocketProtocols(
2207
- typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? protocolsOrOptions : normalizedOptions.protocols
2208
- );
2209
- assertNoManualWebSocketProtocolHeader(normalizedOptions.headers);
2210
- const emulationMode = resolveEmulationMode(
2211
- normalizedOptions.browser,
2212
- normalizedOptions.os,
2213
- normalizedOptions.emulation
2214
- );
2215
- const protocols = normalizeWebSocketProtocolList(
2216
- typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? protocolsOrOptions : normalizedOptions.protocols
2217
- );
2218
- return {
2219
- _internal: true,
2220
- url: normalizeWebSocketUrl(url),
2221
- options: normalizedOptions,
2222
- openDispatchMode: "automatic",
2223
- connect: (callbacks) => {
2224
- const nativeOptions = {
2225
- url: normalizeWebSocketUrl(url),
2226
- headers: headersToTuples(normalizedOptions.headers ?? {}),
2227
- ...protocols && protocols.length > 0 && { protocols },
2228
- ...normalizedOptions.proxy !== void 0 && { proxy: normalizedOptions.proxy },
2229
- onMessage: callbacks.onMessage,
2230
- onClose: callbacks.onClose,
2231
- onError: callbacks.onError
2232
- };
2233
- applyNativeEmulationMode(nativeOptions, emulationMode);
2234
- return nativeBinding.websocketConnect(nativeOptions);
2235
- },
2236
- legacyCallbacks: extractLegacyWebSocketCallbacks(optionsCandidate)
2237
- };
2238
- }
2239
- async connect(connectFn) {
2240
- try {
2241
- const connection = await connectFn({
2242
- onMessage: (data) => {
2243
- this.handleNativeMessage(data);
2244
- },
2245
- onClose: (event) => {
2246
- this.handleNativeClose(event);
2247
- },
2248
- onError: (message) => {
2249
- this.handleNativeError(message);
2250
- }
2251
- });
2252
- this._connection = connection;
2253
- this.protocol = connection.protocol ?? "";
2254
- this.extensions = connection.extensions ?? "";
2255
- if (websocketFinalizer) {
2256
- this._finalizerToken = connection;
2257
- websocketFinalizer.register(this, connection, connection);
2258
- }
2259
- if (this.readyState === _WebSocket.CLOSING) {
2260
- this.startNativeClose();
2261
- return;
2262
- }
2263
- this.readyState = _WebSocket.OPEN;
2264
- if (this._openDispatchMode === "automatic") {
2265
- this.scheduleOpenEventAfterConnect();
2266
- }
2267
- } catch (error) {
2268
- this.handleNativeError(String(error));
2269
- this.finalizeClosed({ code: 1006, reason: "" }, false);
2270
- throw new RequestError(String(error));
2271
- }
2272
- }
2273
- _waitUntilConnected() {
2274
- return this._connectPromise;
2275
- }
2276
- scheduleOpenEventAfterConnect() {
2277
- this.scheduleOpenEventWithDepth(2);
2278
- }
2279
- scheduleOpenEventAfterAwait() {
2280
- this.scheduleOpenEventWithDepth(3);
2281
- }
2282
- scheduleOpenEventWithDepth(depth) {
2283
- if (this._openEventDispatched || this._openEventQueued || this.readyState !== _WebSocket.OPEN) {
2284
- return;
2285
- }
2286
- this._openEventQueued = true;
2287
- const queue = (remaining) => {
2288
- if (remaining === 0) {
2289
- this._openEventQueued = false;
2290
- if (this._openEventDispatched || this.readyState !== _WebSocket.OPEN) {
2291
- return;
2292
- }
2293
- this._openEventDispatched = true;
2294
- this.dispatchOpenEvent();
2295
- return;
2296
- }
2297
- queueMicrotask(() => {
2298
- queue(remaining - 1);
2299
- });
2300
- };
2301
- queue(depth);
2302
- }
2303
- releaseConnectionTracking() {
2304
- if (!this._finalizerToken || !websocketFinalizer) {
2305
- return;
2306
- }
2307
- websocketFinalizer.unregister(this._finalizerToken);
2308
- this._finalizerToken = void 0;
2309
- }
2310
- toMessageEventData(data) {
2311
- if (typeof data === "string") {
2312
- return data;
2313
- }
2314
- if (this._binaryType === "arraybuffer") {
2315
- const arrayBuffer = new ArrayBuffer(data.byteLength);
2316
- new Uint8Array(arrayBuffer).set(data);
2317
- return arrayBuffer;
2318
- }
2319
- if (this._binaryType === "blob") {
2320
- return new Blob([data]);
2321
- }
2322
- return data;
2323
- }
2324
- invokeListener(listener, event) {
2325
- try {
2326
- if (typeof listener === "function") {
2327
- listener.call(this, event);
2328
- } else {
2329
- listener.handleEvent(event);
2330
- }
2331
- } catch {
2332
- }
2333
- }
2334
- createBaseEvent(type) {
2335
- return {
2336
- type,
2337
- isTrusted: false,
2338
- timeStamp: Date.now(),
2339
- target: this,
2340
- currentTarget: this
2341
- };
2342
- }
2343
- getOnHandler(type) {
2344
- switch (type) {
2345
- case "open":
2346
- return this._onopen;
2347
- case "message":
2348
- return this._onmessage;
2349
- case "close":
2350
- return this._onclose;
2351
- case "error":
2352
- return this._onerror;
2353
- default:
2354
- return null;
2355
- }
2356
- }
2357
- getOnHandlerOrder(type) {
2358
- return this._onHandlerOrder[type];
2359
- }
2360
- getListenerMap(type) {
2361
- return this._listeners[type];
2362
- }
2363
- dispatchEvent(type, event) {
2364
- const listenerMap = this.getListenerMap(type);
2365
- const onHandler = this.getOnHandler(type);
2366
- if (listenerMap.size === 0 && !onHandler) {
2367
- return;
2368
- }
2369
- const ordered = [];
2370
- for (const descriptor of listenerMap.values()) {
2371
- ordered.push({
2372
- order: descriptor.order,
2373
- listener: descriptor.listener,
2374
- once: descriptor.once
2375
- });
2376
- }
2377
- if (onHandler) {
2378
- ordered.push({
2379
- order: this.getOnHandlerOrder(type),
2380
- listener: onHandler,
2381
- once: false
2382
- });
2383
- }
2384
- ordered.sort((a, b) => a.order - b.order);
2385
- for (const entry of ordered) {
2386
- if (entry.once) {
2387
- this.removeEventListener(type, entry.listener);
2388
- }
2389
- this.invokeListener(entry.listener, event);
2390
- }
2391
- }
2392
- dispatchOpenEvent() {
2393
- const event = this.createBaseEvent("open");
2394
- this.dispatchEvent("open", event);
2395
- if (!this._closeEventDispatched && this._pendingMessages.length > 0) {
2396
- const pending = this._pendingMessages;
2397
- this._pendingMessages = [];
2398
- for (const data of pending) {
2399
- this.dispatchMessageEvent(this.toMessageEventData(data));
2400
- }
2401
- }
2402
- }
2403
- dispatchMessageEvent(data) {
2404
- const event = {
2405
- ...this.createBaseEvent("message"),
2406
- data
2407
- };
2408
- this.dispatchEvent("message", event);
2409
- }
2410
- dispatchCloseEvent(event) {
2411
- this.dispatchEvent("close", event);
2412
- }
2413
- dispatchErrorEvent(message) {
2414
- const event = {
2415
- ...this.createBaseEvent("error"),
2416
- ...message !== void 0 && { message }
2417
- };
2418
- this.dispatchEvent("error", event);
2419
- }
2420
- handleNativeMessage(data) {
2421
- if (this._closeEventDispatched) {
2422
- return;
2423
- }
2424
- this._legacyCallbacks?.onMessage?.(data);
2425
- if (!this._openEventDispatched && this.readyState === _WebSocket.OPEN) {
2426
- this._pendingMessages.push(data);
2427
- return;
2428
- }
2429
- this.dispatchMessageEvent(this.toMessageEventData(data));
2430
- }
2431
- handleNativeError(message) {
2432
- this._legacyCallbacks?.onError?.(message);
2433
- this.dispatchErrorEvent(message);
2434
- }
2435
- handleNativeClose(event) {
2436
- const wasClean = this.readyState === _WebSocket.CLOSING || event.code === 1e3;
2437
- this.finalizeClosed(event, wasClean);
2438
- }
2439
- finalizeClosed(event, wasClean) {
2440
- if (this._closeEventDispatched) {
2441
- return;
2442
- }
2443
- this.readyState = _WebSocket.CLOSED;
2444
- this._closeEventDispatched = true;
2445
- this._pendingMessages = [];
2446
- this.releaseConnectionTracking();
2447
- const closeEvent = {
2448
- ...this.createBaseEvent("close"),
2449
- code: event.code,
2450
- reason: event.reason,
2451
- wasClean
2452
- };
2453
- this._legacyCallbacks?.onClose?.(closeEvent);
2454
- this.dispatchCloseEvent(closeEvent);
2455
- }
2456
- startNativeClose() {
2457
- if (this._nativeCloseStarted || !this._connection) {
2458
- return;
2459
- }
2460
- this._nativeCloseStarted = true;
2461
- const connection = this._connection;
2462
- const closeOptions = this._closeOptions;
2463
- void nativeBinding.websocketClose(connection, closeOptions).catch((error) => {
2464
- this.handleNativeError(String(error));
2465
- this.finalizeClosed({ code: 1006, reason: "" }, false);
2466
- });
2467
- }
2468
- addEventListener(type, listener, options) {
2469
- if (!listener || !isWebSocketListenerType(type)) {
2470
- return;
2471
- }
2472
- const normalizedListener = listener;
2473
- if (typeof normalizedListener !== "function" && (typeof normalizedListener !== "object" || normalizedListener === null || typeof normalizedListener.handleEvent !== "function")) {
2474
- return;
2475
- }
2476
- const listenerMap = this.getListenerMap(type);
2477
- if (listenerMap.has(normalizedListener)) {
2478
- return;
2479
- }
2480
- const parsedOptions = typeof options === "boolean" ? {} : options ?? {};
2481
- const once = parsedOptions.once === true;
2482
- const signal = parsedOptions.signal;
2483
- if (signal?.aborted) {
2484
- return;
2485
- }
2486
- const descriptor = {
2487
- listener: normalizedListener,
2488
- order: ++this._listenerOrderCounter,
2489
- once
2490
- };
2491
- if (signal) {
2492
- const onAbort = () => {
2493
- this.removeEventListener(type, normalizedListener);
2494
- };
2495
- descriptor.abortSignal = signal;
2496
- descriptor.abortHandler = onAbort;
2497
- signal.addEventListener("abort", onAbort, { once: true });
2498
- }
2499
- listenerMap.set(normalizedListener, descriptor);
2500
- }
2501
- removeEventListener(type, listener) {
2502
- if (!listener || !isWebSocketListenerType(type)) {
2503
- return;
2504
- }
2505
- const normalizedListener = listener;
2506
- if (typeof normalizedListener !== "function" && typeof normalizedListener !== "object") {
2507
- return;
2508
- }
2509
- const listenerMap = this.getListenerMap(type);
2510
- const descriptor = listenerMap.get(normalizedListener);
2511
- if (!descriptor) {
2512
- return;
2513
- }
2514
- if (descriptor.abortSignal && descriptor.abortHandler) {
2515
- descriptor.abortSignal.removeEventListener("abort", descriptor.abortHandler);
2516
- }
2517
- listenerMap.delete(normalizedListener);
2518
- }
2519
- getSendByteLength(data) {
2520
- if (typeof data === "string") {
2521
- return Buffer.byteLength(data);
2522
- }
2523
- if (Buffer.isBuffer(data)) {
2524
- return data.byteLength;
2525
- }
2526
- if (data instanceof ArrayBuffer) {
2527
- return data.byteLength;
2528
- }
2529
- if (ArrayBuffer.isView(data)) {
2530
- return data.byteLength;
2531
- }
2532
- if (typeof Blob !== "undefined" && data instanceof Blob) {
2533
- return data.size;
2534
- }
2535
- throw new TypeError("WebSocket data must be a string, Buffer, ArrayBuffer, ArrayBufferView, or Blob");
2536
- }
2537
- async normalizeSendPayload(data) {
2538
- if (typeof data === "string") {
2539
- return data;
2540
- }
2541
- if (Buffer.isBuffer(data)) {
2542
- return data;
2543
- }
2544
- if (data instanceof ArrayBuffer) {
2545
- return Buffer.from(data);
2546
- }
2547
- if (ArrayBuffer.isView(data)) {
2548
- return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
2549
- }
2550
- if (typeof Blob !== "undefined" && data instanceof Blob) {
2551
- return Buffer.from(await data.arrayBuffer());
2552
- }
2553
- throw new TypeError("WebSocket data must be a string, Buffer, ArrayBuffer, ArrayBufferView, or Blob");
2554
- }
2555
- send(data) {
2556
- if (this.readyState !== _WebSocket.OPEN || !this._connection) {
2557
- throw new RequestError("WebSocket is not open");
2558
- }
2559
- const queuedBytes = this.getSendByteLength(data);
2560
- const connection = this._connection;
2561
- this._bufferedAmount += queuedBytes;
2562
- const sendTask = async () => {
2563
- try {
2564
- const payload = await this.normalizeSendPayload(data);
2565
- await nativeBinding.websocketSend(connection, payload);
2566
- } catch (error) {
2567
- this.handleNativeError(String(error));
2568
- this.finalizeClosed({ code: 1006, reason: "" }, false);
2569
- } finally {
2570
- this._bufferedAmount = Math.max(0, this._bufferedAmount - queuedBytes);
2571
- }
2572
- };
2573
- this._sendChain = this._sendChain.then(sendTask, sendTask);
2574
- }
2575
- close(code, reason) {
2576
- if (this.readyState === _WebSocket.CLOSING || this.readyState === _WebSocket.CLOSED) {
2577
- return;
2578
- }
2579
- this._closeOptions = normalizeWebSocketCloseOptions(code, reason);
2580
- this.readyState = _WebSocket.CLOSING;
2581
- this.startNativeClose();
2582
- }
1691
+ return type === "open" || type === "message" || type === "close" || type === "error";
1692
+ }
1693
+ /**
1694
+ * WHATWG-style WebSocket API with async connection establishment.
1695
+ */
1696
+ var WebSocket = class WebSocket {
1697
+ static CONNECTING = 0;
1698
+ static OPEN = 1;
1699
+ static CLOSING = 2;
1700
+ static CLOSED = 3;
1701
+ url;
1702
+ protocol = "";
1703
+ extensions = "";
1704
+ readyState = WebSocket.CONNECTING;
1705
+ _binaryType = "nodebuffer";
1706
+ _bufferedAmount = 0;
1707
+ _onopen = null;
1708
+ _onmessage = null;
1709
+ _onclose = null;
1710
+ _onerror = null;
1711
+ _onHandlerOrder = {
1712
+ open: -1,
1713
+ message: -1,
1714
+ close: -1,
1715
+ error: -1
1716
+ };
1717
+ _listenerOrderCounter = 0;
1718
+ _listeners = {
1719
+ open: /* @__PURE__ */ new Map(),
1720
+ message: /* @__PURE__ */ new Map(),
1721
+ close: /* @__PURE__ */ new Map(),
1722
+ error: /* @__PURE__ */ new Map()
1723
+ };
1724
+ _legacyCallbacks;
1725
+ _openDispatchMode;
1726
+ _connection;
1727
+ _connectPromise;
1728
+ _closeOptions;
1729
+ _finalizerToken;
1730
+ _openEventDispatched = false;
1731
+ _openEventQueued = false;
1732
+ _closeEventDispatched = false;
1733
+ _nativeCloseStarted = false;
1734
+ _pendingMessages = [];
1735
+ _sendChain = Promise.resolve();
1736
+ constructor(urlOrInit, protocolsOrOptions, maybeOptions) {
1737
+ let init;
1738
+ if (isInternalWebSocketInit(urlOrInit)) init = urlOrInit;
1739
+ else init = WebSocket.buildStandaloneInit(urlOrInit, protocolsOrOptions, maybeOptions);
1740
+ this.url = init.url;
1741
+ this.binaryType = init.options.binaryType ?? "nodebuffer";
1742
+ this._legacyCallbacks = init.legacyCallbacks;
1743
+ this._openDispatchMode = init.openDispatchMode;
1744
+ this._connectPromise = this.connect(init.connect);
1745
+ this._connectPromise.catch(() => void 0);
1746
+ }
1747
+ get binaryType() {
1748
+ return this._binaryType;
1749
+ }
1750
+ set binaryType(value) {
1751
+ if (value === "arraybuffer" || value === "blob" || value === "nodebuffer") this._binaryType = value;
1752
+ }
1753
+ get bufferedAmount() {
1754
+ return this._bufferedAmount;
1755
+ }
1756
+ get onopen() {
1757
+ return this._onopen;
1758
+ }
1759
+ set onopen(listener) {
1760
+ this._onopen = listener;
1761
+ this._onHandlerOrder.open = listener ? ++this._listenerOrderCounter : -1;
1762
+ }
1763
+ get onmessage() {
1764
+ return this._onmessage;
1765
+ }
1766
+ set onmessage(listener) {
1767
+ this._onmessage = listener;
1768
+ this._onHandlerOrder.message = listener ? ++this._listenerOrderCounter : -1;
1769
+ }
1770
+ get onclose() {
1771
+ return this._onclose;
1772
+ }
1773
+ set onclose(listener) {
1774
+ this._onclose = listener;
1775
+ this._onHandlerOrder.close = listener ? ++this._listenerOrderCounter : -1;
1776
+ }
1777
+ get onerror() {
1778
+ return this._onerror;
1779
+ }
1780
+ set onerror(listener) {
1781
+ this._onerror = listener;
1782
+ this._onHandlerOrder.error = listener ? ++this._listenerOrderCounter : -1;
1783
+ }
1784
+ static async _connectWithInit(init) {
1785
+ const ws = new WebSocket(init);
1786
+ await ws._waitUntilConnected();
1787
+ ws.scheduleOpenEventAfterAwait();
1788
+ return ws;
1789
+ }
1790
+ static buildStandaloneInit(url, protocolsOrOptions, maybeOptions) {
1791
+ const optionsCandidate = typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? maybeOptions : protocolsOrOptions ?? maybeOptions;
1792
+ const normalizedOptions = normalizeStandaloneWebSocketOptions(optionsCandidate);
1793
+ validateWebSocketProtocols(typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? protocolsOrOptions : normalizedOptions.protocols);
1794
+ assertNoManualWebSocketProtocolHeader(normalizedOptions.headers);
1795
+ const emulationMode = resolveEmulationMode(normalizedOptions.browser, normalizedOptions.os, normalizedOptions.emulation);
1796
+ const protocols = normalizeWebSocketProtocolList(typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? protocolsOrOptions : normalizedOptions.protocols);
1797
+ return {
1798
+ _internal: true,
1799
+ url: normalizeWebSocketUrl(url),
1800
+ options: normalizedOptions,
1801
+ openDispatchMode: "automatic",
1802
+ connect: (callbacks) => {
1803
+ const nativeOptions = {
1804
+ url: normalizeWebSocketUrl(url),
1805
+ headers: headersToTuples(normalizedOptions.headers ?? {}),
1806
+ ...protocols && protocols.length > 0 && { protocols },
1807
+ ...normalizedOptions.proxy !== void 0 && { proxy: normalizedOptions.proxy },
1808
+ ...normalizedOptions.maxFrameSize !== void 0 && { maxFrameSize: normalizedOptions.maxFrameSize },
1809
+ ...normalizedOptions.maxMessageSize !== void 0 && { maxMessageSize: normalizedOptions.maxMessageSize },
1810
+ onMessage: callbacks.onMessage,
1811
+ onClose: callbacks.onClose,
1812
+ onError: callbacks.onError
1813
+ };
1814
+ applyNativeEmulationMode(nativeOptions, emulationMode);
1815
+ return nativeBinding.websocketConnect(nativeOptions);
1816
+ },
1817
+ legacyCallbacks: extractLegacyWebSocketCallbacks(optionsCandidate)
1818
+ };
1819
+ }
1820
+ async connect(connectFn) {
1821
+ try {
1822
+ const connection = await connectFn({
1823
+ onMessage: (data) => {
1824
+ this.handleNativeMessage(data);
1825
+ },
1826
+ onClose: (event) => {
1827
+ this.handleNativeClose(event);
1828
+ },
1829
+ onError: (message) => {
1830
+ this.handleNativeError(message);
1831
+ }
1832
+ });
1833
+ this._connection = connection;
1834
+ this.protocol = connection.protocol ?? "";
1835
+ this.extensions = connection.extensions ?? "";
1836
+ if (websocketFinalizer) {
1837
+ this._finalizerToken = connection;
1838
+ websocketFinalizer.register(this, connection, connection);
1839
+ }
1840
+ if (this.readyState === WebSocket.CLOSING) {
1841
+ this.startNativeClose();
1842
+ return;
1843
+ }
1844
+ this.readyState = WebSocket.OPEN;
1845
+ if (this._openDispatchMode === "automatic") this.scheduleOpenEventAfterConnect();
1846
+ } catch (error) {
1847
+ this.handleNativeError(String(error));
1848
+ this.finalizeClosed({
1849
+ code: 1006,
1850
+ reason: ""
1851
+ }, false);
1852
+ throw new RequestError(String(error));
1853
+ }
1854
+ }
1855
+ _waitUntilConnected() {
1856
+ return this._connectPromise;
1857
+ }
1858
+ scheduleOpenEventAfterConnect() {
1859
+ this.scheduleOpenEventWithDepth(2);
1860
+ }
1861
+ scheduleOpenEventAfterAwait() {
1862
+ this.scheduleOpenEventWithDepth(3);
1863
+ }
1864
+ scheduleOpenEventWithDepth(depth) {
1865
+ if (this._openEventDispatched || this._openEventQueued || this.readyState !== WebSocket.OPEN) return;
1866
+ this._openEventQueued = true;
1867
+ const queue = (remaining) => {
1868
+ if (remaining === 0) {
1869
+ this._openEventQueued = false;
1870
+ if (this._openEventDispatched || this.readyState !== WebSocket.OPEN) return;
1871
+ this._openEventDispatched = true;
1872
+ this.dispatchOpenEvent();
1873
+ return;
1874
+ }
1875
+ queueMicrotask(() => {
1876
+ queue(remaining - 1);
1877
+ });
1878
+ };
1879
+ queue(depth);
1880
+ }
1881
+ releaseConnectionTracking() {
1882
+ if (!this._finalizerToken || !websocketFinalizer) return;
1883
+ websocketFinalizer.unregister(this._finalizerToken);
1884
+ this._finalizerToken = void 0;
1885
+ }
1886
+ toMessageEventData(data) {
1887
+ if (typeof data === "string") return data;
1888
+ if (this._binaryType === "arraybuffer") {
1889
+ const arrayBuffer = new ArrayBuffer(data.byteLength);
1890
+ new Uint8Array(arrayBuffer).set(data);
1891
+ return arrayBuffer;
1892
+ }
1893
+ if (this._binaryType === "blob") return new Blob([data]);
1894
+ return data;
1895
+ }
1896
+ invokeListener(listener, event) {
1897
+ try {
1898
+ if (typeof listener === "function") listener.call(this, event);
1899
+ else listener.handleEvent(event);
1900
+ } catch {}
1901
+ }
1902
+ createBaseEvent(type) {
1903
+ return {
1904
+ type,
1905
+ isTrusted: false,
1906
+ timeStamp: Date.now(),
1907
+ target: this,
1908
+ currentTarget: this
1909
+ };
1910
+ }
1911
+ getOnHandler(type) {
1912
+ switch (type) {
1913
+ case "open": return this._onopen;
1914
+ case "message": return this._onmessage;
1915
+ case "close": return this._onclose;
1916
+ case "error": return this._onerror;
1917
+ default: return null;
1918
+ }
1919
+ }
1920
+ getOnHandlerOrder(type) {
1921
+ return this._onHandlerOrder[type];
1922
+ }
1923
+ getListenerMap(type) {
1924
+ return this._listeners[type];
1925
+ }
1926
+ dispatchEvent(type, event) {
1927
+ const listenerMap = this.getListenerMap(type);
1928
+ const onHandler = this.getOnHandler(type);
1929
+ if (listenerMap.size === 0 && !onHandler) return;
1930
+ const ordered = [];
1931
+ for (const descriptor of listenerMap.values()) ordered.push({
1932
+ order: descriptor.order,
1933
+ listener: descriptor.listener,
1934
+ once: descriptor.once
1935
+ });
1936
+ if (onHandler) ordered.push({
1937
+ order: this.getOnHandlerOrder(type),
1938
+ listener: onHandler,
1939
+ once: false
1940
+ });
1941
+ ordered.sort((a, b) => a.order - b.order);
1942
+ for (const entry of ordered) {
1943
+ if (entry.once) this.removeEventListener(type, entry.listener);
1944
+ this.invokeListener(entry.listener, event);
1945
+ }
1946
+ }
1947
+ dispatchOpenEvent() {
1948
+ const event = this.createBaseEvent("open");
1949
+ this.dispatchEvent("open", event);
1950
+ if (!this._closeEventDispatched && this._pendingMessages.length > 0) {
1951
+ const pending = this._pendingMessages;
1952
+ this._pendingMessages = [];
1953
+ for (const data of pending) this.dispatchMessageEvent(this.toMessageEventData(data));
1954
+ }
1955
+ }
1956
+ dispatchMessageEvent(data) {
1957
+ const event = {
1958
+ ...this.createBaseEvent("message"),
1959
+ data
1960
+ };
1961
+ this.dispatchEvent("message", event);
1962
+ }
1963
+ dispatchCloseEvent(event) {
1964
+ this.dispatchEvent("close", event);
1965
+ }
1966
+ dispatchErrorEvent(message) {
1967
+ const event = {
1968
+ ...this.createBaseEvent("error"),
1969
+ ...message !== void 0 && { message }
1970
+ };
1971
+ this.dispatchEvent("error", event);
1972
+ }
1973
+ handleNativeMessage(data) {
1974
+ if (this._closeEventDispatched) return;
1975
+ this._legacyCallbacks?.onMessage?.(data);
1976
+ if (!this._openEventDispatched && this.readyState === WebSocket.OPEN) {
1977
+ this._pendingMessages.push(data);
1978
+ return;
1979
+ }
1980
+ this.dispatchMessageEvent(this.toMessageEventData(data));
1981
+ }
1982
+ handleNativeError(message) {
1983
+ this._legacyCallbacks?.onError?.(message);
1984
+ this.dispatchErrorEvent(message);
1985
+ }
1986
+ handleNativeClose(event) {
1987
+ const wasClean = this.readyState === WebSocket.CLOSING || event.code === 1e3;
1988
+ this.finalizeClosed(event, wasClean);
1989
+ }
1990
+ finalizeClosed(event, wasClean) {
1991
+ if (this._closeEventDispatched) return;
1992
+ this.readyState = WebSocket.CLOSED;
1993
+ this._closeEventDispatched = true;
1994
+ this._pendingMessages = [];
1995
+ this.releaseConnectionTracking();
1996
+ const closeEvent = {
1997
+ ...this.createBaseEvent("close"),
1998
+ code: event.code,
1999
+ reason: event.reason,
2000
+ wasClean
2001
+ };
2002
+ this._legacyCallbacks?.onClose?.(closeEvent);
2003
+ this.dispatchCloseEvent(closeEvent);
2004
+ }
2005
+ startNativeClose() {
2006
+ if (this._nativeCloseStarted || !this._connection) return;
2007
+ this._nativeCloseStarted = true;
2008
+ const connection = this._connection;
2009
+ const closeOptions = this._closeOptions;
2010
+ nativeBinding.websocketClose(connection, closeOptions).catch((error) => {
2011
+ this.handleNativeError(String(error));
2012
+ this.finalizeClosed({
2013
+ code: 1006,
2014
+ reason: ""
2015
+ }, false);
2016
+ });
2017
+ }
2018
+ addEventListener(type, listener, options) {
2019
+ if (!listener || !isWebSocketListenerType(type)) return;
2020
+ const normalizedListener = listener;
2021
+ if (typeof normalizedListener !== "function" && (typeof normalizedListener !== "object" || normalizedListener === null || typeof normalizedListener.handleEvent !== "function")) return;
2022
+ const listenerMap = this.getListenerMap(type);
2023
+ if (listenerMap.has(normalizedListener)) return;
2024
+ const parsedOptions = typeof options === "boolean" ? {} : options ?? {};
2025
+ const once = parsedOptions.once === true;
2026
+ const signal = parsedOptions.signal;
2027
+ if (signal?.aborted) return;
2028
+ const descriptor = {
2029
+ listener: normalizedListener,
2030
+ order: ++this._listenerOrderCounter,
2031
+ once
2032
+ };
2033
+ if (signal) {
2034
+ const onAbort = () => {
2035
+ this.removeEventListener(type, normalizedListener);
2036
+ };
2037
+ descriptor.abortSignal = signal;
2038
+ descriptor.abortHandler = onAbort;
2039
+ signal.addEventListener("abort", onAbort, { once: true });
2040
+ }
2041
+ listenerMap.set(normalizedListener, descriptor);
2042
+ }
2043
+ removeEventListener(type, listener) {
2044
+ if (!listener || !isWebSocketListenerType(type)) return;
2045
+ const normalizedListener = listener;
2046
+ if (typeof normalizedListener !== "function" && typeof normalizedListener !== "object") return;
2047
+ const listenerMap = this.getListenerMap(type);
2048
+ const descriptor = listenerMap.get(normalizedListener);
2049
+ if (!descriptor) return;
2050
+ if (descriptor.abortSignal && descriptor.abortHandler) descriptor.abortSignal.removeEventListener("abort", descriptor.abortHandler);
2051
+ listenerMap.delete(normalizedListener);
2052
+ }
2053
+ getSendByteLength(data) {
2054
+ if (typeof data === "string") return Buffer.byteLength(data);
2055
+ if (Buffer.isBuffer(data)) return data.byteLength;
2056
+ if (data instanceof ArrayBuffer) return data.byteLength;
2057
+ if (ArrayBuffer.isView(data)) return data.byteLength;
2058
+ if (typeof Blob !== "undefined" && data instanceof Blob) return data.size;
2059
+ throw new TypeError("WebSocket data must be a string, Buffer, ArrayBuffer, ArrayBufferView, or Blob");
2060
+ }
2061
+ async normalizeSendPayload(data) {
2062
+ if (typeof data === "string") return data;
2063
+ if (Buffer.isBuffer(data)) return data;
2064
+ if (data instanceof ArrayBuffer) return Buffer.from(data);
2065
+ if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
2066
+ if (typeof Blob !== "undefined" && data instanceof Blob) return Buffer.from(await data.arrayBuffer());
2067
+ throw new TypeError("WebSocket data must be a string, Buffer, ArrayBuffer, ArrayBufferView, or Blob");
2068
+ }
2069
+ send(data) {
2070
+ if (this.readyState !== WebSocket.OPEN || !this._connection) throw new RequestError("WebSocket is not open");
2071
+ const queuedBytes = this.getSendByteLength(data);
2072
+ const connection = this._connection;
2073
+ this._bufferedAmount += queuedBytes;
2074
+ const sendTask = async () => {
2075
+ try {
2076
+ const payload = await this.normalizeSendPayload(data);
2077
+ await nativeBinding.websocketSend(connection, payload);
2078
+ } catch (error) {
2079
+ this.handleNativeError(String(error));
2080
+ this.finalizeClosed({
2081
+ code: 1006,
2082
+ reason: ""
2083
+ }, false);
2084
+ } finally {
2085
+ this._bufferedAmount = Math.max(0, this._bufferedAmount - queuedBytes);
2086
+ }
2087
+ };
2088
+ this._sendChain = this._sendChain.then(sendTask, sendTask);
2089
+ }
2090
+ close(code, reason) {
2091
+ if (this.readyState === WebSocket.CLOSING || this.readyState === WebSocket.CLOSED) return;
2092
+ this._closeOptions = normalizeWebSocketCloseOptions(code, reason);
2093
+ this.readyState = WebSocket.CLOSING;
2094
+ this.startNativeClose();
2095
+ }
2583
2096
  };
2584
2097
  function isInternalWebSocketInit(value) {
2585
- if (!isPlainObject(value)) {
2586
- return false;
2587
- }
2588
- const candidate = value;
2589
- return candidate._internal === true && typeof candidate.url === "string" && typeof candidate.connect === "function";
2098
+ if (!isPlainObject(value)) return false;
2099
+ const candidate = value;
2100
+ return candidate._internal === true && typeof candidate.url === "string" && typeof candidate.connect === "function";
2590
2101
  }
2591
2102
  function normalizeStandaloneWebSocketArgs(urlOrOptions, options) {
2592
- if (typeof urlOrOptions === "string" || urlOrOptions instanceof URL) {
2593
- const normalizedOptions2 = normalizeStandaloneWebSocketOptions(options);
2594
- return {
2595
- url: normalizeWebSocketUrl(urlOrOptions),
2596
- options: normalizedOptions2,
2597
- legacyCallbacks: extractLegacyWebSocketCallbacks(options)
2598
- };
2599
- }
2600
- const legacy = urlOrOptions;
2601
- const normalizedOptions = normalizeStandaloneWebSocketOptions(legacy);
2602
- return {
2603
- url: normalizeWebSocketUrl(legacy.url),
2604
- options: normalizedOptions,
2605
- legacyCallbacks: extractLegacyWebSocketCallbacks(legacy)
2606
- };
2103
+ if (typeof urlOrOptions === "string" || urlOrOptions instanceof URL) {
2104
+ const normalizedOptions = normalizeStandaloneWebSocketOptions(options);
2105
+ return {
2106
+ url: normalizeWebSocketUrl(urlOrOptions),
2107
+ options: normalizedOptions,
2108
+ legacyCallbacks: extractLegacyWebSocketCallbacks(options)
2109
+ };
2110
+ }
2111
+ const legacy = urlOrOptions;
2112
+ const normalizedOptions = normalizeStandaloneWebSocketOptions(legacy);
2113
+ return {
2114
+ url: normalizeWebSocketUrl(legacy.url),
2115
+ options: normalizedOptions,
2116
+ legacyCallbacks: extractLegacyWebSocketCallbacks(legacy)
2117
+ };
2607
2118
  }
2608
2119
  function normalizeSessionWebSocketArgs(urlOrOptions, options) {
2609
- if (typeof urlOrOptions === "string" || urlOrOptions instanceof URL) {
2610
- const normalizedOptions2 = normalizeSessionWebSocketOptions(options);
2611
- return {
2612
- url: normalizeWebSocketUrl(urlOrOptions),
2613
- options: normalizedOptions2,
2614
- legacyCallbacks: extractLegacyWebSocketCallbacks(options)
2615
- };
2616
- }
2617
- const legacy = urlOrOptions;
2618
- const normalizedOptions = normalizeSessionWebSocketOptions(legacy);
2619
- return {
2620
- url: normalizeWebSocketUrl(legacy.url),
2621
- options: normalizedOptions,
2622
- legacyCallbacks: extractLegacyWebSocketCallbacks(legacy)
2623
- };
2120
+ if (typeof urlOrOptions === "string" || urlOrOptions instanceof URL) {
2121
+ const normalizedOptions = normalizeSessionWebSocketOptions(options);
2122
+ return {
2123
+ url: normalizeWebSocketUrl(urlOrOptions),
2124
+ options: normalizedOptions,
2125
+ legacyCallbacks: extractLegacyWebSocketCallbacks(options)
2126
+ };
2127
+ }
2128
+ const legacy = urlOrOptions;
2129
+ const normalizedOptions = normalizeSessionWebSocketOptions(legacy);
2130
+ return {
2131
+ url: normalizeWebSocketUrl(legacy.url),
2132
+ options: normalizedOptions,
2133
+ legacyCallbacks: extractLegacyWebSocketCallbacks(legacy)
2134
+ };
2624
2135
  }
2625
2136
  async function websocket(urlOrOptions, options) {
2626
- const normalized = normalizeStandaloneWebSocketArgs(urlOrOptions, options);
2627
- validateWebSocketProtocols(normalized.options.protocols);
2628
- assertNoManualWebSocketProtocolHeader(normalized.options.headers);
2629
- const emulationMode = resolveEmulationMode(
2630
- normalized.options.browser,
2631
- normalized.options.os,
2632
- normalized.options.emulation
2633
- );
2634
- const protocols = normalizeWebSocketProtocolList(normalized.options.protocols);
2635
- return WebSocket._connectWithInit({
2636
- _internal: true,
2637
- url: normalized.url,
2638
- options: normalized.options,
2639
- openDispatchMode: "deferred",
2640
- connect: (callbacks) => {
2641
- const nativeOptions = {
2642
- url: normalized.url,
2643
- headers: headersToTuples(normalized.options.headers ?? {}),
2644
- ...protocols && protocols.length > 0 && { protocols },
2645
- ...normalized.options.proxy !== void 0 && { proxy: normalized.options.proxy },
2646
- onMessage: callbacks.onMessage,
2647
- onClose: callbacks.onClose,
2648
- onError: callbacks.onError
2649
- };
2650
- applyNativeEmulationMode(nativeOptions, emulationMode);
2651
- return nativeBinding.websocketConnect(nativeOptions);
2652
- },
2653
- legacyCallbacks: normalized.legacyCallbacks
2654
- });
2137
+ const normalized = normalizeStandaloneWebSocketArgs(urlOrOptions, options);
2138
+ validateWebSocketProtocols(normalized.options.protocols);
2139
+ assertNoManualWebSocketProtocolHeader(normalized.options.headers);
2140
+ const emulationMode = resolveEmulationMode(normalized.options.browser, normalized.options.os, normalized.options.emulation);
2141
+ const protocols = normalizeWebSocketProtocolList(normalized.options.protocols);
2142
+ return WebSocket._connectWithInit({
2143
+ _internal: true,
2144
+ url: normalized.url,
2145
+ options: normalized.options,
2146
+ openDispatchMode: "deferred",
2147
+ connect: (callbacks) => {
2148
+ const nativeOptions = {
2149
+ url: normalized.url,
2150
+ headers: headersToTuples(normalized.options.headers ?? {}),
2151
+ ...protocols && protocols.length > 0 && { protocols },
2152
+ ...normalized.options.proxy !== void 0 && { proxy: normalized.options.proxy },
2153
+ ...normalized.options.maxFrameSize !== void 0 && { maxFrameSize: normalized.options.maxFrameSize },
2154
+ ...normalized.options.maxMessageSize !== void 0 && { maxMessageSize: normalized.options.maxMessageSize },
2155
+ onMessage: callbacks.onMessage,
2156
+ onClose: callbacks.onClose,
2157
+ onError: callbacks.onError
2158
+ };
2159
+ applyNativeEmulationMode(nativeOptions, emulationMode);
2160
+ return nativeBinding.websocketConnect(nativeOptions);
2161
+ },
2162
+ legacyCallbacks: normalized.legacyCallbacks
2163
+ });
2655
2164
  }
2656
2165
  var wreq_js_default = {
2657
- fetch,
2658
- request,
2659
- get,
2660
- post,
2661
- getProfiles,
2662
- getOperatingSystems,
2663
- createTransport,
2664
- createSession,
2665
- withSession,
2666
- websocket,
2667
- WebSocket,
2668
- Headers,
2669
- Response,
2670
- Transport,
2671
- Session,
2672
- RequestError
2673
- };
2674
- export {
2675
- Headers,
2676
- RequestError,
2677
- Response,
2678
- Session,
2679
- Transport,
2680
- WebSocket,
2681
- createSession,
2682
- createTransport,
2683
- wreq_js_default as default,
2684
- fetch,
2685
- get,
2686
- getOperatingSystems,
2687
- getProfiles,
2688
- post,
2689
- request,
2690
- websocket,
2691
- withSession
2166
+ fetch,
2167
+ request,
2168
+ get,
2169
+ post,
2170
+ getProfiles,
2171
+ getOperatingSystems,
2172
+ createTransport,
2173
+ createSession,
2174
+ withSession,
2175
+ websocket,
2176
+ WebSocket,
2177
+ Headers,
2178
+ Response,
2179
+ Transport,
2180
+ Session,
2181
+ RequestError
2692
2182
  };
2183
+ //#endregion
2184
+ export { Headers, RequestError, Response, Session, Transport, WebSocket, createSession, createTransport, wreq_js_default as default, fetch, get, getOperatingSystems, getProfiles, post, request, websocket, withSession };
2185
+
2693
2186
  //# sourceMappingURL=wreq-js.js.map