import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { defineConfig, type Plugin } from 'vite'; import react from '@vitejs/plugin-react'; /** Emits dist/sw.js with a build id, so a deploy that changes files installs a new worker (docs/07 ยง11). */ function serviceWorker(): Plugin { return { name: 'bg-service-worker', apply: 'build', generateBundle(_, bundle) { const src = readFileSync(new URL('./sw.js', import.meta.url), 'utf8'); const offline = readFileSync(new URL('./public/offline.html', import.meta.url), 'utf8'); const files = Object.keys(bundle).sort().join('\n'); const build = createHash('sha256').update(src).update(offline).update(files).digest('hex').slice(0, 12); if (!src.includes("'__BUILD__'")) throw new Error('sw.js: VERSION placeholder missing'); this.emitFile({ type: 'asset', fileName: 'sw.js', source: src.replace("'__BUILD__'", `'${build}'`) }); }, }; } export default defineConfig({ plugins: [react(), serviceWorker()], server: { port: 5173, proxy: { '/api': 'http://localhost:3000', '/healthz': 'http://localhost:3000', '/ws': { target: 'ws://localhost:3000', ws: true }, }, }, build: { target: 'es2022', cssCodeSplit: true, sourcemap: false, }, });