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

main.ts

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