// @ts-check import { fileURLToPath, URL } from "node:url"; import { extname, relative, resolve, join } from "node:path"; import fs from "node:fs/promises"; import { existsSync } from "node:fs"; import { getSrcPath } from "./getSrcPath.js"; import getResolvedSrc from "./getResolvedSrc.js"; import { cwd, sharp } from "../../utils/runtimeChecks.js"; import throwErrorIfUnsupported from "./throwErrorIfUnsupported.js"; const { getImageDetails } = await (sharp ? import("./imagetools.js") : import("./codecs.js")); export default async function getProcessedImage( src, transformConfigs, { skipCache = false } = {} ) { const isRemote = src.startsWith("http"); const ext = isRemote ? extname(new URL(src).pathname).slice(1) : extname(src).slice(1); throwErrorIfUnsupported(src, ext); let base; if (src.match("(http://|https://|data:image/).*")) { ({ src, base } = await getResolvedSrc(src)); } else { const { default: { isSsrBuild }, } = await import("../../astroViteConfigs.js"); if (isSsrBuild) { const filename = fileURLToPath(import.meta.url); const assetPath = resolve(filename, "../../client") + src; src = "/" + relative(cwd, assetPath); } } const { w, h, ar, width = w, height = h, aspect = ar, ...rest } = transformConfigs; let path = src.replace(/\\/g, `/`); // @todo : remove this let imagePath = isRemote ? join(cwd, path) : await getSrcPath(src); if(!existsSync(imagePath)) { console.log("getProcessedImage::imagePath does not exist", imagePath); return { path, base, rest, }; } const imageBuffer = await fs.readFile(imagePath); const { image, imageWidth, imageHeight, imageFormat } = await getImageDetails(imageBuffer, width, height, aspect); return { path, base, rest, image, imageWidth, imageHeight, imageFormat, }; }