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 __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
));

// ../../node_modules/protocols/lib/index.js
var require_lib = __commonJS({
  "../../node_modules/protocols/lib/index.js"(exports, module) {
    "use strict";
    module.exports = function protocols(input, first) {
      if (first === true) {
        first = 0;
      }
      var prots = "";
      if (typeof input === "string") {
        try {
          prots = new URL(input).protocol;
        } catch (e) {
        }
      } else if (input && input.constructor === URL) {
        prots = input.protocol;
      }
      var splits = prots.split(/\:|\+/).filter(Boolean);
      if (typeof first === "number") {
        return splits[first];
      }
      return splits;
    };
  }
});

// ../../node_modules/parse-path/lib/index.js
var require_lib2 = __commonJS({
  "../../node_modules/parse-path/lib/index.js"(exports, module) {
    "use strict";
    var protocols = require_lib();
    function parsePath(url) {
      var output = {
        protocols: [],
        protocol: null,
        port: null,
        resource: "",
        host: "",
        user: "",
        password: "",
        pathname: "",
        hash: "",
        search: "",
        href: url,
        query: {},
        parse_failed: false
      };
      try {
        var parsed2 = new URL(url);
        output.protocols = protocols(parsed2);
        output.protocol = output.protocols[0];
        output.port = parsed2.port;
        output.resource = parsed2.hostname;
        output.host = parsed2.host;
        output.user = parsed2.username || "";
        output.password = parsed2.password || "";
        output.pathname = parsed2.pathname;
        output.hash = parsed2.hash.slice(1);
        output.search = parsed2.search.slice(1);
        output.href = parsed2.href;
        output.query = Object.fromEntries(parsed2.searchParams);
      } catch (e) {
        output.protocols = ["file"];
        output.protocol = output.protocols[0];
        output.port = "";
        output.resource = "";
        output.user = "";
        output.pathname = "";
        output.hash = "";
        output.search = "";
        output.href = url;
        output.query = {};
        output.parse_failed = true;
      }
      return output;
    }
    module.exports = parsePath;
  }
});

// ../../node_modules/parse-url/dist/index.js
var require_dist = __commonJS({
  "../../node_modules/parse-url/dist/index.js"(exports, module) {
    "use strict";
    var require$$1 = require_lib2();
    function _interopDefaultLegacy(e) {
      return e && typeof e === "object" && "default" in e ? e : { "default": e };
    }
    var require$$1__default = /* @__PURE__ */ _interopDefaultLegacy(require$$1);
    function getAugmentedNamespace(n) {
      if (n.__esModule) return n;
      var f = n.default;
      if (typeof f == "function") {
        var a = function a2() {
          if (this instanceof a2) {
            var args = [null];
            args.push.apply(args, arguments);
            var Ctor = Function.bind.apply(f, args);
            return new Ctor();
          }
          return f.apply(this, arguments);
        };
        a.prototype = f.prototype;
      } else a = {};
      Object.defineProperty(a, "__esModule", { value: true });
      Object.keys(n).forEach(function(k) {
        var d = Object.getOwnPropertyDescriptor(n, k);
        Object.defineProperty(a, k, d.get ? d : {
          enumerable: true,
          get: function() {
            return n[k];
          }
        });
      });
      return a;
    }
    var src = {};
    var DATA_URL_DEFAULT_MIME_TYPE = "text/plain";
    var DATA_URL_DEFAULT_CHARSET = "us-ascii";
    var testParameter = (name, filters) => filters.some((filter) => filter instanceof RegExp ? filter.test(name) : filter === name);
    var normalizeDataURL = (urlString, { stripHash }) => {
      const match = /^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(urlString);
      if (!match) {
        throw new Error(`Invalid URL: ${urlString}`);
      }
      let { type, data, hash } = match.groups;
      const mediaType = type.split(";");
      hash = stripHash ? "" : hash;
      let isBase64 = false;
      if (mediaType[mediaType.length - 1] === "base64") {
        mediaType.pop();
        isBase64 = true;
      }
      const mimeType = (mediaType.shift() || "").toLowerCase();
      const attributes = mediaType.map((attribute) => {
        let [key, value = ""] = attribute.split("=").map((string) => string.trim());
        if (key === "charset") {
          value = value.toLowerCase();
          if (value === DATA_URL_DEFAULT_CHARSET) {
            return "";
          }
        }
        return `${key}${value ? `=${value}` : ""}`;
      }).filter(Boolean);
      const normalizedMediaType = [
        ...attributes
      ];
      if (isBase64) {
        normalizedMediaType.push("base64");
      }
      if (normalizedMediaType.length > 0 || mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE) {
        normalizedMediaType.unshift(mimeType);
      }
      return `data:${normalizedMediaType.join(";")},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ""}`;
    };
    function normalizeUrl(urlString, options) {
      options = {
        defaultProtocol: "http:",
        normalizeProtocol: true,
        forceHttp: false,
        forceHttps: false,
        stripAuthentication: true,
        stripHash: false,
        stripTextFragment: true,
        stripWWW: true,
        removeQueryParameters: [/^utm_\w+/i],
        removeTrailingSlash: true,
        removeSingleSlash: true,
        removeDirectoryIndex: false,
        sortQueryParameters: true,
        ...options
      };
      urlString = urlString.trim();
      if (/^data:/i.test(urlString)) {
        return normalizeDataURL(urlString, options);
      }
      if (/^view-source:/i.test(urlString)) {
        throw new Error("`view-source:` is not supported as it is a non-standard protocol");
      }
      const hasRelativeProtocol = urlString.startsWith("//");
      const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString);
      if (!isRelativeUrl) {
        urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol);
      }
      const urlObject = new URL(urlString);
      if (options.forceHttp && options.forceHttps) {
        throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");
      }
      if (options.forceHttp && urlObject.protocol === "https:") {
        urlObject.protocol = "http:";
      }
      if (options.forceHttps && urlObject.protocol === "http:") {
        urlObject.protocol = "https:";
      }
      if (options.stripAuthentication) {
        urlObject.username = "";
        urlObject.password = "";
      }
      if (options.stripHash) {
        urlObject.hash = "";
      } else if (options.stripTextFragment) {
        urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, "");
      }
      if (urlObject.pathname) {
        const protocolRegex = /\b[a-z][a-z\d+\-.]{1,50}:\/\//g;
        let lastIndex = 0;
        let result = "";
        for (; ; ) {
          const match = protocolRegex.exec(urlObject.pathname);
          if (!match) {
            break;
          }
          const protocol = match[0];
          const protocolAtIndex = match.index;
          const intermediate = urlObject.pathname.slice(lastIndex, protocolAtIndex);
          result += intermediate.replace(/\/{2,}/g, "/");
          result += protocol;
          lastIndex = protocolAtIndex + protocol.length;
        }
        const remnant = urlObject.pathname.slice(lastIndex, urlObject.pathname.length);
        result += remnant.replace(/\/{2,}/g, "/");
        urlObject.pathname = result;
      }
      if (urlObject.pathname) {
        try {
          urlObject.pathname = decodeURI(urlObject.pathname);
        } catch {
        }
      }
      if (options.removeDirectoryIndex === true) {
        options.removeDirectoryIndex = [/^index\.[a-z]+$/];
      }
      if (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) {
        let pathComponents = urlObject.pathname.split("/");
        const lastComponent = pathComponents[pathComponents.length - 1];
        if (testParameter(lastComponent, options.removeDirectoryIndex)) {
          pathComponents = pathComponents.slice(0, -1);
          urlObject.pathname = pathComponents.slice(1).join("/") + "/";
        }
      }
      if (urlObject.hostname) {
        urlObject.hostname = urlObject.hostname.replace(/\.$/, "");
        if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) {
          urlObject.hostname = urlObject.hostname.replace(/^www\./, "");
        }
      }
      if (Array.isArray(options.removeQueryParameters)) {
        for (const key of [...urlObject.searchParams.keys()]) {
          if (testParameter(key, options.removeQueryParameters)) {
            urlObject.searchParams.delete(key);
          }
        }
      }
      if (options.removeQueryParameters === true) {
        urlObject.search = "";
      }
      if (options.sortQueryParameters) {
        urlObject.searchParams.sort();
        try {
          urlObject.search = decodeURIComponent(urlObject.search);
        } catch {
        }
      }
      if (options.removeTrailingSlash) {
        urlObject.pathname = urlObject.pathname.replace(/\/$/, "");
      }
      const oldUrlString = urlString;
      urlString = urlObject.toString();
      if (!options.removeSingleSlash && urlObject.pathname === "/" && !oldUrlString.endsWith("/") && urlObject.hash === "") {
        urlString = urlString.replace(/\/$/, "");
      }
      if ((options.removeTrailingSlash || urlObject.pathname === "/") && urlObject.hash === "" && options.removeSingleSlash) {
        urlString = urlString.replace(/\/$/, "");
      }
      if (hasRelativeProtocol && !options.normalizeProtocol) {
        urlString = urlString.replace(/^http:\/\//, "//");
      }
      if (options.stripProtocol) {
        urlString = urlString.replace(/^(?:https?:)?\/\//, "");
      }
      return urlString;
    }
    var normalizeUrl$1 = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      "default": normalizeUrl
    });
    var require$$0 = /* @__PURE__ */ getAugmentedNamespace(normalizeUrl$1);
    Object.defineProperty(src, "__esModule", {
      value: true
    });
    var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
      return typeof obj;
    } : function(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
    var _normalizeUrl = require$$0;
    var _normalizeUrl2 = _interopRequireDefault(_normalizeUrl);
    var _parsePath = require$$1__default["default"];
    var _parsePath2 = _interopRequireDefault(_parsePath);
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }
    var parseUrl = function parseUrl2(url) {
      var normalize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
      var GIT_RE = /^(?:([a-zA-Z_][a-zA-Z0-9_-]{0,31})@|https?:\/\/)([\w\.\-@]+)[\/:](([\~,\.\w,\-,\_,\/,\s]|%[0-9A-Fa-f]{2})+?(?:\.git|\/)?)$/;
      var throwErr = function throwErr2(msg) {
        var err = new Error(msg);
        err.subject_url = url;
        throw err;
      };
      if (typeof url !== "string" || !url.trim()) {
        throwErr("Invalid url.");
      }
      if (url.length > parseUrl2.MAX_INPUT_LENGTH) {
        throwErr("Input exceeds maximum length. If needed, change the value of parseUrl.MAX_INPUT_LENGTH.");
      }
      if (normalize) {
        if ((typeof normalize === "undefined" ? "undefined" : _typeof(normalize)) !== "object") {
          normalize = {
            stripHash: false
          };
        }
        url = (0, _normalizeUrl2.default)(url, normalize);
      }
      var parsed2 = (0, _parsePath2.default)(url);
      if (parsed2.parse_failed) {
        var matched = parsed2.href.match(GIT_RE);
        if (matched) {
          parsed2.protocols = ["ssh"];
          parsed2.protocol = "ssh";
          parsed2.resource = matched[2];
          parsed2.host = matched[2];
          parsed2.user = matched[1];
          parsed2.pathname = "/" + matched[3];
          parsed2.parse_failed = false;
        } else {
          throwErr("URL parsing failed.");
        }
      }
      return parsed2;
    };
    parseUrl.MAX_INPUT_LENGTH = 2048;
    var _default = src.default = parseUrl;
    module.exports = _default;
  }
});

// ../../node_modules/is-ssh/lib/index.js
var require_lib3 = __commonJS({
  "../../node_modules/is-ssh/lib/index.js"(exports, module) {
    "use strict";
    var protocols = require_lib();
    function isSsh(input) {
      if (Array.isArray(input)) {
        return input.indexOf("ssh") !== -1 || input.indexOf("rsync") !== -1;
      }
      if (typeof input !== "string") {
        return false;
      }
      var prots = protocols(input);
      input = input.substring(input.indexOf("://") + 3);
      if (isSsh(prots)) {
        return true;
      }
      var urlPortPattern = new RegExp(".([a-zA-Z\\d]+):(\\d+)/");
      return !input.match(urlPortPattern) && input.indexOf("@") < input.indexOf(":");
    }
    module.exports = isSsh;
  }
});

// ../../node_modules/git-up/lib/index.js
var require_lib4 = __commonJS({
  "../../node_modules/git-up/lib/index.js"(exports, module) {
    "use strict";
    var parseUrl = require_dist();
    var isSsh = require_lib3();
    function gitUp(input) {
      let output = parseUrl(input);
      output.token = "";
      if (output.password === "x-oauth-basic") {
        output.token = output.user;
      } else if (output.user === "x-token-auth") {
        output.token = output.password;
      }
      if (isSsh(output.protocols) || output.protocols.length === 0 && isSsh(input)) {
        output.protocol = "ssh";
      } else if (output.protocols.length) {
        output.protocol = output.protocols[0];
      } else {
        output.protocol = "file";
        output.protocols = ["file"];
      }
      output.href = output.href.replace(/\/$/, "");
      return output;
    }
    module.exports = gitUp;
  }
});

// ../../node_modules/git-url-parse/lib/index.js
var require_lib5 = __commonJS({
  "../../node_modules/git-url-parse/lib/index.js"(exports, module) {
    "use strict";
    var gitUp = require_lib4();
    function gitUrlParse2(url, refs) {
      refs = refs || [];
      if (typeof url !== "string") {
        throw new Error("The url must be a string.");
      }
      if (!refs.every(function(item) {
        return typeof item === "string";
      })) {
        throw new Error("The refs should contain only strings");
      }
      var shorthandRe = /^([a-z\d-]{1,39})\/([-\.\w]{1,100})$/i;
      if (shorthandRe.test(url)) {
        url = "https://github.com/" + url;
      }
      var urlInfo = gitUp(url), sourceParts = urlInfo.resource.split("."), splits = null;
      urlInfo.toString = function(type) {
        return gitUrlParse2.stringify(this, type);
      };
      urlInfo.source = sourceParts.length > 2 ? sourceParts.slice(1 - sourceParts.length).join(".") : urlInfo.source = urlInfo.resource;
      urlInfo.git_suffix = /\.git$/.test(urlInfo.pathname);
      urlInfo.name = decodeURIComponent((urlInfo.pathname || urlInfo.href).replace(/(^\/)|(\/$)/g, "").replace(/\.git$/, ""));
      urlInfo.owner = decodeURIComponent(urlInfo.user);
      switch (urlInfo.source) {
        case "git.cloudforge.com":
          urlInfo.owner = urlInfo.user;
          urlInfo.organization = sourceParts[0];
          urlInfo.source = "cloudforge.com";
          break;
        case "visualstudio.com":
          if (urlInfo.resource === "vs-ssh.visualstudio.com") {
            splits = urlInfo.name.split("/");
            if (splits.length === 4) {
              urlInfo.organization = splits[1];
              urlInfo.owner = splits[2];
              urlInfo.name = splits[3];
              urlInfo.full_name = splits[2] + "/" + splits[3];
            }
            break;
          } else {
            splits = urlInfo.name.split("/");
            if (splits.length === 2) {
              urlInfo.owner = splits[1];
              urlInfo.name = splits[1];
              urlInfo.full_name = "_git/" + urlInfo.name;
            } else if (splits.length === 3) {
              urlInfo.name = splits[2];
              if (splits[0] === "DefaultCollection") {
                urlInfo.owner = splits[2];
                urlInfo.organization = splits[0];
                urlInfo.full_name = urlInfo.organization + "/_git/" + urlInfo.name;
              } else {
                urlInfo.owner = splits[0];
                urlInfo.full_name = urlInfo.owner + "/_git/" + urlInfo.name;
              }
            } else if (splits.length === 4) {
              urlInfo.organization = splits[0];
              urlInfo.owner = splits[1];
              urlInfo.name = splits[3];
              urlInfo.full_name = urlInfo.organization + "/" + urlInfo.owner + "/_git/" + urlInfo.name;
            }
            break;
          }
        // Azure DevOps (formerly Visual Studio Team Services)
        case "dev.azure.com":
        case "azure.com":
          if (urlInfo.resource === "ssh.dev.azure.com") {
            splits = urlInfo.name.split("/");
            if (splits.length === 4) {
              urlInfo.organization = splits[1];
              urlInfo.owner = splits[2];
              urlInfo.name = splits[3];
            }
            break;
          } else {
            splits = urlInfo.name.split("/");
            if (splits.length === 5) {
              urlInfo.organization = splits[0];
              urlInfo.owner = splits[1];
              urlInfo.name = splits[4];
              urlInfo.full_name = "_git/" + urlInfo.name;
            } else if (splits.length === 3) {
              urlInfo.name = splits[2];
              if (splits[0] === "DefaultCollection") {
                urlInfo.owner = splits[2];
                urlInfo.organization = splits[0];
                urlInfo.full_name = urlInfo.organization + "/_git/" + urlInfo.name;
              } else {
                urlInfo.owner = splits[0];
                urlInfo.full_name = urlInfo.owner + "/_git/" + urlInfo.name;
              }
            } else if (splits.length === 4) {
              urlInfo.organization = splits[0];
              urlInfo.owner = splits[1];
              urlInfo.name = splits[3];
              urlInfo.full_name = urlInfo.organization + "/" + urlInfo.owner + "/_git/" + urlInfo.name;
            }
            if (urlInfo.query && urlInfo.query["path"]) {
              urlInfo.filepath = urlInfo.query["path"].replace(/^\/+/g, "");
            }
            if (urlInfo.query && urlInfo.query["version"]) {
              urlInfo.ref = urlInfo.query["version"].replace(/^GB/, "");
            }
            break;
          }
        default:
          splits = urlInfo.name.split("/");
          var nameIndex = splits.length - 1;
          if (splits.length >= 2) {
            var dashIndex = splits.indexOf("-", 2);
            var blobIndex = splits.indexOf("blob", 2);
            var treeIndex = splits.indexOf("tree", 2);
            var commitIndex = splits.indexOf("commit", 2);
            var issuesIndex = splits.indexOf("issues", 2);
            var srcIndex = splits.indexOf("src", 2);
            var rawIndex = splits.indexOf("raw", 2);
            var editIndex = splits.indexOf("edit", 2);
            nameIndex = dashIndex > 0 ? dashIndex - 1 : blobIndex > 0 && treeIndex > 0 ? Math.min(blobIndex - 1, treeIndex - 1) : blobIndex > 0 ? blobIndex - 1 : issuesIndex > 0 ? issuesIndex - 1 : treeIndex > 0 ? treeIndex - 1 : commitIndex > 0 ? commitIndex - 1 : srcIndex > 0 ? srcIndex - 1 : rawIndex > 0 ? rawIndex - 1 : editIndex > 0 ? editIndex - 1 : nameIndex;
            urlInfo.owner = splits.slice(0, nameIndex).join("/");
            urlInfo.name = splits[nameIndex];
            if (commitIndex && issuesIndex < 0) {
              urlInfo.commit = splits[nameIndex + 2];
            }
          }
          urlInfo.ref = "";
          urlInfo.filepathtype = "";
          urlInfo.filepath = "";
          var offsetNameIndex = splits.length > nameIndex && splits[nameIndex + 1] === "-" ? nameIndex + 1 : nameIndex;
          if (splits.length > offsetNameIndex + 2 && ["raw", "src", "blob", "tree", "edit"].indexOf(splits[offsetNameIndex + 1]) >= 0) {
            urlInfo.filepathtype = splits[offsetNameIndex + 1];
            urlInfo.ref = splits[offsetNameIndex + 2];
            if (splits.length > offsetNameIndex + 3) {
              urlInfo.filepath = splits.slice(offsetNameIndex + 3).join("/");
            }
          }
          urlInfo.organization = urlInfo.owner;
          break;
      }
      if (!urlInfo.full_name) {
        urlInfo.full_name = urlInfo.owner;
        if (urlInfo.name) {
          urlInfo.full_name && (urlInfo.full_name += "/");
          urlInfo.full_name += urlInfo.name;
        }
      }
      if (urlInfo.owner.startsWith("scm/")) {
        urlInfo.source = "bitbucket-server";
        urlInfo.owner = urlInfo.owner.replace("scm/", "");
        urlInfo.organization = urlInfo.owner;
        urlInfo.full_name = urlInfo.owner + "/" + urlInfo.name;
      }
      var bitbucket = /(projects|users)\/(.*?)\/repos\/(.*?)((\/.*$)|$)/;
      var matches = bitbucket.exec(urlInfo.pathname);
      if (matches != null) {
        urlInfo.source = "bitbucket-server";
        if (matches[1] === "users") {
          urlInfo.owner = "~" + matches[2];
        } else {
          urlInfo.owner = matches[2];
        }
        urlInfo.organization = urlInfo.owner;
        urlInfo.name = matches[3];
        splits = matches[4].split("/");
        if (splits.length > 1) {
          if (["raw", "browse"].indexOf(splits[1]) >= 0) {
            urlInfo.filepathtype = splits[1];
            if (splits.length > 2) {
              urlInfo.filepath = splits.slice(2).join("/");
            }
          } else if (splits[1] === "commits" && splits.length > 2) {
            urlInfo.commit = splits[2];
          }
        }
        urlInfo.full_name = urlInfo.owner + "/" + urlInfo.name;
        if (urlInfo.query.at) {
          urlInfo.ref = urlInfo.query.at;
        } else {
          urlInfo.ref = "";
        }
      }
      if (refs.length !== 0 && urlInfo.ref) {
        urlInfo.ref = findLongestMatchingSubstring(urlInfo.href, refs) || urlInfo.ref;
        urlInfo.filepath = urlInfo.href.split(urlInfo.ref + "/")[1];
      }
      return urlInfo;
    }
    gitUrlParse2.stringify = function(obj, type) {
      type = type || (obj.protocols && obj.protocols.length ? obj.protocols.join("+") : obj.protocol);
      var port = obj.port ? ":" + obj.port : "";
      var user = obj.user || "git";
      var maybeGitSuffix = obj.git_suffix ? ".git" : "";
      switch (type) {
        case "ssh":
          if (port) return "ssh://" + user + "@" + obj.resource + port + "/" + obj.full_name + maybeGitSuffix;
          else return user + "@" + obj.resource + ":" + obj.full_name + maybeGitSuffix;
        case "git+ssh":
        case "ssh+git":
        case "ftp":
        case "ftps":
          return type + "://" + user + "@" + obj.resource + port + "/" + obj.full_name + maybeGitSuffix;
        case "http":
        case "https":
          var auth = obj.token ? buildToken(obj) : obj.user && (obj.protocols.includes("http") || obj.protocols.includes("https")) ? obj.user + "@" : "";
          return type + "://" + auth + obj.resource + port + "/" + buildPath(obj) + maybeGitSuffix;
        default:
          return obj.href;
      }
    };
    function buildToken(obj) {
      switch (obj.source) {
        case "bitbucket.org":
          return "x-token-auth:" + obj.token + "@";
        default:
          return obj.token + "@";
      }
    }
    function buildPath(obj) {
      switch (obj.source) {
        case "bitbucket-server":
          return "scm/" + obj.full_name;
        default:
          var encoded_full_name = obj.full_name.split("/").map(function(x) {
            return encodeURIComponent(x);
          }).join("/");
          return encoded_full_name;
      }
    }
    function findLongestMatchingSubstring(string, array) {
      var longestMatch = "";
      array.forEach(function(item) {
        if (string.includes(item) && item.length > longestMatch.length) {
          longestMatch = item;
        }
      });
      return longestMatch;
    }
    module.exports = gitUrlParse2;
  }
});

// src/adapters/codex/local-tools-mcp-server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

// ../git/dist/signed-commit.js
import * as childProcess3 from "child_process";

// ../git/dist/concurrency.js
async function mapWithConcurrency(items, concurrency, mapper, options) {
  if (items.length === 0)
    return [];
  const results = new Array(items.length);
  let index = 0;
  const worker = async () => {
    while (index < items.length) {
      if (options?.signal?.aborted)
        return;
      const i = index++;
      results[i] = await mapper(items[i]);
    }
  };
  await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, () => worker()));
  return results;
}

// ../git/dist/gh.js
import * as childProcess from "child_process";
function execGh(args, options = {}) {
  const env = options.env ? { ...process.env, ...options.env } : process.env;
  return new Promise((resolve2) => {
    const child = childProcess.execFile("gh", args, { cwd: options.cwd, env, timeout: options.timeoutMs ?? 0 }, (error, stdout, stderr) => {
      if (!error) {
        resolve2({ stdout, stderr, exitCode: 0 });
        return;
      }
      const err = error;
      const timedOut = err.killed === true && !!options.timeoutMs;
      const exitCode = typeof err.code === "number" ? err.code : err.code === "ENOENT" ? 127 : 1;
      resolve2({
        stdout: stdout ?? err.stdout ?? "",
        stderr: stderr ?? err.stderr ?? "",
        exitCode,
        error: timedOut ? `gh timed out after ${options.timeoutMs}ms` : err.message
      });
    });
    if (options.input !== void 0) {
      child.stdin?.end(options.input);
    }
  });
}
var TRANSIENT_GH_PATTERNS = [
  /HTTP 5\d\d/,
  /HTTP 499/,
  /\btimed out\b/i,
  /\bETIMEDOUT\b/,
  /\bECONNRESET\b/,
  /\bECONNREFUSED\b/,
  /\bEAI_AGAIN\b/,
  /connection reset/i
];
function isTransientGhFailure(res) {
  if (res.exitCode === 0) {
    return false;
  }
  const text = `${res.stderr} ${res.error ?? ""} ${res.stdout}`;
  return TRANSIENT_GH_PATTERNS.some((re) => re.test(text));
}
var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
async function execGhWithRetry(args, options = {}, retry = {}, exec = execGh) {
  const maxAttempts = retry.maxAttempts ?? 3;
  const backoffMs = retry.backoffMs ?? 500;
  let res = await exec(args, options);
  for (let attempt = 2; attempt <= maxAttempts && isTransientGhFailure(res); attempt++) {
    await sleep(backoffMs * 2 ** (attempt - 2));
    res = await exec(args, options);
  }
  return res;
}

// ../git/dist/trailers.js
function buildPostHogTrailers(taskId) {
  const trailers = ["Generated-By: PostHog Code"];
  if (taskId)
    trailers.push(`Task-Id: ${taskId}`);
  return trailers;
}

// ../git/dist/utils.js
var import_git_url_parse = __toESM(require_lib5(), 1);
import * as childProcess2 from "child_process";
import * as fs from "fs/promises";
import * as os from "os";
import * as path from "path";
function parseGithubUrl(url) {
  if (!url)
    return null;
  let parsed2;
  try {
    parsed2 = (0, import_git_url_parse.default)(url.trim());
  } catch {
    return null;
  }
  const resource = parsed2.resource.toLowerCase();
  if (resource !== "github.com" && resource !== "ssh.github.com")
    return null;
  const raw = parsed2.pathname.split("/");
  if (raw[0] !== "")
    return null;
  const parts = raw[raw.length - 1] === "" ? raw.slice(1, -1) : raw.slice(1);
  if (parts.length < 2 || parts.some((p) => p === ""))
    return null;
  const [owner, repoRaw, segment, num] = parts;
  const repo = repoRaw.replace(/\.git$/, "");
  if (segment === "issues" || segment === "pull") {
    const number = Number(num);
    if (!Number.isInteger(number) || number <= 0)
      return null;
    return {
      kind: segment === "pull" ? "pr" : "issue",
      owner,
      repo,
      number
    };
  }
  return { kind: "repo", owner, repo };
}

// ../git/dist/signed-commit.js
var DEFAULT_MAX_PAYLOAD_BYTES = 35 * 1024 * 1024;
var MAX_GIT_BUFFER = 256 * 1024 * 1024;
var GH_GRAPHQL_TIMEOUT_MS = 3e4;
var OversizedFileError = class extends Error {
  path;
  bytes;
  maxBytes;
  constructor(path2, bytes, maxBytes) {
    super(`File '${path2}' (~${Math.round(bytes / 1024 / 1024)}MB once base64-encoded) exceeds the per-commit request limit (~${Math.round(maxBytes / 1024 / 1024)}MB). A single file cannot be split across createCommitOnBranch requests; use Git LFS or a local signing key for this change.`);
    this.path = path2;
    this.bytes = bytes;
    this.maxBytes = maxBytes;
    this.name = "OversizedFileError";
  }
};
function runGit(args, cwd) {
  return new Promise((resolve2) => {
    childProcess3.execFile("git", args, { cwd, maxBuffer: MAX_GIT_BUFFER, encoding: "buffer" }, (error, stdout, stderr) => {
      const err = error;
      const exitCode = err && typeof err.code === "number" ? err.code : err ? 1 : 0;
      resolve2({
        stdout: stdout ?? Buffer.alloc(0),
        stderr: (stderr ?? Buffer.alloc(0)).toString("utf8"),
        exitCode
      });
    });
  });
}
async function gitText(args, cwd) {
  const r = await runGit(args, cwd);
  if (r.exitCode !== 0) {
    throw new Error(`git ${args.join(" ")} failed: ${r.stderr.trim()}`);
  }
  return r.stdout.toString("utf8").trim();
}
async function resolveRepoNameWithOwner(ctx2) {
  const url = await gitText(["remote", "get-url", "origin"], ctx2.cwd);
  const parsed2 = parseGithubUrl(url);
  if (!parsed2) {
    throw new Error(`Could not parse owner/repo from origin remote: ${url}`);
  }
  return `${parsed2.owner}/${parsed2.repo}`;
}
async function resolveBaseBranch(ctx2) {
  if (ctx2.baseBranch)
    return ctx2.baseBranch;
  const r = await runGit(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], ctx2.cwd);
  if (r.exitCode !== 0)
    return null;
  return r.stdout.toString("utf8").trim().replace(/^origin\//, "") || null;
}
async function resolveBranchName(ctx2, input) {
  const branch = input.branch ? input.branch.replace(/^refs\/heads\//, "") : await resolveCurrentBranch(ctx2);
  const baseBranch = await resolveBaseBranch(ctx2);
  if (baseBranch && branch === baseBranch) {
    throw new Error(`Refusing to commit directly to base branch '${baseBranch}'. Pass a 'branch' name prefixed with posthog-code/.`);
  }
  return branch;
}
async function resolveCurrentBranch(ctx2) {
  const current = await gitText(["rev-parse", "--abbrev-ref", "HEAD"], ctx2.cwd);
  if (!current || current === "HEAD") {
    throw new Error("Detached HEAD \u2014 pass a `branch` to git_signed_commit (e.g. posthog-code/...).");
  }
  return current;
}
async function remoteTip(ctx2, branch) {
  const out = await gitText(["ls-remote", "--heads", "origin", branch], ctx2.cwd);
  if (!out)
    return null;
  return out.split("	")[0]?.trim() || null;
}
async function createRef(ctx2, repo, branch, sha) {
  const res = await execGh([
    "api",
    "-X",
    "POST",
    `/repos/${repo}/git/refs`,
    "-f",
    `ref=refs/heads/${branch}`,
    "-f",
    `sha=${sha}`
  ], { cwd: ctx2.cwd, env: ghTokenEnv(ctx2.token) });
  if (res.exitCode !== 0) {
    throw new Error(`Failed to create branch '${branch}': ${res.stderr || res.error}`);
  }
}
var GITHUB_TOKEN_ENV_VARS = ["GH_TOKEN", "GITHUB_TOKEN"];
function readGithubTokenFromEnv(env = process.env) {
  for (const name of GITHUB_TOKEN_ENV_VARS) {
    if (env[name])
      return env[name];
  }
  return void 0;
}
function ghTokenEnv(token) {
  return Object.fromEntries(GITHUB_TOKEN_ENV_VARS.map((name) => [name, token]));
}
var STAGED_READ_CONCURRENCY = 16;
async function buildFileChanges(ctx2, baseOid) {
  const diff = await runGit(["diff", "--cached", "-z", "--no-renames", "--name-status", baseOid], ctx2.cwd);
  if (diff.exitCode !== 0) {
    throw new Error(`git diff --cached failed: ${diff.stderr.trim()}`);
  }
  const tokens = diff.stdout.toString("utf8").split("\0").filter(Boolean);
  const addPaths = [];
  const deletions = [];
  for (let i = 0; i + 1 < tokens.length; i += 2) {
    const path2 = tokens[i + 1];
    if (tokens[i].startsWith("D")) {
      deletions.push({ path: path2 });
    } else {
      addPaths.push(path2);
    }
  }
  const additions = await mapWithConcurrency(addPaths, STAGED_READ_CONCURRENCY, async (path2) => {
    const r = await runGit(["show", `:${path2}`], ctx2.cwd);
    if (r.exitCode !== 0) {
      throw new Error(`Failed to read staged file '${path2}': ${r.stderr.trim()}`);
    }
    return { path: path2, contents: r.stdout.toString("base64") };
  });
  return { additions, deletions };
}
function additionBytes(a) {
  return a.contents.length + a.path.length + 32;
}
function chunkFileChanges(changes, maxBytes) {
  for (const a of changes.additions) {
    const bytes = additionBytes(a);
    if (bytes > maxBytes)
      throw new OversizedFileError(a.path, bytes, maxBytes);
  }
  if (changes.additions.length === 0) {
    return [{ additions: [], deletions: changes.deletions }];
  }
  const chunks = [];
  let cur = { additions: [], deletions: [...changes.deletions] };
  let curBytes = changes.deletions.reduce((n, d) => n + d.path.length + 16, 0);
  for (const a of changes.additions) {
    const bytes = additionBytes(a);
    if (cur.additions.length > 0 && curBytes + bytes > maxBytes) {
      chunks.push(cur);
      cur = { additions: [], deletions: [] };
      curBytes = 0;
    }
    cur.additions.push(a);
    curBytes += bytes;
  }
  chunks.push(cur);
  return chunks;
}
var CREATE_COMMIT_MUTATION = `mutation($input: CreateCommitOnBranchInput!) {
  createCommitOnBranch(input: $input) { commit { oid url } }
}`;
async function createCommitOnBranch(ctx2, repo, branch, expectedHeadOid, headline, body, changes) {
  const payload = JSON.stringify({
    query: CREATE_COMMIT_MUTATION,
    variables: {
      input: {
        branch: { repositoryNameWithOwner: repo, branchName: branch },
        expectedHeadOid,
        message: { headline, body },
        fileChanges: changes
      }
    }
  });
  const res = await execGhWithRetry(["api", "graphql", "--input", "-"], {
    cwd: ctx2.cwd,
    input: payload,
    env: ghTokenEnv(ctx2.token),
    // Bound each attempt so a stalled connection can't hang the tool forever.
    timeoutMs: GH_GRAPHQL_TIMEOUT_MS
  }, { maxAttempts: 3 });
  if (res.exitCode !== 0) {
    throw new Error(`createCommitOnBranch failed: ${res.stderr || res.error || res.stdout}`);
  }
  let parsed2;
  try {
    parsed2 = JSON.parse(res.stdout);
  } catch {
    throw new Error(`createCommitOnBranch returned non-JSON: ${res.stdout.slice(0, 500)}`);
  }
  if (parsed2.errors) {
    throw new Error(`createCommitOnBranch errors: ${JSON.stringify(parsed2.errors)}`);
  }
  const commit = parsed2.data?.createCommitOnBranch?.commit;
  if (!commit?.oid) {
    throw new Error(`createCommitOnBranch returned no commit: ${res.stdout}`);
  }
  return commit;
}
async function syncLocalCheckout(ctx2, branch, newOid) {
  const steps = [
    ["fetch", ["fetch", "--no-tags", "origin", branch]],
    ["update-ref", ["update-ref", `refs/heads/${branch}`, newOid]],
    ["symbolic-ref", ["symbolic-ref", "HEAD", `refs/heads/${branch}`]],
    ["reset", ["reset", "-q"]]
  ];
  for (const [label, args] of steps) {
    const r = await runGit(args, ctx2.cwd);
    if (r.exitCode !== 0) {
      process.stderr.write(`[signed-commit] local sync step '${label}' failed after committing ${newOid}: ${r.stderr.trim()}
`);
    }
  }
}
async function createSignedCommit(ctx2, input) {
  const [repo, branch] = await Promise.all([
    resolveRepoNameWithOwner(ctx2),
    resolveBranchName(ctx2, input)
  ]);
  if (input.paths && input.paths.length > 0) {
    const r = await runGit(["add", "--", ...input.paths], ctx2.cwd);
    if (r.exitCode !== 0) {
      throw new Error(`git add failed: ${r.stderr.trim()}`);
    }
  }
  let tip = await remoteTip(ctx2, branch);
  if (tip === null) {
    const baseSha = await gitText(["rev-parse", "HEAD"], ctx2.cwd);
    await createRef(ctx2, repo, branch, baseSha);
    tip = baseSha;
  } else {
    await runGit(["fetch", "--no-tags", "origin", branch], ctx2.cwd);
  }
  const changes = await buildFileChanges(ctx2, tip);
  if (changes.additions.length === 0 && changes.deletions.length === 0) {
    throw new Error("No staged changes to commit. Stage files with `git add` first (or pass `paths`).");
  }
  const chunks = chunkFileChanges(changes, DEFAULT_MAX_PAYLOAD_BYTES);
  const body = [input.body, buildPostHogTrailers(ctx2.taskId).join("\n")].filter(Boolean).join("\n\n");
  const commits = [];
  let expectedHeadOid = tip;
  for (let i = 0; i < chunks.length; i++) {
    const headline = chunks.length > 1 ? `${input.message} \u2014 part ${i + 1}/${chunks.length}` : input.message;
    const commit = await createCommitOnBranch(ctx2, repo, branch, expectedHeadOid, headline, body, chunks[i]);
    commits.push({ sha: commit.oid, url: commit.url });
    expectedHeadOid = commit.oid;
  }
  await syncLocalCheckout(ctx2, branch, expectedHeadOid);
  return { branch, commits };
}

// src/utils/common.ts
var IS_ROOT = typeof process !== "undefined" && (process.geteuid?.() ?? process.getuid?.()) === 0;
var ALLOW_BYPASS = !IS_ROOT || !!process.env.IS_SANDBOX;
function isCloudRun(meta) {
  if (meta?.environment) {
    return meta.environment === "cloud";
  }
  return !!process.env.IS_SANDBOX;
}
function resolveGithubToken() {
  return readGithubTokenFromEnv();
}

// src/adapters/signed-commit-shared.ts
import { z } from "zod";

// src/adapters/local-tools/registry.ts
var LOCAL_TOOLS_MCP_NAME = "posthog-code-tools";
function defineLocalTool(def) {
  return def;
}
function qualifiedLocalToolName(toolName) {
  return `mcp__${LOCAL_TOOLS_MCP_NAME}__${toolName}`;
}

// src/adapters/signed-commit-shared.ts
var SIGNED_COMMIT_TOOL_NAME = "git_signed_commit";
var SIGNED_COMMIT_QUALIFIED_TOOL_NAME = qualifiedLocalToolName(
  SIGNED_COMMIT_TOOL_NAME
);
var SIGNED_COMMIT_TOOL_DESCRIPTION = "Create a GitHub-signed (Verified) commit on the branch. Stage files with `git add` first (or pass `paths`), then call this instead of `git commit`/`git push` \u2014 those are blocked because all commits must be signed. The commit is created via GitHub's API and your local checkout is kept in sync. For a new branch, pass `branch` (prefixed with `posthog-code/`) and the tool creates it on the remote.";
var signedCommitToolSchema = {
  message: z.string().describe("Commit headline (first line)."),
  body: z.string().optional().describe("Optional extended commit body."),
  branch: z.string().optional().describe(
    "Target branch; defaults to the current branch. Use a posthog-code/ prefix for new branches."
  ),
  paths: z.array(z.string()).optional().describe(
    "Files to stage before committing; defaults to already-staged files."
  )
};
function formatSignedCommitResult(result) {
  const list = result.commits.map((c) => `- ${c.sha} ${c.url}`).join("\n");
  return `Created ${result.commits.length} signed commit(s) on ${result.branch}:
${list}`;
}
async function runSignedCommitTool(ctx2, args) {
  try {
    const result = await createSignedCommit(ctx2, args);
    return {
      content: [{ type: "text", text: formatSignedCommitResult(result) }]
    };
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    return {
      content: [
        { type: "text", text: `${SIGNED_COMMIT_TOOL_NAME} failed: ${message}` }
      ],
      isError: true
    };
  }
}

// src/adapters/local-tools/tools/signed-commit.ts
var signedCommitTool = defineLocalTool({
  name: SIGNED_COMMIT_TOOL_NAME,
  description: SIGNED_COMMIT_TOOL_DESCRIPTION,
  schema: signedCommitToolSchema,
  alwaysLoad: true,
  isEnabled: (_ctx, meta) => isCloudRun(meta),
  handler: (ctx2, args) => {
    const token = ctx2.token ?? resolveGithubToken();
    if (!token) {
      return Promise.resolve({
        content: [
          {
            type: "text",
            text: `${SIGNED_COMMIT_TOOL_NAME} failed: no GitHub token in env (GH_TOKEN/GITHUB_TOKEN)`
          }
        ],
        isError: true
      });
    }
    return runSignedCommitTool(
      { cwd: ctx2.cwd, token, taskId: ctx2.taskId },
      args
    );
  }
});

// src/adapters/local-tools/index.ts
var LOCAL_TOOLS = [signedCommitTool];

// src/adapters/codex/local-tools-mcp-server.ts
function die(message) {
  process.stderr.write(`[local-tools-mcp-server] ${message}
`);
  process.exit(1);
}
var ctxEnv = process.env.POSTHOG_LOCAL_TOOLS_CTX;
if (!ctxEnv) {
  die("POSTHOG_LOCAL_TOOLS_CTX env var is required");
}
var parsed;
try {
  parsed = JSON.parse(Buffer.from(ctxEnv, "base64").toString("utf-8"));
} catch (err) {
  die(`Failed to parse POSTHOG_LOCAL_TOOLS_CTX as base64-encoded JSON: ${err}`);
}
if (!parsed.cwd) {
  die("POSTHOG_LOCAL_TOOLS_CTX must include cwd");
}
var ctx = {
  cwd: parsed.cwd,
  token: parsed.token ?? readGithubTokenFromEnv(),
  taskId: parsed.taskId
};
var enabledNames = (process.env.POSTHOG_LOCAL_TOOLS_ENABLED ?? "").split(",").filter(Boolean);
var tools = LOCAL_TOOLS.filter((t) => enabledNames.includes(t.name));
if (tools.length === 0) {
  die("POSTHOG_LOCAL_TOOLS_ENABLED listed no known tools");
}
var server = new McpServer({
  name: LOCAL_TOOLS_MCP_NAME,
  version: "1.0.0"
});
for (const t of tools) {
  server.tool(
    t.name,
    t.description,
    t.schema,
    async (args) => t.handler(ctx, args)
  );
}
var transport = new StdioServerTransport();
await server.connect(transport);
/*! Bundled license information:

git-url-parse/lib/index.js:
  (*!
   * buildToken
   * Builds OAuth token prefix (helper function)
   *
   * @name buildToken
   * @function
   * @param {GitUrl} obj The parsed Git url object.
   * @return {String} token prefix
   *)
*/
//# sourceMappingURL=local-tools-mcp-server.js.map