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