"use strict";
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 __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);
var archive_exports = {};
__export(archive_exports, {
  downloadFile: () => downloadFile,
  extractBinaryFromTarGz: () => extractBinaryFromTarGz,
  extractTarGzFromUrl: () => extractTarGzFromUrl,
  extractZip: () => extractZip,
  fetchJson: () => fetchJson
});
module.exports = __toCommonJS(archive_exports);
var path = __toESM(require("path"));
var fs = __toESM(require("fs"));
var http = __toESM(require("http"));
var https = __toESM(require("https"));
var zlib = __toESM(require("zlib"));
function fetchJson(url) {
  return new Promise((resolve, reject) => {
    const mod = url.startsWith("https") ? https : http;
    mod.get(url, { headers: { "User-Agent": "kirograph" } }, (res) => {
      if (res.statusCode === 301 || res.statusCode === 302) {
        return resolve(fetchJson(res.headers.location));
      }
      if (res.statusCode !== 200) {
        return reject(new Error(`HTTP ${res.statusCode}`));
      }
      let body = "";
      res.on("data", (c) => body += c);
      res.on("end", () => {
        try {
          resolve(JSON.parse(body));
        } catch (e) {
          reject(e);
        }
      });
    }).on("error", reject);
  });
}
function downloadFile(url, dest) {
  return new Promise((resolve, reject) => {
    function doGet(currentUrl) {
      const mod = currentUrl.startsWith("https") ? https : http;
      mod.get(currentUrl, { headers: { "User-Agent": "kirograph" } }, (res) => {
        if (res.statusCode === 301 || res.statusCode === 302) return doGet(res.headers.location);
        if (res.statusCode !== 200) return reject(new Error(`Download failed: HTTP ${res.statusCode}`));
        const out = fs.createWriteStream(dest);
        res.pipe(out);
        out.on("finish", () => out.close(() => resolve()));
        out.on("error", reject);
      }).on("error", reject);
    }
    doGet(url);
  });
}
async function extractZip(zipPath, destDir) {
  const buf = await fs.promises.readFile(zipPath);
  const resolvedDest = path.resolve(destDir);
  let eocdOffset = -1;
  for (let i = buf.length - 22; i >= 0; i--) {
    if (buf.readUInt32LE(i) === 101010256) {
      eocdOffset = i;
      break;
    }
  }
  if (eocdOffset === -1) throw new Error("Invalid ZIP: EOCD not found");
  const cdCount = buf.readUInt16LE(eocdOffset + 10);
  const cdOffset = buf.readUInt32LE(eocdOffset + 16);
  let cdPos = cdOffset;
  for (let i = 0; i < cdCount; i++) {
    if (buf.readUInt32LE(cdPos) !== 33639248) throw new Error("Invalid ZIP: bad CD signature");
    const compMethod = buf.readUInt16LE(cdPos + 10);
    const compSize = buf.readUInt32LE(cdPos + 20);
    const uncompSize = buf.readUInt32LE(cdPos + 24);
    const fileNameLen = buf.readUInt16LE(cdPos + 28);
    const extraLen = buf.readUInt16LE(cdPos + 30);
    const commentLen = buf.readUInt16LE(cdPos + 32);
    const localOffset = buf.readUInt32LE(cdPos + 42);
    const fileName = buf.slice(cdPos + 46, cdPos + 46 + fileNameLen).toString("utf8");
    cdPos += 46 + fileNameLen + extraLen + commentLen;
    if (fileName.endsWith("/") || uncompSize === 0 && compSize === 0) continue;
    const destPath = path.resolve(resolvedDest, fileName);
    if (!destPath.startsWith(resolvedDest + path.sep) && destPath !== resolvedDest) continue;
    if (buf.readUInt32LE(localOffset) !== 67324752) throw new Error("Invalid ZIP: bad LFH signature");
    const localFileNameLen = buf.readUInt16LE(localOffset + 26);
    const localExtraLen = buf.readUInt16LE(localOffset + 28);
    const dataOffset = localOffset + 30 + localFileNameLen + localExtraLen;
    const compData = buf.slice(dataOffset, dataOffset + compSize);
    let fileData;
    if (compMethod === 0) {
      fileData = compData;
    } else if (compMethod === 8) {
      fileData = await new Promise((resolve, reject) => {
        zlib.inflateRaw(compData, (err, result) => err ? reject(err) : resolve(result));
      });
    } else {
      continue;
    }
    await fs.promises.mkdir(path.dirname(destPath), { recursive: true });
    await fs.promises.writeFile(destPath, fileData);
  }
}
function extractTarGzFromUrl(url, destDir, opts) {
  const resolvedDest = path.resolve(destDir);
  return new Promise((resolve, reject) => {
    fs.mkdirSync(resolvedDest, { recursive: true });
    function doGet(currentUrl) {
      const mod = currentUrl.startsWith("https") ? https : http;
      mod.get(currentUrl, { headers: { "User-Agent": "kirograph" } }, (res) => {
        if (res.statusCode === 301 || res.statusCode === 302) {
          return doGet(res.headers.location);
        }
        if (res.statusCode !== 200) {
          return reject(new Error(`Download failed: HTTP ${res.statusCode}`));
        }
        const gunzip = zlib.createGunzip();
        res.pipe(gunzip);
        let tarBuffer = Buffer.alloc(0);
        let offset = 0;
        let foundFile = null;
        function extractEntries(final = false) {
          while (offset + 512 <= tarBuffer.length) {
            const header = tarBuffer.slice(offset, offset + 512);
            const nameRaw = header.slice(0, 100).toString("utf8").replace(/\0/g, "");
            const sizeOctal = header.slice(124, 136).toString("utf8").replace(/\0/g, "").trim();
            const typeFlag = header[156];
            const size = parseInt(sizeOctal, 8) || 0;
            const dataStart = offset + 512;
            const dataEnd = dataStart + size;
            if (nameRaw === "") {
              offset += 512;
              continue;
            }
            const relName = opts?.stripPrefix && nameRaw.startsWith(opts.stripPrefix) ? nameRaw.slice(opts.stripPrefix.length) : nameRaw;
            if (opts?.findFile && path.basename(nameRaw) === opts.findFile) {
              if (tarBuffer.length >= dataEnd || final) {
                foundFile = tarBuffer.slice(dataStart, dataEnd);
                resolve(foundFile);
                return;
              }
              return;
            }
            const destPath = path.resolve(resolvedDest, relName);
            if (!destPath.startsWith(resolvedDest + path.sep) && destPath !== resolvedDest) {
              offset = dataStart + Math.ceil(size / 512) * 512;
              continue;
            }
            if (typeFlag === 53 || nameRaw.endsWith("/")) {
              try {
                fs.mkdirSync(destPath, { recursive: true });
              } catch {
              }
              offset = dataStart;
              continue;
            }
            if (tarBuffer.length < dataEnd && !final) return;
            if (relName && !relName.endsWith("/")) {
              try {
                fs.mkdirSync(path.dirname(destPath), { recursive: true });
                fs.writeFileSync(destPath, tarBuffer.slice(dataStart, dataEnd));
              } catch {
              }
            }
            offset = dataStart + Math.ceil(size / 512) * 512;
          }
        }
        gunzip.on("data", (chunk) => {
          tarBuffer = Buffer.concat([tarBuffer, chunk]);
          extractEntries();
        });
        gunzip.on("end", () => {
          extractEntries(true);
          if (opts?.findFile && !foundFile) {
            reject(new Error(`${opts.findFile} not found in archive`));
          } else {
            resolve(foundFile ?? void 0);
          }
        });
        gunzip.on("error", reject);
      }).on("error", reject);
    }
    doGet(url);
  });
}
async function extractBinaryFromTarGz(url, binaryName, destPath) {
  const destDir = path.dirname(destPath);
  fs.mkdirSync(destDir, { recursive: true });
  const content = await extractTarGzFromUrl(url, destDir, { findFile: binaryName });
  if (content && Buffer.isBuffer(content)) {
    fs.writeFileSync(destPath, content);
    try {
      fs.chmodSync(destPath, 493);
    } catch {
    }
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  downloadFile,
  extractBinaryFromTarGz,
  extractTarGzFromUrl,
  extractZip,
  fetchJson
});
//# sourceMappingURL=archive.js.map
