@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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