Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

vite.config.ts

423 lines15.7 KB

1import * as NodeZlib from "node:zlib";
2​
3import react from "@vitejs/plugin-react";
4import { tanstackRouter } from "@tanstack/router-plugin/vite";
5import compression from "compression";
6import { playwright } from "vite-plus/test/browser-playwright";
7import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
8import "vite-plus/test/config";
9import { defineConfig, type Connect, type Plugin } from "vite-plus";
10import * as Hash from "effect/Hash";
11import pkg from "./package.json" with { type: "json" };
12import pdfjsPkg from "pdfjs-dist/package.json" with { type: "json" };
13​
14import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
15​
16import { loadRepoEnv } from "../../scripts/lib/public-config";
17import { resolveTaggedSourceVersion } from "../../scripts/lib/tagged-source-version";
18import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses";
19import { tailwindPlugins } from "./vite/tailwind";
20import { warmBundledDevPlugin } from "./vite/warmBundledDev";
21import { formatAppDisplayName, resolveWebAppStageLabel } from "./src/branding.logic";
22​
23const repoEnv = loadRepoEnv();
24Object.assign(process.env, repoEnv);
25​
26// Signal single-origin dev explicitly; loadRepoEnv can restore deleted URL keys from .env.
27const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
28​
29const port = Number(process.env.PORT ?? 5733);
30const explicitHost = process.env.HOST?.trim();
31const host = explicitHost || "localhost";
32const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
33const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
34const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
35const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
36const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
37const configuredClerkCliOAuthClientId = repoEnv.VITE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || "";
38const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() || "";
39const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";
40const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";
41const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
42const configuredReleaseChannel =
43 process.env.T3CODE_BUILT_DEV === "1" ? "dev" : process.env.VITE_RELEASE_CHANNEL?.trim() || "";
44const configuredDesktopUpdateRepository =
45 process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
46 process.env.GITHUB_REPOSITORY?.trim() ||
47 "";
48const configuredHostedAppUrl = (() => {
49 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
50 if (explicitHostedAppUrl) {
51 return explicitHostedAppUrl;
52 }
53 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
54 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
55 }
56 if (process.env.VERCEL_URL) {
57 return `https://${process.env.VERCEL_URL}`;
58 }
59 return undefined;
60})();
61const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
62​
63// `vp run dev --share --built` rebuilds on every change. The license manifest
64// is about 2 s of each build, and nothing in that mode reads it.
65const builtDev = process.env.T3CODE_BUILT_DEV === "1";
66​
67const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
68const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
69​
70// Bundled dev and `build --watch` pass Rolldown `exclude` but not Vite's default `ignored`, so
71// they watch node_modules. Those files are pnpm-store hardlinks shared by every worktree, so each
72// `vp i` or worktree removal elsewhere rebuilds every long-running server and leaks native memory.
73const rolldownWatchExclude = [/[\\/]node_modules[\\/]/];
74​
75const buildSourcemap: boolean | "hidden" =
76 sourcemapEnv === "0" || sourcemapEnv === "false"
77 ? false
78 : sourcemapEnv === "hidden"
79 ? "hidden"
80 : true;
81​
82const unitTestProject = {
83 extends: true,
84 test: {
85 name: "unit",
86 include: ["src/**/*.test.{ts,tsx}"],
87 exclude: ["src/**/*.browser.test.{ts,tsx}"],
88 hookTimeout: 15_000,
89 testTimeout: 15_000,
90 setupFiles: [
91 "../../packages/shared/src/testing/longTempDir.ts",
92 "../../packages/shared/src/testing/providerEnv.ts",
93 "../../packages/shared/src/testing/gitEnv.ts",
94 ],
95 },
96} satisfies TestProjectInlineConfiguration;
97​
98// Hash checkout paths to ports 20000-23999; Vitest's fixed port collides under inherited strictPort.
99// Stay below ephemeral ranges: Windows reserves Hyper-V/WSL blocks there and EACCES is not skipped.
100const browserTestApiPort = 20_000 + ((Hash.string(import.meta.dirname) >>> 0) % 4_000);
101​
102const browserTestProject = {
103 extends: true,
104 // Pre-bundle lazy browser and worker dependencies to avoid mid-run reloads.
105 optimizeDeps: {
106 include: [
107 "vite-plus/test/browser",
108 "@base-ui/react/autocomplete",
109 "@effect/vitest",
110 "@pierre/diffs/ssr",
111 "effect/testing",
112 "saxes",
113 "@betteroffice/docx/editor",
114 "@betteroffice/docx/layout",
115 "@betteroffice/docx/layout/render",
116 "@betteroffice/docx/yrs",
117 "@betteroffice/fonts",
118 "@betteroffice/pptx",
119 "@betteroffice/xlsx",
120 "@betteroffice/xlsx/headless",
121 "fast-xml-parser",
122 "entities",
123 "dompurify",
124 "heic-to/csp",
125 "jszip",
126 "pdfjs-dist",
127 "sql.js",
128 "tiff",
129 ],
130 },
131 test: {
132 name: "browser",
133 include: ["src/**/*.browser.test.{ts,tsx}"],
134 hookTimeout: 15_000,
135 testTimeout: 15_000,
136 setupFiles: ["./test/browserSetup.ts"],
137 api: { port: browserTestApiPort, strictPort: false },
138 browser: {
139 enabled: true,
140 headless: true,
141 provider: playwright(),
142 instances: [{ browser: "chromium" }],
143 screenshotFailures: false,
144 commands: {
145 // Playwright's mouse outlives each test, so whatever mounts under its last
146 // position starts hovered. test/browserSetup.ts parks it off the page before each test.
147 resetPointer: async ({ page }) => {
148 await page.mouse.move(-1, -1);
149 },
150 // A press held across a render: userEvent only offers whole clicks.
151 pointerDown: async ({ page }) => {
152 await page.mouse.down();
153 },
154 pointerUp: async ({ page }) => {
155 await page.mouse.up();
156 },
157 },
158 },
159 },
160} satisfies TestProjectInlineConfiguration;
161​
162function resolveDevProxyTarget(
163 backendPort: string | undefined,
164 wsUrl: string | undefined,
165): string | undefined {
166 const port = Number(backendPort?.trim());
167 if (Number.isInteger(port) && port > 0) {
168 return `http://localhost:${port}/`;
169 }
170​
171 // dev:desktop connects directly to the backend; derive its target from the explicit WebSocket URL.
172 if (!wsUrl) {
173 return undefined;
174 }
175​
176 try {
177 const url = new URL(wsUrl);
178 if (url.protocol === "ws:") {
179 url.protocol = "http:";
180 } else if (url.protocol === "wss:") {
181 url.protocol = "https:";
182 }
183 url.pathname = "";
184 url.search = "";
185 url.hash = "";
186 return url.toString();
187 } catch {
188 return undefined;
189 }
191​
192const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
193​
194// Brotli quality 5 encodes in hundreds of ms; default quality 11 would replace transfer stalls with encode stalls.
195function devCompressionPlugin(): Plugin {
196 return {
197 name: "t3code:dev-compression",
198 apply: "serve",
199 configureServer(server) {
200 server.middlewares.use(
201 compression({
202 brotli: { params: { [NodeZlib.constants.BROTLI_PARAM_QUALITY]: 5 } },
203 }) as unknown as Connect.NextHandleFunction,
204 );
205 },
206 };
208​
209// A static import cycle between chunks can run a chunk before the values it imports exist,
210// which blanks the app at boot. Fail the build instead of shipping it.
211function chunkCycleGuardPlugin(): Plugin {
212 return {
213 name: "t3code:chunk-cycle-guard",
214 apply: "build",
215 generateBundle(_options, bundle) {
216 const done = new Set<string>();
217 const visit = (fileName: string, path: string[]) => {
218 if (done.has(fileName)) return;
219 const start = path.indexOf(fileName);
220 if (start !== -1) {
221 this.error(`Chunk import cycle: ${[...path.slice(start), fileName].join(" -> ")}`);
222 }
223 const chunk = bundle[fileName];
224 if (chunk?.type !== "chunk") return;
225 for (const imported of chunk.imports) visit(imported, [...path, fileName]);
226 done.add(fileName);
227 };
228 for (const fileName of Object.keys(bundle)) visit(fileName, []);
229 },
230 };
232​
233// Bundled dev never evicts emitted files from memory (vitejs/vite#23781), so hashed names keep
234// a copy of every changed chunk from every rebuild. Fixed names overwrite the previous copy.
235function bundledDevStableNamesPlugin(): Plugin {
236 return {
237 name: "t3code:bundled-dev-stable-names",
238 apply: "serve",
239 outputOptions: (options) => ({
240 ...options,
241 chunkFileNames: "assets/[name].js",
242 assetFileNames: "assets/[name][extname]",
243 }),
244 };
246​
247// Stamps index.html's title with the name branding.ts resolves once the app
248// loads, so a tab opens on the right channel instead of flashing another's.
249// Desktop swaps in its injected branding from an inline script in index.html.
250function bootstrapTitlePlugin(): Plugin {
251 let development = false;
252 return {
253 name: "t3code:bootstrap-title",
254 configResolved(config) {
255 // The same flag Vite exposes to the app as import.meta.env.DEV.
256 development = !config.isProduction;
257 },
258 transformIndexHtml(html) {
259 const stageLabel = resolveWebAppStageLabel({
260 hostedAppChannel: configuredHostedAppChannel,
261 development,
262 });
263 const title = formatAppDisplayName({ baseName: "T3 Code", stageLabel });
264 return html.replace(/<title>[^<]*<\/title>/, `<title>${title}</title>`);
265 },
266 };
268​
269// Allow Tailnet hosts for sharing; Tailscale-controlled DNS prevents attacker rebinding.
270const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
271 .split(",")
272 .map((entry) => entry.trim())
273 .filter((entry) => entry.length > 0);
274const allowedHosts = [".ts.net", ...configuredAllowedHosts];
275​
276export default defineConfig(({ command }) => {
277 // `vp dev` and `--built` dev pair this client with a server run from source, which reports the
278 // manifest version. Only a production build is paired with a packed server.
279 const configuredAppVersion =
280 process.env.APP_VERSION?.trim() ||
281 (command === "build" && !builtDev
282 ? resolveTaggedSourceVersion(`${import.meta.dirname}/../..`, pkg.version)
283 : pkg.version);
284 return {
285 run: {
286 tasks: {
287 // A local tsbuildinfo is leftover build state, not a typecheck input.
288 typecheck: {
289 command: "effect-tsgo tsrs --noEmit",
290 cache: { input: [{ auto: true }, "!*.tsbuildinfo"] },
291 },
292 },
293 },
294 assetsInclude: ["**/*.wasm"],
295 plugins: [
296 bootstrapTitlePlugin(),
297 devCompressionPlugin(),
298 chunkCycleGuardPlugin(),
299 builtDev
300 ? undefined
301 : thirdPartyLicensesPlugin({
302 bundleName: "web",
303 configFile: new URL("../../third-party-licenses.config.json", import.meta.url),
304 packageManifests: [
305 { bundle: "web", path: new URL("./package.json", import.meta.url) },
306 { bundle: "server", path: new URL("../server/package.json", import.meta.url) },
307 { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },
308 ],
309 }),
310 tanstackRouter({ autoCodeSplitting: true }),
311 react({ compiler: true }),
312 tailwindPlugins(bundledDev),
313 warmBundledDevPlugin(),
314 bundledDev ? bundledDevStableNamesPlugin() : undefined,
315 ],
316 optimizeDeps: {
317 include: [
318 "@clerk/clerk-js",
319 "@clerk/react/internal",
320 "@pierre/diffs",
321 "@pierre/diffs/edit",
322 "@pierre/diffs/react",
323 "@pierre/diffs/worker/worker.js",
324 "effect/Array",
325 "effect/Order",
326 "react-dom/client",
327 ],
328 },
329 define: {
330 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
331 // Override .env URLs with empty values in single-origin dev so clients use window.location.origin.
332 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
333 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
334 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
335 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
336 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
337 configuredClerkCliOAuthClientId,
338 ),
339 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
340 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
341 configuredRelayTracingDataset,
342 ),
343 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
344 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
345 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
346 "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify(
347 configuredDesktopUpdateRepository,
348 ),
349 "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel),
350 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
351 },
352 resolve: {
353 tsconfigPaths: true,
354 dedupe: ["react", "react-dom"],
355 },
356 experimental: {
357 bundledDev,
358 },
359 server: {
360 host,
361 port,
362 strictPort: true,
363 allowedHosts,
364 // Warm the module graph before first request to avoid serial import transforms over tailnet.
365 // Bundled dev ignores this; warmBundledDevPlugin handles it there.
366 warmup: {
367 clientFiles: ["./src/main.tsx"],
368 },
369 watch: { exclude: rolldownWatchExclude },
370 ...(devProxyTarget
371 ? {
372 // Share prefixes with the backend catch-all so the proxy and 404 lists cannot drift.
373 proxy: Object.fromEntries(
374 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
375 prefix,
376 {
377 target: devProxyTarget,
378 // Keep the client's Host: OAuth metadata, cookie Origin checks and DPoP proofs
379 // all compare against the URL the client used.
380 changeOrigin: false,
381 ...(prefix === "/ws" || prefix === "/api" ? { ws: true } : {}),
382 },
383 ]),
384 ),
385 }
386 : {}),
387 // Electron needs an explicit HMR host; elsewhere derive it from page origin for Tailscale/LAN.
388 ...(explicitHost
389 ? {
390 hmr: {
391 protocol: "ws",
392 host: explicitHost,
393 clientPort: port,
394 },
395 }
396 : {}),
397 },
398 // Tailwind needs devSourcemap to avoid Rolldown SOURCEMAP_BROKEN on sourcemapped builds.
399 css: {
400 devSourcemap: buildSourcemap !== false,
401 },
402 build: {
403 outDir: "dist",
404 emptyOutDir: true,
405 manifest: true,
406 sourcemap: buildSourcemap,
407 ...(builtDev ? { watch: { exclude: rolldownWatchExclude } } : {}),
408 rolldownOptions: {
409 output: {
410 // PDF.js resolves decoder modules and ICC data relative to wasmUrl.
411 assetFileNames: (asset) =>
412 asset.originalFileNames.some((path) => /[/\\]pdfjs-dist[/\\]wasm[/\\]/.test(path))
413 ? `assets/pdfjs-${pdfjsPkg.version}/[name][extname]`
414 : "assets/[name]-[hash][extname]",
415 },
416 },
417 },
418 worker: { format: "es" },
419 test: {
420 projects: [defineProject(unitTestProject), defineProject(browserTestProject)],
421 },
422 };
423});