summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/remark-collect-images.ts
diff options
context:
space:
mode:
authorGravatar Erika <3019731+Princesseuh@users.noreply.github.com> 2023-04-04 10:21:13 +0200
committerGravatar GitHub <noreply@github.com> 2023-04-04 10:21:13 +0200
commita1a4f45b51a80215fa7598da83bd0d9c5acd20d2 (patch)
treecc6a7ff9586548f1f0f8b3c96746636ec3e060c2 /packages/markdown/remark/src/remark-collect-images.ts
parent366decbe335d3a84a8b76caac443f07b8a85a6a0 (diff)
downloadastro-a1a4f45b51a80215fa7598da83bd0d9c5acd20d2.tar.gz
astro-a1a4f45b51a80215fa7598da83bd0d9c5acd20d2.tar.zst
astro-a1a4f45b51a80215fa7598da83bd0d9c5acd20d2.zip
fix(images): Simpler logic for collecting images in Markdown (#6744)
Diffstat (limited to 'packages/markdown/remark/src/remark-collect-images.ts')
-rw-r--r--packages/markdown/remark/src/remark-collect-images.ts24
1 files changed, 19 insertions, 5 deletions
diff --git a/packages/markdown/remark/src/remark-collect-images.ts b/packages/markdown/remark/src/remark-collect-images.ts
index afc61c468..470b770ed 100644
--- a/packages/markdown/remark/src/remark-collect-images.ts
+++ b/packages/markdown/remark/src/remark-collect-images.ts
@@ -1,17 +1,31 @@
import type { Image } from 'mdast';
import { visit } from 'unist-util-visit';
-import type { VFile } from 'vfile';
+import type { MarkdownVFile } from './types';
export default function toRemarkCollectImages() {
return () =>
- async function (tree: any, vfile: VFile) {
+ async function (tree: any, vfile: MarkdownVFile) {
if (typeof vfile?.path !== 'string') return;
const imagePaths = new Set<string>();
- visit(tree, 'image', function raiseError(node: Image) {
- imagePaths.add(node.url);
+ visit(tree, 'image', (node: Image) => {
+ if (shouldOptimizeImage(node.url)) imagePaths.add(node.url);
});
- vfile.data.imagePaths = Array.from(imagePaths);
+ vfile.data.imagePaths = imagePaths;
};
}
+
+function shouldOptimizeImage(src: string) {
+ // Optimize anything that is NOT external or an absolute path to `public/`
+ return !isValidUrl(src) && !src.startsWith('/');
+}
+
+function isValidUrl(str: string): boolean {
+ try {
+ new URL(str);
+ return true;
+ } catch {
+ return false;
+ }
+}