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

vite.config.ts

233 lines9.5 KB

1import tailwindcss from "@tailwindcss/vite";
2import react, { reactCompilerPreset } from "@vitejs/plugin-react";
3import babel from "@rolldown/plugin-babel";
4import { tanstackRouter } from "@tanstack/router-plugin/vite";
5import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
6import "vite-plus/test/config";
7import { defineConfig } from "vite-plus";
8import pkg from "./package.json" with { type: "json" };
9​
10import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
11​
12import { loadRepoEnv } from "../../scripts/lib/public-config";
13​
14const repoEnv = loadRepoEnv();
15Object.assign(process.env, repoEnv);
16​
17// Single-origin dev is signalled positively, because it cannot be inferred
18// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
19// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
20// a developer with either URL in their `.env` gets it back here. Baking it then
21// pins the client to localhost and breaks every non-localhost origin — the
22// exact failure single-origin mode exists to prevent, and an invisible one
23// since the page still loads.
24const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
25​
26const port = Number(process.env.PORT ?? 5733);
27const explicitHost = process.env.HOST?.trim();
28const host = explicitHost || "localhost";
29const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
30const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
31const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
32const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
33const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
34const configuredClerkCliOAuthClientId = repoEnv.VITE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || "";
35const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() || "";
36const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";
37const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";
38const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
39const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
40const configuredHostedAppUrl = (() => {
41 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
42 if (explicitHostedAppUrl) {
43 return explicitHostedAppUrl;
44 }
45 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
46 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
47 }
48 if (process.env.VERCEL_URL) {
49 return `https://${process.env.VERCEL_URL}`;
50 }
51 return undefined;
52})();
53const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
54​
55// Vite 8.1's experimental bundled dev mode: serves rolldown-bundled chunks in
56// dev for much faster startup/reload on large module graphs, with HMR served
57// as hot patches. Opt-in while experimental: T3CODE_BUNDLED_DEV=1 pnpm dev:web
58const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
59const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
60​
61const buildSourcemap: boolean | "hidden" =
62 sourcemapEnv === "0" || sourcemapEnv === "false"
63 ? false
64 : sourcemapEnv === "hidden"
65 ? "hidden"
66 : true;
67​
68const unitTestProject = {
69 extends: true,
70 test: {
71 name: "unit",
72 include: ["src/**/*.test.{ts,tsx}"],
73 // The web runtime suite exercises auth bootstrap, saved environments,
74 // and websocket subscription lifecycles. Under the full monorepo test
75 // run, those async tests can exceed Vitest's default 5s budget.
76 hookTimeout: 15_000,
77 testTimeout: 15_000,
78 },
79} satisfies TestProjectInlineConfiguration;
80​
81function resolveDevProxyTarget(
82 backendPort: string | undefined,
83 wsUrl: string | undefined,
84): string | undefined {
85 // Browser dev is single-origin: the backend port is proxied through this
86 // server so the app works from any origin (localhost, tailnet, LAN, phone).
87 // T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
88 const port = Number(backendPort?.trim());
89 if (Number.isInteger(port) && port > 0) {
90 return `http://localhost:${port}/`;
91 }
92​
93 // dev:desktop still points the renderer straight at the backend, so fall
94 // back to deriving the target from the explicit websocket URL.
95 if (!wsUrl) {
96 return undefined;
97 }
98​
99 try {
100 const url = new URL(wsUrl);
101 if (url.protocol === "ws:") {
102 url.protocol = "http:";
103 } else if (url.protocol === "wss:") {
104 url.protocol = "https:";
105 }
106 url.pathname = "";
107 url.search = "";
108 url.hash = "";
109 return url.toString();
110 } catch {
111 return undefined;
112 }
114​
115const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
116​
117// Vite rejects requests whose Host header isn't localhost, which blocks sharing
118// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
119// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
120// Anything else (ngrok, a LAN IP alias) goes through the env var.
121const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
122 .split(",")
123 .map((entry) => entry.trim())
124 .filter((entry) => entry.length > 0);
125const allowedHosts = [".ts.net", ...configuredAllowedHosts];
126​
127export default defineConfig(() => {
128 return {
129 plugins: [
130 tanstackRouter(),
131 react(),
132 babel({
133 // We need to be explicit about the parser options after moving to @vitejs/plugin-react v6.0.0
134 // This is because the babel plugin only automatically parses typescript and jsx based on relative paths (e.g. "**/*.ts")
135 // whereas the previous version of the plugin parsed all files with a .ts extension.
136 // This is causing our packages/ directory to fail to parse, as they are not relative to the CWD.
137 parserOpts: { plugins: ["typescript", "jsx"] },
138 presets: [reactCompilerPreset()],
139 }),
140 tailwindcss(),
141 ],
142 optimizeDeps: {
143 include: [
144 "@clerk/clerk-js",
145 "@clerk/react/internal",
146 "@pierre/diffs",
147 "@pierre/diffs/editor",
148 "@pierre/diffs/react",
149 "@pierre/diffs/worker/worker.js",
150 "effect/Array",
151 "effect/Order",
152 "react-dom/client",
153 ],
154 },
155 define: {
156 // In dev mode, tell the web app where the WebSocket server lives
157 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
158 // Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
159 // under single-origin dev this must stay empty even when a `.env`
160 // supplies it, so the client falls back to window.location.origin.
161 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
162 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
163 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
164 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
165 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
166 configuredClerkCliOAuthClientId,
167 ),
168 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
169 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
170 configuredRelayTracingDataset,
171 ),
172 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
173 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
174 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
175 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
176 },
177 resolve: {
178 tsconfigPaths: true,
179 dedupe: ["react", "react-dom"],
180 },
181 experimental: {
182 bundledDev,
183 },
184 server: {
185 host,
186 port,
187 strictPort: true,
188 allowedHosts,
189 ...(devProxyTarget
190 ? {
191 // One entry per shared prefix; the server's dev catch-all 404s the
192 // same list, so the two sides cannot drift. `/ws` is the app's own
193 // socket — Vite's HMR socket is matched separately and exactly
194 // (path "/" plus a vite-hmr subprotocol), so the two upgrade
195 // handlers don't collide.
196 proxy: Object.fromEntries(
197 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
198 prefix,
199 {
200 target: devProxyTarget,
201 changeOrigin: true,
202 ...(prefix === "/ws" ? { ws: true } : {}),
203 },
204 ]),
205 ),
206 }
207 : {}),
208 // Electron's BrowserWindow needs the HMR socket pinned to an explicit
209 // host to connect reliably; dev:desktop is the only mode that sets HOST.
210 // Everywhere else, leaving this unset lets the client derive it from the
211 // page origin, which is what makes HMR work over Tailscale/LAN instead of
212 // failing an attempt against the wrong machine's localhost first.
213 // (Vite 8 logs connection state via console.debug — enable "Verbose".)
214 ...(explicitHost
215 ? {
216 hmr: {
217 protocol: "ws",
218 host: explicitHost,
219 clientPort: port,
220 },
221 }
222 : {}),
223 },
224 build: {
225 outDir: "dist",
226 emptyOutDir: true,
227 sourcemap: buildSourcemap,
228 },
229 test: {
230 projects: [defineProject(unitTestProject)],
231 },
232 };
233});