import { defineConfig } from 'astro/config'; import legacy from '@vitejs/plugin-legacy'; import fs from 'fs'; import path from 'path'; const replacementsPath = new URL('./build-config.json', import.meta.url); const replacements = JSON.parse(fs.readFileSync(replacementsPath, 'utf-8')); function patchCode(code) { let updatedCode = code; for (const [search, replace] of Object.entries(replacements)) { updatedCode = updatedCode.replaceAll(search, replace); } return updatedCode; } //helper function findFileGlobally(dir, filename) { const files = fs.readdirSync(dir); for (const file of files) { const fullPath = path.join(dir, file); if (fs.statSync(fullPath).isDirectory()) { const found = findFileGlobally(fullPath, filename); if (found) return found; } else if (file === filename) { return fullPath; } } return null; } export default defineConfig({ build: { format: 'file' }, integrations: [ { name: 'astro-dev-url-patcher', hooks: { 'astro:server:setup': ({ server }) => { server.middlewares.use((req, res, next) => { if (req.url) { const urlPathname = req.url.split('?')[0]; if (urlPathname.endsWith('.js')) { const filename = path.basename(urlPathname); const publicDir = path.join(process.cwd(), 'public'); let filePath = path.join(publicDir, urlPathname); if (!fs.existsSync(filePath)) { filePath = findFileGlobally(publicDir, filename); } if (filePath && fs.existsSync(filePath)) { const rawCode = fs.readFileSync(filePath, 'utf-8'); const patchedCode = patchCode(rawCode); res.setHeader('Content-Type', 'application/javascript'); res.end(patchedCode); return; } } } next(); }); } } } ], vite: { plugins: [ { name: 'vite-plugin-url-patcher', // bs, dont touch pls transform(code, id) { if (id.endsWith('.js') || id.endsWith('.ts') || id.includes('lang.js')) { return { code: patchCode(code), map: null }; } } }, legacy({ targets: ['ie >= 11', 'chrome >= 30', 'safari >= 7'], polyfills: ['es.promise', 'es.object.assign'] }) ] } });