Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
2import * as NodeHttp from "node:http";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6
7import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { EnvironmentOrchestrationHttpApi } from "@t3tools/contracts";
10import * as NetService from "@t3tools/shared/Net";
11import { assert, it } from "@effect/vitest";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as HttpRouter from "effect/unstable/http/HttpRouter";
15import * as HttpServer from "effect/unstable/http/HttpServer";
16import * as HttpApi from "effect/unstable/httpapi/HttpApi";
17import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
18import * as CliError from "effect/unstable/cli/CliError";
19import * as TestConsole from "effect/testing/TestConsole";
20import { Command } from "effect/unstable/cli";
21
22import { cli } from "./bin.ts";
23import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
24import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
25import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
26import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
27import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
28import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
29import {
30 makePersistedServerRuntimeState,
31 persistServerRuntimeState,
32} from "./serverRuntimeState.ts";
33import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
34import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
35import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
36import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
37
38const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
39class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
40
41const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
42const runCliWithRuntime = (args: ReadonlyArray<string>) =>
43 runCli(args).pipe(Effect.provide(CliRuntimeLayer));
44
45const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
46 Effect.gen(function* () {
47 const result = yield* effect;
48 const output =
49 (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
50 "";
51 return { result, output };
52 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
53
54const makeCliTestServerConfig = (baseDir: string) =>
55 Effect.gen(function* () {
56 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
57 return {
58 logLevel: "Info",
59 traceMinLevel: "Info",
60 traceTimingEnabled: true,
61 traceBatchWindowMs: 200,
62 traceMaxBytes: 10 * 1024 * 1024,
63 traceMaxFiles: 10,
64 otlpTracesUrl: undefined,
65 otlpMetricsUrl: undefined,
66 otlpExportIntervalMs: 10_000,
67 otlpServiceName: "t3-server",
68 mode: "web",
69 port: 0,
70 host: "127.0.0.1",
71 cwd: process.cwd(),
72 baseDir,
73 ...derivedPaths,
74 staticDir: undefined,
75 devUrl: undefined,
76 noBrowser: true,
77 startupPresentation: "browser",
78 desktopBootstrapToken: undefined,
79 autoBootstrapProjectFromCwd: false,
80 logWebSocketEvents: false,
81 tailscaleServeEnabled: false,
82 tailscaleServePort: 443,
83 } satisfies ServerConfigShape;
84 });
85
86const makeProjectPersistenceLayer = (config: ServerConfigShape) =>
87 Layer.mergeAll(
88 OrchestrationLayerLive.pipe(
89 Layer.provideMerge(RepositoryIdentityResolverLive),
90 Layer.provideMerge(SqlitePersistenceLayerLive),
91 ),
92 WorkspacePathsLive,
93 ).pipe(
94 Layer.provideMerge(NodeServices.layer),
95 Layer.provide(Layer.succeed(ServerConfig, config)),
96 );
97
98const readPersistedSnapshot = (baseDir: string) =>
99 Effect.gen(function* () {
100 const config = yield* makeCliTestServerConfig(baseDir);
101 return yield* Effect.gen(function* () {
102 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
103 return yield* projectionSnapshotQuery.getSnapshot();
104 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
105 });
106
107const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
108 Effect.gen(function* () {
109 const config = yield* makeCliTestServerConfig(baseDir);
110 const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe(
111 Layer.provide(orchestrationHttpApiLayer),
112 Layer.provide(environmentAuthenticatedAuthLayer),
113 );
114 const appLayer = HttpRouter.serve(routesLayer, {
115 disableListenLog: true,
116 disableLogger: true,
117 }).pipe(
118 Layer.provideMerge(
119 EnvironmentAuth.layer.pipe(
120 Layer.provideMerge(SqlitePersistenceLayerLive),
121 Layer.provide(ServerSecretStore.layer),
122 ),
123 ),
124 Layer.provideMerge(makeProjectPersistenceLayer(config)),
125 Layer.provideMerge(
126 NodeHttpServer.layer(NodeHttp.createServer, {
127 host: "127.0.0.1",
128 port: 0,
129 }),
130 ),
131 Layer.provideMerge(NodeServices.layer),
132 Layer.provide(Layer.succeed(ServerConfig, config)),
133 );
134
135 return yield* Effect.scoped(
136 Effect.gen(function* () {
137 const server = yield* HttpServer.HttpServer;
138 const address = server.address;
139 if (typeof address === "string" || !("port" in address)) {
140 assert.fail(`Expected TCP address, got ${address}`);
141 }
142 yield* persistServerRuntimeState({
143 path: config.serverRuntimeStatePath,
144 state: yield* makePersistedServerRuntimeState({
145 config,
146 port: address.port,
147 }),
148 });
149 return yield* run();
150 }).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
151 );
152 });
153
154it.layer(NodeServices.layer)("bin cli parsing", (it) => {
155 it.effect("accepts the built-in lowercase log-level flag values", () =>
156 runCliWithRuntime(["--log-level", "debug", "--version"]),
157 );
158
159 it.effect("accepts canonical --no-<flag> boolean negation", () =>
160 runCliWithRuntime(["--no-log-websocket-events", "--version"]),
161 );
162
163 it.effect("rejects invalid log-level casing before launching the server", () =>
164 Effect.gen(function* () {
165 const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
166
167 if (!CliError.isCliError(error)) {
168 assert.fail(`Expected CliError, got ${String(error)}`);
169 }
170 if (error._tag !== "InvalidValue") {
171 assert.fail(`Expected InvalidValue, got ${error._tag}`);
172 }
173 assert.equal(error.option, "log-level");
174 assert.equal(error.value, "Debug");
175 }),
176 );
177
178 it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
179 Effect.gen(function* () {
180 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
181
182 const createdOutput = yield* captureStdout(
183 runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
184 );
185 // @effect-diagnostics-next-line preferSchemaOverJson:off
186 const created = JSON.parse(createdOutput.output) as {
187 readonly id: string;
188 readonly credential: string;
189 };
190 const listedOutput = yield* captureStdout(
191 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
192 );
193 // @effect-diagnostics-next-line preferSchemaOverJson:off
194 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
195 readonly id: string;
196 readonly credential?: string;
197 }>;
198
199 assert.equal(typeof created.id, "string");
200 assert.equal(typeof created.credential, "string");
201 assert.equal(created.credential.length > 0, true);
202 assert.equal(listed.length, 1);
203 assert.equal(listed[0]?.id, created.id);
204 assert.equal("credential" in (listed[0] ?? {}), false);
205 }),
206 );
207
208 it.effect("executes auth session subcommands and redacts secrets from list output", () =>
209 Effect.gen(function* () {
210 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
211
212 const issuedOutput = yield* captureStdout(
213 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
214 );
215 // @effect-diagnostics-next-line preferSchemaOverJson:off
216 const issued = JSON.parse(issuedOutput.output) as {
217 readonly sessionId: string;
218 readonly token: string;
219 readonly scopes: ReadonlyArray<string>;
220 };
221 const listedOutput = yield* captureStdout(
222 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
223 );
224 // @effect-diagnostics-next-line preferSchemaOverJson:off
225 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
226 readonly sessionId: string;
227 readonly token?: string;
228 readonly scopes: ReadonlyArray<string>;
229 }>;
230
231 assert.equal(typeof issued.sessionId, "string");
232 assert.equal(typeof issued.token, "string");
233 assert.deepEqual(issued.scopes, [
234 "orchestration:read",
235 "orchestration:operate",
236 "terminal:operate",
237 "review:write",
238 "relay:read",
239 "access:read",
240 "access:write",
241 "relay:write",
242 ]);
243 assert.equal(listed.length, 1);
244 assert.equal(listed[0]?.sessionId, issued.sessionId);
245 assert.deepEqual(listed[0]?.scopes, [
246 "orchestration:read",
247 "orchestration:operate",
248 "terminal:operate",
249 "review:write",
250 "relay:read",
251 "access:read",
252 "access:write",
253 "relay:write",
254 ]);
255 assert.equal("token" in (listed[0] ?? {}), false);
256 }),
257 );
258
259 it.effect("rejects invalid ttl values before running auth commands", () =>
260 Effect.gen(function* () {
261 const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
262 Effect.flip,
263 );
264
265 if (!CliError.isCliError(error)) {
266 assert.fail(`Expected CliError, got ${String(error)}`);
267 }
268 if (error._tag !== "ShowHelp") {
269 assert.fail(`Expected ShowHelp, got ${error._tag}`);
270 }
271 assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
272 const ttlError = error.errors[0] as CliError.CliError | undefined;
273 if (!ttlError || ttlError._tag !== "InvalidValue") {
274 assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
275 }
276 assert.equal(ttlError.option, "ttl");
277 assert.equal(ttlError.value, "soon");
278 assert.isTrue(ttlError.message.includes("Invalid duration"));
279 assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
280 }),
281 );
282
283 it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
284 Effect.gen(function* () {
285 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
286 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
287
288 yield* runCliWithRuntime([
289 "project",
290 "add",
291 workspaceRoot,
292 "--title",
293 "Alpha",
294 "--base-dir",
295 baseDir,
296 ]);
297 const afterAdd = yield* readPersistedSnapshot(baseDir);
298 const addedProject = afterAdd.projects.find(
299 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
300 );
301 assert.isTrue(addedProject !== undefined);
302 assert.equal(addedProject?.title, "Alpha");
303
304 yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
305 const afterRename = yield* readPersistedSnapshot(baseDir);
306 const renamedProject = afterRename.projects.find(
307 (project) => project.id === addedProject?.id,
308 );
309 assert.equal(renamedProject?.title, "Beta");
310 assert.equal(renamedProject?.deletedAt, null);
311
312 yield* runCliWithRuntime([
313 "project",
314 "remove",
315 addedProject?.id ?? "",
316 "--base-dir",
317 baseDir,
318 ]);
319 const afterRemove = yield* readPersistedSnapshot(baseDir);
320 const removedProject = afterRemove.projects.find(
321 (project) => project.id === addedProject?.id,
322 );
323 assert.isTrue((removedProject?.deletedAt ?? null) !== null);
324 }),
325 );
326
327 it.effect("routes project commands through a running server when runtime state is present", () =>
328 Effect.gen(function* () {
329 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-"));
330 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-"));
331
332 yield* withLiveProjectCliServer(baseDir, () =>
333 Effect.gen(function* () {
334 yield* runCliWithRuntime([
335 "project",
336 "add",
337 workspaceRoot,
338 "--title",
339 "Live Project",
340 "--base-dir",
341 baseDir,
342 ]);
343 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
344 const readModel = yield* projectionSnapshotQuery.getSnapshot();
345 const addedProject = readModel.projects.find(
346 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
347 );
348 assert.isTrue(addedProject !== undefined);
349 assert.equal(addedProject?.title, "Live Project");
350 }),
351 );
352 }),
353 );
354
355 it.effect("rejects dev-url on project commands", () =>
356 Effect.gen(function* () {
357 const workspaceRoot = mkdtempSync(
358 join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
359 );
360 const error = yield* runCliWithRuntime([
361 "project",
362 "add",
363 workspaceRoot,
364 "--dev-url",
365 "http://127.0.0.1:5173",
366 ]).pipe(Effect.flip);
367
368 if (!CliError.isCliError(error)) {
369 assert.fail(`Expected CliError, got ${String(error)}`);
370 }
371 if (error._tag !== "ShowHelp") {
372 assert.fail(`Expected ShowHelp, got ${error._tag}`);
373 }
374 assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
375 const optionError = error.errors[0] as CliError.CliError | undefined;
376 if (!optionError || optionError._tag !== "UnrecognizedOption") {
377 assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
378 }
379 assert.equal(optionError.option, "--dev-url");
380 }),
381 );
382});