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

vite.config.ts

389 lines14.0 KB

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