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