Files
medusa-store/www/packages/remark-rehype-plugins/src/broken-link-checker.ts
Shahed Nasser 4fe28f5a95 chore: reorganize docs apps (#7228)
* reorganize docs apps

* add README

* fix directory

* add condition for old docs
2024-05-03 17:36:38 +03:00

32 lines
967 B
TypeScript

import { existsSync } from "fs"
import path from "path"
import type { Transformer } from "unified"
import type { UnistNode, UnistTree } from "./types/index.js"
export function brokenLinkCheckerPlugin(): Transformer {
return async (tree, file) => {
const { visit } = await import("unist-util-visit")
const currentPageFilePath = file.history[0].replace(
`/${path.basename(file.history[0])}`,
""
)
visit(tree as UnistTree, "element", (node: UnistNode) => {
if (node.tagName !== "a" || !node.properties?.href?.match(/page\.mdx?/)) {
return
}
// get absolute path of the URL
const linkedFilePath = path
.resolve(currentPageFilePath, node.properties.href)
.replace(/#.*$/, "")
// check if the file exists
if (!existsSync(linkedFilePath)) {
throw new Error(
`Broken link found! ${node.properties.href} linked in ${file.history[0]}`
)
}
})
}
}