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

vite.config.ts

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