import rehypeParse from "rehype-parse";
import remarkGfm from "remark-gfm";
import remarkParse from "remark-parse";
import { unified } from "unified";
import { visit } from "unist-util-visit";

export function extract(md: string) {
  const images: string[] = [];
  const mdast = unified().use(remarkParse).use(remarkGfm).parse(md);
  visit(mdast, "image", (node) => {
    images.push(node.url);
  });
  visit(mdast, "html", (node) => {
    const hast = unified()
      .use(rehypeParse, { fragment: true })
      .parse(node.value);
    visit(hast, "element", (node) => {
      if (node.tagName === "img") {
        images.push(node.properties?.src as string);
      }
    });
  });
  return images;
}
