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

vite.config.ts

285 lines10.9 KB

1import * as NodeZlib from "node:zlib";
2​
3import react from "@vitejs/plugin-react";
4import { tanstackRouter } from "@tanstack/router-plugin/vite";
5import compression from "compression";
6import { playwright } from "vite-plus/test/browser-playwright";
7import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
8import "vite-plus/test/config";
9import { defineConfig, type Connect, type Plugin } from "vite-plus";
10import * as Hash from "effect/Hash";
11import pkg from "./package.json" with { type: "json" };
12​
13import {
14 DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES,
15 DEV_PROXIED_PATH_PREFIXES,
16} from "@t3tools/shared/devProxy";
17​
18import { loadRepoEnv } from "../../scripts/lib/public-config";
19import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses";
20import { tailwindPlugins } from "./vite/tailwind";
21​
22const repoEnv = loadRepoEnv();
23Object.assign(process.env, repoEnv);
24​
25// Single-origin dev is signalled positively, because it cannot be inferred from
26// the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys but
27// `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so a
28// developer with either URL in their `.env` gets it back here.
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 configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
45const configuredHostedAppUrl = (() => {
46 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
47 if (explicitHostedAppUrl) {
48 return explicitHostedAppUrl;
49 }
50 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
51 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
52 }
53 if (process.env.VERCEL_URL) {
54 return `https://${process.env.VERCEL_URL}`;
55 }
56 return undefined;
57})();
58const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
59​
60const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
61const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
62​
63const buildSourcemap: boolean | "hidden" =
64 sourcemapEnv === "0" || sourcemapEnv === "false"
65 ? false
66 : sourcemapEnv === "hidden"
67 ? "hidden"
68 : true;
69​
70const unitTestProject = {
71 extends: true,
72 test: {
73 name: "unit",
74 include: ["src/**/*.test.{ts,tsx}"],
75 exclude: ["src/**/*.browser.test.{ts,tsx}"],
76 hookTimeout: 15_000,
77 testTimeout: 15_000,
78 setupFiles: ["../../packages/shared/src/testing/longTempDir.ts"],
79 },
80} satisfies TestProjectInlineConfiguration;
81​
82// Anything that renders React or touches the DOM is named *.browser.test.{ts,tsx} and runs
83// in headless Chromium through the same plugins as the app, so it exercises compiled code.
84// Vitest's fixed browser API port (63315) collides when two checkouts run
85// browser tests at once, and `server.strictPort` above is inherited, so the
86// second run fails instead of moving on. Hash the checkout path like
87// scripts/dev-runner.ts does, into 61000-64999 (above Linux's ephemeral range).
88const browserTestApiPort = 61_000 + ((Hash.string(import.meta.dirname) >>> 0) % 4_000);
89​
90const browserTestProject = {
91 extends: true,
92 // Pre-bundled so the first test importing userEvent does not trigger a mid-run reload.
93 optimizeDeps: { include: ["vite-plus/test/browser"] },
94 test: {
95 name: "browser",
96 include: ["src/**/*.browser.test.{ts,tsx}"],
97 hookTimeout: 15_000,
98 testTimeout: 15_000,
99 api: { port: browserTestApiPort, strictPort: false },
100 browser: {
101 enabled: true,
102 headless: true,
103 provider: playwright(),
104 instances: [{ browser: "chromium" }],
105 screenshotFailures: false,
106 },
107 },
108} satisfies TestProjectInlineConfiguration;
109​
110function resolveDevProxyTarget(
111 backendPort: string | undefined,
112 wsUrl: string | undefined,
113): string | undefined {
114 const port = Number(backendPort?.trim());
115 if (Number.isInteger(port) && port > 0) {
116 return `http://localhost:${port}/`;
117 }
118​
119 // dev:desktop still points the renderer straight at the backend, so fall
120 // back to deriving the target from the explicit websocket URL.
121 if (!wsUrl) {
122 return undefined;
123 }
124​
125 try {
126 const url = new URL(wsUrl);
127 if (url.protocol === "ws:") {
128 url.protocol = "http:";
129 } else if (url.protocol === "wss:") {
130 url.protocol = "https:";
131 }
132 url.pathname = "";
133 url.search = "";
134 url.hash = "";
135 return url.toString();
136 } catch {
137 return undefined;
138 }
140​
141const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
142​
143// Brotli quality 5 keeps encode time in the hundreds of ms; the default
144// (quality 11) would trade the transfer stall for an equally long encode stall.
145function devCompressionPlugin(): Plugin {
146 return {
147 name: "t3code:dev-compression",
148 apply: "serve",
149 configureServer(server) {
150 server.middlewares.use(
151 compression({
152 brotli: { params: { [NodeZlib.constants.BROTLI_PARAM_QUALITY]: 5 } },
153 }) as unknown as Connect.NextHandleFunction,
154 );
155 },
156 };
158​
159// Vite rejects requests whose Host header isn't localhost, which blocks sharing
160// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
161// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
162const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
163 .split(",")
164 .map((entry) => entry.trim())
165 .filter((entry) => entry.length > 0);
166const allowedHosts = [".ts.net", ...configuredAllowedHosts];
167​
168export default defineConfig(() => {
169 return {
170 assetsInclude: ["**/*.wasm"],
171 plugins: [
172 devCompressionPlugin(),
173 thirdPartyLicensesPlugin({
174 bundleName: "web",
175 configFile: new URL("../../third-party-licenses.config.json", import.meta.url),
176 packageManifests: [
177 { bundle: "web", path: new URL("./package.json", import.meta.url) },
178 { bundle: "server", path: new URL("../server/package.json", import.meta.url) },
179 { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },
180 ],
181 }),
182 tanstackRouter({ autoCodeSplitting: true }),
183 react({ compiler: true }),
184 tailwindPlugins(bundledDev),
185 ],
186 optimizeDeps: {
187 include: [
188 "@clerk/clerk-js",
189 "@clerk/react/internal",
190 "@pierre/diffs",
191 "@pierre/diffs/edit",
192 "@pierre/diffs/react",
193 "@pierre/diffs/worker/worker.js",
194 "effect/Array",
195 "effect/Order",
196 "react-dom/client",
197 ],
198 },
199 define: {
200 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
201 // Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
202 // under single-origin dev this must stay empty even when a `.env`
203 // supplies it, so the client falls back to window.location.origin.
204 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
205 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
206 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
207 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
208 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
209 configuredClerkCliOAuthClientId,
210 ),
211 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
212 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
213 configuredRelayTracingDataset,
214 ),
215 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
216 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
217 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
218 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
219 },
220 resolve: {
221 tsconfigPaths: true,
222 dedupe: ["react", "react-dom"],
223 },
224 experimental: {
225 bundledDev,
226 },
227 server: {
228 host,
229 port,
230 strictPort: true,
231 allowedHosts,
232 // Transform the whole module graph at server start instead of on the
233 // first request. Without this, a cold worktree discovers and transforms
234 // modules one import-level at a time while the browser waits — which
235 // over a tailnet origin turns into minutes of waterfall.
236 warmup: {
237 clientFiles: ["./src/main.tsx"],
238 },
239 ...(devProxyTarget
240 ? {
241 // One entry per shared prefix; the server's dev catch-all 404s the
242 // same list, so the two sides cannot drift.
243 proxy: Object.fromEntries(
244 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
245 prefix,
246 {
247 target: devProxyTarget,
248 changeOrigin: !DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES.has(prefix),
249 ...(prefix === "/ws" || prefix === "/api" ? { ws: true } : {}),
250 },
251 ]),
252 ),
253 }
254 : {}),
255 // Electron's BrowserWindow needs the HMR socket pinned to an explicit
256 // host to connect reliably; dev:desktop is the only mode that sets HOST.
257 // Everywhere else, leaving this unset lets the client derive it from the
258 // page origin, which is what makes HMR work over Tailscale/LAN instead of
259 // failing an attempt against the wrong machine's localhost first.
260 ...(explicitHost
261 ? {
262 hmr: {
263 protocol: "ws",
264 host: explicitHost,
265 clientPort: port,
266 },
267 }
268 : {}),
269 },
270 // @tailwindcss/vite only emits a CSS sourcemap when devSourcemap is on; without it
271 // rolldown flags the transform as SOURCEMAP_BROKEN on every sourcemapped build.
272 css: {
273 devSourcemap: buildSourcemap !== false,
274 },
275 build: {
276 outDir: "dist",
277 emptyOutDir: true,
278 manifest: true,
279 sourcemap: buildSourcemap,
280 },
281 test: {
282 projects: [defineProject(unitTestProject), defineProject(browserTestProject)],
283 },
284 };
285});