返回 DeepSeek-Reasonix
vite.config.ts
根目录 / desktop / frontend / vite.config.ts
1 import { createRequire } from "node:module";
2 import { defineConfig, searchForWorkspaceRoot, type Plugin } from "vite";
3 import react from "@vitejs/plugin-react";
4 import { execSync } from "node:child_process";
5 import { access, mkdir, readdir, rename, writeFile } from "node:fs/promises";
6 import { dirname, resolve } from "node:path";
7 import { fileURLToPath } from "node:url";
8 import { rewriteDragRegions, shellFromEnv } from "./scripts/shell-css.mjs";
9
10 const devPort = Number(process.env.REASONIX_DESKTOP_VITE_PORT || "5173");
11 const configDir = dirname(fileURLToPath(import.meta.url));
12
13 // Stamps the build commit into the bundle so a minified crash stack can be mapped
14 // back to the sourcemap of the exact build. Falls back to "dev" off a git checkout.
15 function buildCommit(): string {
16 if (process.env.REASONIX_COMMIT) return process.env.REASONIX_COMMIT;
17 try {
18 return execSync("git rev-parse --short HEAD", { cwd: configDir }).toString().trim();
19 } catch {
20 return "dev";
21 }
22 }
23
24 function buildChannel(): string {
25 return process.env.REASONIX_CHANNEL || "stable";
26 }
27
28 // A crossorigin module/stylesheet fetched over a custom app scheme is CORS-blocked
29 // when the protocol handler sends no Access-Control-Allow-Origin, so the bundle
30 // never loads and the window paints blank; plain HTTP origins tolerate it.
31 function stripCrossorigin(): Plugin {
32 return {
33 name: "strip-crossorigin",
34 enforce: "post",
35 transformIndexHtml: (html) => html.replace(/\s+crossorigin(?==["']|[\s/>])/g, ""),
36 };
37 }
38
39 function archiveHiddenSourcemaps(commit: string): Plugin {
40 async function collectMapFiles(dir: string): Promise<string[]> {
41 const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
42 const files: string[] = [];
43 for (const entry of entries) {
44 const p = resolve(dir, entry.name);
45 if (entry.isDirectory()) files.push(...(await collectMapFiles(p)));
46 else if (entry.isFile() && entry.name.endsWith(".map")) files.push(p);
47 }
48 return files;
49 }
50
51 return {
52 name: "archive-hidden-sourcemaps",
53 apply: "build",
54 closeBundle: async () => {
55 const distDir = resolve(configDir, "dist");
56 const maps = await collectMapFiles(distDir);
57 if (!maps.length) return;
58
59 const archiveDir = resolve(configDir, "sourcemaps", commit);
60 await mkdir(archiveDir, { recursive: true });
61 const records = await Promise.all(maps.map(async (mapPath) => {
62 const map = mapPath.slice(distDir.length + 1).replaceAll("\\", "/");
63 return {
64 source: mapPath,
65 archive: map.replaceAll("/", "__"),
66 map,
67 bundle: map.slice(0, -4),
68 bundleExists: await access(mapPath.slice(0, -4)).then(() => true, () => false),
69 };
70 }));
71 await Promise.all(
72 records.map(async (record) => {
73 await rename(record.source, resolve(archiveDir, record.archive));
74 }),
75 );
76 const manifestRecord = ({ archive, map, bundle }: (typeof records)[number]) => ({ archive, map, bundle });
77 await writeFile(
78 resolve(archiveDir, "manifest.json"),
79 JSON.stringify({
80 schemaVersion: 1,
81 commit,
82 channel: buildChannel(),
83 archivedAt: new Date().toISOString(),
84 maps: records.filter((record) => record.bundleExists).map(manifestRecord),
85 orphanMaps: records.filter((record) => !record.bundleExists).map(manifestRecord),
86 }, null, 2) + "\n",
87 );
88 },
89 };
90 }
91
92 // One stylesheet serves the browser and the Electron shell: the Electron build
93 // rewrites the drag-region marker property to -webkit-app-region at bundle time
94 // (scripts/shell-css.mjs), so the browser bundle stays byte-identical and no rule
95 // is declared twice.
96 function shellDragRegions(): Plugin {
97 const shell = shellFromEnv();
98 return {
99 name: "shell-drag-regions",
100 apply: "build",
101 enforce: "post",
102 generateBundle(_options, bundle) {
103 if (shell !== "electron") return;
104 for (const asset of Object.values(bundle)) {
105 if (asset.type === "asset" && asset.fileName.endsWith(".css") && typeof asset.source === "string") {
106 asset.source = rewriteDragRegions(asset.source, shell);
107 }
108 }
109 },
110 };
111 }
112
113 // Vite must empty dist before production builds so stale hashed assets disappear.
114 // Recreate the tracked placeholder afterwards so git status stays clean and
115 // Go's //go:embed all:frontend/dist still works on a fresh checkout.
116 function keepDistPlaceholder(): Plugin {
117 return {
118 name: "keep-dist-placeholder",
119 apply: "build",
120 closeBundle: async () => {
121 const distDir = resolve(configDir, "dist");
122 await mkdir(distDir, { recursive: true });
123 await writeFile(resolve(distDir, ".gitkeep"), "\n");
124 },
125 };
126 }
127
128 const commit = buildCommit();
129 const channel = buildChannel();
130
131 const nodeModulePath = String.raw`[\\/]node_modules[\\/](?:\.pnpm[\\/][^\\/]+[\\/]node_modules[\\/])?`;
132 const vendorReact = new RegExp(`${nodeModulePath}(?:react|react-dom)(?:[\\/]|$)`);
133 const vendorMarkdown = new RegExp(
134 `${nodeModulePath}(?:react-markdown|remark-gfm|remark-math|remark-parse|remark-rehype|rehype-katex|katex|unified|vfile|hast-util-to-jsx-runtime|html-url-attributes)(?:[\\/]|$)`,
135 );
136 const vendorHighlight = new RegExp(`${nodeModulePath}highlight\\.js(?:[\\/]|$)`);
137
138 // base: "./" so built asset URLs are relative: the shell serves dist from the app
139 // root over its custom scheme, where absolute "/assets/..." URLs 404.
140 export default defineConfig({
141 // errorRecovery tells lightningcss to skip unparseable rules instead of
142 // failing the whole build. Vite 8 + lightningcss 1.32.0 can reject valid
143 // @keyframes in concatenated CSS bundles (heartbeat.css + styles.css).
144 css: {
145 lightningcss: { errorRecovery: true },
146 },
147 plugins: [react(), stripCrossorigin(), shellDragRegions(), archiveHiddenSourcemaps(commit), keepDistPlaceholder()],
148 base: "./",
149 define: { __BUILD_COMMIT__: JSON.stringify(commit), __BUILD_CHANNEL__: JSON.stringify(channel) },
150 resolve: {
151 alias: {
152 // decode-named-character-reference (micromark/remark dependency) ships a
153 // browser condition (index.dom.js) that calls document.createElement at
154 // module scope. That explodes inside markdown.worker.ts (WorkerGlobalScope
155 // has no document), killing the off-main-thread parse on first use. The
156 // default entry is DOM-free and works in both window and worker, so pin
157 // it for every bundle. The package is a direct devDependency so this
158 // resolve works under pnpm's non-hoisted layout.
159 "decode-named-character-reference": createRequire(import.meta.url).resolve("decode-named-character-reference"),
160 // hast-util-from-html-isomorphic (rehype-katex dependency) has the same
161 // shape: its browser entry constructs a DOMParser at module scope, which
162 // WorkerGlobalScope lacks. Pin the isomorphic default (parse5) entry.
163 "hast-util-from-html-isomorphic": createRequire(import.meta.url).resolve("hast-util-from-html-isomorphic"),
164 },
165 },
166 build: {
167 outDir: "dist",
168 emptyOutDir: true,
169 sourcemap: "hidden",
170 target: "es2021",
171 // Use terser for smaller output (esbuild is faster to build but produces
172 // larger bundles). Disabled for dev builds via the default.
173 minify: "terser",
174 terserOptions: {
175 compress: {
176 // Keep warn/error so crash breadcrumbs still capture them; drop the noise.
177 drop_console: ["log", "debug", "info", "trace"],
178 passes: 2,
179 },
180 // Preserve names so minified crash stacks stay readable.
181 keep_classnames: true,
182 keep_fnames: true,
183 },
184 rolldownOptions: {
185 output: {
186 // Manual chunk splitting: keep the heavy markdown/math/code pipeline
187 // in a separate chunk so it can be cached independently from the
188 // app shell. The vendor chunk splits react+react-dom (stable, rarely
189 // changes) from the markdown stack (changes more often).
190 codeSplitting: {
191 groups: [
192 { name: "vendor-react", test: vendorReact },
193 { name: "vendor-markdown", test: vendorMarkdown },
194 { name: "vendor-highlight", test: vendorHighlight },
195 ],
196 },
197 },
198 },
199 // Raise the warning limit — the markdown vendor chunk is legitimately large
200 // (katex alone is ~300KB). The manual split ensures it's cached separately.
201 chunkSizeWarningLimit: 600,
202 },
203 server: {
204 // Bind IPv4 — unset host listens on ::1, which fails for clients on Windows
205 // hosts where IPv6 loopback is filtered.
206 host: "127.0.0.1",
207 port: devPort,
208 strictPort: true,
209 fs: {
210 // Browser-dev theme mocks use the same embedded source assets as the
211 // desktop build. Keep the allow-list narrow while retaining Vite's
212 // workspace root.
213 allow: [searchForWorkspaceRoot(configDir), resolve(configDir, "../themes/official")],
214 },
215 },
216 });
217
217 lines TYPESCRIPT