utils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // src/helper/ssg/utils.ts
  2. import { METHOD_NAME_ALL } from "../../router.js";
  3. import { findTargetHandler, isMiddleware } from "../../utils/handler.js";
  4. var dirname = (path) => {
  5. const separatedPath = path.split(/[\/\\]/);
  6. return separatedPath.slice(0, -1).join("/");
  7. };
  8. var normalizePath = (path) => {
  9. return path.replace(/(\\)/g, "/").replace(/\/$/g, "");
  10. };
  11. var handleParent = (resultPaths, beforeParentFlag) => {
  12. if (resultPaths.length === 0 || beforeParentFlag) {
  13. resultPaths.push("..");
  14. } else {
  15. resultPaths.pop();
  16. }
  17. };
  18. var handleNonDot = (path, resultPaths) => {
  19. path = path.replace(/^\.(?!.)/, "");
  20. if (path !== "") {
  21. resultPaths.push(path);
  22. }
  23. };
  24. var handleSegments = (paths, resultPaths) => {
  25. let beforeParentFlag = false;
  26. for (const path of paths) {
  27. if (path === "..") {
  28. handleParent(resultPaths, beforeParentFlag);
  29. beforeParentFlag = true;
  30. } else {
  31. handleNonDot(path, resultPaths);
  32. beforeParentFlag = false;
  33. }
  34. }
  35. };
  36. var joinPaths = (...paths) => {
  37. paths = paths.map(normalizePath);
  38. const resultPaths = [];
  39. handleSegments(paths.join("/").split("/"), resultPaths);
  40. return (paths[0][0] === "/" ? "/" : "") + resultPaths.join("/");
  41. };
  42. var filterStaticGenerateRoutes = (hono) => {
  43. return hono.routes.reduce((acc, { method, handler, path }) => {
  44. const targetHandler = findTargetHandler(handler);
  45. if (["GET", METHOD_NAME_ALL].includes(method) && !isMiddleware(targetHandler)) {
  46. acc.push({ path });
  47. }
  48. return acc;
  49. }, []);
  50. };
  51. var isDynamicRoute = (path) => {
  52. return path.split("/").some((segment) => segment.startsWith(":") || segment.includes("*"));
  53. };
  54. var ensureWithinOutDir = (outDir, filePath) => {
  55. const normalizedOutDir = joinPaths("/", outDir);
  56. const normalizedFilePath = joinPaths("/", filePath);
  57. if (normalizedFilePath !== normalizedOutDir && !normalizedFilePath.startsWith(`${normalizedOutDir}/`)) {
  58. throw new Error(`Path traversal detected: "${filePath}" is outside the output directory`);
  59. }
  60. };
  61. export {
  62. dirname,
  63. ensureWithinOutDir,
  64. filterStaticGenerateRoutes,
  65. isDynamicRoute,
  66. joinPaths
  67. };