Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeOS from "node:os";
4
5import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as NetService from "@t3tools/shared/Net";
8import { resolveGitWorktreePath, resolveWorktreeT3Home } from "@t3tools/shared/devHome";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Config from "effect/Config";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Hash from "effect/Hash";
15import * as Layer from "effect/Layer";
16import * as Logger from "effect/Logger";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as Schema from "effect/Schema";
20import { Argument, Command, Flag } from "effect/cli";
21import { ChildProcess } from "effect/process";
22
23import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
24import { loadRepoEnv } from "./lib/public-config.ts";
25
26Object.assign(process.env, loadRepoEnv());
27
28const BASE_SERVER_PORT = 13773;
29const BASE_WEB_PORT = 5733;
30const MAX_HASH_OFFSET = 3000;
31const MAX_PORT = 65535;
32const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
33// Browsers block these ports before networking even when curl accepts them.
34// https://fetch.spec.whatwg.org/#port-blocking
35const FETCH_BAD_PORTS = new Set([
36 0, 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102,
37 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
38 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
39 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
40 6669, 6679, 6697, 10080,
41]);
42// Dev binds loopback; other interfaces cannot establish port availability.
43const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
44// A pruned migrate-dev-db copy is tens of MB; some worktrees hold a full copy
45// of the live database instead.
46const LARGE_DEV_DATABASE_BYTES = 500 * 1024 * 1024;
47
48/** Only loopback and wildcard binds keep the loopback proxy target reachable. */
49export function isProxiableBindHost(host: string): boolean {
50 const normalized = host.trim();
51 return (
52 normalized === "" ||
53 normalized === "localhost" ||
54 normalized === "127.0.0.1" ||
55 normalized === "::1" ||
56 normalized === "[::1]" ||
57 normalized === "0.0.0.0" ||
58 normalized === "::" ||
59 normalized === "[::]"
60 );
61}
62
63export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
64 path.join(NodeOS.homedir(), ".t3"),
65);
66
67const MODE_ARGS = {
68 dev: [
69 "run",
70 "--filter=@t3tools/contracts",
71 "--filter=@t3tools/web",
72 "--filter=t3",
73 "--parallel",
74 "dev",
75 ],
76 "dev:server": ["run", "--filter=t3", "dev"],
77 "dev:web": ["run", "--filter=@t3tools/web", "dev"],
78 "dev:desktop": ["run", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "dev"],
79} as const satisfies Record<string, ReadonlyArray<string>>;
80
81// `--built`: the web package rebuilds into apps/web/dist and the backend serves
82// it, so no Vite dev server runs.
83const BUILT_DEV_ARGS = [
84 "run",
85 "--filter=@t3tools/web",
86 "--filter=t3",
87 "--parallel",
88 "dev:built",
89] as const;
90
91type DevMode = keyof typeof MODE_ARGS;
92// Only backend ports honor --host/T3CODE_HOST; web ports stay loopback.
93type PortAvailabilityCheck<R = never> = (
94 port: number,
95 role?: "server" | "web",
96) => Effect.Effect<boolean, never, R>;
97
98const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
99
100export function isBrowserAllowedPort(port: number): boolean {
101 return !FETCH_BAD_PORTS.has(port);
102}
103
104export class DevRunnerConfigurationError extends Schema.TaggedError<DevRunnerConfigurationError>()(
105 "DevRunnerConfigurationError",
106 {
107 configKeys: Schema.Array(Schema.String),
108 cause: Schema.Defect(),
109 },
110) {
111 override get message(): string {
112 return `Failed to read dev-runner configuration: ${this.configKeys.join(", ")}.`;
113 }
114}
115
116export class DevRunnerInvalidPortOffsetError extends Schema.TaggedError<DevRunnerInvalidPortOffsetError>()(
117 "DevRunnerInvalidPortOffsetError",
118 {
119 configKey: Schema.Literal("T3CODE_PORT_OFFSET"),
120 portOffset: Schema.Number,
121 minimum: Schema.Number,
122 },
123) {
124 override get message(): string {
125 return `${this.configKey} must be at least ${this.minimum}; received ${this.portOffset}.`;
126 }
127}
128
129export class DevRunnerPortExhaustedError extends Schema.TaggedError<DevRunnerPortExhaustedError>()(
130 "DevRunnerPortExhaustedError",
131 {
132 startOffset: Schema.Number,
133 requireServerPort: Schema.Boolean,
134 requireWebPort: Schema.Boolean,
135 baseServerPort: Schema.Number,
136 baseWebPort: Schema.Number,
137 maximumPort: Schema.Number,
138 },
139) {
140 override get message(): string {
141 return `No required dev ports were available from offset ${this.startOffset} through maximum port ${this.maximumPort}.`;
142 }
143}
144
145export class DevRunnerProcessError extends Schema.TaggedError<DevRunnerProcessError>()(
146 "DevRunnerProcessError",
147 {
148 operation: Schema.Literals(["spawn", "wait-for-exit"]),
149 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
150 executable: Schema.Literal("vp"),
151 argumentCount: Schema.Number,
152 shell: Schema.Boolean,
153 cause: Schema.Defect(),
154 },
155) {
156 override get message(): string {
157 return `Dev-runner process operation "${this.operation}" failed for mode "${this.mode}".`;
158 }
159}
160
161export class DevRunnerProcessExitError extends Schema.TaggedError<DevRunnerProcessExitError>()(
162 "DevRunnerProcessExitError",
163 {
164 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
165 executable: Schema.Literal("vp"),
166 argumentCount: Schema.Number,
167 shell: Schema.Boolean,
168 exitCode: Schema.Number,
169 },
170) {
171 override get message(): string {
172 return `Dev-runner process exited with code ${this.exitCode} in mode "${this.mode}".`;
173 }
174}
175
176export class DevRunnerHostNotProxiableError extends Schema.TaggedError<DevRunnerHostNotProxiableError>()(
177 "DevRunnerHostNotProxiableError",
178 {
179 mode: Schema.Literals(["dev", "dev:web"]),
180 host: Schema.String,
181 },
182) {
183 override get message(): string {
184 return `--host ${this.host} cannot be combined with ${this.mode}: single-origin browser dev proxies the backend at localhost, and a backend bound only to ${this.host} leaves localhost unanswered, so every proxied request fails. Use a wildcard (0.0.0.0 or ::) to serve that interface and loopback together, or --share for remote access.`;
185 }
186}
187
188export class DevRunnerBuiltNeedsShareError extends Schema.TaggedError<DevRunnerBuiltNeedsShareError>()(
189 "DevRunnerBuiltNeedsShareError",
190 {
191 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
192 },
193) {
194 override get message(): string {
195 return `--built only works with \`dev --share\` (got ${this.mode}${this.mode === "dev" ? " without --share" : ""}): the backend serves the built client on the tailnet URL.`;
196 }
197}
198
199const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
200 Config.String(name).pipe(
201 Config.option,
202 Config.map((value) => Option.getOrUndefined(value)),
203 );
204const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
205 Config.Boolean(name).pipe(
206 Config.option,
207 Config.map((value) => Option.getOrUndefined(value)),
208 );
209const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
210 Config.Port(name).pipe(
211 Config.option,
212 Config.map((value) => Option.getOrUndefined(value)),
213 );
214const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
215 Config.Int(name).pipe(
216 Config.option,
217 Config.map((value) => Option.getOrUndefined(value)),
218 );
219const OffsetConfig = Config.all({
220 portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
221 devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
222});
223
224export function resolveOffset(config: {
225 readonly portOffset: number | undefined;
226 readonly devInstance: string | undefined;
227 readonly worktreePath?: string | undefined;
228}): Effect.Effect<
229 { readonly offset: number; readonly source: string },
230 DevRunnerInvalidPortOffsetError
231> {
232 if (config.portOffset !== undefined) {
233 if (config.portOffset < 0) {
234 return Effect.fail(
235 new DevRunnerInvalidPortOffsetError({
236 configKey: "T3CODE_PORT_OFFSET",
237 portOffset: config.portOffset,
238 minimum: 0,
239 }),
240 );
241 }
242 return Effect.succeed({
243 offset: config.portOffset,
244 source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
245 });
246 }
247
248 const seed = config.devInstance?.trim();
249 if (seed) {
250 if (/^\d+$/.test(seed)) {
251 return Effect.succeed({
252 offset: Number(seed),
253 source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
254 });
255 }
256
257 const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
258 return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
259 }
260
261 const worktreePath = config.worktreePath?.trim();
262 if (worktreePath) {
263 const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
264 return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
265 }
266
267 return Effect.succeed({ offset: 0, source: "default ports" });
268}
269
270const resolveBaseDir = Effect.fn("dev-runner.resolveBaseDir")(function* (
271 baseDir: string | undefined,
272): Effect.fn.Return<string, never, Path.Path> {
273 const path = yield* Path.Path;
274 const configured = baseDir?.trim();
275
276 if (configured) {
277 return path.resolve(configured);
278 }
279
280 return yield* DEFAULT_T3_HOME;
281});
282
283interface CreateDevRunnerEnvInput {
284 readonly mode: DevMode;
285 readonly baseEnv: NodeJS.ProcessEnv;
286 readonly serverOffset: number;
287 readonly webOffset: number;
288 readonly t3Home: string | undefined;
289 readonly browser: boolean | undefined;
290 readonly autoBootstrapProjectFromCwd: boolean | undefined;
291 readonly logWebSocketEvents: boolean | undefined;
292 readonly host: string | undefined;
293 readonly port: number | undefined;
294 readonly devUrl: URL | undefined;
295}
296
297export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(function* ({
298 mode,
299 baseEnv,
300 serverOffset,
301 webOffset,
302 t3Home,
303 browser,
304 autoBootstrapProjectFromCwd,
305 logWebSocketEvents,
306 host,
307 port,
308 devUrl,
309}: CreateDevRunnerEnvInput): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
310 const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
311 const webPort = BASE_WEB_PORT + webOffset;
312 const configuredBaseDir = t3Home?.trim() || undefined;
313 const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
314 const isDesktopMode = mode === "dev:desktop";
315
316 const output: NodeJS.ProcessEnv = {
317 ...baseEnv,
318 PORT: String(webPort),
319 VITE_DEV_SERVER_URL:
320 devUrl?.toString() ??
321 `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
322 };
323
324 if (configuredBaseDir !== undefined) {
325 output.T3CODE_HOME = resolvedBaseDir;
326 } else {
327 delete output.T3CODE_HOME;
328 }
329
330 // Managed T3 service shells leak launcher variables that make dev servers fail version checks.
331 // Dev-runner servers are never launcher-managed (serviceLauncherClient.ts resolveStartup).
332 delete output.T3_SERVICE_LAUNCHER_CONTEXT;
333 delete output.T3_BOOT_SERVICE_UNIT;
334
335 // Each worktree has its own state, so a dev server would count as a new
336 // install of the developer's real accounts. Set it explicitly to opt in.
337 output.T3CODE_TELEMETRY_ENABLED = baseEnv.T3CODE_TELEMETRY_ENABLED ?? "false";
338
339 if (!isDesktopMode) {
340 output.T3CODE_PORT = String(serverPort);
341 // An inherited HOST pins Vite's HMR socket via explicitHost in apps/web/vite.config.ts.
342 // Only desktop mode should set it.
343 delete output.HOST;
344 if (mode === "dev" || mode === "dev:web") {
345 // Browser dev is single-origin: everything (including /ws) is proxied
346 // through Vite, so the client must resolve its backend from
347 // window.location.origin rather than a baked-in localhost URL.
348 delete output.VITE_HTTP_URL;
349 delete output.VITE_WS_URL;
350 // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
351 // which merges `.env`/`.env.local` *under* this env, so a developer
352 // with either URL in their `.env` would get it back and silently lose
353 // single-origin mode.
354 output.T3CODE_SINGLE_ORIGIN_DEV = "1";
355 } else {
356 output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
357 output.VITE_WS_URL = `ws://localhost:${serverPort}`;
358 delete output.T3CODE_SINGLE_ORIGIN_DEV;
359 }
360 } else {
361 output.T3CODE_PORT = String(serverPort);
362 output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
363 output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
364 // Desktop pins the renderer to loopback on purpose; an ambient marker
365 // must not make Vite drop those URLs.
366 delete output.T3CODE_SINGLE_ORIGIN_DEV;
367 delete output.T3CODE_MODE;
368 delete output.T3CODE_NO_BROWSER;
369 delete output.T3CODE_HOST;
370 delete output.T3CODE_DEV_AUTH_TOKEN;
371 }
372
373 if (!isDesktopMode && host !== undefined) {
374 output.T3CODE_HOST = host;
375 }
376
377 if (!isDesktopMode) {
378 output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
379 }
380
381 if (autoBootstrapProjectFromCwd !== undefined) {
382 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
383 } else {
384 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
385 }
386
387 if (logWebSocketEvents !== undefined) {
388 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
389 } else {
390 delete output.T3CODE_LOG_WS_EVENTS;
391 }
392
393 if (mode === "dev") {
394 output.T3CODE_MODE = "web";
395 delete output.T3CODE_DESKTOP_WS_URL;
396 }
397
398 if (mode === "dev:server" || mode === "dev:web") {
399 output.T3CODE_MODE = "web";
400 delete output.T3CODE_DESKTOP_WS_URL;
401 }
402
403 if (isDesktopMode) {
404 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
405 delete output.T3CODE_DESKTOP_WS_URL;
406 }
407
408 return output;
409});
410
411function portPairForOffset(offset: number): {
412 readonly serverPort: number;
413 readonly webPort: number;
414} {
415 return {
416 serverPort: BASE_SERVER_PORT + offset,
417 webPort: BASE_WEB_PORT + offset,
418 };
419}
420
421export const checkPortAvailabilityOnHosts = Effect.fn("dev-runner.checkPortAvailabilityOnHosts")(
422 function* <R>(
423 port: number,
424 hosts: ReadonlyArray<string>,
425 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
426 ): Effect.fn.Return<boolean, never, R> {
427 for (const host of hosts) {
428 if (!(yield* canListenOnHost(port, host))) {
429 return false;
430 }
431 }
432
433 return true;
434 },
435);
436
437export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
438 const host = configuredHost?.trim();
439 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
440 return DEV_PORT_PROBE_HOSTS;
441 }
442 return [...DEV_PORT_PROBE_HOSTS, host];
443}
444
445const makeDefaultCheckPortAvailability =
446 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
447 (port, role) =>
448 Effect.gen(function* () {
449 const net = yield* NetService.NetService;
450 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
451 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
452 net.canListenOnHost(candidatePort, host),
453 );
454 });
455
456const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
457
458interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
459 readonly startOffset: number;
460 readonly requireServerPort: boolean;
461 readonly requireWebPort: boolean;
462 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
463}
464
465export const findFirstAvailableOffset = Effect.fn("dev-runner.findFirstAvailableOffset")(function* <
466 R = NetService.NetService,
467>({
468 startOffset,
469 requireServerPort,
470 requireWebPort,
471 checkPortAvailability,
472}: FindFirstAvailableOffsetInput<R>): Effect.fn.Return<number, DevRunnerPortExhaustedError, R> {
473 const checkPort = (checkPortAvailability ??
474 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
475
476 for (let candidate = startOffset; ; candidate += 1) {
477 const { serverPort, webPort } = portPairForOffset(candidate);
478 const serverPortOutOfRange = serverPort > MAX_PORT;
479 const webPortOutOfRange = webPort > MAX_PORT;
480
481 if (
482 (requireServerPort && serverPortOutOfRange) ||
483 (requireWebPort && webPortOutOfRange) ||
484 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
485 ) {
486 break;
487 }
488
489 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
490 continue;
491 }
492
493 const checks: Array<Effect.Effect<boolean, never, R>> = [];
494 if (requireServerPort) {
495 checks.push(checkPort(serverPort, "server"));
496 }
497 if (requireWebPort) {
498 checks.push(checkPort(webPort, "web"));
499 }
500
501 if (checks.length === 0) {
502 return candidate;
503 }
504
505 const availability = yield* Effect.all(checks);
506 if (availability.every(Boolean)) {
507 return candidate;
508 }
509 }
510
511 return yield* new DevRunnerPortExhaustedError({
512 startOffset,
513 requireServerPort,
514 requireWebPort,
515 baseServerPort: BASE_SERVER_PORT,
516 baseWebPort: BASE_WEB_PORT,
517 maximumPort: MAX_PORT,
518 });
519});
520
521interface ResolveModePortOffsetsInput<R = NetService.NetService> {
522 readonly mode: DevMode;
523 readonly startOffset: number;
524 readonly hasExplicitServerPort: boolean;
525 readonly hasExplicitDevUrl: boolean;
526 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
527}
528
529export const resolveModePortOffsets = Effect.fn("dev-runner.resolveModePortOffsets")(function* <
530 R = NetService.NetService,
531>({
532 mode,
533 startOffset,
534 hasExplicitServerPort,
535 hasExplicitDevUrl,
536 checkPortAvailability,
537}: ResolveModePortOffsetsInput<R>): Effect.fn.Return<
538 { readonly serverOffset: number; readonly webOffset: number },
539 DevRunnerPortExhaustedError,
540 R
541> {
542 const checkPort = (checkPortAvailability ??
543 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
544
545 if (mode === "dev:web") {
546 if (hasExplicitDevUrl) {
547 return { serverOffset: startOffset, webOffset: startOffset };
548 }
549
550 const webOffset = yield* findFirstAvailableOffset({
551 startOffset,
552 requireServerPort: false,
553 requireWebPort: true,
554 checkPortAvailability: checkPort,
555 });
556 return { serverOffset: startOffset, webOffset };
557 }
558
559 if (mode === "dev:server") {
560 if (hasExplicitServerPort) {
561 return { serverOffset: startOffset, webOffset: startOffset };
562 }
563
564 const serverOffset = yield* findFirstAvailableOffset({
565 startOffset,
566 requireServerPort: true,
567 requireWebPort: false,
568 checkPortAvailability: checkPort,
569 });
570 return { serverOffset, webOffset: serverOffset };
571 }
572
573 const sharedOffset = yield* findFirstAvailableOffset({
574 startOffset,
575 requireServerPort: !hasExplicitServerPort,
576 requireWebPort: !hasExplicitDevUrl,
577 checkPortAvailability: checkPort,
578 });
579
580 return { serverOffset: sharedOffset, webOffset: sharedOffset };
581});
582
583/** Best effort: a failed first-start step warns, and dev still starts. */
584const runRepoScript = Effect.fn("dev-runner.runRepoScript")(function* (
585 script: string,
586 args: ReadonlyArray<string>,
587 env: NodeJS.ProcessEnv,
588) {
589 const path = yield* Path.Path;
590 const repoRoot = path.dirname(import.meta.dirname);
591 const exitCode = yield* ChildProcess.make(
592 yield* HostProcess.ExecutablePath,
593 [path.join(repoRoot, script), ...args],
594 { cwd: repoRoot, stdin: "ignore", stdout: "inherit", stderr: "inherit", env, extendEnv: false },
595 ).pipe(
596 Effect.flatMap((child) => child.exitCode),
597 Effect.scoped,
598 Effect.orElseSucceed(() => -1),
599 );
600 if (exitCode !== 0) {
601 yield* Effect.logWarning(`[dev-runner] ${script} failed; starting anyway.`);
602 }
603});
604
605/**
606 * The first start in a worktree seeds its empty database from the live install
607 * and warms the web dependency cache. Each step checks for its own output, so
608 * later starts skip it.
609 */
610const prepareFirstStart = Effect.fn("dev-runner.prepareFirstStart")(function* (input: {
611 readonly mode: DevMode;
612 readonly seed: boolean;
613 readonly worktreeHome: string | undefined;
614 readonly env: NodeJS.ProcessEnv;
615}) {
616 const fs = yield* FileSystem.FileSystem;
617 const path = yield* Path.Path;
618 const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false));
619
620 if (input.worktreeHome !== undefined && input.mode !== "dev:web") {
621 const stateDir = path.join(input.worktreeHome, "userdata");
622 for (const name of ["statev2.sqlite", "state.sqlite"]) {
623 const file = path.join(stateDir, name);
624 const info = yield* fs.stat(file).pipe(Effect.option);
625 if (Option.isSome(info) && Number(info.value.size) > LARGE_DEV_DATABASE_BYTES) {
626 yield* Effect.logWarning(
627 `[dev-runner] ${file} is ${Math.round(Number(info.value.size) / 1024 / 1024)} MB. With the dev server stopped, \`vp run migrate-dev-db\` rebuilds statev2.sqlite as a small copy of recent data.`,
628 );
629 }
630 }
631 const source = path.join(yield* HostProcess.HomeDirectory, ".t3", "userdata", "statev2.sqlite");
632 // A V1 state.sqlite counts as data too: the server imports it only while
633 // statev2.sqlite is missing, so seeding would hide it.
634 if (
635 input.seed &&
636 !(yield* exists(path.join(stateDir, "statev2.sqlite"))) &&
637 !(yield* exists(path.join(stateDir, "state.sqlite"))) &&
638 (yield* exists(source))
639 ) {
640 yield* Effect.logInfo(
641 `[dev-runner] seeding ${input.worktreeHome} from ${source} (read-only). --no-seed or T3CODE_DEV_SEED=0 skips this.`,
642 );
643 yield* runRepoScript(
644 "apps/server/scripts/migrate-dev-db.ts",
645 ["--base-dir", input.worktreeHome, "--source", source],
646 input.env,
647 );
648 }
649 }
650
651 const repoRoot = path.dirname(import.meta.dirname);
652 if (
653 input.mode !== "dev:server" &&
654 !(yield* exists(path.join(repoRoot, "apps/web/node_modules/.vite/deps/_metadata.json")))
655 ) {
656 yield* runRepoScript("apps/web/scripts/warm-dep-cache.ts", [], input.env);
657 }
658});
659
660interface DevRunnerCliInput {
661 readonly mode: DevMode;
662 readonly t3Home: string | undefined;
663 readonly browser: boolean | undefined;
664 readonly autoBootstrapProjectFromCwd: boolean | undefined;
665 readonly logWebSocketEvents: boolean | undefined;
666 readonly host: string | undefined;
667 readonly port: number | undefined;
668 readonly devUrl: URL | undefined;
669 readonly dryRun: boolean;
670 readonly share: boolean;
671 readonly seed?: boolean | undefined;
672 readonly built: boolean;
673 readonly runArgs: ReadonlyArray<string>;
674}
675
676export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput")(function* (
677 input: DevRunnerCliInput,
678) {
679 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
680 Effect.mapError(
681 (cause) =>
682 new DevRunnerConfigurationError({
683 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
684 cause,
685 }),
686 ),
687 );
688
689 if (
690 (input.mode === "dev" || input.mode === "dev:web") &&
691 input.host !== undefined &&
692 !isProxiableBindHost(input.host)
693 ) {
694 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
695 }
696
697 if (input.built && (input.mode !== "dev" || !input.share)) {
698 return yield* new DevRunnerBuiltNeedsShareError({ mode: input.mode });
699 }
700
701 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
702
703 const { offset, source } = yield* resolveOffset({
704 portOffset,
705 devInstance,
706 worktreePath,
707 });
708
709 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
710 mode: input.mode,
711 startOffset: offset,
712 hasExplicitServerPort: input.port !== undefined,
713 hasExplicitDevUrl: input.devUrl !== undefined,
714 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
715 });
716
717 const hostEnvironment = yield* HostProcess.Environment;
718 // A dev server started inside a worktree defaults to that worktree's own
719 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
720 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
721 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
722 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
723 // as one would skip the worktree default and land on the shared home —
724 // exactly the outcome this precedence exists to prevent.
725 const resolvedT3Home =
726 (input.t3Home?.trim() || undefined) ??
727 worktreeHome ??
728 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
729 const env = yield* createDevRunnerEnv({
730 mode: input.mode,
731 baseEnv: hostEnvironment,
732 serverOffset,
733 webOffset,
734 t3Home: resolvedT3Home,
735 browser: input.browser,
736 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
737 logWebSocketEvents: input.logWebSocketEvents,
738 host: input.host,
739 port: input.port,
740 devUrl: input.devUrl,
741 });
742
743 const selectionSuffix =
744 serverOffset !== offset || webOffset !== offset
745 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
746 : "";
747 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
748
749 yield* Effect.logInfo(
750 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
751 );
752
753 // Before the share block: --dry-run only resolves and prints. Sharing would
754 // replace, then tear down, whatever mapping the port already had — a
755 // surprising side effect from a command documented as inert.
756 if (input.dryRun) {
757 return;
758 }
759
760 const sharedWebPort = BASE_WEB_PORT + webOffset;
761 let built = false;
762 if (input.share) {
763 if (input.mode === "dev:server") {
764 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
765 } else if (input.mode === "dev:desktop") {
766 yield* Effect.logWarning(
767 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
768 );
769 } else {
770 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
771 // process (and reboots), so the cleanup has to be registered atomically
772 // with creating it. An interrupt landing in between would otherwise
773 // leave a mapping pointing at a port nothing is listening on.
774 const shared = yield* Effect.acquireRelease(
775 shareDevServer({
776 webPort: sharedWebPort,
777 // The backend binds 127.0.0.1 unless --host changes it. A wildcard
778 // still answers there; `--host ::1` binds only the IPv6 loopback.
779 ...(input.built
780 ? {
781 localTarget: {
782 port: Number(env.T3CODE_PORT),
783 host: ["::1", "[::1]"].includes(input.host?.trim() ?? "") ? "[::1]" : "127.0.0.1",
784 },
785 }
786 : {}),
787 }),
788 () =>
789 unshareDevServer(sharedWebPort).pipe(
790 Effect.flatMap((result) =>
791 result.cleared
792 ? Effect.void
793 : Effect.logWarning(
794 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
795 result.explanation ? `: ${result.explanation}` : ""
796 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
797 ),
798 ),
799 ),
800 ).pipe(
801 Effect.tapError((error: DevShareError) =>
802 Effect.logWarning(
803 `[dev-runner] could not share on the tailnet: ${error.message}${
804 error.hint ? ` — ${error.hint}` : ""
805 }`,
806 ),
807 ),
808 Effect.option,
809 Effect.map(Option.getOrUndefined),
810 );
811
812 if (shared) {
813 // The app is reached from the tailnet origin. Vite already allows
814 // *.ts.net hosts; the backend needs the origin for credentialed
815 // requests that bypass the proxy (desktop renderer, direct calls).
816 env.T3CODE_DEV_ALLOWED_ORIGINS = [
817 env.T3CODE_DEV_ALLOWED_ORIGINS,
818 new URL(shared.url).origin,
819 ]
820 .filter((entry) => entry && entry.length > 0)
821 .join(",");
822 if (input.devUrl === undefined) {
823 env.VITE_DEV_SERVER_URL = shared.url;
824 }
825 if (input.built) {
826 built = true;
827 env.T3CODE_BUILT_DEV = "1";
828 } else if (env.T3CODE_BUNDLED_DEV === undefined) {
829 // A shared origin serves a remote browser, where unbundled dev's
830 // per-module requests each pay a tailnet round trip — a cold module
831 // graph takes minutes to first paint. Bundled dev collapses that to a
832 // few chunk requests.
833 env.T3CODE_BUNDLED_DEV = "1";
834 }
835 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
836 } else if (input.built) {
837 yield* Effect.logWarning(
838 "[dev-runner] --built needs the tailnet share; running the Vite dev server instead.",
839 );
840 }
841 }
842 }
843
844 // After sharing, so the warm step sees the same bundled-dev env as Vite.
845 yield* prepareFirstStart({
846 mode: input.mode,
847 seed: input.seed !== false,
848 worktreeHome: baseDir === worktreeHome ? worktreeHome : undefined,
849 env,
850 });
851
852 const args = [...(built ? BUILT_DEV_ARGS : MODE_ARGS[input.mode]), ...input.runArgs];
853 const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
854 const processContext = {
855 mode: input.mode,
856 executable: "vp" as const,
857 argumentCount: args.length,
858 shell: spawnCommand.shell,
859 } as const;
860 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
861 stdin: "inherit",
862 stdout: "inherit",
863 stderr: "inherit",
864 env,
865 extendEnv: false,
866 shell: spawnCommand.shell,
867 // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
868 // reach it directly. Effect defaults to detached: true on non-Windows,
869 // which would put the runner in a new group and require manual forwarding.
870 detached: false,
871 forceKillAfter: "1500 millis",
872 }).pipe(
873 Effect.mapError(
874 (cause) =>
875 new DevRunnerProcessError({
876 ...processContext,
877 operation: "spawn",
878 cause,
879 }),
880 ),
881 );
882
883 const exitCode = yield* child.exitCode.pipe(
884 Effect.mapError(
885 (cause) =>
886 new DevRunnerProcessError({
887 ...processContext,
888 operation: "wait-for-exit",
889 cause,
890 }),
891 ),
892 );
893 if (exitCode !== 0) {
894 return yield* new DevRunnerProcessExitError({
895 ...processContext,
896 exitCode,
897 });
898 }
899});
900
901const devRunnerCli = Command.make("dev-runner", {
902 mode: Argument.Literals("mode", DEV_RUNNER_MODES).pipe(
903 Argument.withDescription("Development mode to run."),
904 ),
905 t3Home: Flag.String("home-dir").pipe(
906 Flag.withDescription(
907 "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME). Inside a git worktree this defaults to that worktree's own .t3 so dev state stays off the shared home.",
908 ),
909 Flag.optional,
910 Flag.map(Option.getOrUndefined),
911 ),
912 browser: Flag.Boolean("browser").pipe(
913 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
914 Flag.withDefault(false),
915 ),
916 autoBootstrapProjectFromCwd: Flag.Boolean("auto-bootstrap-project-from-cwd").pipe(
917 Flag.withDescription(
918 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
919 ),
920 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
921 ),
922 logWebSocketEvents: Flag.Boolean("log-websocket-events").pipe(
923 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
924 Flag.withAlias("log-ws-events"),
925 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
926 ),
927 host: Flag.String("host").pipe(
928 Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
929 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
930 ),
931 port: Flag.Int("port").pipe(
932 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
933 Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
934 Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
935 ),
936 devUrl: Flag.String("dev-url").pipe(
937 Flag.withSchema(Schema.URLFromString),
938 Flag.withDescription(
939 "Explicit web dev URL override (forwards to VITE_DEV_SERVER_URL). Ambient VITE_DEV_SERVER_URL values are ignored so a parent dev app cannot redirect the child runner.",
940 ),
941 Flag.optional,
942 Flag.map(Option.getOrUndefined),
943 ),
944 dryRun: Flag.Boolean("dry-run").pipe(
945 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
946 Flag.withDefault(false),
947 ),
948 share: Flag.Boolean("share").pipe(
949 Flag.withDescription(
950 "Publish the web dev server on this machine's tailnet over HTTPS (via `tailscale serve`) and print the pairing URL for it. Removed again on exit.",
951 ),
952 Flag.withDefault(false),
953 ),
954 seed: Flag.Boolean("seed").pipe(
955 Flag.withDescription(
956 "Seed an empty worktree database from ~/.t3 on first start (read-only, via migrate-dev-db). On by default; --no-seed or T3CODE_DEV_SEED=0 skips it.",
957 ),
958 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_DEV_SEED")),
959 ),
960 built: Flag.Boolean("built").pipe(
961 Flag.withDescription(
962 "With --share: serve a production web build from the backend instead of the Vite dev server. Rebuilds on change, no HMR, much smaller remote loads.",
963 ),
964 Flag.withDefault(false),
965 ),
966 runArgs: Argument.String("run-arg").pipe(
967 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
968 Argument.variadic(),
969 ),
970}).pipe(
971 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
972 Command.withHandler((input) => runDevRunnerWithInput(input)),
973);
974
975const cliRuntimeLayer = Layer.mergeAll(
976 Logger.layer([Logger.consolePretty()]),
977 NodeServices.layer,
978 NetService.layer,
979);
980
981if (import.meta.main) {
982 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
983 Effect.scoped,
984 Effect.provide(cliRuntimeLayer),
985 NodeRuntime.runMain,
986 );
987}