// @ts-check import fs from "node:fs" import { fileURLToPath } from "node:url" import { posix as path, resolve } from "node:path" import { saveAndCopyAsset } from "./utils/saveAndCopyAsset.js" import vitePluginAstroImageTools, { store } from "../plugin/index.js" import pMap from "p-map" import { DEFAULT_IO_DELAY } from "../constants.js" const filename = fileURLToPath(import.meta.url); const astroViteConfigsPath = resolve(filename, "../../astroViteConfigs.js"); export default { name: "imagetools", hooks: { "astro:config:setup": async function ({ config, command, updateConfig }) { const environment = command; const isSsrBuild = command === "build" && !!config.adapter && config.output === "server"; let projectBase = path.normalize(config.base); if (projectBase.startsWith("./")) projectBase = projectBase.slice(1); if (!projectBase.startsWith("/")) projectBase = "/" + projectBase; if (projectBase.endsWith("/")) projectBase = projectBase.slice(0, -1); const astroViteConfigs = { environment, isSsrBuild, projectBase, publicDir: fileURLToPath(config.publicDir.href), rootDir: fileURLToPath(config.root.href), }; await fs.promises.writeFile( astroViteConfigsPath, `export default ${JSON.stringify(astroViteConfigs)}` ); updateConfig({ vite: { plugins: [vitePluginAstroImageTools], }, }); }, "astro:build:done": async function closeBundle() { const { default: astroViteConfigs } = await import( // @ts-ignore "../astroViteConfigs.js" ); const { mode, outDir, assetsDir, isSsrBuild } = astroViteConfigs; if (mode === "production") { const allEntries = [...store.entries()]; const assetPaths = allEntries.filter( ([, { hash = null } = {}]) => hash ); await pMap( assetPaths, async ([assetPath, { hash, image, buffer }]) => { // delay, otherwise unknown errors occur (sharp/vips) await new Promise((resolve) => setTimeout(resolve, DEFAULT_IO_DELAY)); try { await saveAndCopyAsset( hash, image, buffer, outDir, assetsDir, assetPath, isSsrBuild ); } catch (error) { console.error(error) } console.log(`Image processed: ${assetPath}`) }, // higher concurrency causes sharp/vips errors as well { concurrency: 1 } ); } }, }, };