/**
 * @license
 * Copyright 2022-2026 Greg Lauckhart <greg@lauckhart.com>
 * SPDX-License-Identifier: Apache-2.0
 */
import { GLOBSTAR, Minimatch } from "minimatch";
import { FilesystemSync } from "./file.js";
class GlobError extends Error {
}
function globSync(pattern, fs = FilesystemSync()) {
  if (typeof pattern === "string") {
    return [...globOneSync(pattern, fs)];
  }
  const result = Array();
  for (const p of pattern) {
    result.push(...globOneSync(p, fs));
  }
  return result;
}
function globOneSync(pattern, fs) {
  const mm = new Minimatch(pattern.replace(/\\/g, "/"), {});
  const results = /* @__PURE__ */ new Set();
  for (const part of mm.set) {
    for (const path of globOnePartSync(mm, part, fs)) {
      results.add(path);
    }
  }
  return results;
}
function globOnePartSync(mm, segments, fs) {
  let rootPath = "";
  let didOne = false;
  while (typeof segments[0] === "string") {
    if (didOne) {
      rootPath += "/";
    } else {
      didOne = true;
    }
    rootPath += segments.shift();
  }
  if (!segments.length) {
    const stat = fs.stat(rootPath);
    if (stat?.[rootPath.endsWith("/") ? "isDirectory" : "isFile"]) {
      return [fs.resolve(rootPath)];
    }
    return [];
  }
  const results = /* @__PURE__ */ new Set();
  function match(path, segments2) {
    if (!segments2.length) {
      results.add(fs.resolve(path));
      return;
    }
    if (typeof segments2[0] === "string") {
      const subpath = fs.resolve(path, segments2[0]);
      if (fs.stat(fs.resolve(path, segments2[0]))) {
        match(subpath, segments2.slice(1));
        return;
      }
    }
    if (segments2.length === 1 && segments2[0] === GLOBSTAR) {
      results.add(fs.resolve(path));
    }
    const subnames = fs.readdir(path);
    if (!subnames) {
      return;
    }
    for (const subname of subnames) {
      const subpath = fs.resolve(path, subname);
      if (segments2[0] !== GLOBSTAR) {
        if (mm.matchOne([subname], segments2, true)) {
          match(subpath, segments2.slice(1));
        }
        continue;
      }
      if (segments2.length > 1) {
        if (mm.matchOne([subname], segments2.slice(1), true)) {
          match(subpath, segments2.slice(2));
        }
      }
      match(subpath, segments2);
    }
  }
  match(rootPath, segments);
  return results;
}
export {
  GlobError,
  globSync
};
//# sourceMappingURL=glob.js.map
