import pathToRegexp from "path-to-regexp";
import getFlatMenu from "./getFlatMenus.mjs";
import { isUrl, stripQueryStringAndHashFromPath } from "./transformRoute.mjs";
function getMenuMatches(flatMenuKeys = [], path, exact) {
  return flatMenuKeys.filter((item) => {
    if (item === "/" && path === "/") {
      return true;
    }
    if (item !== "/" && item !== "/*" && item && !isUrl(item)) {
      const pathKey = stripQueryStringAndHashFromPath(item);
      try {
        if (exact) {
          if (pathToRegexp(`${pathKey}`).test(path)) {
            return true;
          }
        }
        if (pathToRegexp(`${pathKey}`, []).test(path)) {
          return true;
        }
        if (pathToRegexp(`${pathKey}/(.*)`).test(path)) {
          return true;
        }
      } catch (error) {
      }
    }
    return false;
  }).sort((a, b) => {
    if (a === path) {
      return 10;
    }
    if (b === path) {
      return -10;
    }
    return a.substr(1).split("/").length - b.substr(1).split("/").length;
  });
}
function getMatchMenu(pathname, menuData, fullKeys, exact) {
  const flatMenus = getFlatMenu(menuData);
  const flatMenuKeys = Object.keys(flatMenus);
  let menuPathKeys = getMenuMatches(flatMenuKeys, pathname || "/", exact);
  if (!menuPathKeys || menuPathKeys.length < 1) {
    return [];
  }
  if (!fullKeys) {
    menuPathKeys = [menuPathKeys[menuPathKeys.length - 1]];
  }
  return menuPathKeys.map((menuPathKey) => {
    const menuItem = flatMenus[menuPathKey] || {
      pro_layout_parentKeys: "",
      key: ""
    };
    const map = /* @__PURE__ */ new Map();
    const parentItems = (menuItem.pro_layout_parentKeys || []).map((key) => {
      if (map.has(key)) {
        return null;
      }
      map.set(key, true);
      return flatMenus[key];
    }).filter((item) => item);
    if (menuItem.key) {
      parentItems.push(menuItem);
    }
    return parentItems;
  }).flat(1);
}
var stdin_default = getMatchMenu;
export {
  stdin_default as default,
  getMatchMenu,
  getMenuMatches
};
