Skip to content

Instantly share code, notes, and snippets.

@moshest
Last active June 20, 2024 21:37
Show Gist options
  • Save moshest/4d26ac8342b3c440bd38bdeaeac5e1d9 to your computer and use it in GitHub Desktop.
Save moshest/4d26ac8342b3c440bd38bdeaeac5e1d9 to your computer and use it in GitHub Desktop.
// v7.0.4
// https://bundlejs.com/?q=https-proxy-agent&treeshake=%5B%7B+HttpsProxyAgent+%7D%5D&config=%7B%22esbuild%22%3A%7B%22target%22%3A%5B%22es2020%22%5D%2C%22format%22%3A%22cjs%22%2C%22minify%22%3Afalse%2C%22platform%22%3A%22node%22%7D%7D
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// http-url:https://unpkg.com/[email protected]/index.js
var require_ms_2_1 = __commonJS({
"http-url:https://unpkg.com/[email protected]/index.js"(exports2, module2) {
var s = 1e3;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
module2.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === "string" && val.length > 0) {
return parse(val);
} else if (type === "number" && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
return void 0;
}
}
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + "d";
}
if (msAbs >= h) {
return Math.round(ms / h) + "h";
}
if (msAbs >= m) {
return Math.round(ms / m) + "m";
}
if (msAbs >= s) {
return Math.round(ms / s) + "s";
}
return ms + "ms";
}
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, "day");
}
if (msAbs >= h) {
return plural(ms, msAbs, h, "hour");
}
if (msAbs >= m) {
return plural(ms, msAbs, m, "minute");
}
if (msAbs >= s) {
return plural(ms, msAbs, s, "second");
}
return ms + " ms";
}
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
}
}
});
// http-url:https://unpkg.com/[email protected]/src/common
var require_common = __commonJS({
"http-url:https://unpkg.com/[email protected]/src/common"(exports2, module2) {
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require_ms_2_1();
createDebug.destroy = destroy;
Object.keys(env).forEach((key) => {
createDebug[key] = env[key];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
if (!debug.enabled) {
return;
}
const self = debug;
const curr = Number(/* @__PURE__ */ new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%") {
return "%";
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === "function") {
const val = args[index];
match = formatter.call(self, val);
args.splice(index, 1);
index--;
}
return match;
});
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy;
Object.defineProperty(debug, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
continue;
}
namespaces = split[i].replace(/\*/g, ".*?");
if (namespaces[0] === "-") {
createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
} else {
createDebug.names.push(new RegExp("^" + namespaces + "$"));
}
}
}
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
function enabled(name) {
if (name[name.length - 1] === "*") {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
}
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
module2.exports = setup;
}
});
// http-url:https://unpkg.com/[email protected]/src/browser.js
var require_browser = __commonJS({
"http-url:https://unpkg.com/[email protected]/src/browser.js"(exports2, module2) {
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load;
exports2.useColors = useColors;
exports2.storage = localstorage();
exports2.destroy = /* @__PURE__ */ (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
exports2.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
return true;
}
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
if (match === "%%") {
return;
}
index++;
if (match === "%c") {
lastC = index;
}
});
args.splice(lastC, 0, c);
}
exports2.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
if (namespaces) {
exports2.storage.setItem("debug", namespaces);
} else {
exports2.storage.removeItem("debug");
}
} catch (error) {
}
}
function load() {
let r;
try {
r = exports2.storage.getItem("debug");
} catch (error) {
}
if (!r && typeof process !== "undefined" && "env" in process) {
r = process.env.DEBUG;
}
return r;
}
function localstorage() {
try {
return localStorage;
} catch (error) {
}
}
module2.exports = require_common()(exports2);
var { formatters } = module2.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
}
});
// http-url:https://unpkg.com/[email protected]/dist/helpers
var require_helpers = __commonJS({
"http-url:https://unpkg.com/[email protected]/dist/helpers"(exports2) {
"use strict";
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.req = exports2.json = exports2.toBuffer = void 0;
var http = __importStar(require("http"));
var https = __importStar(require("https"));
async function toBuffer(stream) {
let length = 0;
const chunks = [];
for await (const chunk of stream) {
length += chunk.length;
chunks.push(chunk);
}
return Buffer.concat(chunks, length);
}
exports2.toBuffer = toBuffer;
async function json(stream) {
const buf = await toBuffer(stream);
const str = buf.toString("utf8");
try {
return JSON.parse(str);
} catch (_err) {
const err = _err;
err.message += ` (input: ${str})`;
throw err;
}
}
exports2.json = json;
function req(url, opts = {}) {
const href = typeof url === "string" ? url : url.href;
const req2 = (href.startsWith("https:") ? https : http).request(url, opts);
const promise = new Promise((resolve, reject) => {
req2.once("response", resolve).once("error", reject).end();
});
req2.then = promise.then.bind(promise);
return req2;
}
exports2.req = req;
}
});
// http-url:https://unpkg.com/[email protected]/dist/index.js
var require_dist = __commonJS({
"http-url:https://unpkg.com/[email protected]/dist/index.js"(exports2) {
"use strict";
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.Agent = void 0;
var net = __importStar(require("net"));
var http = __importStar(require("http"));
var https_1 = require("https");
__exportStar(require_helpers(), exports2);
var INTERNAL = Symbol("AgentBaseInternalState");
var Agent = class extends http.Agent {
constructor(opts) {
super(opts);
this[INTERNAL] = {};
}
/**
* Determine whether this is an `http` or `https` request.
*/
isSecureEndpoint(options) {
if (options) {
if (typeof options.secureEndpoint === "boolean") {
return options.secureEndpoint;
}
if (typeof options.protocol === "string") {
return options.protocol === "https:";
}
}
const { stack } = new Error();
if (typeof stack !== "string")
return false;
return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1);
}
// In order to support async signatures in `connect()` and Node's native
// connection pooling in `http.Agent`, the array of sockets for each origin
// has to be updated synchronously. This is so the length of the array is
// accurate when `addRequest()` is next called. We achieve this by creating a
// fake socket and adding it to `sockets[origin]` and incrementing
// `totalSocketCount`.
incrementSockets(name) {
if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
return null;
}
if (!this.sockets[name]) {
this.sockets[name] = [];
}
const fakeSocket = new net.Socket({ writable: false });
this.sockets[name].push(fakeSocket);
this.totalSocketCount++;
return fakeSocket;
}
decrementSockets(name, socket) {
if (!this.sockets[name] || socket === null) {
return;
}
const sockets = this.sockets[name];
const index = sockets.indexOf(socket);
if (index !== -1) {
sockets.splice(index, 1);
this.totalSocketCount--;
if (sockets.length === 0) {
delete this.sockets[name];
}
}
}
// In order to properly update the socket pool, we need to call `getName()` on
// the core `https.Agent` if it is a secureEndpoint.
getName(options) {
const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options);
if (secureEndpoint) {
return https_1.Agent.prototype.getName.call(this, options);
}
return super.getName(options);
}
createSocket(req, options, cb) {
const connectOpts = {
...options,
secureEndpoint: this.isSecureEndpoint(options)
};
const name = this.getName(connectOpts);
const fakeSocket = this.incrementSockets(name);
Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
this.decrementSockets(name, fakeSocket);
if (socket instanceof http.Agent) {
return socket.addRequest(req, connectOpts);
}
this[INTERNAL].currentSocket = socket;
super.createSocket(req, options, cb);
}, (err) => {
this.decrementSockets(name, fakeSocket);
cb(err);
});
}
createConnection() {
const socket = this[INTERNAL].currentSocket;
this[INTERNAL].currentSocket = void 0;
if (!socket) {
throw new Error("No socket was returned in the `connect()` function");
}
return socket;
}
get defaultPort() {
return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
}
set defaultPort(v) {
if (this[INTERNAL]) {
this[INTERNAL].defaultPort = v;
}
}
get protocol() {
return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
}
set protocol(v) {
if (this[INTERNAL]) {
this[INTERNAL].protocol = v;
}
}
};
exports2.Agent = Agent;
}
});
// http-url:https://unpkg.com/[email protected]/dist/parse-proxy-response
var require_parse_proxy_response = __commonJS({
"http-url:https://unpkg.com/[email protected]/dist/parse-proxy-response"(exports2) {
"use strict";
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.parseProxyResponse = void 0;
var debug_1 = __importDefault(require_browser());
var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
function parseProxyResponse(socket) {
return new Promise((resolve, reject) => {
let buffersLength = 0;
const buffers = [];
function read() {
const b = socket.read();
if (b)
ondata(b);
else
socket.once("readable", read);
}
function cleanup() {
socket.removeListener("end", onend);
socket.removeListener("error", onerror);
socket.removeListener("readable", read);
}
function onend() {
cleanup();
debug("onend");
reject(new Error("Proxy connection ended before receiving CONNECT response"));
}
function onerror(err) {
cleanup();
debug("onerror %o", err);
reject(err);
}
function ondata(b) {
buffers.push(b);
buffersLength += b.length;
const buffered = Buffer.concat(buffers, buffersLength);
const endOfHeaders = buffered.indexOf("\r\n\r\n");
if (endOfHeaders === -1) {
debug("have not received end of HTTP headers yet...");
read();
return;
}
const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n");
const firstLine = headerParts.shift();
if (!firstLine) {
socket.destroy();
return reject(new Error("No header received from proxy CONNECT response"));
}
const firstLineParts = firstLine.split(" ");
const statusCode = +firstLineParts[1];
const statusText = firstLineParts.slice(2).join(" ");
const headers = {};
for (const header of headerParts) {
if (!header)
continue;
const firstColon = header.indexOf(":");
if (firstColon === -1) {
socket.destroy();
return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
}
const key = header.slice(0, firstColon).toLowerCase();
const value = header.slice(firstColon + 1).trimStart();
const current = headers[key];
if (typeof current === "string") {
headers[key] = [current, value];
} else if (Array.isArray(current)) {
current.push(value);
} else {
headers[key] = value;
}
}
debug("got proxy server response: %o %o", firstLine, headers);
cleanup();
resolve({
connect: {
statusCode,
statusText,
headers
},
buffered
});
}
socket.on("error", onerror);
socket.on("end", onend);
read();
});
}
exports2.parseProxyResponse = parseProxyResponse;
}
});
// http-url:https://unpkg.com/[email protected]/dist/index.js
var require_dist2 = __commonJS({
"http-url:https://unpkg.com/[email protected]/dist/index.js"(exports2) {
"use strict";
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.HttpsProxyAgent = void 0;
var net = __importStar(require("net"));
var tls = __importStar(require("tls"));
var assert_1 = __importDefault(require("assert"));
var debug_1 = __importDefault(require_browser());
var agent_base_1 = require_dist();
var url_1 = require("url");
var parse_proxy_response_1 = require_parse_proxy_response();
var debug = (0, debug_1.default)("https-proxy-agent");
var HttpsProxyAgent2 = class extends agent_base_1.Agent {
constructor(proxy, opts) {
super(opts);
this.options = { path: void 0 };
this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy;
this.proxyHeaders = opts?.headers ?? {};
debug("Creating new HttpsProxyAgent instance: %o", this.proxy.href);
const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
this.connectOpts = {
// Attempt to negotiate http/1.1 for proxy servers that support http/2
ALPNProtocols: ["http/1.1"],
...opts ? omit(opts, "headers") : null,
host,
port
};
}
/**
* Called when the node-core HTTP client library is creating a
* new HTTP request.
*/
async connect(req, opts) {
const { proxy } = this;
if (!opts.host) {
throw new TypeError('No "host" provided');
}
let socket;
if (proxy.protocol === "https:") {
debug("Creating `tls.Socket`: %o", this.connectOpts);
const servername = this.connectOpts.servername || this.connectOpts.host;
socket = tls.connect({
...this.connectOpts,
servername: servername && net.isIP(servername) ? void 0 : servername
});
} else {
debug("Creating `net.Socket`: %o", this.connectOpts);
socket = net.connect(this.connectOpts);
}
const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r
`;
if (proxy.username || proxy.password) {
const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
}
headers.Host = `${host}:${opts.port}`;
if (!headers["Proxy-Connection"]) {
headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
}
for (const name of Object.keys(headers)) {
payload += `${name}: ${headers[name]}\r
`;
}
const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
socket.write(`${payload}\r
`);
const { connect, buffered } = await proxyResponsePromise;
req.emit("proxyConnect", connect);
this.emit("proxyConnect", connect, req);
if (connect.statusCode === 200) {
req.once("socket", resume);
if (opts.secureEndpoint) {
debug("Upgrading socket connection to TLS");
const servername = opts.servername || opts.host;
return tls.connect({
...omit(opts, "host", "path", "port"),
socket,
servername: net.isIP(servername) ? void 0 : servername
});
}
return socket;
}
socket.destroy();
const fakeSocket = new net.Socket({ writable: false });
fakeSocket.readable = true;
req.once("socket", (s) => {
debug("Replaying proxy buffer for failed request");
(0, assert_1.default)(s.listenerCount("data") > 0);
s.push(buffered);
s.push(null);
});
return fakeSocket;
}
};
HttpsProxyAgent2.protocols = ["http", "https"];
exports2.HttpsProxyAgent = HttpsProxyAgent2;
function resume(socket) {
socket.resume();
}
function omit(obj, ...keys) {
const ret = {};
let key;
for (key in obj) {
if (!keys.includes(key)) {
ret[key] = obj[key];
}
}
return ret;
}
}
});
// /input.ts
var input_exports = {};
__export(input_exports, {
HttpsProxyAgent: () => import_https_proxy_agent.HttpsProxyAgent
});
module.exports = __toCommonJS(input_exports);
var import_https_proxy_agent = __toESM(require_dist2());
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
HttpsProxyAgent
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment