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

main.ts

317 lines10.2 KB

1/**
2 * CliConfig - CLI/runtime bootstrap service definitions.
3 *
4 * Defines startup-only service contracts used while resolving process config
5 * and constructing server runtime layers.
6 *
7 * @module CliConfig
8 */
9import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
10import { Command, Flag } from "effect/unstable/cli";
11import { NetService } from "@t3tools/shared/Net";
12import {
13 DEFAULT_PORT,
14 resolveStaticDir,
15 ServerConfig,
16 type RuntimeMode,
17 type ServerConfigShape,
18} from "./config";
19import { fixPath, resolveStateDir } from "./os-jank";
20import { Open } from "./open";
21import * as SqlitePersistence from "./persistence/Layers/Sqlite";
22import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
23import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
24import { Server } from "./wsServer";
25import { ServerLoggerLive } from "./serverLogger";
26​
27export class StartupError extends Data.TaggedError("StartupError")<{
28 readonly message: string;
29 readonly cause?: unknown;
30}> {}
31​
32interface CliInput {
33 readonly mode: Option.Option<RuntimeMode>;
34 readonly port: Option.Option<number>;
35 readonly host: Option.Option<string>;
36 readonly stateDir: Option.Option<string>;
37 readonly devUrl: Option.Option<URL>;
38 readonly noBrowser: Option.Option<boolean>;
39 readonly authToken: Option.Option<string>;
40 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
41 readonly logWebSocketEvents: Option.Option<boolean>;
43​
44/**
45 * CliConfigShape - Startup helpers required while building server layers.
46 */
47export interface CliConfigShape {
48 /**
49 * Current process working directory.
50 */
51 readonly cwd: string;
52​
53 /**
54 * Apply OS-specific PATH normalization.
55 */
56 readonly fixPath: Effect.Effect<void>;
57​
58 /**
59 * Resolve static web asset directory for server mode.
60 */
61 readonly resolveStaticDir: Effect.Effect<string | undefined>;
63​
64/**
65 * CliConfig - Service tag for startup CLI/runtime helpers.
66 */
67export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
68 "t3/main/CliConfig",
69) {
70 static readonly layer = Layer.effect(
71 CliConfig,
72 Effect.gen(function* () {
73 const fileSystem = yield* FileSystem.FileSystem;
74 const path = yield* Path.Path;
75 return {
76 cwd: process.cwd(),
77 fixPath: Effect.sync(fixPath),
78 resolveStaticDir: resolveStaticDir().pipe(
79 Effect.provideService(FileSystem.FileSystem, fileSystem),
80 Effect.provideService(Path.Path, path),
81 ),
82 } satisfies CliConfigShape;
83 }),
84 );
86​
87const CliEnvConfig = Config.all({
88 mode: Config.string("T3CODE_MODE").pipe(
89 Config.option,
90 Config.map(
91 Option.match<RuntimeMode, string>({
92 onNone: () => "web",
93 onSome: (value) => (value === "desktop" ? "desktop" : "web"),
94 }),
95 ),
96 ),
97 port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
98 host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
99 stateDir: Config.string("T3CODE_STATE_DIR").pipe(
100 Config.option,
101 Config.map(Option.getOrUndefined),
102 ),
103 devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
104 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
105 Config.option,
106 Config.map(Option.getOrUndefined),
107 ),
108 authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
109 Config.option,
110 Config.map(Option.getOrUndefined),
111 ),
112 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
113 Config.option,
114 Config.map(Option.getOrUndefined),
115 ),
116 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
117 Config.option,
118 Config.map(Option.getOrUndefined),
119 ),
120});
121​
122const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
123 Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
124​
125const ServerConfigLive = (input: CliInput) =>
126 Layer.effect(
127 ServerConfig,
128 Effect.gen(function* () {
129 const cliConfig = yield* CliConfig;
130 const { findAvailablePort } = yield* NetService;
131 const env = yield* CliEnvConfig.asEffect().pipe(
132 Effect.mapError(
133 (cause) =>
134 new StartupError({ message: "Failed to read environment configuration", cause }),
135 ),
136 );
137​
138 const mode = Option.getOrElse(input.mode, () => env.mode);
139​
140 const port = yield* Option.match(input.port, {
141 onSome: (value) => Effect.succeed(value),
142 onNone: () => {
143 if (env.port) {
144 return Effect.succeed(env.port);
145 }
146 if (mode === "desktop") {
147 return Effect.succeed(DEFAULT_PORT);
148 }
149 return findAvailablePort(DEFAULT_PORT);
150 },
151 });
152 const stateDir = yield* resolveStateDir(
153 Option.getOrUndefined(input.stateDir) ?? env.stateDir,
154 );
155 const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
156 const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
157 const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
158 const autoBootstrapProjectFromCwd = resolveBooleanFlag(
159 input.autoBootstrapProjectFromCwd,
160 env.autoBootstrapProjectFromCwd ?? mode === "web",
161 );
162 const logWebSocketEvents = resolveBooleanFlag(
163 input.logWebSocketEvents,
164 env.logWebSocketEvents ?? Boolean(devUrl),
165 );
166 const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
167 const { join } = yield* Path.Path;
168 const keybindingsConfigPath = join(stateDir, "keybindings.json");
169 const host =
170 Option.getOrUndefined(input.host) ??
171 env.host ??
172 (mode === "desktop" ? "127.0.0.1" : undefined);
173​
174 const config: ServerConfigShape = {
175 mode,
176 port,
177 cwd: cliConfig.cwd,
178 keybindingsConfigPath,
179 host,
180 stateDir,
181 staticDir,
182 devUrl,
183 noBrowser,
184 authToken,
185 autoBootstrapProjectFromCwd,
186 logWebSocketEvents,
187 } satisfies ServerConfigShape;
188​
189 return config;
190 }),
191 );
192​
193const LayerLive = (input: CliInput) =>
194 Layer.empty.pipe(
195 Layer.provideMerge(makeServerRuntimeServicesLayer()),
196 Layer.provideMerge(makeServerProviderLayer()),
197 Layer.provideMerge(ProviderHealthLive),
198 Layer.provideMerge(SqlitePersistence.layerConfig),
199 Layer.provideMerge(ServerLoggerLive),
200 Layer.provideMerge(ServerConfigLive(input)),
201 );
202​
203const isWildcardHost = (host: string | undefined): boolean =>
204 host === "0.0.0.0" || host === "::" || host === "[::]";
205​
206const formatHostForUrl = (host: string): string =>
207 host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
208​
209const makeServerProgram = (input: CliInput) =>
210 Effect.gen(function* () {
211 const cliConfig = yield* CliConfig;
212 const { start, stopSignal } = yield* Server;
213 const openDeps = yield* Open;
214 yield* cliConfig.fixPath;
215​
216 const config = yield* ServerConfig;
217​
218 if (!config.devUrl && !config.staticDir) {
219 yield* Effect.logWarning(
220 "web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
221 {
222 hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
223 },
224 );
225 }
226​
227 yield* start;
228​
229 const localUrl = `http://localhost:${config.port}`;
230 const bindUrl =
231 config.host && !isWildcardHost(config.host)
232 ? `http://${formatHostForUrl(config.host)}:${config.port}`
233 : localUrl;
234 const { authToken, devUrl, ...safeConfig } = config;
235 yield* Effect.logInfo("T3 Code running", {
236 ...safeConfig,
237 devUrl: devUrl?.toString(),
238 authEnabled: Boolean(authToken),
239 });
240​
241 if (!config.noBrowser) {
242 const target = config.devUrl?.toString() ?? bindUrl;
243 yield* openDeps.openBrowser(target).pipe(
244 Effect.catch(() =>
245 Effect.logInfo("browser auto-open unavailable", {
246 hint: `Open ${target} in your browser.`,
247 }),
248 ),
249 );
250 }
251​
252 return yield* stopSignal;
253 }).pipe(Effect.provide(LayerLive(input)));
254​
255/**
256 * These flags mirrors the environment variables and the config shape.
257 */
258​
259const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
260 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
261 Flag.optional,
262);
263const portFlag = Flag.integer("port").pipe(
264 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
265 Flag.withDescription("Port for the HTTP/WebSocket server."),
266 Flag.optional,
267);
268const hostFlag = Flag.string("host").pipe(
269 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
270 Flag.optional,
271);
272const stateDirFlag = Flag.string("state-dir").pipe(
273 Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
274 Flag.optional,
275);
276const devUrlFlag = Flag.string("dev-url").pipe(
277 Flag.withSchema(Schema.URLFromString),
278 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
279 Flag.optional,
280);
281const noBrowserFlag = Flag.boolean("no-browser").pipe(
282 Flag.withDescription("Disable automatic browser opening."),
283 Flag.optional,
284);
285const authTokenFlag = Flag.string("auth-token").pipe(
286 Flag.withDescription("Auth token required for WebSocket connections."),
287 Flag.withAlias("token"),
288 Flag.optional,
289);
290const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
291 Flag.withDescription(
292 "Create a project for the current working directory on startup when missing.",
293 ),
294 Flag.optional,
295);
296const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
297 Flag.withDescription(
298 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
299 ),
300 Flag.withAlias("log-ws-events"),
301 Flag.optional,
302);
303​
304export const t3Cli = Command.make("t3", {
305 mode: modeFlag,
306 port: portFlag,
307 host: hostFlag,
308 stateDir: stateDirFlag,
309 devUrl: devUrlFlag,
310 noBrowser: noBrowserFlag,
311 authToken: authTokenFlag,
312 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
313 logWebSocketEvents: logWebSocketEventsFlag,
314}).pipe(
315 Command.withDescription("Run the T3 Code server."),
316 Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
317);