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