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
chromium.js392 linesDownload Raw Back to chromium
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 chromium_exports = {};30__export(chromium_exports, {31  Chromium: () => Chromium,32  waitForReadyState: () => waitForReadyState33});34module.exports = __toCommonJS(chromium_exports);35var import_fs = __toESM(require("fs"));36var import_os = __toESM(require("os"));37var import_path = __toESM(require("path"));38var import_chromiumSwitches = require("./chromiumSwitches");39var import_crBrowser = require("./crBrowser");40var import_crConnection = require("./crConnection");41var import_utils = require("../../utils");42var import_ascii = require("../utils/ascii");43var import_debugLogger = require("../utils/debugLogger");44var import_manualPromise = require("../../utils/isomorphic/manualPromise");45var import_network = require("../utils/network");46var import_userAgent = require("../utils/userAgent");47var import_browserContext = require("../browserContext");48var import_browserType = require("../browserType");49var import_helper = require("../helper");50var import_registry = require("../registry");51var import_transport = require("../transport");52var import_crDevTools = require("./crDevTools");53var import_browser = require("../browser");54var import_fileUtils = require("../utils/fileUtils");55var import_processLauncher = require("../utils/processLauncher");56const ARTIFACTS_FOLDER = import_path.default.join(import_os.default.tmpdir(), "playwright-artifacts-");57class Chromium extends import_browserType.BrowserType {58  constructor(parent) {59    super(parent, "chromium");60    if ((0, import_utils.debugMode)() === "inspector")61      this._devtools = this._createDevTools();62  }63  async connectOverCDP(progress, endpointURL, options) {64    return await this._connectOverCDPInternal(progress, endpointURL, options);65  }66  async _connectOverCDPInternal(progress, endpointURL, options, onClose) {67    let headersMap;68    if (options.headers)69      headersMap = (0, import_utils.headersArrayToObject)(options.headers, false);70    if (!headersMap)71      headersMap = { "User-Agent": (0, import_userAgent.getUserAgent)() };72    else if (headersMap && !Object.keys(headersMap).some((key) => key.toLowerCase() === "user-agent"))73      headersMap["User-Agent"] = (0, import_userAgent.getUserAgent)();74    const artifactsDir = await progress.race(import_fs.default.promises.mkdtemp(ARTIFACTS_FOLDER));75    const doCleanup = async () => {76      await (0, import_fileUtils.removeFolders)([artifactsDir]);77      const cb = onClose;78      onClose = void 0;79      await cb?.();80    };81    let chromeTransport;82    const doClose = async () => {83      await chromeTransport?.closeAndWait();84      await doCleanup();85    };86    try {87      const wsEndpoint = await urlToWSEndpoint(progress, endpointURL, headersMap);88      chromeTransport = await import_transport.WebSocketTransport.connect(progress, wsEndpoint, { headers: headersMap });89      const browserProcess = { close: doClose, kill: doClose };90      const persistent = { noDefaultViewport: true };91      const browserOptions = {92        slowMo: options.slowMo,93        name: "chromium",94        isChromium: true,95        persistent,96        browserProcess,97        protocolLogger: import_helper.helper.debugProtocolLogger(),98        browserLogsCollector: new import_debugLogger.RecentLogsCollector(),99        artifactsDir,100        downloadsPath: options.downloadsPath || artifactsDir,101        tracesDir: options.tracesDir || artifactsDir,102        originalLaunchOptions: {}103      };104      (0, import_browserContext.validateBrowserContextOptions)(persistent, browserOptions);105      const browser = await progress.race(import_crBrowser.CRBrowser.connect(this.attribution.playwright, chromeTransport, browserOptions));106      browser._isCollocatedWithServer = false;107      browser.on(import_browser.Browser.Events.Disconnected, doCleanup);108      return browser;109    } catch (error) {110      await doClose().catch(() => {111      });112      throw error;113    }114  }115  _createDevTools() {116    const directory = import_registry.registry.findExecutable("chromium").directory;117    return directory ? new import_crDevTools.CRDevTools(import_path.default.join(directory, "devtools-preferences.json")) : void 0;118  }119  async connectToTransport(transport, options, browserLogsCollector) {120    let devtools = this._devtools;121    if (options.__testHookForDevTools) {122      devtools = this._createDevTools();123      await options.__testHookForDevTools(devtools);124    }125    try {126      return await import_crBrowser.CRBrowser.connect(this.attribution.playwright, transport, options, devtools);127    } catch (e) {128      if (browserLogsCollector.recentLogs().some((log) => log.includes("Failed to create a ProcessSingleton for your profile directory."))) {129        throw new Error(130          "Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium."131        );132      }133      throw e;134    }135  }136  doRewriteStartupLog(error) {137    if (!error.logs)138      return error;139    if (error.logs.includes("Missing X server"))140      error.logs = "\n" + (0, import_ascii.wrapInASCIIBox)(import_browserType.kNoXServerRunningError, 1);141    if (!error.logs.includes("crbug.com/357670") && !error.logs.includes("No usable sandbox!") && !error.logs.includes("crbug.com/638180"))142      return error;143    error.logs = [144      `Chromium sandboxing failed!`,145      `================================`,146      `To avoid the sandboxing issue, do either of the following:`,147      `  - (preferred): Configure your environment to support sandboxing`,148      `  - (alternative): Launch Chromium without sandbox using 'chromiumSandbox: false' option`,149      `================================`,150      ``151    ].join("\n");152    return error;153  }154  amendEnvironment(env) {155    return env;156  }157  attemptToGracefullyCloseBrowser(transport) {158    const message = { method: "Browser.close", id: import_crConnection.kBrowserCloseMessageId, params: {} };159    transport.send(message);160  }161  async _launchWithSeleniumHub(progress, hubUrl, options) {162    await progress.race(this._createArtifactDirs(options));163    if (!hubUrl.endsWith("/"))164      hubUrl = hubUrl + "/";165    const args = this._innerDefaultArgs(options);166    args.push("--remote-debugging-port=0");167    const isEdge = options.channel && options.channel.startsWith("msedge");168    let desiredCapabilities = {169      "browserName": isEdge ? "MicrosoftEdge" : "chrome",170      [isEdge ? "ms:edgeOptions" : "goog:chromeOptions"]: { args }171    };172    if (process.env.SELENIUM_REMOTE_CAPABILITIES) {173      const remoteCapabilities = parseSeleniumRemoteParams({ name: "capabilities", value: process.env.SELENIUM_REMOTE_CAPABILITIES }, progress);174      if (remoteCapabilities)175        desiredCapabilities = { ...desiredCapabilities, ...remoteCapabilities };176    }177    let headers = {};178    if (process.env.SELENIUM_REMOTE_HEADERS) {179      const remoteHeaders = parseSeleniumRemoteParams({ name: "headers", value: process.env.SELENIUM_REMOTE_HEADERS }, progress);180      if (remoteHeaders)181        headers = remoteHeaders;182    }183    progress.log(`<selenium> connecting to ${hubUrl}`);184    const response = await (0, import_network.fetchData)(progress, {185      url: hubUrl + "session",186      method: "POST",187      headers: {188        "Content-Type": "application/json; charset=utf-8",189        ...headers190      },191      data: JSON.stringify({192        capabilities: { alwaysMatch: desiredCapabilities }193      })194    }, seleniumErrorHandler);195    const value = JSON.parse(response).value;196    const sessionId = value.sessionId;197    progress.log(`<selenium> connected to sessionId=${sessionId}`);198    const disconnectFromSelenium = async () => {199      progress.log(`<selenium> disconnecting from sessionId=${sessionId}`);200      await (0, import_network.fetchData)(void 0, {201        url: hubUrl + "session/" + sessionId,202        method: "DELETE",203        headers204      }).catch((error) => progress.log(`<error disconnecting from selenium>: ${error}`));205      progress.log(`<selenium> disconnected from sessionId=${sessionId}`);206      import_processLauncher.gracefullyCloseSet.delete(disconnectFromSelenium);207    };208    import_processLauncher.gracefullyCloseSet.add(disconnectFromSelenium);209    try {210      const capabilities = value.capabilities;211      let endpointURL;212      if (capabilities["se:cdp"]) {213        progress.log(`<selenium> using selenium v4`);214        const endpointURLString = addProtocol(capabilities["se:cdp"]);215        endpointURL = new URL(endpointURLString);216        if (endpointURL.hostname === "localhost" || endpointURL.hostname === "127.0.0.1")217          endpointURL.hostname = new URL(hubUrl).hostname;218        progress.log(`<selenium> retrieved endpoint ${endpointURL.toString()} for sessionId=${sessionId}`);219      } else {220        progress.log(`<selenium> using selenium v3`);221        const maybeChromeOptions = capabilities["goog:chromeOptions"];222        const chromeOptions = maybeChromeOptions && typeof maybeChromeOptions === "object" ? maybeChromeOptions : void 0;223        const debuggerAddress = chromeOptions && typeof chromeOptions.debuggerAddress === "string" ? chromeOptions.debuggerAddress : void 0;224        const chromeOptionsURL = typeof maybeChromeOptions === "string" ? maybeChromeOptions : void 0;225        const endpointURLString = addProtocol(debuggerAddress || chromeOptionsURL).replace("localhost", "127.0.0.1");226        progress.log(`<selenium> retrieved endpoint ${endpointURLString} for sessionId=${sessionId}`);227        endpointURL = new URL(endpointURLString);228        if (endpointURL.hostname === "localhost" || endpointURL.hostname === "127.0.0.1") {229          const sessionInfoUrl = new URL(hubUrl).origin + "/grid/api/testsession?session=" + sessionId;230          try {231            const sessionResponse = await (0, import_network.fetchData)(progress, {232              url: sessionInfoUrl,233              method: "GET",234              headers235            }, seleniumErrorHandler);236            const proxyId = JSON.parse(sessionResponse).proxyId;237            endpointURL.hostname = new URL(proxyId).hostname;238            progress.log(`<selenium> resolved endpoint ip ${endpointURL.toString()} for sessionId=${sessionId}`);239          } catch (e) {240            progress.log(`<selenium> unable to resolve endpoint ip for sessionId=${sessionId}, running in standalone?`);241          }242        }243      }244      return await this._connectOverCDPInternal(progress, endpointURL.toString(), {245        ...options,246        headers: (0, import_utils.headersObjectToArray)(headers)247      }, disconnectFromSelenium);248    } catch (e) {249      await disconnectFromSelenium();250      throw e;251    }252  }253  async defaultArgs(options, isPersistent, userDataDir) {254    const chromeArguments = this._innerDefaultArgs(options);255    chromeArguments.push(`--user-data-dir=${userDataDir}`);256    if (options.cdpPort !== void 0)257      chromeArguments.push(`--remote-debugging-port=${options.cdpPort}`);258    else259      chromeArguments.push("--remote-debugging-pipe");260    if (isPersistent)261      chromeArguments.push("about:blank");262    else263      chromeArguments.push("--no-startup-window");264    return chromeArguments;265  }266  _innerDefaultArgs(options) {267    const { args = [] } = options;268    const userDataDirArg = args.find((arg) => arg.startsWith("--user-data-dir"));269    if (userDataDirArg)270      throw this._createUserDataDirArgMisuseError("--user-data-dir");271    if (args.find((arg) => arg.startsWith("--remote-debugging-pipe")))272      throw new Error("Playwright manages remote debugging connection itself.");273    if (args.find((arg) => !arg.startsWith("-")))274      throw new Error("Arguments can not specify page to be opened");275    const chromeArguments = [...(0, import_chromiumSwitches.chromiumSwitches)(options.assistantMode, options.channel)];276    if (import_os.default.platform() === "darwin") {277      chromeArguments.push("--enable-unsafe-swiftshader");278    }279    if (options.devtools)280      chromeArguments.push("--auto-open-devtools-for-tabs");281    if (options.headless) {282      chromeArguments.push("--headless");283      chromeArguments.push(284        "--hide-scrollbars",285        "--mute-audio",286        "--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4"287      );288    }289    if (options.chromiumSandbox !== true)290      chromeArguments.push("--no-sandbox");291    const proxy = options.proxyOverride || options.proxy;292    if (proxy) {293      const proxyURL = new URL(proxy.server);294      const isSocks = proxyURL.protocol === "socks5:";295      if (isSocks && !options.socksProxyPort) {296        chromeArguments.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${proxyURL.hostname}"`);297      }298      chromeArguments.push(`--proxy-server=${proxy.server}`);299      const proxyBypassRules = [];300      if (options.socksProxyPort)301        proxyBypassRules.push("<-loopback>");302      if (proxy.bypass)303        proxyBypassRules.push(...proxy.bypass.split(",").map((t) => t.trim()).map((t) => t.startsWith(".") ? "*" + t : t));304      if (!process.env.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK && !proxyBypassRules.includes("<-loopback>"))305        proxyBypassRules.push("<-loopback>");306      if (proxyBypassRules.length > 0)307        chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`);308    }309    chromeArguments.push(...args);310    return chromeArguments;311  }312  async waitForReadyState(options, browserLogsCollector) {313    return waitForReadyState(options, browserLogsCollector);314  }315  getExecutableName(options) {316    if (options.channel)317      return options.channel;318    return options.headless ? "chromium-headless-shell" : "chromium";319  }320}321async function waitForReadyState(options, browserLogsCollector) {322  if (options.cdpPort === void 0 && !options.args?.some((a) => a.startsWith("--remote-debugging-port")))323    return {};324  const result = new import_manualPromise.ManualPromise();325  browserLogsCollector.onMessage((message) => {326    if (message.includes("Failed to create a ProcessSingleton for your profile directory.")) {327      result.reject(new Error("Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium."));328    }329    const match = message.match(/DevTools listening on (.*)/);330    if (match)331      result.resolve({ wsEndpoint: match[1] });332  });333  return result;334}335async function urlToWSEndpoint(progress, endpointURL, headers) {336  if (endpointURL.startsWith("ws"))337    return endpointURL;338  progress.log(`<ws preparing> retrieving websocket url from ${endpointURL}`);339  const url = new URL(endpointURL);340  if (!url.pathname.endsWith("/"))341    url.pathname += "/";342  url.pathname += "json/version/";343  const httpURL = url.toString();344  const json = await (0, import_network.fetchData)(345    progress,346    {347      url: httpURL,348      headers349    },350    async (_, resp) => new Error(`Unexpected status ${resp.statusCode} when connecting to ${httpURL}.351This does not look like a DevTools server, try connecting via ws://.`)352  );353  return JSON.parse(json).webSocketDebuggerUrl;354}355async function seleniumErrorHandler(params, response) {356  const body = await streamToString(response);357  let message = body;358  try {359    const json = JSON.parse(body);360    message = json.value.localizedMessage || json.value.message;361  } catch (e) {362  }363  return new Error(`Error connecting to Selenium at ${params.url}: ${message}`);364}365function addProtocol(url) {366  if (!["ws://", "wss://", "http://", "https://"].some((protocol) => url.startsWith(protocol)))367    return "http://" + url;368  return url;369}370function streamToString(stream) {371  return new Promise((resolve, reject) => {372    const chunks = [];373    stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));374    stream.on("error", reject);375    stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));376  });377}378function parseSeleniumRemoteParams(env, progress) {379  try {380    const parsed = JSON.parse(env.value);381    progress.log(`<selenium> using additional ${env.name} "${env.value}"`);382    return parsed;383  } catch (e) {384    progress.log(`<selenium> ignoring additional ${env.name} "${env.value}": ${e}`);385  }386}387// Annotate the CommonJS export names for ESM import in node:3880 && (module.exports = {389  Chromium,390  waitForReadyState391});392 
Brunobkr/llama.cpp_AlgMor24_github · Team Ai