wreq-js 2.2.2 → 2.3.1

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