@byfriends/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1181 @@
1
+ import { fileURLToPath as __cjsShimFileURLToPath } from 'node:url';
2
+ import { dirname as __cjsShimDirname } from 'node:path';
3
+ const __filename = __cjsShimFileURLToPath(import.meta.url);
4
+ const __dirname = __cjsShimDirname(__filename);
5
+ import { n as __esmMin } from "./index.mjs";
6
+ import { i as init_esm_min, n as FormData, o as Blob, r as formDataToBlob, s as init_fetch_blob, t as init_from } from "./from-CeYuGzYt.mjs";
7
+ import Ns, { PassThrough, pipeline } from "node:stream";
8
+ import http from "node:http";
9
+ import { format } from "node:url";
10
+ import https from "node:https";
11
+ import zlib from "node:zlib";
12
+ import { Buffer as Buffer$1 } from "node:buffer";
13
+ import { deprecate, promisify, types } from "node:util";
14
+ import { isIP } from "node:net";
15
+ //#region ../../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js
16
+ /**
17
+ * Returns a `Buffer` instance from the given data URI `uri`.
18
+ *
19
+ * @param {String} uri Data URI to turn into a Buffer instance
20
+ * @returns {Buffer} Buffer instance from Data URI
21
+ * @api public
22
+ */
23
+ function dataUriToBuffer(uri) {
24
+ if (!/^data:/i.test(uri)) throw new TypeError("`uri` does not appear to be a Data URI (must begin with \"data:\")");
25
+ uri = uri.replace(/\r?\n/g, "");
26
+ const firstComma = uri.indexOf(",");
27
+ if (firstComma === -1 || firstComma <= 4) throw new TypeError("malformed data: URI");
28
+ const meta = uri.substring(5, firstComma).split(";");
29
+ let charset = "";
30
+ let base64 = false;
31
+ const type = meta[0] || "text/plain";
32
+ let typeFull = type;
33
+ for (let i = 1; i < meta.length; i++) if (meta[i] === "base64") base64 = true;
34
+ else if (meta[i]) {
35
+ typeFull += `;${meta[i]}`;
36
+ if (meta[i].indexOf("charset=") === 0) charset = meta[i].substring(8);
37
+ }
38
+ if (!meta[0] && !charset.length) {
39
+ typeFull += ";charset=US-ASCII";
40
+ charset = "US-ASCII";
41
+ }
42
+ const encoding = base64 ? "base64" : "ascii";
43
+ const data = unescape(uri.substring(firstComma + 1));
44
+ const buffer = Buffer.from(data, encoding);
45
+ buffer.type = type;
46
+ buffer.typeFull = typeFull;
47
+ buffer.charset = charset;
48
+ return buffer;
49
+ }
50
+ var init_dist = __esmMin((() => {}));
51
+ //#endregion
52
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js
53
+ var FetchBaseError;
54
+ var init_base = __esmMin((() => {
55
+ FetchBaseError = class extends Error {
56
+ constructor(message, type) {
57
+ super(message);
58
+ Error.captureStackTrace(this, this.constructor);
59
+ this.type = type;
60
+ }
61
+ get name() {
62
+ return this.constructor.name;
63
+ }
64
+ get [Symbol.toStringTag]() {
65
+ return this.constructor.name;
66
+ }
67
+ };
68
+ }));
69
+ //#endregion
70
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js
71
+ var FetchError;
72
+ var init_fetch_error = __esmMin((() => {
73
+ init_base();
74
+ FetchError = class extends FetchBaseError {
75
+ /**
76
+ * @param {string} message - Error message for human
77
+ * @param {string} [type] - Error type for machine
78
+ * @param {SystemError} [systemError] - For Node.js system error
79
+ */
80
+ constructor(message, type, systemError) {
81
+ super(message, type);
82
+ if (systemError) {
83
+ this.code = this.errno = systemError.code;
84
+ this.erroredSysCall = systemError.syscall;
85
+ }
86
+ }
87
+ };
88
+ }));
89
+ //#endregion
90
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js
91
+ var NAME, isURLSearchParameters, isBlob, isAbortSignal, isDomainOrSubdomain, isSameProtocol;
92
+ var init_is = __esmMin((() => {
93
+ NAME = Symbol.toStringTag;
94
+ isURLSearchParameters = (object) => {
95
+ return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
96
+ };
97
+ isBlob = (object) => {
98
+ return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
99
+ };
100
+ isAbortSignal = (object) => {
101
+ return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget");
102
+ };
103
+ isDomainOrSubdomain = (destination, original) => {
104
+ const orig = new URL(original).hostname;
105
+ const dest = new URL(destination).hostname;
106
+ return orig === dest || orig.endsWith(`.${dest}`);
107
+ };
108
+ isSameProtocol = (destination, original) => {
109
+ return new URL(original).protocol === new URL(destination).protocol;
110
+ };
111
+ }));
112
+ //#endregion
113
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js
114
+ /**
115
+ * Body.js
116
+ *
117
+ * Body interface provides common methods for Request and Response
118
+ */
119
+ /**
120
+ * Consume and convert an entire Body to a Buffer.
121
+ *
122
+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
123
+ *
124
+ * @return Promise
125
+ */
126
+ async function consumeBody(data) {
127
+ if (data[INTERNALS$2].disturbed) throw new TypeError(`body used already for: ${data.url}`);
128
+ data[INTERNALS$2].disturbed = true;
129
+ if (data[INTERNALS$2].error) throw data[INTERNALS$2].error;
130
+ const { body } = data;
131
+ if (body === null) return Buffer$1.alloc(0);
132
+ /* c8 ignore next 3 */
133
+ if (!(body instanceof Ns)) return Buffer$1.alloc(0);
134
+ const accum = [];
135
+ let accumBytes = 0;
136
+ try {
137
+ for await (const chunk of body) {
138
+ if (data.size > 0 && accumBytes + chunk.length > data.size) {
139
+ const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
140
+ body.destroy(error);
141
+ throw error;
142
+ }
143
+ accumBytes += chunk.length;
144
+ accum.push(chunk);
145
+ }
146
+ } catch (error) {
147
+ throw error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, "system", error);
148
+ }
149
+ if (body.readableEnded === true || body._readableState.ended === true) try {
150
+ if (accum.every((c) => typeof c === "string")) return Buffer$1.from(accum.join(""));
151
+ return Buffer$1.concat(accum, accumBytes);
152
+ } catch (error) {
153
+ throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, "system", error);
154
+ }
155
+ else throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
156
+ }
157
+ var pipeline$1, INTERNALS$2, Body, clone, getNonSpecFormDataBoundary, extractContentType, getTotalBytes, writeToStream;
158
+ var init_body = __esmMin((() => {
159
+ init_fetch_blob();
160
+ init_esm_min();
161
+ init_fetch_error();
162
+ init_base();
163
+ init_is();
164
+ pipeline$1 = promisify(Ns.pipeline);
165
+ INTERNALS$2 = Symbol("Body internals");
166
+ Body = class {
167
+ constructor(body, { size = 0 } = {}) {
168
+ let boundary = null;
169
+ if (body === null) body = null;
170
+ else if (isURLSearchParameters(body)) body = Buffer$1.from(body.toString());
171
+ else if (isBlob(body)) {} else if (Buffer$1.isBuffer(body)) {} else if (types.isAnyArrayBuffer(body)) body = Buffer$1.from(body);
172
+ else if (ArrayBuffer.isView(body)) body = Buffer$1.from(body.buffer, body.byteOffset, body.byteLength);
173
+ else if (body instanceof Ns) {} else if (body instanceof FormData) {
174
+ body = formDataToBlob(body);
175
+ boundary = body.type.split("=")[1];
176
+ } else body = Buffer$1.from(String(body));
177
+ let stream = body;
178
+ if (Buffer$1.isBuffer(body)) stream = Ns.Readable.from(body);
179
+ else if (isBlob(body)) stream = Ns.Readable.from(body.stream());
180
+ this[INTERNALS$2] = {
181
+ body,
182
+ stream,
183
+ boundary,
184
+ disturbed: false,
185
+ error: null
186
+ };
187
+ this.size = size;
188
+ if (body instanceof Ns) body.on("error", (error_) => {
189
+ const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
190
+ this[INTERNALS$2].error = error;
191
+ });
192
+ }
193
+ get body() {
194
+ return this[INTERNALS$2].stream;
195
+ }
196
+ get bodyUsed() {
197
+ return this[INTERNALS$2].disturbed;
198
+ }
199
+ /**
200
+ * Decode response as ArrayBuffer
201
+ *
202
+ * @return Promise
203
+ */
204
+ async arrayBuffer() {
205
+ const { buffer, byteOffset, byteLength } = await consumeBody(this);
206
+ return buffer.slice(byteOffset, byteOffset + byteLength);
207
+ }
208
+ async formData() {
209
+ const ct = this.headers.get("content-type");
210
+ if (ct.startsWith("application/x-www-form-urlencoded")) {
211
+ const formData = new FormData();
212
+ const parameters = new URLSearchParams(await this.text());
213
+ for (const [name, value] of parameters) formData.append(name, value);
214
+ return formData;
215
+ }
216
+ const { toFormData } = await import("./multipart-parser-Dap8Nj6i.mjs");
217
+ return toFormData(this.body, ct);
218
+ }
219
+ /**
220
+ * Return raw response as Blob
221
+ *
222
+ * @return Promise
223
+ */
224
+ async blob() {
225
+ const ct = this.headers && this.headers.get("content-type") || this[INTERNALS$2].body && this[INTERNALS$2].body.type || "";
226
+ return new Blob([await this.arrayBuffer()], { type: ct });
227
+ }
228
+ /**
229
+ * Decode response as json
230
+ *
231
+ * @return Promise
232
+ */
233
+ async json() {
234
+ const text = await this.text();
235
+ return JSON.parse(text);
236
+ }
237
+ /**
238
+ * Decode response as text
239
+ *
240
+ * @return Promise
241
+ */
242
+ async text() {
243
+ const buffer = await consumeBody(this);
244
+ return new TextDecoder().decode(buffer);
245
+ }
246
+ /**
247
+ * Decode response as buffer (non-spec api)
248
+ *
249
+ * @return Promise
250
+ */
251
+ buffer() {
252
+ return consumeBody(this);
253
+ }
254
+ };
255
+ Body.prototype.buffer = deprecate(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer");
256
+ Object.defineProperties(Body.prototype, {
257
+ body: { enumerable: true },
258
+ bodyUsed: { enumerable: true },
259
+ arrayBuffer: { enumerable: true },
260
+ blob: { enumerable: true },
261
+ json: { enumerable: true },
262
+ text: { enumerable: true },
263
+ data: { get: deprecate(() => {}, "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (response)") }
264
+ });
265
+ clone = (instance, highWaterMark) => {
266
+ let p1;
267
+ let p2;
268
+ let { body } = instance[INTERNALS$2];
269
+ if (instance.bodyUsed) throw new Error("cannot clone body after it is used");
270
+ if (body instanceof Ns && typeof body.getBoundary !== "function") {
271
+ p1 = new PassThrough({ highWaterMark });
272
+ p2 = new PassThrough({ highWaterMark });
273
+ body.pipe(p1);
274
+ body.pipe(p2);
275
+ instance[INTERNALS$2].stream = p1;
276
+ body = p2;
277
+ }
278
+ return body;
279
+ };
280
+ getNonSpecFormDataBoundary = deprecate((body) => body.getBoundary(), "form-data doesn't follow the spec and requires special treatment. Use alternative package", "https://github.com/node-fetch/node-fetch/issues/1167");
281
+ extractContentType = (body, request) => {
282
+ if (body === null) return null;
283
+ if (typeof body === "string") return "text/plain;charset=UTF-8";
284
+ if (isURLSearchParameters(body)) return "application/x-www-form-urlencoded;charset=UTF-8";
285
+ if (isBlob(body)) return body.type || null;
286
+ if (Buffer$1.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) return null;
287
+ if (body instanceof FormData) return `multipart/form-data; boundary=${request[INTERNALS$2].boundary}`;
288
+ if (body && typeof body.getBoundary === "function") return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
289
+ if (body instanceof Ns) return null;
290
+ return "text/plain;charset=UTF-8";
291
+ };
292
+ getTotalBytes = (request) => {
293
+ const { body } = request[INTERNALS$2];
294
+ if (body === null) return 0;
295
+ if (isBlob(body)) return body.size;
296
+ if (Buffer$1.isBuffer(body)) return body.length;
297
+ if (body && typeof body.getLengthSync === "function") return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
298
+ return null;
299
+ };
300
+ writeToStream = async (dest, { body }) => {
301
+ if (body === null) dest.end();
302
+ else await pipeline$1(body, dest);
303
+ };
304
+ }));
305
+ //#endregion
306
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
307
+ /**
308
+ * Headers.js
309
+ *
310
+ * Headers class offers convenient helpers
311
+ */
312
+ /**
313
+ * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do
314
+ * not conform to HTTP grammar productions.
315
+ * @param {import('http').IncomingMessage['rawHeaders']} headers
316
+ */
317
+ function fromRawHeaders(headers = []) {
318
+ return new Headers(headers.reduce((result, value, index, array) => {
319
+ if (index % 2 === 0) result.push(array.slice(index, index + 2));
320
+ return result;
321
+ }, []).filter(([name, value]) => {
322
+ try {
323
+ validateHeaderName(name);
324
+ validateHeaderValue(name, String(value));
325
+ return true;
326
+ } catch {
327
+ return false;
328
+ }
329
+ }));
330
+ }
331
+ var validateHeaderName, validateHeaderValue, Headers;
332
+ var init_headers = __esmMin((() => {
333
+ validateHeaderName = typeof http.validateHeaderName === "function" ? http.validateHeaderName : (name) => {
334
+ if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
335
+ const error = /* @__PURE__ */ new TypeError(`Header name must be a valid HTTP token [${name}]`);
336
+ Object.defineProperty(error, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
337
+ throw error;
338
+ }
339
+ };
340
+ validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name, value) => {
341
+ if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
342
+ const error = /* @__PURE__ */ new TypeError(`Invalid character in header content ["${name}"]`);
343
+ Object.defineProperty(error, "code", { value: "ERR_INVALID_CHAR" });
344
+ throw error;
345
+ }
346
+ };
347
+ Headers = class Headers extends URLSearchParams {
348
+ /**
349
+ * Headers class
350
+ *
351
+ * @constructor
352
+ * @param {HeadersInit} [init] - Response headers
353
+ */
354
+ constructor(init) {
355
+ /** @type {string[][]} */
356
+ let result = [];
357
+ if (init instanceof Headers) {
358
+ const raw = init.raw();
359
+ for (const [name, values] of Object.entries(raw)) result.push(...values.map((value) => [name, value]));
360
+ } else if (init == null) {} else if (typeof init === "object" && !types.isBoxedPrimitive(init)) {
361
+ const method = init[Symbol.iterator];
362
+ if (method == null) result.push(...Object.entries(init));
363
+ else {
364
+ if (typeof method !== "function") throw new TypeError("Header pairs must be iterable");
365
+ result = [...init].map((pair) => {
366
+ if (typeof pair !== "object" || types.isBoxedPrimitive(pair)) throw new TypeError("Each header pair must be an iterable object");
367
+ return [...pair];
368
+ }).map((pair) => {
369
+ if (pair.length !== 2) throw new TypeError("Each header pair must be a name/value tuple");
370
+ return [...pair];
371
+ });
372
+ }
373
+ } else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
374
+ result = result.length > 0 ? result.map(([name, value]) => {
375
+ validateHeaderName(name);
376
+ validateHeaderValue(name, String(value));
377
+ return [String(name).toLowerCase(), String(value)];
378
+ }) : void 0;
379
+ super(result);
380
+ return new Proxy(this, { get(target, p, receiver) {
381
+ switch (p) {
382
+ case "append":
383
+ case "set": return (name, value) => {
384
+ validateHeaderName(name);
385
+ validateHeaderValue(name, String(value));
386
+ return URLSearchParams.prototype[p].call(target, String(name).toLowerCase(), String(value));
387
+ };
388
+ case "delete":
389
+ case "has":
390
+ case "getAll": return (name) => {
391
+ validateHeaderName(name);
392
+ return URLSearchParams.prototype[p].call(target, String(name).toLowerCase());
393
+ };
394
+ case "keys": return () => {
395
+ target.sort();
396
+ return new Set(URLSearchParams.prototype.keys.call(target)).keys();
397
+ };
398
+ default: return Reflect.get(target, p, receiver);
399
+ }
400
+ } });
401
+ /* c8 ignore next */
402
+ }
403
+ get [Symbol.toStringTag]() {
404
+ return this.constructor.name;
405
+ }
406
+ toString() {
407
+ return Object.prototype.toString.call(this);
408
+ }
409
+ get(name) {
410
+ const values = this.getAll(name);
411
+ if (values.length === 0) return null;
412
+ let value = values.join(", ");
413
+ if (/^content-encoding$/i.test(name)) value = value.toLowerCase();
414
+ return value;
415
+ }
416
+ forEach(callback, thisArg = void 0) {
417
+ for (const name of this.keys()) Reflect.apply(callback, thisArg, [
418
+ this.get(name),
419
+ name,
420
+ this
421
+ ]);
422
+ }
423
+ *values() {
424
+ for (const name of this.keys()) yield this.get(name);
425
+ }
426
+ /**
427
+ * @type {() => IterableIterator<[string, string]>}
428
+ */
429
+ *entries() {
430
+ for (const name of this.keys()) yield [name, this.get(name)];
431
+ }
432
+ [Symbol.iterator]() {
433
+ return this.entries();
434
+ }
435
+ /**
436
+ * Node-fetch non-spec method
437
+ * returning all headers and their values as array
438
+ * @returns {Record<string, string[]>}
439
+ */
440
+ raw() {
441
+ return [...this.keys()].reduce((result, key) => {
442
+ result[key] = this.getAll(key);
443
+ return result;
444
+ }, {});
445
+ }
446
+ /**
447
+ * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
448
+ */
449
+ [Symbol.for("nodejs.util.inspect.custom")]() {
450
+ return [...this.keys()].reduce((result, key) => {
451
+ const values = this.getAll(key);
452
+ if (key === "host") result[key] = values[0];
453
+ else result[key] = values.length > 1 ? values : values[0];
454
+ return result;
455
+ }, {});
456
+ }
457
+ };
458
+ /**
459
+ * Re-shaping object for Web IDL tests
460
+ * Only need to do it for overridden methods
461
+ */
462
+ Object.defineProperties(Headers.prototype, [
463
+ "get",
464
+ "entries",
465
+ "forEach",
466
+ "values"
467
+ ].reduce((result, property) => {
468
+ result[property] = { enumerable: true };
469
+ return result;
470
+ }, {}));
471
+ }));
472
+ //#endregion
473
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js
474
+ var redirectStatus, isRedirect;
475
+ var init_is_redirect = __esmMin((() => {
476
+ redirectStatus = new Set([
477
+ 301,
478
+ 302,
479
+ 303,
480
+ 307,
481
+ 308
482
+ ]);
483
+ isRedirect = (code) => {
484
+ return redirectStatus.has(code);
485
+ };
486
+ }));
487
+ //#endregion
488
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js
489
+ var INTERNALS$1, Response;
490
+ var init_response = __esmMin((() => {
491
+ init_headers();
492
+ init_body();
493
+ init_is_redirect();
494
+ INTERNALS$1 = Symbol("Response internals");
495
+ Response = class Response extends Body {
496
+ constructor(body = null, options = {}) {
497
+ super(body, options);
498
+ const status = options.status != null ? options.status : 200;
499
+ const headers = new Headers(options.headers);
500
+ if (body !== null && !headers.has("Content-Type")) {
501
+ const contentType = extractContentType(body, this);
502
+ if (contentType) headers.append("Content-Type", contentType);
503
+ }
504
+ this[INTERNALS$1] = {
505
+ type: "default",
506
+ url: options.url,
507
+ status,
508
+ statusText: options.statusText || "",
509
+ headers,
510
+ counter: options.counter,
511
+ highWaterMark: options.highWaterMark
512
+ };
513
+ }
514
+ get type() {
515
+ return this[INTERNALS$1].type;
516
+ }
517
+ get url() {
518
+ return this[INTERNALS$1].url || "";
519
+ }
520
+ get status() {
521
+ return this[INTERNALS$1].status;
522
+ }
523
+ /**
524
+ * Convenience property representing if the request ended normally
525
+ */
526
+ get ok() {
527
+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
528
+ }
529
+ get redirected() {
530
+ return this[INTERNALS$1].counter > 0;
531
+ }
532
+ get statusText() {
533
+ return this[INTERNALS$1].statusText;
534
+ }
535
+ get headers() {
536
+ return this[INTERNALS$1].headers;
537
+ }
538
+ get highWaterMark() {
539
+ return this[INTERNALS$1].highWaterMark;
540
+ }
541
+ /**
542
+ * Clone this response
543
+ *
544
+ * @return Response
545
+ */
546
+ clone() {
547
+ return new Response(clone(this, this.highWaterMark), {
548
+ type: this.type,
549
+ url: this.url,
550
+ status: this.status,
551
+ statusText: this.statusText,
552
+ headers: this.headers,
553
+ ok: this.ok,
554
+ redirected: this.redirected,
555
+ size: this.size,
556
+ highWaterMark: this.highWaterMark
557
+ });
558
+ }
559
+ /**
560
+ * @param {string} url The URL that the new response is to originate from.
561
+ * @param {number} status An optional status code for the response (e.g., 302.)
562
+ * @returns {Response} A Response object.
563
+ */
564
+ static redirect(url, status = 302) {
565
+ if (!isRedirect(status)) throw new RangeError("Failed to execute \"redirect\" on \"response\": Invalid status code");
566
+ return new Response(null, {
567
+ headers: { location: new URL(url).toString() },
568
+ status
569
+ });
570
+ }
571
+ static error() {
572
+ const response = new Response(null, {
573
+ status: 0,
574
+ statusText: ""
575
+ });
576
+ response[INTERNALS$1].type = "error";
577
+ return response;
578
+ }
579
+ static json(data = void 0, init = {}) {
580
+ const body = JSON.stringify(data);
581
+ if (body === void 0) throw new TypeError("data is not JSON serializable");
582
+ const headers = new Headers(init && init.headers);
583
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
584
+ return new Response(body, {
585
+ ...init,
586
+ headers
587
+ });
588
+ }
589
+ get [Symbol.toStringTag]() {
590
+ return "Response";
591
+ }
592
+ };
593
+ Object.defineProperties(Response.prototype, {
594
+ type: { enumerable: true },
595
+ url: { enumerable: true },
596
+ status: { enumerable: true },
597
+ ok: { enumerable: true },
598
+ redirected: { enumerable: true },
599
+ statusText: { enumerable: true },
600
+ headers: { enumerable: true },
601
+ clone: { enumerable: true }
602
+ });
603
+ }));
604
+ //#endregion
605
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js
606
+ var getSearch;
607
+ var init_get_search = __esmMin((() => {
608
+ getSearch = (parsedURL) => {
609
+ if (parsedURL.search) return parsedURL.search;
610
+ const lastOffset = parsedURL.href.length - 1;
611
+ const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
612
+ return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
613
+ };
614
+ }));
615
+ //#endregion
616
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js
617
+ /**
618
+ * @external URL
619
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL}
620
+ */
621
+ /**
622
+ * @module utils/referrer
623
+ * @private
624
+ */
625
+ /**
626
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy §8.4. Strip url for use as a referrer}
627
+ * @param {string} URL
628
+ * @param {boolean} [originOnly=false]
629
+ */
630
+ function stripURLForUseAsAReferrer(url, originOnly = false) {
631
+ if (url == null) return "no-referrer";
632
+ url = new URL(url);
633
+ if (/^(about|blob|data):$/.test(url.protocol)) return "no-referrer";
634
+ url.username = "";
635
+ url.password = "";
636
+ url.hash = "";
637
+ if (originOnly) {
638
+ url.pathname = "";
639
+ url.search = "";
640
+ }
641
+ return url;
642
+ }
643
+ /**
644
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy §3. Referrer Policies}
645
+ * @param {string} referrerPolicy
646
+ * @returns {string} referrerPolicy
647
+ */
648
+ function validateReferrerPolicy(referrerPolicy) {
649
+ if (!ReferrerPolicy.has(referrerPolicy)) throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
650
+ return referrerPolicy;
651
+ }
652
+ /**
653
+ * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?}
654
+ * @param {external:URL} url
655
+ * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
656
+ */
657
+ function isOriginPotentiallyTrustworthy(url) {
658
+ if (/^(http|ws)s:$/.test(url.protocol)) return true;
659
+ const hostIp = url.host.replace(/(^\[)|(]$)/g, "");
660
+ const hostIPVersion = isIP(hostIp);
661
+ if (hostIPVersion === 4 && /^127\./.test(hostIp)) return true;
662
+ if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) return true;
663
+ if (url.host === "localhost" || url.host.endsWith(".localhost")) return false;
664
+ if (url.protocol === "file:") return true;
665
+ return false;
666
+ }
667
+ /**
668
+ * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?}
669
+ * @param {external:URL} url
670
+ * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
671
+ */
672
+ function isUrlPotentiallyTrustworthy(url) {
673
+ if (/^about:(blank|srcdoc)$/.test(url)) return true;
674
+ if (url.protocol === "data:") return true;
675
+ if (/^(blob|filesystem):$/.test(url.protocol)) return true;
676
+ return isOriginPotentiallyTrustworthy(url);
677
+ }
678
+ /**
679
+ * Modifies the referrerURL to enforce any extra security policy considerations.
680
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7
681
+ * @callback module:utils/referrer~referrerURLCallback
682
+ * @param {external:URL} referrerURL
683
+ * @returns {external:URL} modified referrerURL
684
+ */
685
+ /**
686
+ * Modifies the referrerOrigin to enforce any extra security policy considerations.
687
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7
688
+ * @callback module:utils/referrer~referrerOriginCallback
689
+ * @param {external:URL} referrerOrigin
690
+ * @returns {external:URL} modified referrerOrigin
691
+ */
692
+ /**
693
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}
694
+ * @param {Request} request
695
+ * @param {object} o
696
+ * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback
697
+ * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback
698
+ * @returns {external:URL} Request's referrer
699
+ */
700
+ function determineRequestsReferrer(request, { referrerURLCallback, referrerOriginCallback } = {}) {
701
+ if (request.referrer === "no-referrer" || request.referrerPolicy === "") return null;
702
+ const policy = request.referrerPolicy;
703
+ if (request.referrer === "about:client") return "no-referrer";
704
+ const referrerSource = request.referrer;
705
+ let referrerURL = stripURLForUseAsAReferrer(referrerSource);
706
+ let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
707
+ if (referrerURL.toString().length > 4096) referrerURL = referrerOrigin;
708
+ if (referrerURLCallback) referrerURL = referrerURLCallback(referrerURL);
709
+ if (referrerOriginCallback) referrerOrigin = referrerOriginCallback(referrerOrigin);
710
+ const currentURL = new URL(request.url);
711
+ switch (policy) {
712
+ case "no-referrer": return "no-referrer";
713
+ case "origin": return referrerOrigin;
714
+ case "unsafe-url": return referrerURL;
715
+ case "strict-origin":
716
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) return "no-referrer";
717
+ return referrerOrigin.toString();
718
+ case "strict-origin-when-cross-origin":
719
+ if (referrerURL.origin === currentURL.origin) return referrerURL;
720
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) return "no-referrer";
721
+ return referrerOrigin;
722
+ case "same-origin":
723
+ if (referrerURL.origin === currentURL.origin) return referrerURL;
724
+ return "no-referrer";
725
+ case "origin-when-cross-origin":
726
+ if (referrerURL.origin === currentURL.origin) return referrerURL;
727
+ return referrerOrigin;
728
+ case "no-referrer-when-downgrade":
729
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) return "no-referrer";
730
+ return referrerURL;
731
+ default: throw new TypeError(`Invalid referrerPolicy: ${policy}`);
732
+ }
733
+ }
734
+ /**
735
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header}
736
+ * @param {Headers} headers Response headers
737
+ * @returns {string} policy
738
+ */
739
+ function parseReferrerPolicyFromHeader(headers) {
740
+ const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
741
+ let policy = "";
742
+ for (const token of policyTokens) if (token && ReferrerPolicy.has(token)) policy = token;
743
+ return policy;
744
+ }
745
+ var ReferrerPolicy, DEFAULT_REFERRER_POLICY;
746
+ var init_referrer = __esmMin((() => {
747
+ ReferrerPolicy = new Set([
748
+ "",
749
+ "no-referrer",
750
+ "no-referrer-when-downgrade",
751
+ "same-origin",
752
+ "origin",
753
+ "strict-origin",
754
+ "origin-when-cross-origin",
755
+ "strict-origin-when-cross-origin",
756
+ "unsafe-url"
757
+ ]);
758
+ DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
759
+ }));
760
+ //#endregion
761
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js
762
+ /**
763
+ * Request.js
764
+ *
765
+ * Request class contains server only options
766
+ *
767
+ * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
768
+ */
769
+ var INTERNALS, isRequest, doBadDataWarn, Request, getNodeRequestOptions;
770
+ var init_request = __esmMin((() => {
771
+ init_headers();
772
+ init_body();
773
+ init_is();
774
+ init_get_search();
775
+ init_referrer();
776
+ INTERNALS = Symbol("Request internals");
777
+ isRequest = (object) => {
778
+ return typeof object === "object" && typeof object[INTERNALS] === "object";
779
+ };
780
+ doBadDataWarn = deprecate(() => {}, ".data is not a valid RequestInit property, use .body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (request)");
781
+ Request = class Request extends Body {
782
+ constructor(input, init = {}) {
783
+ let parsedURL;
784
+ if (isRequest(input)) parsedURL = new URL(input.url);
785
+ else {
786
+ parsedURL = new URL(input);
787
+ input = {};
788
+ }
789
+ if (parsedURL.username !== "" || parsedURL.password !== "") throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
790
+ let method = init.method || input.method || "GET";
791
+ if (/^(delete|get|head|options|post|put)$/i.test(method)) method = method.toUpperCase();
792
+ if (!isRequest(init) && "data" in init) doBadDataWarn();
793
+ if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) throw new TypeError("Request with GET/HEAD method cannot have body");
794
+ const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
795
+ super(inputBody, { size: init.size || input.size || 0 });
796
+ const headers = new Headers(init.headers || input.headers || {});
797
+ if (inputBody !== null && !headers.has("Content-Type")) {
798
+ const contentType = extractContentType(inputBody, this);
799
+ if (contentType) headers.set("Content-Type", contentType);
800
+ }
801
+ let signal = isRequest(input) ? input.signal : null;
802
+ if ("signal" in init) signal = init.signal;
803
+ if (signal != null && !isAbortSignal(signal)) throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
804
+ let referrer = init.referrer == null ? input.referrer : init.referrer;
805
+ if (referrer === "") referrer = "no-referrer";
806
+ else if (referrer) {
807
+ const parsedReferrer = new URL(referrer);
808
+ referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
809
+ } else referrer = void 0;
810
+ this[INTERNALS] = {
811
+ method,
812
+ redirect: init.redirect || input.redirect || "follow",
813
+ headers,
814
+ parsedURL,
815
+ signal,
816
+ referrer
817
+ };
818
+ this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow;
819
+ this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress;
820
+ this.counter = init.counter || input.counter || 0;
821
+ this.agent = init.agent || input.agent;
822
+ this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;
823
+ this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;
824
+ this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || "";
825
+ }
826
+ /** @returns {string} */
827
+ get method() {
828
+ return this[INTERNALS].method;
829
+ }
830
+ /** @returns {string} */
831
+ get url() {
832
+ return format(this[INTERNALS].parsedURL);
833
+ }
834
+ /** @returns {Headers} */
835
+ get headers() {
836
+ return this[INTERNALS].headers;
837
+ }
838
+ get redirect() {
839
+ return this[INTERNALS].redirect;
840
+ }
841
+ /** @returns {AbortSignal} */
842
+ get signal() {
843
+ return this[INTERNALS].signal;
844
+ }
845
+ get referrer() {
846
+ if (this[INTERNALS].referrer === "no-referrer") return "";
847
+ if (this[INTERNALS].referrer === "client") return "about:client";
848
+ if (this[INTERNALS].referrer) return this[INTERNALS].referrer.toString();
849
+ }
850
+ get referrerPolicy() {
851
+ return this[INTERNALS].referrerPolicy;
852
+ }
853
+ set referrerPolicy(referrerPolicy) {
854
+ this[INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy);
855
+ }
856
+ /**
857
+ * Clone this request
858
+ *
859
+ * @return Request
860
+ */
861
+ clone() {
862
+ return new Request(this);
863
+ }
864
+ get [Symbol.toStringTag]() {
865
+ return "Request";
866
+ }
867
+ };
868
+ Object.defineProperties(Request.prototype, {
869
+ method: { enumerable: true },
870
+ url: { enumerable: true },
871
+ headers: { enumerable: true },
872
+ redirect: { enumerable: true },
873
+ clone: { enumerable: true },
874
+ signal: { enumerable: true },
875
+ referrer: { enumerable: true },
876
+ referrerPolicy: { enumerable: true }
877
+ });
878
+ getNodeRequestOptions = (request) => {
879
+ const { parsedURL } = request[INTERNALS];
880
+ const headers = new Headers(request[INTERNALS].headers);
881
+ if (!headers.has("Accept")) headers.set("Accept", "*/*");
882
+ let contentLengthValue = null;
883
+ if (request.body === null && /^(post|put)$/i.test(request.method)) contentLengthValue = "0";
884
+ if (request.body !== null) {
885
+ const totalBytes = getTotalBytes(request);
886
+ if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) contentLengthValue = String(totalBytes);
887
+ }
888
+ if (contentLengthValue) headers.set("Content-Length", contentLengthValue);
889
+ if (request.referrerPolicy === "") request.referrerPolicy = DEFAULT_REFERRER_POLICY;
890
+ if (request.referrer && request.referrer !== "no-referrer") request[INTERNALS].referrer = determineRequestsReferrer(request);
891
+ else request[INTERNALS].referrer = "no-referrer";
892
+ if (request[INTERNALS].referrer instanceof URL) headers.set("Referer", request.referrer);
893
+ if (!headers.has("User-Agent")) headers.set("User-Agent", "node-fetch");
894
+ if (request.compress && !headers.has("Accept-Encoding")) headers.set("Accept-Encoding", "gzip, deflate, br");
895
+ let { agent } = request;
896
+ if (typeof agent === "function") agent = agent(parsedURL);
897
+ const search = getSearch(parsedURL);
898
+ return {
899
+ /** @type {URL} */
900
+ parsedURL,
901
+ options: {
902
+ path: parsedURL.pathname + search,
903
+ method: request.method,
904
+ headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
905
+ insecureHTTPParser: request.insecureHTTPParser,
906
+ agent
907
+ }
908
+ };
909
+ };
910
+ }));
911
+ //#endregion
912
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js
913
+ var AbortError;
914
+ var init_abort_error = __esmMin((() => {
915
+ init_base();
916
+ AbortError = class extends FetchBaseError {
917
+ constructor(message, type = "aborted") {
918
+ super(message, type);
919
+ }
920
+ };
921
+ }));
922
+ //#endregion
923
+ //#region ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js
924
+ /**
925
+ * Index.js
926
+ *
927
+ * a request API compatible with window.fetch
928
+ *
929
+ * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
930
+ */
931
+ /**
932
+ * Fetch function
933
+ *
934
+ * @param {string | URL | import('./request').default} url - Absolute url or Request instance
935
+ * @param {*} [options_] - Fetch options
936
+ * @return {Promise<import('./response').default>}
937
+ */
938
+ async function fetch(url, options_) {
939
+ return new Promise((resolve, reject) => {
940
+ const request = new Request(url, options_);
941
+ const { parsedURL, options } = getNodeRequestOptions(request);
942
+ if (!supportedSchemas.has(parsedURL.protocol)) throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`);
943
+ if (parsedURL.protocol === "data:") {
944
+ const data = dataUriToBuffer(request.url);
945
+ resolve(new Response(data, { headers: { "Content-Type": data.typeFull } }));
946
+ return;
947
+ }
948
+ const send = (parsedURL.protocol === "https:" ? https : http).request;
949
+ const { signal } = request;
950
+ let response = null;
951
+ const abort = () => {
952
+ const error = new AbortError("The operation was aborted.");
953
+ reject(error);
954
+ if (request.body && request.body instanceof Ns.Readable) request.body.destroy(error);
955
+ if (!response || !response.body) return;
956
+ response.body.emit("error", error);
957
+ };
958
+ if (signal && signal.aborted) {
959
+ abort();
960
+ return;
961
+ }
962
+ const abortAndFinalize = () => {
963
+ abort();
964
+ finalize();
965
+ };
966
+ const request_ = send(parsedURL.toString(), options);
967
+ if (signal) signal.addEventListener("abort", abortAndFinalize);
968
+ const finalize = () => {
969
+ request_.abort();
970
+ if (signal) signal.removeEventListener("abort", abortAndFinalize);
971
+ };
972
+ request_.on("error", (error) => {
973
+ reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, "system", error));
974
+ finalize();
975
+ });
976
+ fixResponseChunkedTransferBadEnding(request_, (error) => {
977
+ if (response && response.body) response.body.destroy(error);
978
+ });
979
+ /* c8 ignore next 18 */
980
+ if (process.version < "v14") request_.on("socket", (s) => {
981
+ let endedWithEventsCount;
982
+ s.prependListener("end", () => {
983
+ endedWithEventsCount = s._eventsCount;
984
+ });
985
+ s.prependListener("close", (hadError) => {
986
+ if (response && endedWithEventsCount < s._eventsCount && !hadError) {
987
+ const error = /* @__PURE__ */ new Error("Premature close");
988
+ error.code = "ERR_STREAM_PREMATURE_CLOSE";
989
+ response.body.emit("error", error);
990
+ }
991
+ });
992
+ });
993
+ request_.on("response", (response_) => {
994
+ request_.setTimeout(0);
995
+ const headers = fromRawHeaders(response_.rawHeaders);
996
+ if (isRedirect(response_.statusCode)) {
997
+ const location = headers.get("Location");
998
+ let locationURL = null;
999
+ try {
1000
+ locationURL = location === null ? null : new URL(location, request.url);
1001
+ } catch {
1002
+ if (request.redirect !== "manual") {
1003
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
1004
+ finalize();
1005
+ return;
1006
+ }
1007
+ }
1008
+ switch (request.redirect) {
1009
+ case "error":
1010
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect"));
1011
+ finalize();
1012
+ return;
1013
+ case "manual": break;
1014
+ case "follow": {
1015
+ if (locationURL === null) break;
1016
+ if (request.counter >= request.follow) {
1017
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect"));
1018
+ finalize();
1019
+ return;
1020
+ }
1021
+ const requestOptions = {
1022
+ headers: new Headers(request.headers),
1023
+ follow: request.follow,
1024
+ counter: request.counter + 1,
1025
+ agent: request.agent,
1026
+ compress: request.compress,
1027
+ method: request.method,
1028
+ body: clone(request),
1029
+ signal: request.signal,
1030
+ size: request.size,
1031
+ referrer: request.referrer,
1032
+ referrerPolicy: request.referrerPolicy
1033
+ };
1034
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) for (const name of [
1035
+ "authorization",
1036
+ "www-authenticate",
1037
+ "cookie",
1038
+ "cookie2"
1039
+ ]) requestOptions.headers.delete(name);
1040
+ if (response_.statusCode !== 303 && request.body && options_.body instanceof Ns.Readable) {
1041
+ reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
1042
+ finalize();
1043
+ return;
1044
+ }
1045
+ if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request.method === "POST") {
1046
+ requestOptions.method = "GET";
1047
+ requestOptions.body = void 0;
1048
+ requestOptions.headers.delete("content-length");
1049
+ }
1050
+ const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
1051
+ if (responseReferrerPolicy) requestOptions.referrerPolicy = responseReferrerPolicy;
1052
+ resolve(fetch(new Request(locationURL, requestOptions)));
1053
+ finalize();
1054
+ return;
1055
+ }
1056
+ default: return reject(/* @__PURE__ */ new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));
1057
+ }
1058
+ }
1059
+ if (signal) response_.once("end", () => {
1060
+ signal.removeEventListener("abort", abortAndFinalize);
1061
+ });
1062
+ let body = pipeline(response_, new PassThrough(), (error) => {
1063
+ if (error) reject(error);
1064
+ });
1065
+ /* c8 ignore next 3 */
1066
+ if (process.version < "v12.10") response_.on("aborted", abortAndFinalize);
1067
+ const responseOptions = {
1068
+ url: request.url,
1069
+ status: response_.statusCode,
1070
+ statusText: response_.statusMessage,
1071
+ headers,
1072
+ size: request.size,
1073
+ counter: request.counter,
1074
+ highWaterMark: request.highWaterMark
1075
+ };
1076
+ const codings = headers.get("Content-Encoding");
1077
+ if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
1078
+ response = new Response(body, responseOptions);
1079
+ resolve(response);
1080
+ return;
1081
+ }
1082
+ const zlibOptions = {
1083
+ flush: zlib.Z_SYNC_FLUSH,
1084
+ finishFlush: zlib.Z_SYNC_FLUSH
1085
+ };
1086
+ if (codings === "gzip" || codings === "x-gzip") {
1087
+ body = pipeline(body, zlib.createGunzip(zlibOptions), (error) => {
1088
+ if (error) reject(error);
1089
+ });
1090
+ response = new Response(body, responseOptions);
1091
+ resolve(response);
1092
+ return;
1093
+ }
1094
+ if (codings === "deflate" || codings === "x-deflate") {
1095
+ const raw = pipeline(response_, new PassThrough(), (error) => {
1096
+ if (error) reject(error);
1097
+ });
1098
+ raw.once("data", (chunk) => {
1099
+ if ((chunk[0] & 15) === 8) body = pipeline(body, zlib.createInflate(), (error) => {
1100
+ if (error) reject(error);
1101
+ });
1102
+ else body = pipeline(body, zlib.createInflateRaw(), (error) => {
1103
+ if (error) reject(error);
1104
+ });
1105
+ response = new Response(body, responseOptions);
1106
+ resolve(response);
1107
+ });
1108
+ raw.once("end", () => {
1109
+ if (!response) {
1110
+ response = new Response(body, responseOptions);
1111
+ resolve(response);
1112
+ }
1113
+ });
1114
+ return;
1115
+ }
1116
+ if (codings === "br") {
1117
+ body = pipeline(body, zlib.createBrotliDecompress(), (error) => {
1118
+ if (error) reject(error);
1119
+ });
1120
+ response = new Response(body, responseOptions);
1121
+ resolve(response);
1122
+ return;
1123
+ }
1124
+ response = new Response(body, responseOptions);
1125
+ resolve(response);
1126
+ });
1127
+ writeToStream(request_, request).catch(reject);
1128
+ });
1129
+ }
1130
+ function fixResponseChunkedTransferBadEnding(request, errorCallback) {
1131
+ const LAST_CHUNK = Buffer$1.from("0\r\n\r\n");
1132
+ let isChunkedTransfer = false;
1133
+ let properLastChunkReceived = false;
1134
+ let previousChunk;
1135
+ request.on("response", (response) => {
1136
+ const { headers } = response;
1137
+ isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
1138
+ });
1139
+ request.on("socket", (socket) => {
1140
+ const onSocketClose = () => {
1141
+ if (isChunkedTransfer && !properLastChunkReceived) {
1142
+ const error = /* @__PURE__ */ new Error("Premature close");
1143
+ error.code = "ERR_STREAM_PREMATURE_CLOSE";
1144
+ errorCallback(error);
1145
+ }
1146
+ };
1147
+ const onData = (buf) => {
1148
+ properLastChunkReceived = Buffer$1.compare(buf.slice(-5), LAST_CHUNK) === 0;
1149
+ if (!properLastChunkReceived && previousChunk) properLastChunkReceived = Buffer$1.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && Buffer$1.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0;
1150
+ previousChunk = buf;
1151
+ };
1152
+ socket.prependListener("close", onSocketClose);
1153
+ socket.on("data", onData);
1154
+ request.on("close", () => {
1155
+ socket.removeListener("close", onSocketClose);
1156
+ socket.removeListener("data", onData);
1157
+ });
1158
+ });
1159
+ }
1160
+ var supportedSchemas;
1161
+ //#endregion
1162
+ __esmMin((() => {
1163
+ init_dist();
1164
+ init_body();
1165
+ init_response();
1166
+ init_headers();
1167
+ init_request();
1168
+ init_fetch_error();
1169
+ init_abort_error();
1170
+ init_is_redirect();
1171
+ init_esm_min();
1172
+ init_is();
1173
+ init_referrer();
1174
+ init_from();
1175
+ supportedSchemas = new Set([
1176
+ "data:",
1177
+ "http:",
1178
+ "https:"
1179
+ ]);
1180
+ }))();
1181
+ export { fetch as default };