From 8bab2339374763d19dbc4cc2c7ce4ad8a2a49694 Mon Sep 17 00:00:00 2001 From: Matt Kane Date: Wed, 28 Aug 2024 21:02:08 +0100 Subject: [PATCH] fix: resolve content layer images without filePath set (#11858) --- .changeset/rich-kings-wait.md | 5 +++++ .../astro/src/assets/utils/resolveImports.ts | 6 ++++-- packages/astro/src/content/runtime.ts | 19 ++++++++----------- .../src/content/vite-plugin-content-assets.ts | 10 +++++++++- packages/astro/test/content-layer.test.js | 15 +++++++++++++++ .../content-outside-src/columbia-copy.md | 1 + .../content-layer/src/content/config.ts | 19 ++++++++++++++++++- .../src/pages/collections.json.js | 3 +++ 8 files changed, 63 insertions(+), 15 deletions(-) create mode 100644 .changeset/rich-kings-wait.md diff --git a/.changeset/rich-kings-wait.md b/.changeset/rich-kings-wait.md new file mode 100644 index 000000000000..7f5aa677f71d --- /dev/null +++ b/.changeset/rich-kings-wait.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Correctly resolves content layer images when filePath is not set diff --git a/packages/astro/src/assets/utils/resolveImports.ts b/packages/astro/src/assets/utils/resolveImports.ts index 8d147552ece5..6dd6d1fdb4cf 100644 --- a/packages/astro/src/assets/utils/resolveImports.ts +++ b/packages/astro/src/assets/utils/resolveImports.ts @@ -10,7 +10,7 @@ import { VALID_INPUT_FORMATS } from '../consts.js'; * @param filePath The path to the file that contains the imagem relative to the site root * @returns A module id of the image that can be rsolved by Vite, or undefined if it is not a local image */ -export function imageSrcToImportId(imageSrc: string, filePath: string): string | undefined { +export function imageSrcToImportId(imageSrc: string, filePath?: string): string | undefined { // If the import is coming from the data store it will have a special prefix to identify it // as an image import. We remove this prefix so that we can resolve the image correctly. imageSrc = removeBase(imageSrc, IMAGE_IMPORT_PREFIX); @@ -32,7 +32,9 @@ export function imageSrcToImportId(imageSrc: string, filePath: string): string | // importer and get the correct full path for the imported image. const params = new URLSearchParams(CONTENT_IMAGE_FLAG); - params.set('importer', filePath); + if (filePath) { + params.set('importer', filePath); + } return `${imageSrc}?${params.toString()}`; } diff --git a/packages/astro/src/content/runtime.ts b/packages/astro/src/content/runtime.ts index b462e2e23a46..439d7e11e9cc 100644 --- a/packages/astro/src/content/runtime.ts +++ b/packages/astro/src/content/runtime.ts @@ -84,9 +84,7 @@ export function createGetCollection({ const result = []; for (const rawEntry of store.values(collection)) { - const data = rawEntry.filePath - ? updateImageReferencesInData(rawEntry.data, rawEntry.filePath, imageAssetMap) - : rawEntry.data; + const data = updateImageReferencesInData(rawEntry.data, rawEntry.filePath, imageAssetMap); const entry = { ...rawEntry, @@ -303,11 +301,9 @@ export function createGetEntry({ return; } - if (entry.filePath) { - // @ts-expect-error virtual module - const { default: imageAssetMap } = await import('astro:asset-imports'); - entry.data = updateImageReferencesInData(entry.data, entry.filePath, imageAssetMap); - } + // @ts-expect-error virtual module + const { default: imageAssetMap } = await import('astro:asset-imports'); + entry.data = updateImageReferencesInData(entry.data, entry.filePath, imageAssetMap); return { ...entry, collection, @@ -415,18 +411,19 @@ async function updateImageReferencesInBody(html: string, fileName: string) { function updateImageReferencesInData>( data: T, - fileName: string, - imageAssetMap: Map, + fileName?: string, + imageAssetMap?: Map, ): T { return new Traverse(data).map(function (ctx, val) { if (typeof val === 'string' && val.startsWith(IMAGE_IMPORT_PREFIX)) { const src = val.replace(IMAGE_IMPORT_PREFIX, ''); + const id = imageSrcToImportId(src, fileName); if (!id) { ctx.update(src); return; } - const imported = imageAssetMap.get(id); + const imported = imageAssetMap?.get(id); if (imported) { ctx.update(imported); } else { diff --git a/packages/astro/src/content/vite-plugin-content-assets.ts b/packages/astro/src/content/vite-plugin-content-assets.ts index b810b8f71a4e..d33de87724f9 100644 --- a/packages/astro/src/content/vite-plugin-content-assets.ts +++ b/packages/astro/src/content/vite-plugin-content-assets.ts @@ -6,6 +6,7 @@ import { getAssetsPrefix } from '../assets/utils/getAssetsPrefix.js'; import type { BuildInternals } from '../core/build/internal.js'; import type { AstroBuildPlugin } from '../core/build/plugin.js'; import type { StaticBuildOptions } from '../core/build/types.js'; +import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { ModuleLoader } from '../core/module-loader/loader.js'; import { createViteLoader } from '../core/module-loader/vite.js'; import { joinPaths, prependForwardSlash } from '../core/path.js'; @@ -42,7 +43,14 @@ export function astroContentAssetPropagationPlugin({ ? fileURLToPath(new URL(importerParam, settings.config.root)) : importer; - return this.resolve(base, importerPath, { skipSelf: true, ...opts }); + const resolved = this.resolve(base, importerPath, { skipSelf: true, ...opts }); + if (!resolved) { + throw new AstroError({ + ...AstroErrorData.ImageNotFound, + message: AstroErrorData.ImageNotFound.message(base), + }); + } + return resolved; } if (hasContentFlag(id, CONTENT_RENDER_FLAG)) { const base = id.split('?')[0]; diff --git a/packages/astro/test/content-layer.test.js b/packages/astro/test/content-layer.test.js index 41c05206bad2..d8d6a3b4512f 100644 --- a/packages/astro/test/content-layer.test.js +++ b/packages/astro/test/content-layer.test.js @@ -129,6 +129,21 @@ describe('Content Layer', () => { assert.ok(json.entryWithReference.data.publishedDate instanceof Date); }); + it('loads images in frontmatter', async () => { + assert.ok(json.entryWithReference.data.heroImage.src.startsWith('/_astro')); + assert.equal(json.entryWithReference.data.heroImage.format, 'jpg'); + }); + + it('loads images from custom loaders', async () => { + assert.ok(json.images[0].data.image.src.startsWith('/_astro')); + assert.equal(json.images[0].data.image.format, 'jpg'); + }); + + it('handles remote images in custom loaders', async () => { + console.log(json.images[1].data.image); + assert.ok(json.images[1].data.image.startsWith('https://')); + }); + it('returns a referenced entry', async () => { assert.ok(json.hasOwnProperty('referencedEntry')); assert.deepEqual(json.referencedEntry, { diff --git a/packages/astro/test/fixtures/content-layer/content-outside-src/columbia-copy.md b/packages/astro/test/fixtures/content-layer/content-outside-src/columbia-copy.md index 6e770b2afd95..e5ca2b3a5358 100644 --- a/packages/astro/test/fixtures/content-layer/content-outside-src/columbia-copy.md +++ b/packages/astro/test/fixtures/content-layer/content-outside-src/columbia-copy.md @@ -4,6 +4,7 @@ description: 'Learn about the Columbia NASA space shuttle.' publishedDate: 'Sat May 21 2022 00:00:00 GMT-0400 (Eastern Daylight Time)' tags: [space, 90s] cat: tabby +heroImage: "./shuttle.jpg" --- **Source:** [Wikipedia](https://en.wikipedia.org/wiki/Space_Shuttle_Endeavour) diff --git a/packages/astro/test/fixtures/content-layer/src/content/config.ts b/packages/astro/test/fixtures/content-layer/src/content/config.ts index 1689a56b1c28..5e25d83b95de 100644 --- a/packages/astro/test/fixtures/content-layer/src/content/config.ts +++ b/packages/astro/test/fixtures/content-layer/src/content/config.ts @@ -85,6 +85,23 @@ const numbers = defineCollection({ loader: glob({ pattern: 'src/data/glob-data/*', base: '.' }), }); +const images = defineCollection({ + loader: () => [ + { + id: '1', + image: '@images/shuttle.jpg' + }, + { + id: '2', + image: 'https://images.unsplash.com/photo-1457364887197-9150188c107b?w=800&fm=jpg&fit=crop' + } + ], + schema: ({image}) => z.object({ + id: z.string(), + image: image() + }) +}); + const increment = defineCollection({ loader: { name: 'increment-loader', @@ -108,4 +125,4 @@ const increment = defineCollection({ }); -export const collections = { blog, dogs, cats, numbers, spacecraft, increment }; +export const collections = { blog, dogs, cats, numbers, spacecraft, increment, images }; diff --git a/packages/astro/test/fixtures/content-layer/src/pages/collections.json.js b/packages/astro/test/fixtures/content-layer/src/pages/collections.json.js index f637bf80d02f..7db3156ca2e0 100644 --- a/packages/astro/test/fixtures/content-layer/src/pages/collections.json.js +++ b/packages/astro/test/fixtures/content-layer/src/pages/collections.json.js @@ -16,6 +16,8 @@ export async function GET() { const increment = await getEntry('increment', 'value'); + const images = await getCollection('images'); + return new Response( devalue.stringify({ customLoader, @@ -25,6 +27,7 @@ export async function GET() { entryWithReference, referencedEntry, increment, + images }) ); }