|
1 | | -import type { ImagePath } from '../types' |
| 1 | +import { existsSync } from 'node:fs' |
| 2 | +import { join } from 'node:path' |
| 3 | + |
| 4 | +import type { GlobMap, ImagePath, ImportModule, ResolvedImage } from '../types' |
| 5 | + |
| 6 | +import { PREFIX } from '../constants' |
| 7 | + |
| 8 | +const PUBLIC_DIR = join(process.cwd(), 'public') |
| 9 | + |
| 10 | +const globFilesInSrc: GlobMap = ({ ...import.meta.glob('/src/**/*.{png,jpg,jpeg,svg}') } as unknown) as GlobMap |
| 11 | + |
| 12 | +function warnFiles(filePath: string | undefined) { |
| 13 | + if (!filePath) return |
| 14 | + |
| 15 | + const lowerPath = filePath.toLowerCase() |
| 16 | + |
| 17 | + if (lowerPath.includes(`${join('/', 'public')}`) || lowerPath.includes('/public/') || filePath.startsWith(PUBLIC_DIR)) { |
| 18 | + console.warn( |
| 19 | + `${PREFIX} Warning: image resolved from /public. Images should not be placed in /public — move them to /src so Astro can process them correctly.` |
| 20 | + ) |
| 21 | + } |
| 22 | + |
| 23 | + if (lowerPath.endsWith('.webp') || lowerPath.endsWith('.avif')) { |
| 24 | + const extension = lowerPath.endsWith('.webp') ? 'webp' : 'avif' |
| 25 | + console.warn( |
| 26 | + `${PREFIX} Warning: image is in ${extension} format. These formats are usually already optimized; using this component to re-process them may degrade quality.` |
| 27 | + ) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +function isObject(v: unknown): v is Record<string, unknown> { |
| 32 | + return typeof v === 'object' && v !== null |
| 33 | +} |
| 34 | + |
| 35 | +function isPromise(v: unknown): v is Promise<unknown> { |
| 36 | + if (!isObject(v)) return false |
| 37 | + const promise = v as { then?: unknown } |
| 38 | + return typeof promise.then === 'function' |
| 39 | +} |
| 40 | + |
| 41 | +function hasSrc(v: unknown): v is ResolvedImage { |
| 42 | + return isObject(v) && typeof (v as Record<string, unknown>)['src'] === 'string' |
| 43 | +} |
| 44 | + |
| 45 | +function isRemoteUrl(v: string) { |
| 46 | + return /^https?:\/\//.test(v) |
| 47 | +} |
| 48 | + |
| 49 | +function findGlobMatch(keys: string[], path: string) { |
| 50 | + const candidates = [path.replace(/^\//, ''), `/${path.replace(/^\//, '')}`] |
| 51 | + const match = keys.find((k) => candidates.includes(k) || k.endsWith(path) || k.endsWith(path.replace(/^\//, ''))) |
| 52 | + if (match) return match |
| 53 | + |
| 54 | + const fileName = path.split('/').pop() |
| 55 | + if (!fileName) return null |
| 56 | + |
| 57 | + return keys.find((k) => k.endsWith(`/${fileName}`) || k.endsWith(fileName)) ?? null |
| 58 | +} |
2 | 59 |
|
3 | 60 | export async function resolveImagePath(path: ImagePath) { |
4 | | - // If it's a string, we can't resolve it here. ex: Remote images URLs |
5 | | - if (typeof path === 'string') return null |
6 | | - // Handle dynamic imports |
7 | | - if ('then' in path && typeof path.then === 'function') return (await path).default |
8 | | - if ('src' in path) return path |
| 61 | + if (path == null) return null |
| 62 | + |
| 63 | + // validate dynamic import (Promise-like) |
| 64 | + if (isPromise(path)) { |
| 65 | + const mod = (await (path as Promise<ImportModule>)) as ImportModule |
| 66 | + const resolved = (mod.default ?? mod) as unknown |
| 67 | + if (hasSrc(resolved)) { |
| 68 | + warnFiles(resolved.src) |
| 69 | + return resolved |
| 70 | + } |
| 71 | + if (typeof resolved === 'string') { |
| 72 | + warnFiles(resolved) |
| 73 | + return resolved |
| 74 | + } |
| 75 | + return null |
| 76 | + } |
| 77 | + |
| 78 | + // validate already-resolved object (import result or { src: ... }) |
| 79 | + if (isObject(path)) { |
| 80 | + const obj = path as Record<string, unknown> |
| 81 | + const objSrc = typeof obj['src'] === 'string' ? (obj['src'] as string) : undefined |
| 82 | + warnFiles(objSrc) |
| 83 | + return hasSrc(obj) ? (obj as ResolvedImage) : null |
| 84 | + } |
| 85 | + |
| 86 | + // validate string path |
| 87 | + if (typeof path === 'string') { |
| 88 | + if (isRemoteUrl(path)) return path |
| 89 | + |
| 90 | + const keys = Object.keys(globFilesInSrc) |
| 91 | + const matchKey = findGlobMatch(keys, path) |
| 92 | + |
| 93 | + if (matchKey) { |
| 94 | + try { |
| 95 | + const mod = await globFilesInSrc[matchKey]() |
| 96 | + const resolved = (mod.default ?? mod) as unknown |
| 97 | + |
| 98 | + if (hasSrc(resolved)) { |
| 99 | + warnFiles((resolved as ResolvedImage).src) |
| 100 | + return resolved as ResolvedImage |
| 101 | + } |
| 102 | + |
| 103 | + if (typeof resolved === 'string') { |
| 104 | + warnFiles(resolved) |
| 105 | + return resolved |
| 106 | + } |
| 107 | + } catch (err) { |
| 108 | + console.log(`${PREFIX} resolveImagePath: failed to import glob match "${matchKey}" — falling back to filesystem.`, err) |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + // If module doesn't expose a usable value, fall through to filesystem check |
| 113 | + try { |
| 114 | + const absCandidate = path.startsWith('/') ? join(process.cwd(), path) : join(process.cwd(), path) |
| 115 | + |
| 116 | + if (existsSync(absCandidate)) { |
| 117 | + warnFiles(absCandidate) |
| 118 | + return { src: `/@fs${absCandidate}` } |
| 119 | + } |
| 120 | + } catch (err) { |
| 121 | + console.debug(`${PREFIX} resolveImagePath: filesystem check failed for "${path}".`, err) |
| 122 | + } |
| 123 | + |
| 124 | + return null |
| 125 | + } |
| 126 | + |
9 | 127 | return null |
10 | 128 | } |
0 commit comments