index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // src/helper/route/index.ts
  2. import { GET_MATCH_RESULT } from "../../request/constants.js";
  3. import { getPattern, splitRoutingPath } from "../../utils/url.js";
  4. var matchedRoutes = (c) => (
  5. // @ts-expect-error c.req[GET_MATCH_RESULT] is not typed
  6. c.req[GET_MATCH_RESULT][0].map(([[, route]]) => route)
  7. );
  8. var routePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? "";
  9. var baseRoutePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.basePath ?? "";
  10. var basePathCacheMap = /* @__PURE__ */ new WeakMap();
  11. var basePath = (c, index) => {
  12. index ??= c.req.routeIndex;
  13. const cache = basePathCacheMap.get(c) || [];
  14. if (typeof cache[index] === "string") {
  15. return cache[index];
  16. }
  17. let result;
  18. const rp = baseRoutePath(c, index);
  19. if (!/[:*]/.test(rp)) {
  20. result = rp;
  21. } else {
  22. const paths = splitRoutingPath(rp);
  23. const reqPath = c.req.path;
  24. let basePathLength = 0;
  25. for (let i = 0, len = paths.length; i < len; i++) {
  26. const pattern = getPattern(paths[i], paths[i + 1]);
  27. if (pattern) {
  28. const re = pattern[2] === true || pattern === "*" ? /[^\/]+/ : pattern[2];
  29. basePathLength += reqPath.substring(basePathLength + 1).match(re)?.[0].length || 0;
  30. } else {
  31. basePathLength += paths[i].length;
  32. }
  33. basePathLength += 1;
  34. }
  35. result = reqPath.substring(0, basePathLength);
  36. }
  37. cache[index] = result;
  38. basePathCacheMap.set(c, cache);
  39. return result;
  40. };
  41. export {
  42. basePath,
  43. baseRoutePath,
  44. matchedRoutes,
  45. routePath
  46. };