import { defineConfig } from "vite"; import { sveltekit } from "@sveltejs/kit/vite"; import process from "node:process"; import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; // The installer build sets RUNESTONE_VERSION. It writes package.json only after the build completes. const packageVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version; const appVersion = process.env.RUNESTONE_VERSION || packageVersion; const host = process.env.TAURI_DEV_HOST; const monacoCss = `${process.cwd().replaceAll("\\", "/")}/node_modules/monaco-editor/min/vs/editor/editor.main.css`; /** * CSP mode for the smoke tests (`RUNESTONE_CSP=1`, or `pnpm smoke --csp`). * The dev server sends the policy of `src-tauri/tauri.conf.json` with each HTML page, as the installed app does. * It adds only what the dev server needs: * - script-src: the SHA-256 hash of each inline script in the page. Tauri adds the same hashes to the installed app. * - connect-src: the Vite HMR WebSocket on the address of the page. */ /** @returns {import("vite").Plugin} */ function contentSecurityPolicy() { const config = JSON.parse(readFileSync(new URL("./src-tauri/tauri.conf.json", import.meta.url), "utf8")); /** @type {Record} */ const policy = config.app.security.csp; /** @param {string} html @param {string | undefined} address */ const policyFor = (html, address) => { const directives = { ...policy }; const hashes = [...html.matchAll(/]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)] .map(([, code]) => `'sha256-${createHash("sha256").update(code).digest("base64")}'`); directives["script-src"] = [directives["script-src"], ...hashes].join(" "); directives["connect-src"] = `${directives["connect-src"]} ws://${address}`; return Object.entries(directives).map(([name, sources]) => `${name} ${sources}`).join("; "); }; return { name: "runestone-csp", configureServer(server) { // Buffer each HTML response, then send it with the policy header. Other responses pass unchanged, // because Tauri sends the policy only with HTML pages. server.middlewares.use((request, original, next) => { if (request.method !== "GET" || !request.headers.accept?.includes("text/html")) return next(); /** @type {any} The response methods have overloads. The replacements accept all their forms. */ const response = original; /** @type {Buffer[]} */ const chunks = []; const send = { writeHead: response.writeHead.bind(response), end: response.end.bind(response) }; /** @type {any[] | undefined} */ let head; /** @param {unknown} chunk @param {unknown} encoding */ const add = (chunk, encoding) => { if (typeof chunk === "string") chunks.push(Buffer.from(chunk, /** @type {BufferEncoding} */ (typeof encoding === "string" ? encoding : "utf8"))); else if (chunk instanceof Uint8Array) chunks.push(Buffer.from(chunk)); }; /** @param {any[]} args */ response.writeHead = (...args) => { head = args; return response; }; /** @param {unknown} chunk @param {unknown} encoding @param {unknown} callback */ response.write = (chunk, encoding, callback) => { add(chunk, encoding); const done = typeof encoding === "function" ? encoding : callback; if (typeof done === "function") done(); return true; }; /** @param {unknown} chunk @param {unknown} encoding @param {unknown} callback */ response.end = (chunk, encoding, callback) => { add(chunk, encoding); const body = Buffer.concat(chunks); /** @type {Record} */ const headers = head?.find(item => item && typeof item === "object") ?? {}; const type = String(Object.entries(headers).find(([name]) => name.toLowerCase() === "content-type")?.[1] ?? response.getHeader("content-type") ?? ""); if (type.includes("text/html")) response.setHeader("Content-Security-Policy", policyFor(body.toString("utf8"), request.headers.host)); if (head) send.writeHead(...head); return send.end(body, [chunk, encoding, callback].find(item => typeof item === "function")); }; next(); }); }, }; } // https://vite.dev/config/ export default defineConfig(() => ({ plugins: [...(process.env.RUNESTONE_CSP === "1" ? [contentSecurityPolicy()] : []), sveltekit()], define: { __RUNESTONE_VERSION__: JSON.stringify(appVersion), }, resolve: { alias: { "monaco-editor-css": monacoCss, }, }, optimizeDeps: { include: ["monaco-editor"], }, worker: { format: /** @type {"es"} */ ("es"), }, // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build` // // 1. prevent Vite from obscuring rust errors clearScreen: false, // 2. tauri expects a fixed port, fail if that port is not available server: { port: 1420, strictPort: true, host: host || "127.0.0.1", hmr: host ? { protocol: "ws", host, port: 1421, } : undefined, watch: { // 3. tell Vite to ignore watching `src-tauri` ignored: ["**/src-tauri/**", "**/fixtures/**", "**/.runestone/**", "**/.audit/**", "**/output/**", "**/browser-runtime/dist/**", "**/browser-runtime/output/**"], }, }, }));