11// @ts -expect-error
2- import { outDir } from 'astro:assets' ;
2+ import { outDir , serverDir } from 'astro:assets' ;
33import { readFile } from 'node:fs/promises' ;
4+ import path from 'node:path' ;
45import { fileURLToPath } from 'node:url' ;
56import { isParentDirectory } from '@astrojs/internal-helpers/path' ;
67import type { APIRoute } from '../../types/public/common.js' ;
78import { handleImageRequest } from './shared.js' ;
89
910async function loadLocalImage ( src : string , url : URL ) {
11+ const outDirURL = resolveOutDir ( ) ;
1012 // If the _image segment isn't at the start of the path, we have a base
1113 const idx = url . pathname . indexOf ( '/_image' ) ;
1214 if ( idx > 0 ) {
1315 // Remove the base path
1416 src = src . slice ( idx ) ;
1517 }
16- if ( ! URL . canParse ( '.' + src , outDir ) ) {
18+ if ( ! URL . canParse ( '.' + src , outDirURL ) ) {
1719 return undefined ;
1820 }
19- const fileUrl = new URL ( '.' + src , outDir ) ;
21+ const fileUrl = new URL ( '.' + src , outDirURL ) ;
2022 if ( fileUrl . protocol !== 'file:' ) {
2123 return undefined ;
2224 }
23- if ( ! isParentDirectory ( fileURLToPath ( outDir ) , fileURLToPath ( fileUrl ) ) ) {
25+ if ( ! isParentDirectory ( fileURLToPath ( outDirURL ) , fileURLToPath ( fileUrl ) ) ) {
2426 return undefined ;
2527 }
2628
@@ -44,3 +46,21 @@ export const GET: APIRoute = async ({ request }) => {
4446 } ) ;
4547 }
4648} ;
49+
50+ function resolveOutDir ( ) {
51+ const serverDirPath = fileURLToPath ( serverDir ) ;
52+ const rel = path . relative ( serverDirPath , fileURLToPath ( outDir ) ) ;
53+
54+ const serverFolder = path . basename ( serverDirPath ) ;
55+ let serverEntryFolderURL = path . dirname ( import . meta. url ) ;
56+ while ( ! serverEntryFolderURL . endsWith ( serverFolder ) ) {
57+ serverEntryFolderURL = path . dirname ( serverEntryFolderURL ) ;
58+ }
59+ const serverEntryURL = serverEntryFolderURL + '/entry.mjs' ;
60+ const outDirURL = new URL ( appendForwardSlash ( rel ) , serverEntryURL ) ;
61+ return outDirURL ;
62+ }
63+
64+ function appendForwardSlash ( pth : string ) {
65+ return pth . endsWith ( '/' ) ? pth : pth + '/' ;
66+ }
0 commit comments