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