Skip to content

Commit c77ee53

Browse files
committed
refactor: Simplify Open Graph image URL resolution logic
- Refactored the `resolveOgImageUrl` function to remove asynchronous operations, improving performance and clarity. - Updated the logic to handle image paths more efficiently, ensuring that fallback mechanisms are in place when images are not found. - Enhanced the integration of the image resolution function within the metadata generation process, streamlining the handling of custom and default images.
1 parent b697159 commit c77ee53

File tree

2 files changed

+39
-69
lines changed

2 files changed

+39
-69
lines changed

app/[[...path]]/page.tsx

Lines changed: 8 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -195,11 +195,7 @@ function formatCanonicalTag(tag: string) {
195195
}
196196

197197
// Helper function to resolve OG image URLs
198-
async function resolveOgImageUrl(
199-
imageUrl: string | undefined,
200-
domain: string,
201-
pagePath: string[]
202-
): Promise<string | null> {
198+
function resolveOgImageUrl(imageUrl: string | undefined, domain: string): string | null {
203199
if (!imageUrl) {
204200
return null;
205201
}
@@ -212,63 +208,14 @@ async function resolveOgImageUrl(
212208
return cleanUrl;
213209
}
214210

215-
// Absolute paths (public folder or already processed mdx-images)
211+
// Absolute paths (should already be the hashed path like /mdx-images/overview-HASH.png)
216212
if (cleanUrl.startsWith('/')) {
217213
return `${domain}${cleanUrl}`;
218214
}
219215

220-
// For relative paths, try to find the processed image in /mdx-images/
221-
// Images get hashed during build, so we need to find the hashed version
222-
if (cleanUrl.startsWith('./')) {
223-
const {readdir, access} = await import('fs/promises');
224-
const path = await import('path');
225-
226-
// Extract the base filename without path
227-
const filename = path.basename(cleanUrl);
228-
const nameWithoutExt = filename.replace(path.extname(filename), '');
229-
230-
try {
231-
// Look for the hashed version in public/mdx-images/
232-
const mdxImagesDir = path.join(process.cwd(), 'public', 'mdx-images');
233-
234-
// Check if directory exists first
235-
try {
236-
await access(mdxImagesDir);
237-
} catch (accessError) {
238-
// eslint-disable-next-line no-console
239-
console.warn('mdx-images directory not accessible:', mdxImagesDir, accessError);
240-
return null; // Return null to fall back to default OG image
241-
}
242-
243-
const files = await readdir(mdxImagesDir);
244-
245-
// Find a file that starts with the same base name
246-
const hashedFile = files.find(f => f.startsWith(nameWithoutExt + '-'));
247-
248-
if (hashedFile) {
249-
return `${domain}/mdx-images/${hashedFile}`;
250-
}
251-
252-
// eslint-disable-next-line no-console
253-
console.warn(
254-
'No hashed image found for:',
255-
nameWithoutExt,
256-
'in files:',
257-
files.filter(f => f.includes(nameWithoutExt))
258-
);
259-
} catch (e) {
260-
// eslint-disable-next-line no-console
261-
console.error('Error finding hashed image:', e);
262-
return null; // Return null to fall back to default OG image
263-
}
264-
265-
// If we get here, we couldn't find the image - return null to use default
266-
return null;
267-
}
268-
269-
// Default case: treat as relative to page
270-
const pageDir = pagePath.join('/');
271-
return `${domain}/${pageDir}/${cleanUrl}`;
216+
// If we still have a relative path here, it means the hashing didn't work
217+
// Return null to fall back to default OG image
218+
return null;
272219
}
273220

274221
export async function generateMetadata(props: MetadataProps): Promise<Metadata> {
@@ -313,10 +260,9 @@ export async function generateMetadata(props: MetadataProps): Promise<Metadata>
313260
// Three-tier OG image priority:
314261
// 1. Manual override via og_image frontmatter
315262
if (pageNode.frontmatter.og_image) {
316-
ogImageUrl = await resolveOgImageUrl(
263+
ogImageUrl = resolveOgImageUrl(
317264
pageNode.frontmatter.og_image,
318-
previewDomain ?? domain,
319-
params.path
265+
previewDomain ?? domain
320266
);
321267
}
322268

@@ -329,11 +275,7 @@ export async function generateMetadata(props: MetadataProps): Promise<Metadata>
329275
: `docs/${pageNode.path}`
330276
);
331277
if (doc.firstImage) {
332-
ogImageUrl = await resolveOgImageUrl(
333-
doc.firstImage,
334-
previewDomain ?? domain,
335-
params.path
336-
);
278+
ogImageUrl = resolveOgImageUrl(doc.firstImage, previewDomain ?? domain);
337279
}
338280
} catch (e) {
339281
// If we can't load the doc, just continue without the first image

src/mdx.ts

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -543,8 +543,6 @@ export async function getFileBySlug(slug: string): Promise<SlugFile> {
543543
} catch (e) {
544544
// If we can't create the directory (e.g., read-only filesystem during static generation),
545545
// continue anyway - images should already exist from build time
546-
// eslint-disable-next-line no-console
547-
console.warn('Could not create mdx-images directory:', outdir, (e as Error).message);
548546
}
549547

550548
// If the file contains content that depends on the Release Registry (such as an SDK's latest version), avoid using the cache for that file, i.e. always rebuild it.
@@ -697,6 +695,9 @@ export async function getFileBySlug(slug: string): Promise<SlugFile> {
697695
// Set write to true so that esbuild will output the files.
698696
options.write = true;
699697

698+
// Enable metafile to track input -> output file mappings
699+
options.metafile = true;
700+
700701
return options;
701702
},
702703
}).catch(e => {
@@ -712,11 +713,38 @@ export async function getFileBySlug(slug: string): Promise<SlugFile> {
712713
mergedFrontmatter = {...frontmatter, ...configFrontmatter};
713714
}
714715

716+
// Map the first image to its hashed output filename using esbuild's metafile
717+
let firstImageHashed: string | undefined;
718+
if (firstImageRef[0] && result.metafile) {
719+
const firstImagePath = firstImageRef[0];
720+
721+
// Find the output file that corresponds to this input image
722+
for (const [outputPath, outputInfo] of Object.entries(result.metafile.outputs)) {
723+
if (outputInfo.inputs) {
724+
for (const inputPath of Object.keys(outputInfo.inputs)) {
725+
// Check if this input matches our first image
726+
// Handle both absolute and relative paths
727+
if (
728+
inputPath.endsWith(firstImagePath) ||
729+
inputPath.endsWith(firstImagePath.replace('./', ''))
730+
) {
731+
// Extract just the filename from the output path
732+
firstImageHashed = `/mdx-images/${path.basename(outputPath)}`;
733+
break;
734+
}
735+
}
736+
}
737+
if (firstImageHashed) {
738+
break;
739+
}
740+
}
741+
}
742+
715743
const resultObj: SlugFile = {
716744
matter: result.matter,
717745
mdxSource: code,
718746
toc,
719-
firstImage: firstImageRef[0],
747+
firstImage: firstImageHashed || firstImageRef[0],
720748
frontMatter: {
721749
...mergedFrontmatter,
722750
slug,

0 commit comments

Comments
 (0)