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

vite.config.ts

277 lines11.5 KB

1import * as NodeZlib from "node:zlib";
2​
3import tailwindcss from "@tailwindcss/vite";
4import react, { reactCompilerPreset } from "@vitejs/plugin-react";
5import babel from "@rolldown/plugin-babel";
6import { tanstackRouter } from "@tanstack/router-plugin/vite";
7import compression from "compression";
8import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
9import "vite-plus/test/config";
10import { defineConfig, type Connect, type Plugin } from "vite-plus";
11import pkg from "./package.json" with { type: "json" };
12​
13import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
14​
15import { loadRepoEnv } from "../../scripts/lib/public-config";
16​
17const repoEnv = loadRepoEnv();
18Object.assign(process.env, repoEnv);
19​
20// Single-origin dev is signalled positively, because it cannot be inferred
21// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
22// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
23// a developer with either URL in their `.env` gets it back here. Baking it then
24// pins the client to localhost and breaks every non-localhost origin — the
25// exact failure single-origin mode exists to prevent, and an invisible one
26// since the page still loads.
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 configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
43const configuredHostedAppUrl = (() => {
44 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
45 if (explicitHostedAppUrl) {
46 return explicitHostedAppUrl;
47 }
48 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
49 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
50 }
51 if (process.env.VERCEL_URL) {
52 return `https://${process.env.VERCEL_URL}`;
53 }
54 return undefined;
55})();
56const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
57​
58// Vite 8.1's experimental bundled dev mode: serves rolldown-bundled chunks in
59// dev for much faster startup/reload on large module graphs, with HMR served
60// as hot patches. Opt-in while experimental: T3CODE_BUNDLED_DEV=1 pnpm dev:web
61// The dev runner defaults this on for --share runs (remote browsers pay a
62// round trip per import level in unbundled dev); T3CODE_BUNDLED_DEV=0 opts out.
63const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
64const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
65​
66const buildSourcemap: boolean | "hidden" =
67 sourcemapEnv === "0" || sourcemapEnv === "false"
68 ? false
69 : sourcemapEnv === "hidden"
70 ? "hidden"
71 : true;
72​
73const unitTestProject = {
74 extends: true,
75 test: {
76 name: "unit",
77 include: ["src/**/*.test.{ts,tsx}"],
78 // The web runtime suite exercises auth bootstrap, saved environments,
79 // and websocket subscription lifecycles. Under the full monorepo test
80 // run, those async tests can exceed Vitest's default 5s budget.
81 hookTimeout: 15_000,
82 testTimeout: 15_000,
83 },
84} satisfies TestProjectInlineConfiguration;
85​
86function resolveDevProxyTarget(
87 backendPort: string | undefined,
88 wsUrl: string | undefined,
89): string | undefined {
90 // Browser dev is single-origin: the backend port is proxied through this
91 // server so the app works from any origin (localhost, tailnet, LAN, phone).
92 // T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
93 const port = Number(backendPort?.trim());
94 if (Number.isInteger(port) && port > 0) {
95 return `http://localhost:${port}/`;
96 }
97​
98 // dev:desktop still points the renderer straight at the backend, so fall
99 // back to deriving the target from the explicit websocket URL.
100 if (!wsUrl) {
101 return undefined;
102 }
103​
104 try {
105 const url = new URL(wsUrl);
106 if (url.protocol === "ws:") {
107 url.protocol = "http:";
108 } else if (url.protocol === "wss:") {
109 url.protocol = "https:";
110 }
111 url.pathname = "";
112 url.search = "";
113 url.hash = "";
114 return url.toString();
115 } catch {
116 return undefined;
117 }
119​
120const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
121​
122// Vite's dev server sends JS uncompressed. On localhost that is free; over a
123// shared origin (tailnet, LAN) it is the whole cold-start: bundled dev serves
124// one ~25 MB chunk, and a typical uplink moves that in about a minute while
125// both machines sit idle. Compressing turns it into a few seconds of CPU.
126// Brotli quality 5 keeps encode time in the hundreds of ms; the default
127// (quality 11) would trade the transfer stall for an equally long encode stall.
128function devCompressionPlugin(): Plugin {
129 return {
130 name: "t3code:dev-compression",
131 apply: "serve",
132 configureServer(server) {
133 // compression() is typed against Express's req/res, which extend the
134 // node http objects Connect actually passes — safe to narrow.
135 server.middlewares.use(
136 compression({
137 brotli: { params: { [NodeZlib.constants.BROTLI_PARAM_QUALITY]: 5 } },
138 }) as unknown as Connect.NextHandleFunction,
139 );
140 },
141 };
143​
144// Vite rejects requests whose Host header isn't localhost, which blocks sharing
145// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
146// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
147// Anything else (ngrok, a LAN IP alias) goes through the env var.
148const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
149 .split(",")
150 .map((entry) => entry.trim())
151 .filter((entry) => entry.length > 0);
152const allowedHosts = [".ts.net", ...configuredAllowedHosts];
153​
154export default defineConfig(() => {
155 return {
156 assetsInclude: ["**/*.wasm"],
157 plugins: [
158 devCompressionPlugin(),
159 // Route components load as split chunks so settings, pull-request, and
160 // usage code stay out of the cold-start payload; the router prefetches
161 // them on navigation intent (see getRouter's defaultPreload).
162 tanstackRouter({ autoCodeSplitting: true }),
163 react(),
164 babel({
165 // We need to be explicit about the parser options after moving to @vitejs/plugin-react v6.0.0
166 // This is because the babel plugin only automatically parses typescript and jsx based on relative paths (e.g. "**/*.ts")
167 // whereas the previous version of the plugin parsed all files with a .ts extension.
168 // This is causing our packages/ directory to fail to parse, as they are not relative to the CWD.
169 parserOpts: { plugins: ["typescript", "jsx"] },
170 presets: [reactCompilerPreset()],
171 }),
172 tailwindcss(),
173 ],
174 optimizeDeps: {
175 include: [
176 "@clerk/clerk-js",
177 "@clerk/react/internal",
178 "@pierre/diffs",
179 "@pierre/diffs/editor",
180 "@pierre/diffs/react",
181 "@pierre/diffs/worker/worker.js",
182 "effect/Array",
183 "effect/Order",
184 "react-dom/client",
185 ],
186 },
187 define: {
188 // In dev mode, tell the web app where the WebSocket server lives
189 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
190 // Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
191 // under single-origin dev this must stay empty even when a `.env`
192 // supplies it, so the client falls back to window.location.origin.
193 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
194 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
195 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
196 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
197 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
198 configuredClerkCliOAuthClientId,
199 ),
200 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
201 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
202 configuredRelayTracingDataset,
203 ),
204 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
205 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
206 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
207 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
208 },
209 resolve: {
210 tsconfigPaths: true,
211 dedupe: ["react", "react-dom"],
212 },
213 experimental: {
214 bundledDev,
215 },
216 server: {
217 host,
218 port,
219 strictPort: true,
220 allowedHosts,
221 // Transform the whole module graph at server start instead of on the
222 // first request. Without this, a cold worktree discovers and transforms
223 // modules one import-level at a time while the browser waits — which
224 // over a tailnet origin turns into minutes of waterfall.
225 warmup: {
226 clientFiles: ["./src/main.tsx"],
227 },
228 ...(devProxyTarget
229 ? {
230 // One entry per shared prefix; the server's dev catch-all 404s the
231 // same list, so the two sides cannot drift. `/ws` is the app's own
232 // socket — Vite's HMR socket is matched separately and exactly
233 // (path "/" plus a vite-hmr subprotocol), so the two upgrade
234 // handlers don't collide.
235 proxy: Object.fromEntries(
236 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
237 prefix,
238 {
239 target: devProxyTarget,
240 changeOrigin: true,
241 ...(prefix === "/ws" ? { ws: true } : {}),
242 },
243 ]),
244 ),
245 }
246 : {}),
247 // Electron's BrowserWindow needs the HMR socket pinned to an explicit
248 // host to connect reliably; dev:desktop is the only mode that sets HOST.
249 // Everywhere else, leaving this unset lets the client derive it from the
250 // page origin, which is what makes HMR work over Tailscale/LAN instead of
251 // failing an attempt against the wrong machine's localhost first.
252 // (Vite 8 logs connection state via console.debug — enable "Verbose".)
253 ...(explicitHost
254 ? {
255 hmr: {
256 protocol: "ws",
257 host: explicitHost,
258 clientPort: port,
259 },
260 }
261 : {}),
262 },
263 // @tailwindcss/vite only emits a CSS sourcemap when devSourcemap is on; without it
264 // rolldown flags the transform as SOURCEMAP_BROKEN on every sourcemapped build.
265 css: {
266 devSourcemap: buildSourcemap !== false,
267 },
268 build: {
269 outDir: "dist",
270 emptyOutDir: true,
271 sourcemap: buildSourcemap,
272 },
273 test: {
274 projects: [defineProject(unitTestProject)],
275 },
276 };
277});