Open History to see the last commit
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";
21import { warmBundledDevPlugin } from "./vite/warmBundledDev";
22
23const repoEnv = loadRepoEnv();
24Object.assign(process.env, repoEnv);
25
26// Signal single-origin dev explicitly; loadRepoEnv can restore deleted URL keys from .env.
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 configuredDesktopUpdateRepository =
44 process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
45 process.env.GITHUB_REPOSITORY?.trim() ||
46 "";
47const configuredHostedAppUrl = (() => {
48 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
49 if (explicitHostedAppUrl) {
50 return explicitHostedAppUrl;
51 }
52 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
53 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
54 }
55 if (process.env.VERCEL_URL) {
56 return `https://${process.env.VERCEL_URL}`;
57 }
58 return undefined;
59})();
60const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
61
62// `vp run dev --share --built` rebuilds on every change. The license manifest
63// is about 2 s of each build, and nothing in that mode reads it.
64const builtDev = process.env.T3CODE_BUILT_DEV === "1";
65
66const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
67const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
68
69const buildSourcemap: boolean | "hidden" =
70 sourcemapEnv === "0" || sourcemapEnv === "false"
71 ? false
72 : sourcemapEnv === "hidden"
73 ? "hidden"
74 : true;
75
76const unitTestProject = {
77 extends: true,
78 test: {
79 name: "unit",
80 include: ["src/**/*.test.{ts,tsx}"],
81 exclude: ["src/**/*.browser.test.{ts,tsx}"],
82 hookTimeout: 15_000,
83 testTimeout: 15_000,
84 setupFiles: [
85 "../../packages/shared/src/testing/longTempDir.ts",
86 "../../packages/shared/src/testing/providerEnv.ts",
87 ],
88 },
89} satisfies TestProjectInlineConfiguration;
90
91// Hash checkout paths to ports 61000-64999; Vitest's fixed port collides under inherited strictPort.
92const browserTestApiPort = 61_000 + ((Hash.string(import.meta.dirname) >>> 0) % 4_000);
93
94const browserTestProject = {
95 extends: true,
96 // Pre-bundled so a late first import does not trigger a mid-run reload. The
97 // dependency scan misses autocomplete because tests reach it only through lazy imports.
98 optimizeDeps: { include: ["vite-plus/test/browser", "@base-ui/react/autocomplete"] },
99 test: {
100 name: "browser",
101 include: ["src/**/*.browser.test.{ts,tsx}"],
102 hookTimeout: 15_000,
103 testTimeout: 15_000,
104 setupFiles: ["./test/browserSetup.ts"],
105 api: { port: browserTestApiPort, strictPort: false },
106 browser: {
107 enabled: true,
108 headless: true,
109 provider: playwright(),
110 instances: [{ browser: "chromium" }],
111 screenshotFailures: false,
112 commands: {
113 // Playwright's mouse outlives each test, so whatever mounts under its last
114 // position starts hovered. test/browserSetup.ts parks it off the page before each test.
115 resetPointer: async ({ page }) => {
116 await page.mouse.move(-1, -1);
117 },
118 },
119 },
120 },
121} satisfies TestProjectInlineConfiguration;
122
123function resolveDevProxyTarget(
124 backendPort: string | undefined,
125 wsUrl: string | undefined,
126): string | undefined {
127 const port = Number(backendPort?.trim());
128 if (Number.isInteger(port) && port > 0) {
129 return `http://localhost:${port}/`;
130 }
131
132 // dev:desktop connects directly to the backend; derive its target from the explicit WebSocket URL.
133 if (!wsUrl) {
134 return undefined;
135 }
136
137 try {
138 const url = new URL(wsUrl);
139 if (url.protocol === "ws:") {
140 url.protocol = "http:";
141 } else if (url.protocol === "wss:") {
142 url.protocol = "https:";
143 }
144 url.pathname = "";
145 url.search = "";
146 url.hash = "";
147 return url.toString();
148 } catch {
149 return undefined;
150 }
151}
152
153const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
154
155// Brotli quality 5 encodes in hundreds of ms; default quality 11 would replace transfer stalls with encode stalls.
156function devCompressionPlugin(): Plugin {
157 return {
158 name: "t3code:dev-compression",
159 apply: "serve",
160 configureServer(server) {
161 server.middlewares.use(
162 compression({
163 brotli: { params: { [NodeZlib.constants.BROTLI_PARAM_QUALITY]: 5 } },
164 }) as unknown as Connect.NextHandleFunction,
165 );
166 },
167 };
168}
169
170// Allow Tailnet hosts for sharing; Tailscale-controlled DNS prevents attacker rebinding.
171const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
172 .split(",")
173 .map((entry) => entry.trim())
174 .filter((entry) => entry.length > 0);
175const allowedHosts = [".ts.net", ...configuredAllowedHosts];
176
177export default defineConfig(() => {
178 return {
179 run: {
180 tasks: {
181 // tsc (tsc-rs) rewrites the tsbuildinfo it reads, which keeps a task out of the cache.
182 typecheck: {
183 command: "tsc --noEmit",
184 cache: { input: [{ auto: true }, "!*.tsbuildinfo"] },
185 },
186 },
187 },
188 assetsInclude: ["**/*.wasm"],
189 plugins: [
190 devCompressionPlugin(),
191 builtDev
192 ? undefined
193 : thirdPartyLicensesPlugin({
194 bundleName: "web",
195 configFile: new URL("../../third-party-licenses.config.json", import.meta.url),
196 packageManifests: [
197 { bundle: "web", path: new URL("./package.json", import.meta.url) },
198 { bundle: "server", path: new URL("../server/package.json", import.meta.url) },
199 { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },
200 ],
201 }),
202 tanstackRouter({ autoCodeSplitting: true }),
203 react({ compiler: true }),
204 tailwindPlugins(bundledDev),
205 warmBundledDevPlugin(),
206 ],
207 optimizeDeps: {
208 include: [
209 "@clerk/clerk-js",
210 "@clerk/react/internal",
211 "@pierre/diffs",
212 "@pierre/diffs/edit",
213 "@pierre/diffs/react",
214 "@pierre/diffs/worker/worker.js",
215 "effect/Array",
216 "effect/Order",
217 "react-dom/client",
218 ],
219 },
220 define: {
221 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
222 // Override .env URLs with empty values in single-origin dev so clients use window.location.origin.
223 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
224 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
225 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
226 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
227 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
228 configuredClerkCliOAuthClientId,
229 ),
230 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
231 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
232 configuredRelayTracingDataset,
233 ),
234 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
235 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
236 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
237 "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify(
238 configuredDesktopUpdateRepository,
239 ),
240 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
241 },
242 resolve: {
243 tsconfigPaths: true,
244 dedupe: ["react", "react-dom"],
245 },
246 experimental: {
247 bundledDev,
248 },
249 server: {
250 host,
251 port,
252 strictPort: true,
253 allowedHosts,
254 // Warm the module graph before first request to avoid serial import transforms over tailnet.
255 // Bundled dev ignores this; warmBundledDevPlugin handles it there.
256 warmup: {
257 clientFiles: ["./src/main.tsx"],
258 },
259 ...(devProxyTarget
260 ? {
261 // Share prefixes with the backend catch-all so the proxy and 404 lists cannot drift.
262 proxy: Object.fromEntries(
263 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
264 prefix,
265 {
266 target: devProxyTarget,
267 changeOrigin: !DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES.has(prefix),
268 ...(prefix === "/ws" || prefix === "/api" ? { ws: true } : {}),
269 },
270 ]),
271 ),
272 }
273 : {}),
274 // Electron needs an explicit HMR host; elsewhere derive it from page origin for Tailscale/LAN.
275 ...(explicitHost
276 ? {
277 hmr: {
278 protocol: "ws",
279 host: explicitHost,
280 clientPort: port,
281 },
282 }
283 : {}),
284 },
285 // Tailwind needs devSourcemap to avoid Rolldown SOURCEMAP_BROKEN on sourcemapped builds.
286 css: {
287 devSourcemap: buildSourcemap !== false,
288 },
289 build: {
290 outDir: "dist",
291 emptyOutDir: true,
292 manifest: true,
293 sourcemap: buildSourcemap,
294 },
295 test: {
296 projects: [defineProject(unitTestProject), defineProject(browserTestProject)],
297 },
298 };
299});