Skip to content

Commit 6849e38

Browse files
authored
fix(assets): support images outside of the project in dev (#14982)
* fix(assets): support images outside of the project in dev * chore: changeset
1 parent 02c19eb commit 6849e38

File tree

3 files changed

+22
-8
lines changed

3 files changed

+22
-8
lines changed

.changeset/every-birds-relax.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
Fixes images outside the project directory not working when using astro:assets in development mode

packages/astro/src/assets/endpoint/dev.ts

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,27 @@
11
// @ts-expect-error
22
import { root } from 'astro:config/server';
33
import { readFile } from 'node:fs/promises';
4-
import os from 'node:os';
54
import { fileURLToPath } from 'node:url';
65
import { isParentDirectory } from '@astrojs/internal-helpers/path';
76
import type { APIRoute } from '../../types/public/common.js';
87
import { handleImageRequest, loadRemoteImage } from './shared.js';
98

10-
function replaceFileSystemReferences(src: string) {
11-
return os.platform().includes('win32') ? src.replace(/^\/@fs\//, '') : src.replace(/^\/@fs/, '');
12-
}
13-
149
async function loadLocalImage(src: string, url: URL) {
15-
// Vite uses /@fs/ to denote filesystem access
10+
// Vite uses /@fs/ to denote filesystem access, we can fetch those files directly
1611
if (src.startsWith('/@fs/')) {
17-
src = replaceFileSystemReferences(src);
18-
if (!isParentDirectory(fileURLToPath(root), src)) {
12+
try {
13+
const res = await fetch(new URL(src, url));
14+
15+
if (!res.ok) {
16+
return undefined;
17+
}
18+
19+
return Buffer.from(await res.arrayBuffer());
20+
} catch {
1921
return undefined;
2022
}
2123
}
24+
2225
// Vite allows loading files directly from the filesystem
2326
// as long as they are inside the project root.
2427
if (isParentDirectory(fileURLToPath(root), src)) {

packages/astro/test/core-image.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,12 @@ describe('astro:image', () => {
164164
}),
165165
true,
166166
);
167+
168+
// Verify that the images can be fetched successfully
169+
for (const img of $img.toArray()) {
170+
const imgRes = await fixture.fetch(img.attribs['src']);
171+
assert.equal(imgRes.status, 200);
172+
}
167173
});
168174

169175
it('supports inlined imports', async () => {

0 commit comments

Comments
 (0)