Team Ai
Datasetpublic

Brunobkr/llama.cpp_AlgMor24_github

ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.

sourceHugging Faceupdated 2mo agoView on Hugging Face
0likes3.1kdownloads
socksProxy.js512 linesDownload Raw Back to utils
1"use strict";2var __create = Object.create;3var __defProp = Object.defineProperty;4var __getOwnPropDesc = Object.getOwnPropertyDescriptor;5var __getOwnPropNames = Object.getOwnPropertyNames;6var __getProtoOf = Object.getPrototypeOf;7var __hasOwnProp = Object.prototype.hasOwnProperty;8var __export = (target, all) => {9  for (var name in all)10    __defProp(target, name, { get: all[name], enumerable: true });11};12var __copyProps = (to, from, except, desc) => {13  if (from && typeof from === "object" || typeof from === "function") {14    for (let key of __getOwnPropNames(from))15      if (!__hasOwnProp.call(to, key) && key !== except)16        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });17  }18  return to;19};20var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(21  // If the importer is in node compatibility mode or this is not an ESM22  // file that has been converted to a CommonJS file using a Babel-23  // compatible transform (i.e. "__esModule" has not been set), then set24  // "default" to the CommonJS "module.exports" for node compatibility.25  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,26  mod27));28var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);29var socksProxy_exports = {};30__export(socksProxy_exports, {31  SocksProxy: () => SocksProxy,32  SocksProxyHandler: () => SocksProxyHandler,33  parsePattern: () => parsePattern34});35module.exports = __toCommonJS(socksProxy_exports);36var import_events = __toESM(require("events"));37var import_net = __toESM(require("net"));38var import_assert = require("../../utils/isomorphic/assert");39var import_crypto = require("./crypto");40var import_debugLogger = require("./debugLogger");41var import_happyEyeballs = require("./happyEyeballs");42var SocksAuth = /* @__PURE__ */ ((SocksAuth2) => {43  SocksAuth2[SocksAuth2["NO_AUTHENTICATION_REQUIRED"] = 0] = "NO_AUTHENTICATION_REQUIRED";44  SocksAuth2[SocksAuth2["GSSAPI"] = 1] = "GSSAPI";45  SocksAuth2[SocksAuth2["USERNAME_PASSWORD"] = 2] = "USERNAME_PASSWORD";46  SocksAuth2[SocksAuth2["NO_ACCEPTABLE_METHODS"] = 255] = "NO_ACCEPTABLE_METHODS";47  return SocksAuth2;48})(SocksAuth || {});49var SocksAddressType = /* @__PURE__ */ ((SocksAddressType2) => {50  SocksAddressType2[SocksAddressType2["IPv4"] = 1] = "IPv4";51  SocksAddressType2[SocksAddressType2["FqName"] = 3] = "FqName";52  SocksAddressType2[SocksAddressType2["IPv6"] = 4] = "IPv6";53  return SocksAddressType2;54})(SocksAddressType || {});55var SocksCommand = /* @__PURE__ */ ((SocksCommand2) => {56  SocksCommand2[SocksCommand2["CONNECT"] = 1] = "CONNECT";57  SocksCommand2[SocksCommand2["BIND"] = 2] = "BIND";58  SocksCommand2[SocksCommand2["UDP_ASSOCIATE"] = 3] = "UDP_ASSOCIATE";59  return SocksCommand2;60})(SocksCommand || {});61var SocksReply = /* @__PURE__ */ ((SocksReply2) => {62  SocksReply2[SocksReply2["Succeeded"] = 0] = "Succeeded";63  SocksReply2[SocksReply2["GeneralServerFailure"] = 1] = "GeneralServerFailure";64  SocksReply2[SocksReply2["NotAllowedByRuleSet"] = 2] = "NotAllowedByRuleSet";65  SocksReply2[SocksReply2["NetworkUnreachable"] = 3] = "NetworkUnreachable";66  SocksReply2[SocksReply2["HostUnreachable"] = 4] = "HostUnreachable";67  SocksReply2[SocksReply2["ConnectionRefused"] = 5] = "ConnectionRefused";68  SocksReply2[SocksReply2["TtlExpired"] = 6] = "TtlExpired";69  SocksReply2[SocksReply2["CommandNotSupported"] = 7] = "CommandNotSupported";70  SocksReply2[SocksReply2["AddressTypeNotSupported"] = 8] = "AddressTypeNotSupported";71  return SocksReply2;72})(SocksReply || {});73class SocksConnection {74  constructor(uid, socket, client) {75    this._buffer = Buffer.from([]);76    this._offset = 0;77    this._fence = 0;78    this._uid = uid;79    this._socket = socket;80    this._client = client;81    this._boundOnData = this._onData.bind(this);82    socket.on("data", this._boundOnData);83    socket.on("close", () => this._onClose());84    socket.on("end", () => this._onClose());85    socket.on("error", () => this._onClose());86    this._run().catch(() => this._socket.end());87  }88  async _run() {89    (0, import_assert.assert)(await this._authenticate());90    const { command, host, port } = await this._parseRequest();91    if (command !== 1 /* CONNECT */) {92      this._writeBytes(Buffer.from([93        5,94        7 /* CommandNotSupported */,95        0,96        // RSV97        1,98        // IPv499        0,100        0,101        0,102        0,103        // Address104        0,105        0106        // Port107      ]));108      return;109    }110    this._socket.off("data", this._boundOnData);111    this._client.onSocketRequested({ uid: this._uid, host, port });112  }113  async _authenticate() {114    const version = await this._readByte();115    (0, import_assert.assert)(version === 5, "The VER field must be set to x05 for this version of the protocol, was " + version);116    const nMethods = await this._readByte();117    (0, import_assert.assert)(nMethods, "No authentication methods specified");118    const methods = await this._readBytes(nMethods);119    for (const method of methods) {120      if (method === 0) {121        this._writeBytes(Buffer.from([version, method]));122        return true;123      }124    }125    this._writeBytes(Buffer.from([version, 255 /* NO_ACCEPTABLE_METHODS */]));126    return false;127  }128  async _parseRequest() {129    const version = await this._readByte();130    (0, import_assert.assert)(version === 5, "The VER field must be set to x05 for this version of the protocol, was " + version);131    const command = await this._readByte();132    await this._readByte();133    const addressType = await this._readByte();134    let host = "";135    switch (addressType) {136      case 1 /* IPv4 */:137        host = (await this._readBytes(4)).join(".");138        break;139      case 3 /* FqName */:140        const length = await this._readByte();141        host = (await this._readBytes(length)).toString();142        break;143      case 4 /* IPv6 */:144        const bytes = await this._readBytes(16);145        const tokens = [];146        for (let i = 0; i < 8; ++i)147          tokens.push(bytes.readUInt16BE(i * 2).toString(16));148        host = tokens.join(":");149        break;150    }151    const port = (await this._readBytes(2)).readUInt16BE(0);152    this._buffer = Buffer.from([]);153    this._offset = 0;154    this._fence = 0;155    return {156      command,157      host,158      port159    };160  }161  async _readByte() {162    const buffer = await this._readBytes(1);163    return buffer[0];164  }165  async _readBytes(length) {166    this._fence = this._offset + length;167    if (!this._buffer || this._buffer.length < this._fence)168      await new Promise((f) => this._fenceCallback = f);169    this._offset += length;170    return this._buffer.slice(this._offset - length, this._offset);171  }172  _writeBytes(buffer) {173    if (this._socket.writable)174      this._socket.write(buffer);175  }176  _onClose() {177    this._client.onSocketClosed({ uid: this._uid });178  }179  _onData(buffer) {180    this._buffer = Buffer.concat([this._buffer, buffer]);181    if (this._fenceCallback && this._buffer.length >= this._fence) {182      const callback = this._fenceCallback;183      this._fenceCallback = void 0;184      callback();185    }186  }187  socketConnected(host, port) {188    this._writeBytes(Buffer.from([189      5,190      0 /* Succeeded */,191      0,192      // RSV193      ...ipToSocksAddress(host),194      // ATYP, Address195      port >> 8,196      port & 255197      // Port198    ]));199    this._socket.on("data", (data) => this._client.onSocketData({ uid: this._uid, data }));200  }201  socketFailed(errorCode) {202    const buffer = Buffer.from([203      5,204      0,205      0,206      // RSV207      ...ipToSocksAddress("0.0.0.0"),208      // ATYP, Address209      0,210      0211      // Port212    ]);213    switch (errorCode) {214      case "ENOENT":215      case "ENOTFOUND":216      case "ETIMEDOUT":217      case "EHOSTUNREACH":218        buffer[1] = 4 /* HostUnreachable */;219        break;220      case "ENETUNREACH":221        buffer[1] = 3 /* NetworkUnreachable */;222        break;223      case "ECONNREFUSED":224        buffer[1] = 5 /* ConnectionRefused */;225        break;226      case "ERULESET":227        buffer[1] = 2 /* NotAllowedByRuleSet */;228        break;229    }230    this._writeBytes(buffer);231    this._socket.end();232  }233  sendData(data) {234    this._socket.write(data);235  }236  end() {237    this._socket.end();238  }239  error(error) {240    this._socket.destroy(new Error(error));241  }242}243function hexToNumber(hex) {244  return [...hex].reduce((value, digit) => {245    const code = digit.charCodeAt(0);246    if (code >= 48 && code <= 57)247      return value + code;248    if (code >= 97 && code <= 102)249      return value + (code - 97) + 10;250    if (code >= 65 && code <= 70)251      return value + (code - 65) + 10;252    throw new Error("Invalid IPv6 token " + hex);253  }, 0);254}255function ipToSocksAddress(address) {256  if (import_net.default.isIPv4(address)) {257    return [258      1,259      // IPv4260      ...address.split(".", 4).map((t) => +t & 255)261      // Address262    ];263  }264  if (import_net.default.isIPv6(address)) {265    const result = [4];266    const tokens = address.split(":", 8);267    while (tokens.length < 8)268      tokens.unshift("");269    for (const token of tokens) {270      const value = hexToNumber(token);271      result.push(value >> 8 & 255, value & 255);272    }273    return result;274  }275  throw new Error("Only IPv4 and IPv6 addresses are supported");276}277function starMatchToRegex(pattern) {278  const source = pattern.split("*").map((s) => {279    return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");280  }).join(".*");281  return new RegExp("^" + source + "$");282}283function parsePattern(pattern) {284  if (!pattern)285    return () => false;286  const matchers = pattern.split(",").map((token) => {287    const match = token.match(/^(.*?)(?::(\d+))?$/);288    if (!match)289      throw new Error(`Unsupported token "${token}" in pattern "${pattern}"`);290    const tokenPort = match[2] ? +match[2] : void 0;291    const portMatches = (port) => tokenPort === void 0 || tokenPort === port;292    let tokenHost = match[1];293    if (tokenHost === "<loopback>") {294      return (host, port) => {295        if (!portMatches(port))296          return false;297        return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";298      };299    }300    if (tokenHost === "*")301      return (host, port) => portMatches(port);302    if (import_net.default.isIPv4(tokenHost) || import_net.default.isIPv6(tokenHost))303      return (host, port) => host === tokenHost && portMatches(port);304    if (tokenHost[0] === ".")305      tokenHost = "*" + tokenHost;306    const tokenRegex = starMatchToRegex(tokenHost);307    return (host, port) => {308      if (!portMatches(port))309        return false;310      if (import_net.default.isIPv4(host) || import_net.default.isIPv6(host))311        return false;312      return !!host.match(tokenRegex);313    };314  });315  return (host, port) => matchers.some((matcher) => matcher(host, port));316}317class SocksProxy extends import_events.default {318  constructor() {319    super();320    this._connections = /* @__PURE__ */ new Map();321    this._sockets = /* @__PURE__ */ new Set();322    this._closed = false;323    this._patternMatcher = () => false;324    this._directSockets = /* @__PURE__ */ new Map();325    this._server = new import_net.default.Server((socket) => {326      const uid = (0, import_crypto.createGuid)();327      const connection = new SocksConnection(uid, socket, this);328      this._connections.set(uid, connection);329    });330    this._server.on("connection", (socket) => {331      if (this._closed) {332        socket.destroy();333        return;334      }335      this._sockets.add(socket);336      socket.once("close", () => this._sockets.delete(socket));337    });338  }339  static {340    this.Events = {341      SocksRequested: "socksRequested",342      SocksData: "socksData",343      SocksClosed: "socksClosed"344    };345  }346  setPattern(pattern) {347    try {348      this._patternMatcher = parsePattern(pattern);349    } catch (e) {350      this._patternMatcher = () => false;351    }352  }353  async _handleDirect(request) {354    try {355      const socket = await (0, import_happyEyeballs.createSocket)(request.host, request.port);356      socket.on("data", (data) => this._connections.get(request.uid)?.sendData(data));357      socket.on("error", (error) => {358        this._connections.get(request.uid)?.error(error.message);359        this._directSockets.delete(request.uid);360      });361      socket.on("end", () => {362        this._connections.get(request.uid)?.end();363        this._directSockets.delete(request.uid);364      });365      const localAddress = socket.localAddress;366      const localPort = socket.localPort;367      this._directSockets.set(request.uid, socket);368      this._connections.get(request.uid)?.socketConnected(localAddress, localPort);369    } catch (error) {370      this._connections.get(request.uid)?.socketFailed(error.code);371    }372  }373  port() {374    return this._port;375  }376  async listen(port, hostname) {377    return new Promise((f) => {378      this._server.listen(port, hostname, () => {379        const port2 = this._server.address().port;380        this._port = port2;381        f(port2);382      });383    });384  }385  async close() {386    if (this._closed)387      return;388    this._closed = true;389    for (const socket of this._sockets)390      socket.destroy();391    this._sockets.clear();392    await new Promise((f) => this._server.close(f));393  }394  onSocketRequested(payload) {395    if (!this._patternMatcher(payload.host, payload.port)) {396      this._handleDirect(payload);397      return;398    }399    this.emit(SocksProxy.Events.SocksRequested, payload);400  }401  onSocketData(payload) {402    const direct = this._directSockets.get(payload.uid);403    if (direct) {404      direct.write(payload.data);405      return;406    }407    this.emit(SocksProxy.Events.SocksData, payload);408  }409  onSocketClosed(payload) {410    const direct = this._directSockets.get(payload.uid);411    if (direct) {412      direct.destroy();413      this._directSockets.delete(payload.uid);414      return;415    }416    this.emit(SocksProxy.Events.SocksClosed, payload);417  }418  socketConnected({ uid, host, port }) {419    this._connections.get(uid)?.socketConnected(host, port);420  }421  socketFailed({ uid, errorCode }) {422    this._connections.get(uid)?.socketFailed(errorCode);423  }424  sendSocketData({ uid, data }) {425    this._connections.get(uid)?.sendData(data);426  }427  sendSocketEnd({ uid }) {428    this._connections.get(uid)?.end();429  }430  sendSocketError({ uid, error }) {431    this._connections.get(uid)?.error(error);432  }433}434class SocksProxyHandler extends import_events.default {435  constructor(pattern, redirectPortForTest) {436    super();437    this._sockets = /* @__PURE__ */ new Map();438    this._patternMatcher = () => false;439    this._patternMatcher = parsePattern(pattern);440    this._redirectPortForTest = redirectPortForTest;441  }442  static {443    this.Events = {444      SocksConnected: "socksConnected",445      SocksData: "socksData",446      SocksError: "socksError",447      SocksFailed: "socksFailed",448      SocksEnd: "socksEnd"449    };450  }451  cleanup() {452    for (const uid of this._sockets.keys())453      this.socketClosed({ uid });454  }455  async socketRequested({ uid, host, port }) {456    import_debugLogger.debugLogger.log("socks", `[${uid}] => request ${host}:${port}`);457    if (!this._patternMatcher(host, port)) {458      const payload = { uid, errorCode: "ERULESET" };459      import_debugLogger.debugLogger.log("socks", `[${uid}] <= pattern error ${payload.errorCode}`);460      this.emit(SocksProxyHandler.Events.SocksFailed, payload);461      return;462    }463    if (host === "local.playwright")464      host = "localhost";465    try {466      if (this._redirectPortForTest)467        port = this._redirectPortForTest;468      const socket = await (0, import_happyEyeballs.createSocket)(host, port);469      socket.on("data", (data) => {470        const payload2 = { uid, data };471        this.emit(SocksProxyHandler.Events.SocksData, payload2);472      });473      socket.on("error", (error) => {474        const payload2 = { uid, error: error.message };475        import_debugLogger.debugLogger.log("socks", `[${uid}] <= network socket error ${payload2.error}`);476        this.emit(SocksProxyHandler.Events.SocksError, payload2);477        this._sockets.delete(uid);478      });479      socket.on("end", () => {480        const payload2 = { uid };481        import_debugLogger.debugLogger.log("socks", `[${uid}] <= network socket closed`);482        this.emit(SocksProxyHandler.Events.SocksEnd, payload2);483        this._sockets.delete(uid);484      });485      const localAddress = socket.localAddress;486      const localPort = socket.localPort;487      this._sockets.set(uid, socket);488      const payload = { uid, host: localAddress, port: localPort };489      import_debugLogger.debugLogger.log("socks", `[${uid}] <= connected to network ${payload.host}:${payload.port}`);490      this.emit(SocksProxyHandler.Events.SocksConnected, payload);491    } catch (error) {492      const payload = { uid, errorCode: error.code };493      import_debugLogger.debugLogger.log("socks", `[${uid}] <= connect error ${payload.errorCode}`);494      this.emit(SocksProxyHandler.Events.SocksFailed, payload);495    }496  }497  sendSocketData({ uid, data }) {498    this._sockets.get(uid)?.write(data);499  }500  socketClosed({ uid }) {501    import_debugLogger.debugLogger.log("socks", `[${uid}] <= browser socket closed`);502    this._sockets.get(uid)?.destroy();503    this._sockets.delete(uid);504  }505}506// Annotate the CommonJS export names for ESM import in node:5070 && (module.exports = {508  SocksProxy,509  SocksProxyHandler,510  parsePattern511});512 
Brunobkr/llama.cpp_AlgMor24_github · Team Ai