Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import { Command, GlobalFlag } from "effect/cli";
7import * as CliError from "effect/cli/CliError";
8
9import * as ServerConfig from "../config.ts";
10import { awaitLauncherLoss } from "../launcherWatch.ts";
11import { runServer } from "../server.ts";
12import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
13
14const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(Schema.String));
15
16const runServerCommand = (
17 flags: CliServerFlags,
18 options?: {
19 readonly startupPresentation?: ServerConfig.StartupPresentation;
20 readonly forceAutoBootstrapProjectFromCwd?: boolean;
21 readonly rejectRunningServer?: boolean;
22 },
23) =>
24 Effect.gen(function* () {
25 const logLevel = yield* GlobalFlag.LogLevel;
26 const config = yield* resolveServerConfig(flags, logLevel, options);
27 const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));
28 if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;
29 return yield* Effect.raceFirst(
30 run,
31 awaitLauncherLoss().pipe(
32 // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit).
33 Effect.andThen(Effect.interrupt),
34 ),
35 );
36 });
37
38export const runDefaultServerCommand = (flags: CliServerFlags) =>
39 Effect.gen(function* () {
40 if (Option.isSome(flags.cwd)) {
41 const cwd = flags.cwd.value.trim();
42 const fs = yield* FileSystem.FileSystem;
43 const platform = yield* HostProcess.Platform;
44 const explicitPath =
45 cwd === "." ||
46 cwd === ".." ||
47 cwd === "~" ||
48 /[/\\]/.test(cwd) ||
49 (platform === "win32" && /^[a-z]:/i.test(cwd));
50 if (
51 !explicitPath &&
52 (!(yield* fs.exists(cwd)) || (yield* fs.stat(cwd)).type !== "Directory")
53 ) {
54 return yield* new CliError.UserError({
55 cause: cwd,
56 userMessage: `Unknown command ${yield* encodeCommand(cwd)}. Use "t3 --help" for commands or an explicit path such as "t3 ./my-project" for a new directory.`,
57 });
58 }
59 }
60 return yield* runServerCommand(flags, { rejectRunningServer: true });
61 });
62
63export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
64 Command.withDescription("Run the T3 Code server."),
65 Command.withHandler((flags) => runServerCommand(flags, { rejectRunningServer: true })),
66);
67
68export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
69 Command.withDescription(
70 "Run the T3 Code server without opening a browser and print headless pairing details.",
71 ),
72 Command.withHandler((flags) =>
73 runServerCommand(flags, {
74 startupPresentation: "headless",
75 forceAutoBootstrapProjectFromCwd: false,
76 }),
77 ),
78);