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 { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Config from "effect/Config";
12import * as Effect from "effect/Effect";
13import * as Hash from "effect/Hash";
14import * as Layer from "effect/Layer";
15import * as Logger from "effect/Logger";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19import { Argument, Command, Flag } from "effect/unstable/cli";
20import { ChildProcess } from "effect/unstable/process";
21
22import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
23import { loadRepoEnv } from "./lib/public-config.ts";
24
25Object.assign(process.env, loadRepoEnv());
26
27const BASE_SERVER_PORT = 13773;
28const BASE_WEB_PORT = 5733;
29const MAX_HASH_OFFSET = 3000;
30const MAX_PORT = 65535;
31const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
32// HTTP(S) requests to these ports are blocked by the Fetch standard before a
33// browser reaches the network. Keep the complete list here so explicit or
34// future wider offsets cannot produce a URL that curl accepts but browsers
35// reject. https://fetch.spec.whatwg.org/#port-blocking
36const FETCH_BAD_PORTS = new Set([
37 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,
38 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
39 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
40 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
41 6669, 6679, 6697, 10080,
42]);
43// Dev servers bind loopback, so loopback is the only interface whose
44// availability decides whether we can use a port. Probing wildcards too made
45// the runner walk away from a perfectly free port whenever something else held
46// the same number on another interface — `tailscale serve` does exactly that,
47// which silently moved the ports out from under a URL that had just been shared.
48const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
49
50/**
51 * Bind hosts on which a backend still answers `http://localhost:<port>`, which
52 * is where single-origin browser dev proxies to. Loopback and the wildcards
53 * qualify; a specific interface (e.g. a LAN IP) does not — the OS binds only
54 * that address and the proxy target goes dark.
55 */
56export function isProxiableBindHost(host: string): boolean {
57 const normalized = host.trim();
58 return (
59 normalized === "" ||
60 normalized === "localhost" ||
61 normalized === "127.0.0.1" ||
62 normalized === "::1" ||
63 normalized === "[::1]" ||
64 normalized === "0.0.0.0" ||
65 normalized === "::" ||
66 normalized === "[::]"
67 );
68}
69
70export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
71 path.join(NodeOS.homedir(), ".t3"),
72);
73
74const MODE_ARGS = {
75 dev: [
76 "run",
77 "--filter=@t3tools/contracts",
78 "--filter=@t3tools/web",
79 "--filter=t3",
80 "--parallel",
81 "dev",
82 ],
83 "dev:server": ["run", "--filter=t3", "dev"],
84 "dev:web": ["run", "--filter=@t3tools/web", "dev"],
85 "dev:desktop": ["run", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "dev"],
86} as const satisfies Record<string, ReadonlyArray<string>>;
87
88type DevMode = keyof typeof MODE_ARGS;
89/**
90 * `role` matters because only the backend honours `--host`/`T3CODE_HOST`; the
91 * web port is always loopback. Passed explicitly rather than inferred from the
92 * port number, which stops distinguishing them under a large port offset.
93 */
94type PortAvailabilityCheck<R = never> = (
95 port: number,
96 role?: "server" | "web",
97) => Effect.Effect<boolean, never, R>;
98
99const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
100
101export function getDevRunnerModeArgs(mode: DevMode): ReadonlyArray<string> {
102 return MODE_ARGS[mode];
103}
104
105export function isBrowserAllowedPort(port: number): boolean {
106 return !FETCH_BAD_PORTS.has(port);
107}
108
109export class DevRunnerConfigurationError extends Schema.TaggedErrorClass<DevRunnerConfigurationError>()(
110 "DevRunnerConfigurationError",
111 {
112 configKeys: Schema.Array(Schema.String),
113 cause: Schema.Defect(),
114 },
115) {
116 override get message(): string {
117 return `Failed to read dev-runner configuration: ${this.configKeys.join(", ")}.`;
118 }
119}
120
121export class DevRunnerInvalidPortOffsetError extends Schema.TaggedErrorClass<DevRunnerInvalidPortOffsetError>()(
122 "DevRunnerInvalidPortOffsetError",
123 {
124 configKey: Schema.Literal("T3CODE_PORT_OFFSET"),
125 portOffset: Schema.Number,
126 minimum: Schema.Number,
127 },
128) {
129 override get message(): string {
130 return `${this.configKey} must be at least ${this.minimum}; received ${this.portOffset}.`;
131 }
132}
133
134export class DevRunnerPortExhaustedError extends Schema.TaggedErrorClass<DevRunnerPortExhaustedError>()(
135 "DevRunnerPortExhaustedError",
136 {
137 startOffset: Schema.Number,
138 requireServerPort: Schema.Boolean,
139 requireWebPort: Schema.Boolean,
140 baseServerPort: Schema.Number,
141 baseWebPort: Schema.Number,
142 maximumPort: Schema.Number,
143 },
144) {
145 override get message(): string {
146 return `No required dev ports were available from offset ${this.startOffset} through maximum port ${this.maximumPort}.`;
147 }
148}
149
150export class DevRunnerProcessError extends Schema.TaggedErrorClass<DevRunnerProcessError>()(
151 "DevRunnerProcessError",
152 {
153 operation: Schema.Literals(["spawn", "wait-for-exit"]),
154 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
155 executable: Schema.Literal("vp"),
156 argumentCount: Schema.Number,
157 shell: Schema.Boolean,
158 cause: Schema.Defect(),
159 },
160) {
161 override get message(): string {
162 return `Dev-runner process operation "${this.operation}" failed for mode "${this.mode}".`;
163 }
164}
165
166export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<DevRunnerProcessExitError>()(
167 "DevRunnerProcessExitError",
168 {
169 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
170 executable: Schema.Literal("vp"),
171 argumentCount: Schema.Number,
172 shell: Schema.Boolean,
173 exitCode: Schema.Number,
174 },
175) {
176 override get message(): string {
177 return `Dev-runner process exited with code ${this.exitCode} in mode "${this.mode}".`;
178 }
179}
180
181export class DevRunnerHostNotProxiableError extends Schema.TaggedErrorClass<DevRunnerHostNotProxiableError>()(
182 "DevRunnerHostNotProxiableError",
183 {
184 mode: Schema.Literals(["dev", "dev:web"]),
185 host: Schema.String,
186 },
187) {
188 override get message(): string {
189 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.`;
190 }
191}
192
193export const DevRunnerError = Schema.Union([
194 DevRunnerConfigurationError,
195 DevRunnerHostNotProxiableError,
196 DevRunnerInvalidPortOffsetError,
197 DevRunnerPortExhaustedError,
198 DevRunnerProcessError,
199 DevRunnerProcessExitError,
200]);
201export type DevRunnerError = typeof DevRunnerError.Type;
202export const isDevRunnerError = Schema.is(DevRunnerError);
203
204const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
205 Config.string(name).pipe(
206 Config.option,
207 Config.map((value) => Option.getOrUndefined(value)),
208 );
209const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
210 Config.boolean(name).pipe(
211 Config.option,
212 Config.map((value) => Option.getOrUndefined(value)),
213 );
214const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
215 Config.port(name).pipe(
216 Config.option,
217 Config.map((value) => Option.getOrUndefined(value)),
218 );
219const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
220 Config.int(name).pipe(
221 Config.option,
222 Config.map((value) => Option.getOrUndefined(value)),
223 );
224const OffsetConfig = Config.all({
225 portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
226 devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
227});
228
229export function resolveOffset(config: {
230 readonly portOffset: number | undefined;
231 readonly devInstance: string | undefined;
232 readonly worktreePath?: string | undefined;
233}): Effect.Effect<
234 { readonly offset: number; readonly source: string },
235 DevRunnerInvalidPortOffsetError
236> {
237 if (config.portOffset !== undefined) {
238 if (config.portOffset < 0) {
239 return Effect.fail(
240 new DevRunnerInvalidPortOffsetError({
241 configKey: "T3CODE_PORT_OFFSET",
242 portOffset: config.portOffset,
243 minimum: 0,
244 }),
245 );
246 }
247 return Effect.succeed({
248 offset: config.portOffset,
249 source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
250 });
251 }
252
253 const seed = config.devInstance?.trim();
254 if (seed) {
255 if (/^\d+$/.test(seed)) {
256 return Effect.succeed({
257 offset: Number(seed),
258 source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
259 });
260 }
261
262 const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
263 return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
264 }
265
266 // Worktrees get ports derived from their path so each one is stable across
267 // restarts and distinct from its siblings. Without this every worktree starts
268 // at offset 0 and scan-collides onto whatever happens to be free that minute,
269 // so ports move under you between runs — which breaks any URL you already
270 // shared. The main checkout keeps the documented 5733/13773.
271 const worktreePath = config.worktreePath?.trim();
272 if (worktreePath) {
273 const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
274 return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
275 }
276
277 return Effect.succeed({ offset: 0, source: "default ports" });
278}
279
280function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
281 return Effect.gen(function* () {
282 const path = yield* Path.Path;
283 const configured = baseDir?.trim();
284
285 if (configured) {
286 return path.resolve(configured);
287 }
288
289 return yield* DEFAULT_T3_HOME;
290 });
291}
292
293interface CreateDevRunnerEnvInput {
294 readonly mode: DevMode;
295 readonly baseEnv: NodeJS.ProcessEnv;
296 readonly serverOffset: number;
297 readonly webOffset: number;
298 readonly t3Home: string | undefined;
299 readonly browser: boolean | undefined;
300 readonly autoBootstrapProjectFromCwd: boolean | undefined;
301 readonly logWebSocketEvents: boolean | undefined;
302 readonly host: string | undefined;
303 readonly port: number | undefined;
304 readonly devUrl: URL | undefined;
305}
306
307export function createDevRunnerEnv({
308 mode,
309 baseEnv,
310 serverOffset,
311 webOffset,
312 t3Home,
313 browser,
314 autoBootstrapProjectFromCwd,
315 logWebSocketEvents,
316 host,
317 port,
318 devUrl,
319}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
320 return Effect.gen(function* () {
321 const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
322 const webPort = BASE_WEB_PORT + webOffset;
323 // Precedence (--home-dir > worktree .t3 > ambient T3CODE_HOME) is resolved
324 // by the caller; an unset t3Home here genuinely means "use the default".
325 const configuredBaseDir = t3Home?.trim() || undefined;
326 const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
327 const isDesktopMode = mode === "dev:desktop";
328
329 const output: NodeJS.ProcessEnv = {
330 ...baseEnv,
331 PORT: String(webPort),
332 VITE_DEV_SERVER_URL:
333 devUrl?.toString() ??
334 `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
335 };
336
337 if (configuredBaseDir !== undefined) {
338 output.T3CODE_HOME = resolvedBaseDir;
339 } else {
340 delete output.T3CODE_HOME;
341 }
342
343 // Managed-service context must not leak into a separately launched dev server.
344 delete output.T3_SERVICE_LAUNCHER_CONTEXT;
345 delete output.T3_BOOT_SERVICE_UNIT;
346 delete output.T3CODE_DESKTOP_WS_URL;
347 output.T3CODE_PORT = String(serverPort);
348
349 if (isDesktopMode) {
350 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
351 delete output.T3CODE_MODE;
352 delete output.T3CODE_NO_BROWSER;
353 delete output.T3CODE_HOST;
354 } else {
355 // Inherited HOST would pin Vite's HMR connection to the wrong interface.
356 delete output.HOST;
357 output.T3CODE_MODE = "web";
358 output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
359 if (host !== undefined) output.T3CODE_HOST = host;
360 }
361
362 if (mode === "dev" || mode === "dev:web") {
363 // Remote browsers use Vite's proxy. The marker also prevents .env files
364 // from restoring localhost URLs when vite.config.ts loads the environment.
365 delete output.VITE_HTTP_URL;
366 delete output.VITE_WS_URL;
367 output.T3CODE_SINGLE_ORIGIN_DEV = "1";
368 } else {
369 const backendHost = isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost";
370 output.VITE_HTTP_URL = `http://${backendHost}:${serverPort}`;
371 output.VITE_WS_URL = `ws://${backendHost}:${serverPort}`;
372 delete output.T3CODE_SINGLE_ORIGIN_DEV;
373 }
374
375 if (autoBootstrapProjectFromCwd !== undefined) {
376 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
377 } else {
378 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
379 }
380
381 if (logWebSocketEvents !== undefined) {
382 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
383 } else {
384 delete output.T3CODE_LOG_WS_EVENTS;
385 }
386
387 return output;
388 });
389}
390
391function portPairForOffset(offset: number): {
392 readonly serverPort: number;
393 readonly webPort: number;
394} {
395 return {
396 serverPort: BASE_SERVER_PORT + offset,
397 webPort: BASE_WEB_PORT + offset,
398 };
399}
400
401export function checkPortAvailabilityOnHosts<R>(
402 port: number,
403 hosts: ReadonlyArray<string>,
404 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
405): Effect.Effect<boolean, never, R> {
406 return Effect.gen(function* () {
407 for (const host of hosts) {
408 if (!(yield* canListenOnHost(port, host))) {
409 return false;
410 }
411 }
412
413 return true;
414 });
415}
416
417/**
418 * Hosts to probe for a dev server bound to `configuredHost`.
419 *
420 * Loopback is always checked because the web server and the desktop renderer
421 * target reach it there. When `--host`/`T3CODE_HOST` moves the backend onto
422 * another interface, that interface decides whether the bind actually
423 * succeeds — probing only loopback would hand back a port that is free here
424 * and taken there, and the server would fail to start.
425 *
426 * `configuredHost` applies to the *backend* only. Vite takes its bind address
427 * from `HOST`, which the runner sets for desktop alone, so the web port stays
428 * on loopback and must not be judged against the backend's interface —
429 * a port free on loopback but busy on that interface would otherwise be
430 * rejected for a server that was never going to bind there.
431 */
432export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
433 const host = configuredHost?.trim();
434 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
435 return DEV_PORT_PROBE_HOSTS;
436 }
437 return [...DEV_PORT_PROBE_HOSTS, host];
438}
439
440const makeDefaultCheckPortAvailability =
441 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
442 (port, role) =>
443 Effect.gen(function* () {
444 const net = yield* NetService.NetService;
445 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
446 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
447 net.canListenOnHost(candidatePort, host),
448 );
449 });
450
451const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
452
453interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
454 readonly startOffset: number;
455 readonly requireServerPort: boolean;
456 readonly requireWebPort: boolean;
457 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
458}
459
460export function findFirstAvailableOffset<R = NetService.NetService>({
461 startOffset,
462 requireServerPort,
463 requireWebPort,
464 checkPortAvailability,
465}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerPortExhaustedError, R> {
466 return Effect.gen(function* () {
467 const checkPort = (checkPortAvailability ??
468 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
469
470 for (let candidate = startOffset; ; candidate += 1) {
471 const { serverPort, webPort } = portPairForOffset(candidate);
472 const serverPortOutOfRange = serverPort > MAX_PORT;
473 const webPortOutOfRange = webPort > MAX_PORT;
474
475 if (
476 (requireServerPort && serverPortOutOfRange) ||
477 (requireWebPort && webPortOutOfRange) ||
478 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
479 ) {
480 break;
481 }
482
483 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
484 continue;
485 }
486
487 const checks: Array<Effect.Effect<boolean, never, R>> = [];
488 if (requireServerPort) {
489 checks.push(checkPort(serverPort, "server"));
490 }
491 if (requireWebPort) {
492 checks.push(checkPort(webPort, "web"));
493 }
494
495 if (checks.length === 0) {
496 return candidate;
497 }
498
499 const availability = yield* Effect.all(checks);
500 if (availability.every(Boolean)) {
501 return candidate;
502 }
503 }
504
505 return yield* new DevRunnerPortExhaustedError({
506 startOffset,
507 requireServerPort,
508 requireWebPort,
509 baseServerPort: BASE_SERVER_PORT,
510 baseWebPort: BASE_WEB_PORT,
511 maximumPort: MAX_PORT,
512 });
513 });
514}
515
516interface ResolveModePortOffsetsInput<R = NetService.NetService> {
517 readonly mode: DevMode;
518 readonly startOffset: number;
519 readonly hasExplicitServerPort: boolean;
520 readonly hasExplicitDevUrl: boolean;
521 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
522}
523
524export function resolveModePortOffsets<R = NetService.NetService>({
525 mode,
526 startOffset,
527 hasExplicitServerPort,
528 hasExplicitDevUrl,
529 checkPortAvailability,
530}: ResolveModePortOffsetsInput<R>): Effect.Effect<
531 { readonly serverOffset: number; readonly webOffset: number },
532 DevRunnerPortExhaustedError,
533 R
534> {
535 return Effect.gen(function* () {
536 const checkPort = (checkPortAvailability ??
537 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
538
539 if (mode === "dev:web") {
540 if (hasExplicitDevUrl) {
541 return { serverOffset: startOffset, webOffset: startOffset };
542 }
543
544 const webOffset = yield* findFirstAvailableOffset({
545 startOffset,
546 requireServerPort: false,
547 requireWebPort: true,
548 checkPortAvailability: checkPort,
549 });
550 return { serverOffset: startOffset, webOffset };
551 }
552
553 if (mode === "dev:server") {
554 if (hasExplicitServerPort) {
555 return { serverOffset: startOffset, webOffset: startOffset };
556 }
557
558 const serverOffset = yield* findFirstAvailableOffset({
559 startOffset,
560 requireServerPort: true,
561 requireWebPort: false,
562 checkPortAvailability: checkPort,
563 });
564 return { serverOffset, webOffset: serverOffset };
565 }
566
567 const sharedOffset = yield* findFirstAvailableOffset({
568 startOffset,
569 requireServerPort: !hasExplicitServerPort,
570 requireWebPort: !hasExplicitDevUrl,
571 checkPortAvailability: checkPort,
572 });
573
574 return { serverOffset: sharedOffset, webOffset: sharedOffset };
575 });
576}
577
578interface DevRunnerCliInput {
579 readonly mode: DevMode;
580 readonly t3Home: string | undefined;
581 readonly browser: boolean | undefined;
582 readonly autoBootstrapProjectFromCwd: boolean | undefined;
583 readonly logWebSocketEvents: boolean | undefined;
584 readonly host: string | undefined;
585 readonly port: number | undefined;
586 readonly devUrl: URL | undefined;
587 readonly dryRun: boolean;
588 readonly share: boolean;
589 readonly runArgs: ReadonlyArray<string>;
590}
591
592export function runDevRunnerWithInput(input: DevRunnerCliInput) {
593 return Effect.gen(function* () {
594 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
595 Effect.mapError(
596 (cause) =>
597 new DevRunnerConfigurationError({
598 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
599 cause,
600 }),
601 ),
602 );
603
604 // Single-origin browser dev proxies the backend at localhost. A wildcard
605 // bind still answers there; a specific non-loopback interface does not,
606 // which breaks every proxied request in a way that reads as "server is
607 // broken" rather than "flag combination is unsupported". Reject it up
608 // front instead. (dev:server and dev:desktop don't proxy — untouched.)
609 if (
610 (input.mode === "dev" || input.mode === "dev:web") &&
611 input.host !== undefined &&
612 !isProxiableBindHost(input.host)
613 ) {
614 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
615 }
616
617 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);
618
619 const { offset, source } = yield* resolveOffset({
620 portOffset,
621 devInstance,
622 worktreePath,
623 });
624
625 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
626 mode: input.mode,
627 startOffset: offset,
628 hasExplicitServerPort: input.port !== undefined,
629 hasExplicitDevUrl: input.devUrl !== undefined,
630 // A non-loopback bind host decides whether the backend can actually take
631 // the port, so it has to be probed alongside loopback.
632 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
633 });
634
635 const hostEnvironment = yield* HostProcessEnvironment;
636 // A dev server started inside a worktree defaults to that worktree's own
637 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
638 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
639 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcessWorkingDirectory);
640 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
641 // as one would skip the worktree default and land on the shared home —
642 // exactly the outcome this precedence exists to prevent.
643 const resolvedT3Home =
644 (input.t3Home?.trim() || undefined) ??
645 worktreeHome ??
646 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
647 const env = yield* createDevRunnerEnv({
648 mode: input.mode,
649 baseEnv: hostEnvironment,
650 serverOffset,
651 webOffset,
652 t3Home: resolvedT3Home,
653 browser: input.browser,
654 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
655 logWebSocketEvents: input.logWebSocketEvents,
656 host: input.host,
657 port: input.port,
658 devUrl: input.devUrl,
659 });
660
661 const selectionSuffix =
662 serverOffset !== offset || webOffset !== offset
663 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
664 : "";
665 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
666
667 yield* Effect.logInfo(
668 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
669 );
670
671 // Before the share block: --dry-run only resolves and prints. Sharing would
672 // replace, then tear down, whatever mapping the port already had — a
673 // surprising side effect from a command documented as inert.
674 if (input.dryRun) {
675 return;
676 }
677
678 const sharedWebPort = BASE_WEB_PORT + webOffset;
679 if (input.share) {
680 if (input.mode === "dev:server") {
681 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
682 } else if (input.mode === "dev:desktop") {
683 // Desktop is not single-origin: the renderer gets VITE_HTTP_URL and
684 // VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI
685 // and then watch it dial its own 127.0.0.1 for the backend. Worse,
686 // sharing would overwrite VITE_DEV_SERVER_URL, which is the origin
687 // Electron itself loads the renderer from. Refuse rather than hand out
688 // a URL that is broken in a way the user cannot see.
689 yield* Effect.logWarning(
690 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
691 );
692 } else {
693 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
694 // process (and reboots), so the cleanup has to be registered atomically
695 // with creating it. An interrupt landing in between would otherwise
696 // leave a mapping pointing at a port nothing is listening on.
697 //
698 // Deliberately no ownership tracking beyond that: if a second runner
699 // takes this port during a fast restart, the first's exit can briefly
700 // tear down the new mapping — visible (the URL stops working) and fixed
701 // by re-running --share. A lease protocol closing that window existed
702 // and was removed as more machinery than a dev convenience warrants.
703 //
704 // A tailnet that isn't up shouldn't stop the dev server from starting —
705 // warn, and carry on serving locally.
706 const shared = yield* Effect.acquireRelease(
707 shareDevServer({ webPort: sharedWebPort }),
708 () =>
709 // Serve config outlives this process, so a cleanup that did not
710 // take leaves a tailnet URL pointing at a port nothing serves.
711 unshareDevServer(sharedWebPort).pipe(
712 Effect.flatMap((result) =>
713 result.cleared
714 ? Effect.void
715 : Effect.logWarning(
716 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
717 result.explanation ? `: ${result.explanation}` : ""
718 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
719 ),
720 ),
721 ),
722 ).pipe(
723 Effect.tapError((error: DevShareError) =>
724 Effect.logWarning(
725 `[dev-runner] could not share on the tailnet: ${error.message}${
726 error.hint ? ` — ${error.hint}` : ""
727 }`,
728 ),
729 ),
730 Effect.option,
731 Effect.map(Option.getOrUndefined),
732 );
733
734 if (shared) {
735 // The app is reached from the tailnet origin. Vite already allows
736 // *.ts.net hosts; the backend needs the origin for credentialed
737 // requests that bypass the proxy (desktop renderer, direct calls).
738 env.T3CODE_DEV_ALLOWED_ORIGINS = [
739 env.T3CODE_DEV_ALLOWED_ORIGINS,
740 new URL(shared.url).origin,
741 ]
742 .filter((entry) => entry && entry.length > 0)
743 .join(",");
744 // The server builds its pairing URL from this, so the URL printed at
745 // startup is already the shareable one — no rewriting by hand. An
746 // explicit --dev-url still wins.
747 if (input.devUrl === undefined) {
748 env.VITE_DEV_SERVER_URL = shared.url;
749 }
750 // A shared origin serves a remote browser, where unbundled dev's
751 // per-module requests each pay a tailnet round trip — a cold module
752 // graph takes minutes to first paint. Bundled dev collapses that to
753 // a few chunk requests. Only defaulted, so T3CODE_BUNDLED_DEV=0
754 // still opts a --share run back out.
755 if (env.T3CODE_BUNDLED_DEV === undefined) {
756 env.T3CODE_BUNDLED_DEV = "1";
757 }
758 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
759 }
760 }
761 }
762
763 const spawnCommand = yield* resolveSpawnCommand(
764 "vp",
765 [...MODE_ARGS[input.mode], ...input.runArgs],
766 { env },
767 );
768 const processContext = {
769 mode: input.mode,
770 executable: "vp" as const,
771 argumentCount: spawnCommand.args.length,
772 shell: spawnCommand.shell,
773 } as const;
774 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
775 stdin: "inherit",
776 stdout: "inherit",
777 stderr: "inherit",
778 env,
779 extendEnv: false,
780 shell: spawnCommand.shell,
781 // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
782 // reach it directly. Effect defaults to detached: true on non-Windows,
783 // which would put the runner in a new group and require manual forwarding.
784 detached: false,
785 forceKillAfter: "1500 millis",
786 }).pipe(
787 Effect.mapError(
788 (cause) =>
789 new DevRunnerProcessError({
790 ...processContext,
791 operation: "spawn",
792 cause,
793 }),
794 ),
795 );
796
797 const exitCode = yield* child.exitCode.pipe(
798 Effect.mapError(
799 (cause) =>
800 new DevRunnerProcessError({
801 ...processContext,
802 operation: "wait-for-exit",
803 cause,
804 }),
805 ),
806 );
807 if (exitCode !== 0) {
808 return yield* new DevRunnerProcessExitError({
809 ...processContext,
810 exitCode,
811 });
812 }
813 });
814}
815
816const devRunnerCli = Command.make("dev-runner", {
817 mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
818 Argument.withDescription("Development mode to run."),
819 ),
820 t3Home: Flag.string("home-dir").pipe(
821 Flag.withDescription(
822 "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.",
823 ),
824 Flag.optional,
825 Flag.map(Option.getOrUndefined),
826 ),
827 browser: Flag.boolean("browser").pipe(
828 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
829 ),
830 autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
831 Flag.withDescription(
832 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
833 ),
834 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
835 ),
836 logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
837 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
838 Flag.withAlias("log-ws-events"),
839 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
840 ),
841 host: Flag.string("host").pipe(
842 Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
843 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
844 ),
845 port: Flag.integer("port").pipe(
846 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
847 Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
848 Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
849 ),
850 devUrl: Flag.string("dev-url").pipe(
851 Flag.withSchema(Schema.URLFromString),
852 Flag.withDescription(
853 "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.",
854 ),
855 Flag.optional,
856 Flag.map(Option.getOrUndefined),
857 ),
858 dryRun: Flag.boolean("dry-run").pipe(
859 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
860 Flag.withDefault(false),
861 ),
862 share: Flag.boolean("share").pipe(
863 Flag.withDescription(
864 "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.",
865 ),
866 Flag.withDefault(false),
867 ),
868 runArgs: Argument.string("run-arg").pipe(
869 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
870 Argument.variadic(),
871 ),
872}).pipe(
873 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
874 Command.withHandler((input) => runDevRunnerWithInput(input)),
875);
876
877const cliRuntimeLayer = Layer.mergeAll(
878 Logger.layer([Logger.consolePretty()]),
879 NodeServices.layer,
880 NetService.layer,
881);
882
883if (import.meta.main) {
884 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
885 Effect.scoped,
886 Effect.provide(cliRuntimeLayer),
887 NodeRuntime.runMain,
888 );
889}