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

bin.test.ts

357 lines13.1 KB

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