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

dev-runner.ts

914 lines33.1 KB

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 );
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];
104​
105export function isBrowserAllowedPort(port: number): boolean {
106 return !FETCH_BAD_PORTS.has(port);
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 }
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 }
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 }
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 }
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 }
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 }
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" });
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 });
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;
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 if (!isDesktopMode) {
344 output.T3CODE_PORT = String(serverPort);
345 // HOST is Vite's own bind address, and the desktop branch below is the
346 // only place we set it. An inherited one (an exported HOST, a container,
347 // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
348 // its HMR socket to that address — see the `explicitHost` gate in
349 // apps/web/vite.config.ts. Over a shared origin that is invisible: the
350 // page loads and only HMR quietly dials the wrong machine.
351 delete output.HOST;
352 if (mode === "dev" || mode === "dev:web") {
353 // Browser dev is single-origin: everything (including /ws) is proxied
354 // through Vite, so the client must resolve its backend from
355 // window.location.origin rather than a baked-in localhost URL. See
356 // resolveConfiguredPrimaryTarget in apps/web/src/environments/primary/target.ts
357 // — it only defers to the origin when both of these are absent. Baking
358 // localhost here is what breaks any non-localhost origin (tailnet, LAN,
359 // phone): the remote browser dials its own machine.
360 delete output.VITE_HTTP_URL;
361 delete output.VITE_WS_URL;
362 // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
363 // which merges `.env`/`.env.local` *under* this env, so a developer
364 // with either URL in their `.env` would get it back and silently lose
365 // single-origin mode. This states the intent positively so Vite can
366 // ignore those values rather than infer from their absence.
367 output.T3CODE_SINGLE_ORIGIN_DEV = "1";
368 } else {
369 output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
370 output.VITE_WS_URL = `ws://localhost:${serverPort}`;
371 delete output.T3CODE_SINGLE_ORIGIN_DEV;
372 }
373 } else {
374 output.T3CODE_PORT = String(serverPort);
375 output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
376 output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
377 // Desktop pins the renderer to loopback on purpose; an ambient marker
378 // must not make Vite drop those URLs.
379 delete output.T3CODE_SINGLE_ORIGIN_DEV;
380 delete output.T3CODE_MODE;
381 delete output.T3CODE_NO_BROWSER;
382 delete output.T3CODE_HOST;
383 }
384​
385 if (!isDesktopMode && host !== undefined) {
386 output.T3CODE_HOST = host;
387 }
388​
389 if (!isDesktopMode) {
390 output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
391 }
392​
393 if (autoBootstrapProjectFromCwd !== undefined) {
394 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
395 } else {
396 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
397 }
398​
399 if (logWebSocketEvents !== undefined) {
400 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
401 } else {
402 delete output.T3CODE_LOG_WS_EVENTS;
403 }
404​
405 if (mode === "dev") {
406 output.T3CODE_MODE = "web";
407 delete output.T3CODE_DESKTOP_WS_URL;
408 }
409​
410 if (mode === "dev:server" || mode === "dev:web") {
411 output.T3CODE_MODE = "web";
412 delete output.T3CODE_DESKTOP_WS_URL;
413 }
414​
415 if (isDesktopMode) {
416 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
417 delete output.T3CODE_DESKTOP_WS_URL;
418 }
419​
420 return output;
421 });
423​
424function portPairForOffset(offset: number): {
425 readonly serverPort: number;
426 readonly webPort: number;
427} {
428 return {
429 serverPort: BASE_SERVER_PORT + offset,
430 webPort: BASE_WEB_PORT + offset,
431 };
433​
434export function checkPortAvailabilityOnHosts<R>(
435 port: number,
436 hosts: ReadonlyArray<string>,
437 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
438): Effect.Effect<boolean, never, R> {
439 return Effect.gen(function* () {
440 for (const host of hosts) {
441 if (!(yield* canListenOnHost(port, host))) {
442 return false;
443 }
444 }
445​
446 return true;
447 });
449​
450/**
451 * Hosts to probe for a dev server bound to `configuredHost`.
452 *
453 * Loopback is always checked because the web server and the desktop renderer
454 * target reach it there. When `--host`/`T3CODE_HOST` moves the backend onto
455 * another interface, that interface decides whether the bind actually
456 * succeeds — probing only loopback would hand back a port that is free here
457 * and taken there, and the server would fail to start.
458 *
459 * `configuredHost` applies to the *backend* only. Vite takes its bind address
460 * from `HOST`, which the runner sets for desktop alone, so the web port stays
461 * on loopback and must not be judged against the backend's interface —
462 * a port free on loopback but busy on that interface would otherwise be
463 * rejected for a server that was never going to bind there.
464 */
465export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
466 const host = configuredHost?.trim();
467 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
468 return DEV_PORT_PROBE_HOSTS;
469 }
470 return [...DEV_PORT_PROBE_HOSTS, host];
472​
473const makeDefaultCheckPortAvailability =
474 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
475 (port, role) =>
476 Effect.gen(function* () {
477 const net = yield* NetService.NetService;
478 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
479 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
480 net.canListenOnHost(candidatePort, host),
481 );
482 });
483​
484const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
485​
486interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
487 readonly startOffset: number;
488 readonly requireServerPort: boolean;
489 readonly requireWebPort: boolean;
490 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
492​
493export function findFirstAvailableOffset<R = NetService.NetService>({
494 startOffset,
495 requireServerPort,
496 requireWebPort,
497 checkPortAvailability,
498}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerPortExhaustedError, R> {
499 return Effect.gen(function* () {
500 const checkPort = (checkPortAvailability ??
501 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
502​
503 for (let candidate = startOffset; ; candidate += 1) {
504 const { serverPort, webPort } = portPairForOffset(candidate);
505 const serverPortOutOfRange = serverPort > MAX_PORT;
506 const webPortOutOfRange = webPort > MAX_PORT;
507​
508 if (
509 (requireServerPort && serverPortOutOfRange) ||
510 (requireWebPort && webPortOutOfRange) ||
511 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
512 ) {
513 break;
514 }
515​
516 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
517 continue;
518 }
519​
520 const checks: Array<Effect.Effect<boolean, never, R>> = [];
521 if (requireServerPort) {
522 checks.push(checkPort(serverPort, "server"));
523 }
524 if (requireWebPort) {
525 checks.push(checkPort(webPort, "web"));
526 }
527​
528 if (checks.length === 0) {
529 return candidate;
530 }
531​
532 const availability = yield* Effect.all(checks);
533 if (availability.every(Boolean)) {
534 return candidate;
535 }
536 }
537​
538 return yield* new DevRunnerPortExhaustedError({
539 startOffset,
540 requireServerPort,
541 requireWebPort,
542 baseServerPort: BASE_SERVER_PORT,
543 baseWebPort: BASE_WEB_PORT,
544 maximumPort: MAX_PORT,
545 });
546 });
548​
549interface ResolveModePortOffsetsInput<R = NetService.NetService> {
550 readonly mode: DevMode;
551 readonly startOffset: number;
552 readonly hasExplicitServerPort: boolean;
553 readonly hasExplicitDevUrl: boolean;
554 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
556​
557export function resolveModePortOffsets<R = NetService.NetService>({
558 mode,
559 startOffset,
560 hasExplicitServerPort,
561 hasExplicitDevUrl,
562 checkPortAvailability,
563}: ResolveModePortOffsetsInput<R>): Effect.Effect<
564 { readonly serverOffset: number; readonly webOffset: number },
565 DevRunnerPortExhaustedError,
566 R
567> {
568 return Effect.gen(function* () {
569 const checkPort = (checkPortAvailability ??
570 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
571​
572 if (mode === "dev:web") {
573 if (hasExplicitDevUrl) {
574 return { serverOffset: startOffset, webOffset: startOffset };
575 }
576​
577 const webOffset = yield* findFirstAvailableOffset({
578 startOffset,
579 requireServerPort: false,
580 requireWebPort: true,
581 checkPortAvailability: checkPort,
582 });
583 return { serverOffset: startOffset, webOffset };
584 }
585​
586 if (mode === "dev:server") {
587 if (hasExplicitServerPort) {
588 return { serverOffset: startOffset, webOffset: startOffset };
589 }
590​
591 const serverOffset = yield* findFirstAvailableOffset({
592 startOffset,
593 requireServerPort: true,
594 requireWebPort: false,
595 checkPortAvailability: checkPort,
596 });
597 return { serverOffset, webOffset: serverOffset };
598 }
599​
600 const sharedOffset = yield* findFirstAvailableOffset({
601 startOffset,
602 requireServerPort: !hasExplicitServerPort,
603 requireWebPort: !hasExplicitDevUrl,
604 checkPortAvailability: checkPort,
605 });
606​
607 return { serverOffset: sharedOffset, webOffset: sharedOffset };
608 });
610​
611interface DevRunnerCliInput {
612 readonly mode: DevMode;
613 readonly t3Home: string | undefined;
614 readonly browser: boolean | undefined;
615 readonly autoBootstrapProjectFromCwd: boolean | undefined;
616 readonly logWebSocketEvents: boolean | undefined;
617 readonly host: string | undefined;
618 readonly port: number | undefined;
619 readonly devUrl: URL | undefined;
620 readonly dryRun: boolean;
621 readonly share: boolean;
622 readonly runArgs: ReadonlyArray<string>;
624​
625export function runDevRunnerWithInput(input: DevRunnerCliInput) {
626 return Effect.gen(function* () {
627 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
628 Effect.mapError(
629 (cause) =>
630 new DevRunnerConfigurationError({
631 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
632 cause,
633 }),
634 ),
635 );
636​
637 // Single-origin browser dev proxies the backend at localhost. A wildcard
638 // bind still answers there; a specific non-loopback interface does not,
639 // which breaks every proxied request in a way that reads as "server is
640 // broken" rather than "flag combination is unsupported". Reject it up
641 // front instead. (dev:server and dev:desktop don't proxy — untouched.)
642 if (
643 (input.mode === "dev" || input.mode === "dev:web") &&
644 input.host !== undefined &&
645 !isProxiableBindHost(input.host)
646 ) {
647 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
648 }
649​
650 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);
651​
652 const { offset, source } = yield* resolveOffset({
653 portOffset,
654 devInstance,
655 worktreePath,
656 });
657​
658 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
659 mode: input.mode,
660 startOffset: offset,
661 hasExplicitServerPort: input.port !== undefined,
662 hasExplicitDevUrl: input.devUrl !== undefined,
663 // A non-loopback bind host decides whether the backend can actually take
664 // the port, so it has to be probed alongside loopback.
665 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
666 });
667​
668 const hostEnvironment = yield* HostProcessEnvironment;
669 // A dev server started inside a worktree defaults to that worktree's own
670 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
671 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
672 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcessWorkingDirectory);
673 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
674 // as one would skip the worktree default and land on the shared home —
675 // exactly the outcome this precedence exists to prevent.
676 const resolvedT3Home =
677 (input.t3Home?.trim() || undefined) ??
678 worktreeHome ??
679 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
680 const env = yield* createDevRunnerEnv({
681 mode: input.mode,
682 baseEnv: hostEnvironment,
683 serverOffset,
684 webOffset,
685 t3Home: resolvedT3Home,
686 browser: input.browser,
687 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
688 logWebSocketEvents: input.logWebSocketEvents,
689 host: input.host,
690 port: input.port,
691 devUrl: input.devUrl,
692 });
693​
694 const selectionSuffix =
695 serverOffset !== offset || webOffset !== offset
696 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
697 : "";
698 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
699​
700 yield* Effect.logInfo(
701 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
702 );
703​
704 // Before the share block: --dry-run only resolves and prints. Sharing would
705 // replace, then tear down, whatever mapping the port already had — a
706 // surprising side effect from a command documented as inert.
707 if (input.dryRun) {
708 return;
709 }
710​
711 const sharedWebPort = BASE_WEB_PORT + webOffset;
712 if (input.share) {
713 if (input.mode === "dev:server") {
714 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
715 } else if (input.mode === "dev:desktop") {
716 // Desktop is not single-origin: the renderer gets VITE_HTTP_URL and
717 // VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI
718 // and then watch it dial its own 127.0.0.1 for the backend. Worse,
719 // sharing would overwrite VITE_DEV_SERVER_URL, which is the origin
720 // Electron itself loads the renderer from. Refuse rather than hand out
721 // a URL that is broken in a way the user cannot see.
722 yield* Effect.logWarning(
723 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
724 );
725 } else {
726 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
727 // process (and reboots), so the cleanup has to be registered atomically
728 // with creating it. An interrupt landing in between would otherwise
729 // leave a mapping pointing at a port nothing is listening on.
730 //
731 // Deliberately no ownership tracking beyond that: if a second runner
732 // takes this port during a fast restart, the first's exit can briefly
733 // tear down the new mapping — visible (the URL stops working) and fixed
734 // by re-running --share. A lease protocol closing that window existed
735 // and was removed as more machinery than a dev convenience warrants.
736 //
737 // A tailnet that isn't up shouldn't stop the dev server from starting —
738 // warn, and carry on serving locally.
739 const shared = yield* Effect.acquireRelease(
740 shareDevServer({ webPort: sharedWebPort }),
741 () =>
742 // Serve config outlives this process, so a cleanup that did not
743 // take leaves a tailnet URL pointing at a port nothing serves.
744 unshareDevServer(sharedWebPort).pipe(
745 Effect.flatMap((result) =>
746 result.cleared
747 ? Effect.void
748 : Effect.logWarning(
749 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
750 result.explanation ? `: ${result.explanation}` : ""
751 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
752 ),
753 ),
754 ),
755 ).pipe(
756 Effect.tapError((error: DevShareError) =>
757 Effect.logWarning(
758 `[dev-runner] could not share on the tailnet: ${error.message}${
759 error.hint ? ` — ${error.hint}` : ""
760 }`,
761 ),
762 ),
763 Effect.option,
764 Effect.map(Option.getOrUndefined),
765 );
766​
767 if (shared) {
768 // The app is reached from the tailnet origin. Vite already allows
769 // *.ts.net hosts; the backend needs the origin for credentialed
770 // requests that bypass the proxy (desktop renderer, direct calls).
771 env.T3CODE_DEV_ALLOWED_ORIGINS = [
772 env.T3CODE_DEV_ALLOWED_ORIGINS,
773 new URL(shared.url).origin,
774 ]
775 .filter((entry) => entry && entry.length > 0)
776 .join(",");
777 // The server builds its pairing URL from this, so the URL printed at
778 // startup is already the shareable one — no rewriting by hand. An
779 // explicit --dev-url still wins.
780 if (input.devUrl === undefined) {
781 env.VITE_DEV_SERVER_URL = shared.url;
782 }
783 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
784 }
785 }
786 }
787​
788 const spawnCommand = yield* resolveSpawnCommand(
789 "vp",
790 [...MODE_ARGS[input.mode], ...input.runArgs],
791 { env },
792 );
793 const processContext = {
794 mode: input.mode,
795 executable: "vp" as const,
796 argumentCount: spawnCommand.args.length,
797 shell: spawnCommand.shell,
798 } as const;
799 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
800 stdin: "inherit",
801 stdout: "inherit",
802 stderr: "inherit",
803 env,
804 extendEnv: false,
805 shell: spawnCommand.shell,
806 // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
807 // reach it directly. Effect defaults to detached: true on non-Windows,
808 // which would put the runner in a new group and require manual forwarding.
809 detached: false,
810 forceKillAfter: "1500 millis",
811 }).pipe(
812 Effect.mapError(
813 (cause) =>
814 new DevRunnerProcessError({
815 ...processContext,
816 operation: "spawn",
817 cause,
818 }),
819 ),
820 );
821​
822 const exitCode = yield* child.exitCode.pipe(
823 Effect.mapError(
824 (cause) =>
825 new DevRunnerProcessError({
826 ...processContext,
827 operation: "wait-for-exit",
828 cause,
829 }),
830 ),
831 );
832 if (exitCode !== 0) {
833 return yield* new DevRunnerProcessExitError({
834 ...processContext,
835 exitCode,
836 });
837 }
838 });
840​
841const devRunnerCli = Command.make("dev-runner", {
842 mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
843 Argument.withDescription("Development mode to run."),
844 ),
845 t3Home: Flag.string("home-dir").pipe(
846 Flag.withDescription(
847 "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.",
848 ),
849 Flag.optional,
850 Flag.map(Option.getOrUndefined),
851 ),
852 browser: Flag.boolean("browser").pipe(
853 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
854 ),
855 autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
856 Flag.withDescription(
857 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
858 ),
859 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
860 ),
861 logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
862 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
863 Flag.withAlias("log-ws-events"),
864 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
865 ),
866 host: Flag.string("host").pipe(
867 Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
868 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
869 ),
870 port: Flag.integer("port").pipe(
871 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
872 Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
873 Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
874 ),
875 devUrl: Flag.string("dev-url").pipe(
876 Flag.withSchema(Schema.URLFromString),
877 Flag.withDescription(
878 "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.",
879 ),
880 Flag.optional,
881 Flag.map(Option.getOrUndefined),
882 ),
883 dryRun: Flag.boolean("dry-run").pipe(
884 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
885 Flag.withDefault(false),
886 ),
887 share: Flag.boolean("share").pipe(
888 Flag.withDescription(
889 "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.",
890 ),
891 Flag.withDefault(false),
892 ),
893 runArgs: Argument.string("run-arg").pipe(
894 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
895 Argument.variadic(),
896 ),
897}).pipe(
898 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
899 Command.withHandler((input) => runDevRunnerWithInput(input)),
900);
901​
902const cliRuntimeLayer = Layer.mergeAll(
903 Logger.layer([Logger.consolePretty()]),
904 NodeServices.layer,
905 NetService.layer,
906);
907​
908if (import.meta.main) {
909 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
910 Effect.scoped,
911 Effect.provide(cliRuntimeLayer),
912 NodeRuntime.runMain,
913 );