From dc105b8d42d48f690b1781f08ab14562c14894ca Mon Sep 17 00:00:00 2001 From: Josh Chappelow Date: Mon, 19 Aug 2024 05:50:46 +0900 Subject: [PATCH] refactor: move relative repath after emitESMImage --- .../markdoc/src/content-entry-type.ts | 32 ++++++++----------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/packages/integrations/markdoc/src/content-entry-type.ts b/packages/integrations/markdoc/src/content-entry-type.ts index 451bbb3a75..a625c0165e 100644 --- a/packages/integrations/markdoc/src/content-entry-type.ts +++ b/packages/integrations/markdoc/src/content-entry-type.ts @@ -310,16 +310,8 @@ async function emitOptimizedImages( if ((node.type === 'image' || isComponent) && typeof node.attributes.src === 'string') { let attributeName = isComponent ? 'src' : '__optimizedSrc'; - if (node.attributes.src.startsWith('./') || node.attributes.src.startsWith('../')) { - node.attributes.src = prependForwardSlash( - path.relative( - ctx.astroConfig.root.pathname, - path.join(path.dirname(ctx.filePath), node.attributes.src), - ), - ); - } // If the image isn't an URL or a link to public, try to resolve it. - if (shouldOptimizeImage(node.attributes.src, ctx.astroConfig.root.pathname)) { + if (shouldOptimizeImage(node.attributes.src)) { // Attempt to resolve source with Vite. // This handles relative paths and configured aliases const resolved = await ctx.pluginContext.resolve(node.attributes.src, ctx.filePath); @@ -340,9 +332,17 @@ async function emitOptimizedImages( if (globalThis.astroAsset.referencedImages) globalThis.astroAsset.referencedImages.add(fsPath); } - node.attributes[attributeName] = { ...src, fsPath }; - node.attributes.src = src.src; + // Repath relative image path for use in Markdoc image component + if (node.attributes.src.startsWith('./') || node.attributes.src.startsWith('../')) { + node.attributes.src = prependForwardSlash( + path.relative( + ctx.astroConfig.root.pathname, + path.join(path.dirname(ctx.filePath), node.attributes.src), + ), + ); + } + node.attributes[attributeName] = { ...src, fsPath }; } } else { throw new MarkdocError({ @@ -361,15 +361,9 @@ async function emitOptimizedImages( } } -function shouldOptimizeImage(src: string, rootPath: string) { +function shouldOptimizeImage(src: string) { // Optimize anything that is NOT external or an absolute path to `public/` - if (isValidUrl(src)) return false; - const normPath = path.normalize(src); - if (normPath.startsWith(rootPath) || normPath.startsWith('/')) { - return false; - } - - return true; + return !isValidUrl(src) && !src.startsWith('/'); } /**