import { defineConfig, type HtmlTagDescriptor, type Plugin } from 'vite' import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { readFileSync } from 'node:fs' import siteConfiguration from './site.json' import { THEME_DEFAULTS } from './server/src/themeDefaults.js' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ react(), tailwindcss(), siteConfigurationPlugin(siteConfiguration), themeDefaultsCheck(), ], server: { proxy: { "/api": { target: "http://127.0.0.1:3001", changeOrigin: false, xfwd: true, }, // Uploaded images. nginx serves these in production; in dev // the API does, so they go to the same place as /api. "/uploads": { target: "http://127.0.0.1:3001", changeOrigin: false, }, }, }, build: { // Source maps are written for debugging a production error, but // not linked from the bundle, so the site doesn't publish its // source to every visitor's devtools. sourcemap: 'hidden', }, }) type SiteConfiguration = { title?: string /** The live site's origin, eg. https://nextgenerationofunity.org. */ url?: string description?: string language?: string robots?: { index?: boolean } icons?: { icon?: string } openGraph?: { image?: string } analytics?: { googleAnalyticsId?: string } customScripts?: { headStart?: string headEnd?: string bodyStart?: string bodyEnd?: string } accessibility?: { addBypassLinks?: boolean } } /** Applies /site.json to the generated document shell. */ function siteConfigurationPlugin(config: SiteConfiguration): Plugin { function sanitizeHtmlValue(value: string | undefined): string { return value?.replace(/[^a-zA-Z0-9_-]/g, '') || '' } function escapeHtmlText(value: string): string { return value.replace(/&/g, '&').replace(//g, '>') } function replaceHtmlCommentSlot(html: string, slotName: string, content: string): string { return html.replace(``, content) } const title = config.title ?? 'App' const description = config.description ?? '' const favicon = config.icons?.icon ?? '' const socialImage = config.openGraph?.image ?? '' const language = sanitizeHtmlValue(config.language) || 'en' const googleAnalyticsId = sanitizeHtmlValue(config.analytics?.googleAnalyticsId) const headStart = config.customScripts?.headStart ?? '' const headEnd = config.customScripts?.headEnd ?? '' const bodyStart = config.customScripts?.bodyStart ?? '' const bodyEnd = config.customScripts?.bodyEnd ?? '' // Blocked: nothing may be crawled. Allowed: everything but the // admin and the API, with the sitemap the API serves. const robotsTxt = config.robots?.index === false ? 'User-agent: *\nDisallow: /\n' : 'User-agent: *\nDisallow: /admin\nDisallow: /api\n' + (config.url ? `\nSitemap: ${config.url.replace(/\/$/, '')}/sitemap.xml\n` : '') return { name: 'site-configuration', configureServer(server) { server.middlewares.use((req, res, next) => { if (!robotsTxt || req.url?.split('?')[0] !== '/robots.txt') return next() res.setHeader('Content-Type', 'text/plain; charset=utf-8') res.end(robotsTxt) }) }, generateBundle() { if (!robotsTxt) return this.emitFile({ type: 'asset', fileName: 'robots.txt', source: robotsTxt, }) }, transformIndexHtml: { order: 'pre', handler(html) { let result = html result = replaceHtmlCommentSlot(result, 'site:lang', language) result = replaceHtmlCommentSlot(result, 'site:title', escapeHtmlText(title)) result = replaceHtmlCommentSlot(result, 'site:head-start', headStart) result = replaceHtmlCommentSlot(result, 'site:head-end', headEnd) result = replaceHtmlCommentSlot(result, 'site:body-start', bodyStart) result = replaceHtmlCommentSlot(result, 'site:body-end', bodyEnd) const tags: HtmlTagDescriptor[] = [] if (description) { tags.push({ tag: 'meta', attrs: { name: 'description', content: description }, injectTo: 'head' }) } if (config.robots?.index === false) { tags.push({ tag: 'meta', attrs: { name: 'robots', content: 'noindex, nofollow' }, injectTo: 'head' }) } if (favicon) { tags.push({ tag: 'link', attrs: { rel: 'icon', href: favicon }, injectTo: 'head' }) } if (title) { tags.push({ tag: 'meta', attrs: { property: 'og:title', content: title }, injectTo: 'head' }) } if (description) { tags.push({ tag: 'meta', attrs: { property: 'og:description', content: description }, injectTo: 'head' }) } if (socialImage) { tags.push( { tag: 'meta', attrs: { property: 'og:image', content: socialImage }, injectTo: 'head' }, { tag: 'meta', attrs: { name: 'twitter:card', content: 'summary_large_image' }, injectTo: 'head' }, { tag: 'meta', attrs: { name: 'twitter:image', content: socialImage }, injectTo: 'head' }, ) } if (googleAnalyticsId) { tags.push( { tag: 'script', attrs: { async: true, src: `https://www.googletagmanager.com/gtag/js?id=${googleAnalyticsId}`, }, injectTo: 'head', }, { tag: 'script', children: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', ${JSON.stringify(googleAnalyticsId)}); `, injectTo: 'head', }, ) } if (config.accessibility?.addBypassLinks) { tags.push( { tag: 'style', children: ` .bypass-link { position: fixed; top: 8px; left: 8px; z-index: 2147483647; transform: translateY(-150%); border-radius: 6px; background: #111827; color: #fff; padding: 8px 12px; font: 600 14px/1.2 system-ui, sans-serif; text-decoration: none; } .bypass-link:focus { transform: translateY(0); } `, injectTo: 'head', }, { tag: 'a', attrs: { class: 'bypass-link', href: '#root' }, children: 'Skip to content', injectTo: 'body-prepend', }, ) } return { html: result, tags } }, }, } } /* The colour tokens exist twice: as data in server/src/themeDefaults.js (the admin's defaults, the contrast check) and as CSS in src/index.css (what pages draw with). This stops the build, and the dev server, when the two disagree, naming each difference. */ function themeDefaultsCheck(): Plugin { const read = (css: string, block: RegExp) => { const body = block.exec(css)?.[1] ?? '' return Object.fromEntries( [...body.matchAll(/--color-([a-z-]+):\s*(#[0-9a-f]{6})/gi)].map((m) => [m[1], m[2].toLowerCase()]), ) } return { name: 'theme-defaults-check', buildStart() { const css = readFileSync('src/index.css', 'utf8') const light = read(css, /@theme\s*\{([\s\S]*?)\n\}/) const dark = read(css, /:root\[data-theme="dark"\]\s*\{([\s\S]*?)\}/) const problems: string[] = [] for (const [token, [lightHex, darkHex]] of Object.entries(THEME_DEFAULTS) as [string, string[]][]) { if (light[token] !== lightHex.toLowerCase()) problems.push(`--color-${token} light: index.css ${light[token] ?? 'missing'}, themeDefaults.js ${lightHex}`) // A token index.css doesn't redefine for dark keeps its light value. const cssDark = dark[token] ?? light[token] if (cssDark !== darkHex.toLowerCase()) problems.push(`--color-${token} dark: index.css ${cssDark ?? 'missing'}, themeDefaults.js ${darkHex}`) } if (problems.length) { this.error( `Colour tokens disagree between src/index.css and server/src/themeDefaults.js:\n ${problems.join('\n ')}`, ) } }, } }