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