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

vite.config.ts

539 lines20.7 KB

1import * as NodeZlib from "node:zlib";
2​
3import { vite as gtCompiler } from "@generaltranslation/compiler";
4import react from "@vitejs/plugin-react";
5import { tanstackRouter } from "@tanstack/router-plugin/vite";
6import compression from "compression";
7import { playwright } from "vite-plus/test/browser-playwright";
8import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
9import "vite-plus/test/config";
10import { defineConfig, type Connect, type Plugin } from "vite-plus";
11import * as Hash from "effect/Hash";
12import pkg from "./package.json" with { type: "json" };
13import pdfjsPkg from "pdfjs-dist/package.json" with { type: "json" };
14​
15import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
16​
17import { cliTestFiles } from "../../scripts/lib/cli-test-files";
18import { loadRepoEnv } from "../../scripts/lib/public-config";
19import { resolveTaggedSourceVersion } from "../../scripts/lib/tagged-source-version";
20import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses";
21import { tailwindPlugins } from "./vite/tailwind";
22import { warmBundledDevPlugin } from "./vite/warmBundledDev";
23import { formatAppDisplayName, resolveWebAppStageLabel } from "./src/branding.logic";
24​
25const repoEnv = loadRepoEnv();
26Object.assign(process.env, repoEnv);
27​
28// Signal single-origin dev explicitly; loadRepoEnv can restore deleted URL keys from .env.
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 configuredReleaseChannel =
45 process.env.T3CODE_BUILT_DEV === "1" ? "dev" : process.env.VITE_RELEASE_CHANNEL?.trim() || "";
46const configuredDesktopUpdateRepository =
47 process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
48 process.env.GITHUB_REPOSITORY?.trim() ||
49 "";
50const configuredHostedAppUrl = (() => {
51 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
52 if (explicitHostedAppUrl) {
53 return explicitHostedAppUrl;
54 }
55 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
56 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
57 }
58 if (process.env.VERCEL_URL) {
59 return `https://${process.env.VERCEL_URL}`;
60 }
61 return undefined;
62})();
63const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
64​
65// `vp run dev --share --built` rebuilds on every change. The license manifest
66// is about 2 s of each build, and nothing in that mode reads it.
67const builtDev = process.env.T3CODE_BUILT_DEV === "1";
68​
69const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
70const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
71​
72// Bundled dev and `build --watch` pass Rolldown `exclude` but not Vite's default `ignored`, so
73// they watch node_modules. Those files are pnpm-store hardlinks shared by every worktree, so each
74// `vp i` or worktree removal elsewhere rebuilds every long-running server and leaks native memory.
75const rolldownWatchExclude = [/[\\/]node_modules[\\/]/];
76​
77const buildSourcemap: boolean | "hidden" =
78 sourcemapEnv === "0" || sourcemapEnv === "false"
79 ? false
80 : sourcemapEnv === "hidden"
81 ? "hidden"
82 : true;
83​
84const unitTestProject = {
85 extends: true,
86 test: {
87 name: "unit",
88 include: ["src/**/*.test.{ts,tsx}"],
89 exclude: ["src/**/*.browser.test.{ts,tsx}"],
90 hookTimeout: 15_000,
91 testTimeout: 15_000,
92 setupFiles: [
93 "../../packages/shared/src/testing/longTempDir.ts",
94 "../../packages/shared/src/testing/providerEnv.ts",
95 "../../packages/shared/src/testing/gitEnv.ts",
96 ],
97 },
98} satisfies TestProjectInlineConfiguration;
99​
100// Starting the browser project costs several seconds; skip whichever project
101// a run of named test files does not need.
102const namedTestFiles = await cliTestFiles();
103const namesBrowserTest = namedTestFiles?.some((file) => /\.browser\.test\.tsx?$/.test(file));
104const namesUnitTest = namedTestFiles?.some((file) => !/\.browser\.test\.tsx?$/.test(file));
105​
106// Hash checkout paths to ports 20000-23999; Vitest's fixed port collides under inherited strictPort.
107// Stay below ephemeral ranges: Windows reserves Hyper-V/WSL blocks there and EACCES is not skipped.
108const browserTestApiPort = 20_000 + ((Hash.string(import.meta.dirname) >>> 0) % 4_000);
109​
110const browserTestProject = {
111 extends: true,
112 // Pre-bundle lazy browser and worker dependencies to avoid mid-run reloads.
113 optimizeDeps: {
114 include: [
115 "vite-plus/test/browser",
116 "@base-ui/react/autocomplete",
117 "@effect/vitest",
118 "@pierre/diffs/ssr",
119 "effect/testing",
120 "saxes",
121 "@noble/ciphers/aes.js",
122 "@noble/hashes/hmac.js",
123 "@noble/hashes/legacy.js",
124 "@noble/hashes/pbkdf2.js",
125 "@noble/hashes/sha2.js",
126 "@noble/hashes/utils.js",
127 "@betteroffice/docx/editor",
128 "@betteroffice/docx/layout",
129 "@betteroffice/docx/layout/render",
130 "@betteroffice/docx/yrs",
131 "@betteroffice/fonts",
132 "@betteroffice/pptx",
133 "@betteroffice/xlsx",
134 "@betteroffice/xlsx/headless",
135 "fast-xml-parser",
136 "parse5",
137 "entities",
138 "dompurify",
139 "heic-to/csp",
140 "jszip",
141 "pdfjs-dist",
142 "sql.js",
143 "tiff",
144 ],
145 },
146 test: {
147 name: "browser",
148 include: ["src/**/*.browser.test.{ts,tsx}"],
149 hookTimeout: 15_000,
150 testTimeout: 15_000,
151 setupFiles: ["./test/browserSetup.ts"],
152 api: { port: browserTestApiPort, strictPort: false },
153 browser: {
154 enabled: true,
155 headless: true,
156 provider: playwright(),
157 instances: [{ browser: "chromium" }],
158 screenshotFailures: false,
159 commands: {
160 // Playwright's mouse outlives each test, so whatever mounts under its last
161 // position starts hovered. test/browserSetup.ts parks it off the page before each test.
162 resetPointer: async ({ page }) => {
163 await page.mouse.move(-1, -1);
164 },
165 // A press held across a render: userEvent only offers whole clicks.
166 pointerDown: async ({ page }) => {
167 await page.mouse.down();
168 },
169 pointerUp: async ({ page }) => {
170 await page.mouse.up();
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// A static import cycle between chunks can run a chunk before the values it imports exist,
225// which blanks the app at boot. Fail the build instead of shipping it.
226function chunkCycleGuardPlugin(): Plugin {
227 return {
228 name: "t3code:chunk-cycle-guard",
229 apply: "build",
230 generateBundle(_options, bundle) {
231 const done = new Set<string>();
232 const visit = (fileName: string, path: string[]) => {
233 if (done.has(fileName)) return;
234 const start = path.indexOf(fileName);
235 if (start !== -1) {
236 this.error(`Chunk import cycle: ${[...path.slice(start), fileName].join(" -> ")}`);
237 }
238 const chunk = bundle[fileName];
239 if (chunk?.type !== "chunk") return;
240 for (const imported of chunk.imports) visit(imported, [...path, fileName]);
241 done.add(fileName);
242 };
243 for (const fileName of Object.keys(bundle)) visit(fileName, []);
244 },
245 };
247​
248// Vite emits every `new URL("x.wasm", import.meta.url)` it sees before tree-shaking, so engines we
249// never call (Office "lean" and preflight WASM) still ship in every server archive. A hashed name can
250// only be loaded by output that spells it; unhashed ones (PDF.js decoders) are looked up by name.
251function dropUnreferencedAssetsPlugin(): Plugin {
252 return {
253 name: "t3code:drop-unreferenced-assets",
254 apply: "build",
255 enforce: "post",
256 generateBundle(_options, bundle) {
257 const files = Object.values(bundle);
258 const candidates = files
259 .filter(
260 (file) =>
261 file.type === "asset" &&
262 /\.(?:wasm|m?js)$/.test(file.fileName) &&
263 !file.names.some((name) => file.fileName.endsWith(`/${name}`)),
264 )
265 .map(({ fileName }) => ({
266 fileName,
267 name: fileName.slice(fileName.lastIndexOf("/") + 1),
268 referencedBy: new Set<string>(),
269 }));
270 if (candidates.length === 0) return;
271​
272 // A suffix lookup lets us check each extension occurrence without rescanning the bundle per asset.
273 const suffixLength = candidates.reduce(
274 (length, { name }) => Math.min(length, name.length),
275 12,
276 );
277 const candidatesBySuffix = new Map<string, typeof candidates>();
278 for (const candidate of candidates) {
279 const suffix = candidate.name.slice(-suffixLength);
280 const matches = candidatesBySuffix.get(suffix);
281 if (matches) matches.push(candidate);
282 else candidatesBySuffix.set(suffix, [candidate]);
283 }
284​
285 const decoder = new TextDecoder();
286 for (const file of files) {
287 const content = file.type === "chunk" ? file.code : file.source;
288 if (
289 typeof content !== "string" &&
290 !/\.(?:m?js|css|html|json|webmanifest)$/.test(file.fileName)
291 )
292 continue;
293​
294 const source = typeof content === "string" ? content : decoder.decode(content);
295 for (const match of source.matchAll(/\.(?:wasm|m?js)/g)) {
296 const end = match.index + match[0].length;
297 const matches = candidatesBySuffix.get(source.substring(end - suffixLength, end));
298 for (const candidate of matches ?? []) {
299 if (candidate.fileName !== file.fileName && source.endsWith(candidate.name, end)) {
300 candidate.referencedBy.add(file.fileName);
301 }
302 }
303 }
304 }
305​
306 let removed = true;
307 while (removed) {
308 removed = false;
309 for (const candidate of candidates) {
310 const referenced = Array.from(candidate.referencedBy).some(
311 (fileName) => fileName in bundle,
312 );
313 if (referenced || !(candidate.fileName in bundle)) continue;
314 delete bundle[candidate.fileName];
315 delete bundle[`${candidate.fileName}.map`];
316 removed = true;
317 }
318 }
319 },
320 };
322​
323// @betteroffice/fonts-cjk lists each CJK face twice: whole (`<Face>.otf.zst`) and as progressive
324// slices (`<Face>/...`), 27 MB each. Our Office previews hand the engines whole faces through
325// `loadBundledFontBytes` and never a sliced provider, so only the whole files are ever fetched.
326const CJK_SLICE_ENTRY = /^[ \t]*"[^"\n/]+\/[^"\n]*": \(\) => new URL\([^\n]*\),?[ \t]*$/gm;
327function wholeCjkFontsOnlyPlugin(): Plugin {
328 return {
329 name: "t3code:whole-cjk-fonts-only",
330 transform(code, id) {
331 if (!/[/\\]@betteroffice[/\\]fonts-cjk[/\\]dist[/\\]index\.js$/.test(id)) return;
332 const stripped = code.replace(CJK_SLICE_ENTRY, "");
333 if (stripped === code) this.warn("found no CJK font slice entries to drop");
334 return { code: stripped, map: null };
335 },
336 };
338​
339// Bundled dev never evicts emitted files from memory (vitejs/vite#23781), so hashed names keep
340// a copy of every changed chunk from every rebuild. Fixed names overwrite the previous copy.
341function bundledDevStableNamesPlugin(): Plugin {
342 return {
343 name: "t3code:bundled-dev-stable-names",
344 apply: "serve",
345 outputOptions: (options) => ({
346 ...options,
347 chunkFileNames: "assets/[name].js",
348 assetFileNames: "assets/[name][extname]",
349 }),
350 };
352​
353// Stamps index.html's title with the name branding.ts resolves once the app
354// loads, so a tab opens on the right channel instead of flashing another's.
355// Desktop swaps in its injected branding from an inline script in index.html.
356function bootstrapTitlePlugin(): Plugin {
357 let development = false;
358 return {
359 name: "t3code:bootstrap-title",
360 configResolved(config) {
361 // The same flag Vite exposes to the app as import.meta.env.DEV.
362 development = !config.isProduction;
363 },
364 transformIndexHtml(html) {
365 const stageLabel = resolveWebAppStageLabel({
366 hostedAppChannel: configuredHostedAppChannel,
367 development,
368 });
369 const title = formatAppDisplayName({ baseName: "T3 Code", stageLabel });
370 return html.replace(/<title>[^<]*<\/title>/, `<title>${title}</title>`);
371 },
372 };
374​
375// Allow Tailnet hosts for sharing; Tailscale-controlled DNS prevents attacker rebinding.
376const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
377 .split(",")
378 .map((entry) => entry.trim())
379 .filter((entry) => entry.length > 0);
380const allowedHosts = [".ts.net", ...configuredAllowedHosts];
381​
382export default defineConfig(({ command, mode }) => {
383 // `vp dev` and `--built` dev pair this client with a server run from source, which reports the
384 // manifest version. Only a production build is paired with a packed server.
385 const configuredAppVersion =
386 process.env.APP_VERSION?.trim() ||
387 (command === "build" && !builtDev
388 ? resolveTaggedSourceVersion(`${import.meta.dirname}/../..`, pkg.version)
389 : pkg.version);
390 return {
391 run: {
392 tasks: {
393 // A local tsbuildinfo is leftover build state, not a typecheck input.
394 typecheck: {
395 command: "effect-tsgo tsrs --noEmit",
396 cache: { input: [{ auto: true }, "!*.tsbuildinfo"] },
397 },
398 },
399 },
400 assetsInclude: ["**/*.wasm"],
401 plugins: [
402 bootstrapTitlePlugin(),
403 devCompressionPlugin(),
404 chunkCycleGuardPlugin(),
405 dropUnreferencedAssetsPlugin(),
406 wholeCjkFontsOnlyPlugin(),
407 builtDev
408 ? undefined
409 : thirdPartyLicensesPlugin({
410 bundleName: "web",
411 configFile: new URL("../../third-party-licenses.config.json", import.meta.url),
412 packageManifests: [
413 { bundle: "web", path: new URL("./package.json", import.meta.url) },
414 { bundle: "server", path: new URL("../server/package.json", import.meta.url) },
415 { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },
416 ],
417 }),
418 tanstackRouter({ autoCodeSplitting: true }),
419 // Hashes each <T> and message template before React Compiler reads the file. Builds only until generaltranslation/gt#3093: it doubles dev start, and the runtime computes the same hashes.
420 { ...gtCompiler(), apply: "build" },
421 react({ compiler: true }),
422 tailwindPlugins(bundledDev),
423 warmBundledDevPlugin(),
424 bundledDev ? bundledDevStableNamesPlugin() : undefined,
425 ],
426 optimizeDeps: {
427 include: [
428 "@clerk/clerk-js",
429 "@clerk/react/internal",
430 "@pierre/diffs",
431 "@pierre/diffs/edit",
432 "@pierre/diffs/react",
433 "@pierre/diffs/worker/worker.js",
434 "@t3tools/client-runtime > @zip.js/zip.js/index-native.cjs",
435 "effect/Array",
436 "effect/Order",
437 "react-dom/client",
438 ],
439 },
440 define: {
441 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
442 // Override .env URLs with empty values in single-origin dev so clients use window.location.origin.
443 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
444 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
445 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
446 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
447 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
448 configuredClerkCliOAuthClientId,
449 ),
450 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
451 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
452 configuredRelayTracingDataset,
453 ),
454 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
455 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
456 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
457 "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify(
458 configuredDesktopUpdateRepository,
459 ),
460 "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel),
461 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
462 },
463 resolve: {
464 tsconfigPaths: true,
465 dedupe: ["react", "react-dom"],
466 },
467 experimental: {
468 bundledDev,
469 },
470 server: {
471 host,
472 port,
473 strictPort: true,
474 allowedHosts,
475 // Warm the module graph before first request to avoid serial import transforms over tailnet.
476 // Bundled dev ignores this; warmBundledDevPlugin handles it there.
477 warmup: {
478 clientFiles: ["./src/main.tsx"],
479 },
480 watch: { exclude: rolldownWatchExclude },
481 // Tests render against an in-process fake environment; a session's T3CODE_PORT would route them to a live server.
482 ...(devProxyTarget && mode !== "test"
483 ? {
484 // Share prefixes with the backend catch-all so the proxy and 404 lists cannot drift.
485 proxy: Object.fromEntries(
486 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
487 prefix,
488 {
489 target: devProxyTarget,
490 // Keep the client's Host: OAuth metadata, cookie Origin checks and DPoP proofs
491 // all compare against the URL the client used.
492 changeOrigin: false,
493 ...(prefix === "/ws" || prefix === "/api" ? { ws: true } : {}),
494 },
495 ]),
496 ),
497 }
498 : {}),
499 // Electron needs an explicit HMR host; elsewhere derive it from page origin for Tailscale/LAN.
500 ...(explicitHost
501 ? {
502 hmr: {
503 protocol: "ws",
504 host: explicitHost,
505 clientPort: port,
506 },
507 }
508 : {}),
509 },
510 // Tailwind needs devSourcemap to avoid Rolldown SOURCEMAP_BROKEN on sourcemapped builds.
511 css: {
512 devSourcemap: buildSourcemap !== false,
513 },
514 build: {
515 outDir: "dist",
516 emptyOutDir: true,
517 manifest: true,
518 sourcemap: buildSourcemap,
519 ...(builtDev ? { watch: { exclude: rolldownWatchExclude } } : {}),
520 rolldownOptions: {
521 input: ["index.html", "epub-preview.html"],
522 output: {
523 // PDF.js resolves decoder modules and ICC data relative to wasmUrl.
524 assetFileNames: (asset) =>
525 asset.originalFileNames.some((path) => /[/\\]pdfjs-dist[/\\]wasm[/\\]/.test(path))
526 ? `assets/pdfjs-${pdfjsPkg.version}/[name][extname]`
527 : "assets/[name]-[hash][extname]",
528 },
529 },
530 },
531 worker: { format: "es", plugins: () => [wholeCjkFontsOnlyPlugin()] },
532 test: {
533 projects: [
534 ...(namesUnitTest === false ? [] : [defineProject(unitTestProject)]),
535 ...(namesBrowserTest === false ? [] : [defineProject(browserTestProject)]),
536 ],
537 },
538 };
539});