Open History to see the last commit
1import {
2 AuthAdministrativeScopes,
3 CommandId,
4 EnvironmentHttpApi,
5 EnvironmentHttpCommonError,
6 type ProjectMutation,
7 type ProjectSnapshot,
8 ProjectId,
9} from "@t3tools/contracts";
10import * as Console from "effect/Console";
11import * as Crypto from "effect/Crypto";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as References from "effect/References";
19import * as Schema from "effect/Schema";
20import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
21import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
22import * as HttpApiClient from "effect/http-api/HttpApiClient";
23
24import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
25import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
26
27import * as ServerConfig from "../config.ts";
28import * as SqlitePersistence from "../persistence/Sqlite.ts";
29import * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
30import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
31import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
32import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
33import * as ProjectService from "../project/ProjectService.ts";
34import { projectMutationOperation } from "../project/ProjectMutation.ts";
35import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
36import * as ServerSettings from "../serverSettings.ts";
37import {
38 clearPersistedServerRuntimeState,
39 readPersistedServerRuntimeState,
40} from "../serverRuntimeState.ts";
41import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
42import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
43
44type ProjectMutationTarget = {
45 readonly id: ProjectId;
46 readonly title: string;
47 readonly workspaceRoot: string;
48};
49
50type ProjectCommandExecutionMode = "live" | "offline";
51type ProjectCliDispatchCommand = ProjectMutation;
52
53const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
54
55export class ProjectCommandIdGenerationError extends Schema.TaggedError<ProjectCommandIdGenerationError>()(
56 "ProjectCommandIdGenerationError",
57 {
58 operation: Schema.Literal("generateProjectCommandId"),
59 cause: Schema.Defect(),
60 },
61) {
62 override get message(): string {
63 return "Failed to generate a project command identifier.";
64 }
65}
66
67export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedError<ProjectLiveServerDeclaredResponseError>()(
68 "ProjectLiveServerDeclaredResponseError",
69 {
70 operation: Schema.Literal("callLiveServer"),
71 code: Schema.String,
72 traceId: Schema.String,
73 cause: Schema.Defect(),
74 },
75) {
76 override get message(): string {
77 return `Server request failed (${this.code}, trace ${this.traceId}).`;
78 }
79}
80
81export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedError<ProjectLiveServerUndeclaredStatusError>()(
82 "ProjectLiveServerUndeclaredStatusError",
83 {
84 operation: Schema.Literal("callLiveServer"),
85 status: Schema.Int,
86 cause: Schema.Defect(),
87 },
88) {
89 override get message(): string {
90 return `Server request failed with undeclared status ${this.status}.`;
91 }
92}
93
94export class ProjectLiveServerRequestError extends Schema.TaggedError<ProjectLiveServerRequestError>()(
95 "ProjectLiveServerRequestError",
96 {
97 operation: Schema.Literal("callLiveServer"),
98 cause: Schema.Defect(),
99 },
100) {
101 override get message(): string {
102 return "Failed to call the running server.";
103 }
104}
105
106export class ProjectTitleEmptyError extends Schema.TaggedError<ProjectTitleEmptyError>()(
107 "ProjectTitleEmptyError",
108 {
109 operation: Schema.Literal("validateProjectTitle"),
110 title: Schema.String,
111 },
112) {
113 override get message(): string {
114 return "Project title cannot be empty.";
115 }
116}
117
118export class ProjectIdentifierEmptyError extends Schema.TaggedError<ProjectIdentifierEmptyError>()(
119 "ProjectIdentifierEmptyError",
120 {
121 operation: Schema.Literal("resolveProjectTarget"),
122 identifier: Schema.String,
123 },
124) {
125 override get message(): string {
126 return "Project identifier cannot be empty.";
127 }
128}
129
130export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
131 "ProjectNotFoundError",
132 {
133 operation: Schema.Literal("resolveProjectTarget"),
134 identifier: Schema.String,
135 normalizedWorkspaceRoot: Schema.optional(Schema.String),
136 activeProjectCount: Schema.Number,
137 cause: Schema.optional(Schema.Defect()),
138 },
139) {
140 override get message(): string {
141 return `No active project found for '${this.identifier}'.`;
142 }
143}
144
145export class ProjectAlreadyExistsError extends Schema.TaggedError<ProjectAlreadyExistsError>()(
146 "ProjectAlreadyExistsError",
147 {
148 operation: Schema.Literal("addProject"),
149 projectId: ProjectId,
150 workspaceRoot: Schema.String,
151 },
152) {
153 override get message(): string {
154 return `An active project already exists for '${this.workspaceRoot}'.`;
155 }
156}
157
158export const ProjectCommandError = Schema.Union([
159 ProjectCommandIdGenerationError,
160 ProjectLiveServerDeclaredResponseError,
161 ProjectLiveServerUndeclaredStatusError,
162 ProjectLiveServerRequestError,
163 ProjectTitleEmptyError,
164 ProjectIdentifierEmptyError,
165 ProjectNotFoundError,
166 ProjectAlreadyExistsError,
167]);
168export type ProjectCommandError = typeof ProjectCommandError.Type;
169
170export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
171 if (isEnvironmentHttpCommonError(cause)) {
172 return new ProjectLiveServerDeclaredResponseError({
173 operation: "callLiveServer",
174 code: cause.code,
175 traceId: cause.traceId,
176 cause,
177 });
178 }
179 if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
180 return new ProjectLiveServerUndeclaredStatusError({
181 operation: "callLiveServer",
182 status: cause.response.status,
183 cause,
184 });
185 }
186
187 return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
188}
189
190const projectCommandUuid = Crypto.Crypto.pipe(
191 Effect.flatMap((crypto) => crypto.randomUUIDv4),
192 Effect.mapError(
193 (cause) =>
194 new ProjectCommandIdGenerationError({
195 operation: "generateProjectCommandId",
196 cause,
197 }),
198 ),
199);
200
201const layerProjectCliRuntime = RuntimeLayer.layerProjectService.pipe(
202 Layer.provideMerge(ProjectEnrichmentService.layer),
203 Layer.provideMerge(RepositoryIdentityResolver.layer),
204 Layer.provideMerge(
205 ProjectFaviconResolver.layer.pipe(
206 Layer.provide(WorkspacePaths.layer),
207 Layer.provide(T3ProjectFileLoader.layer),
208 ),
209 ),
210 Layer.provideMerge(WorkspacePaths.layer),
211 Layer.provideMerge(ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer))),
212 Layer.provideMerge(SqlitePersistence.layerConfig),
213);
214
215const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
216const withProjectCliSessionToken = <A, E, R>(
217 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
218 run: (token: string) => Effect.Effect<A, E, R>,
219) =>
220 Effect.acquireUseRelease(
221 environmentAuth.issueSession({
222 scopes: AuthAdministrativeScopes,
223 label: "t3 project cli",
224 }),
225 (issued) => run(issued.token),
226 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
227 );
228
229const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
230 effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
231
232const makeLiveServerClient = (origin: string) =>
233 HttpApiClient.make(EnvironmentHttpApi, {
234 baseUrl: origin,
235 });
236
237const normalizeWorkspaceRootForProjectCommand = Effect.fn(
238 "normalizeWorkspaceRootForProjectCommand",
239)(function* (workspaceRoot: string) {
240 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
241 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
242});
243
244const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
245 workspaceRoot: string,
246 explicitTitle?: string,
247) {
248 if (explicitTitle !== undefined) {
249 const trimmed = explicitTitle.trim();
250 if (trimmed.length > 0) {
251 return trimmed;
252 }
253 return yield* new ProjectTitleEmptyError({
254 operation: "validateProjectTitle",
255 title: explicitTitle,
256 });
257 }
258
259 const path = yield* Path.Path;
260 const basename = path.basename(workspaceRoot).trim();
261 return basename.length > 0 ? basename : "project";
262});
263
264const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
265 readonly snapshot: ProjectSnapshot;
266 readonly identifier: string;
267}) {
268 const trimmedIdentifier = input.identifier.trim();
269 if (trimmedIdentifier.length === 0) {
270 return yield* new ProjectIdentifierEmptyError({
271 operation: "resolveProjectTarget",
272 identifier: input.identifier,
273 });
274 }
275
276 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
277 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
278 if (exactIdMatch) {
279 return {
280 id: exactIdMatch.id,
281 title: exactIdMatch.title,
282 workspaceRoot: exactIdMatch.workspaceRoot,
283 } satisfies ProjectMutationTarget;
284 }
285
286 const normalizedWorkspaceRootResult = yield* Effect.result(
287 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
288 );
289 const normalizedWorkspaceRoot =
290 normalizedWorkspaceRootResult._tag === "Success" ? normalizedWorkspaceRootResult.success : null;
291
292 // A stored workspace path still identifies its project after the directory is gone.
293 const exactWorkspaceMatch = activeProjects.find(
294 (project) => project.workspaceRoot === (normalizedWorkspaceRoot ?? trimmedIdentifier),
295 );
296
297 const resolved = exactWorkspaceMatch;
298 if (!resolved) {
299 return yield* new ProjectNotFoundError({
300 operation: "resolveProjectTarget",
301 identifier: trimmedIdentifier,
302 activeProjectCount: activeProjects.length,
303 ...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
304 ...(normalizedWorkspaceRootResult._tag === "Failure"
305 ? { cause: normalizedWorkspaceRootResult.failure }
306 : {}),
307 });
308 }
309
310 return {
311 id: resolved.id,
312 title: resolved.title,
313 workspaceRoot: resolved.workspaceRoot,
314 } satisfies ProjectMutationTarget;
315});
316
317const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
318 Effect.gen(function* () {
319 const client = yield* makeLiveServerClient(origin);
320 return yield* client.projects.snapshot({
321 headers: { authorization: `Bearer ${bearerToken}` },
322 });
323 }).pipe(
324 withProjectCliLiveServerTimeout,
325 Effect.mapError(projectCommandErrorFromLiveServerRequest),
326 );
327
328const dispatchLiveOrchestrationCommand = (
329 origin: string,
330 bearerToken: string,
331 command: ProjectCliDispatchCommand,
332) =>
333 Effect.gen(function* () {
334 const client = yield* makeLiveServerClient(origin);
335 yield* client.projects.mutate({
336 headers: { authorization: `Bearer ${bearerToken}` },
337 payload: command,
338 } as Parameters<typeof client.projects.mutate>[0]);
339 }).pipe(
340 withProjectCliLiveServerTimeout,
341 Effect.mapError(projectCommandErrorFromLiveServerRequest),
342 );
343
344const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
345 const projects = yield* ProjectService.ProjectService;
346 return yield* projects.snapshot;
347});
348
349const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
350 function* (
351 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
352 config: ServerConfig.ServerConfig["Service"],
353 ) {
354 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
355 if (Option.isNone(runtimeState)) {
356 return Option.none<{ readonly origin: string }>();
357 }
358
359 const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
360 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
361 Effect.as({
362 origin: runtimeState.value.origin,
363 }),
364 ),
365 );
366
367 const attempted = yield* Effect.result(attempt);
368 if (attempted._tag === "Success") {
369 return Option.some(attempted.success);
370 }
371
372 yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
373 origin: runtimeState.value.origin,
374 cause: attempted.failure,
375 });
376 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
377 return Option.none<{ readonly origin: string }>();
378 },
379);
380
381const runProjectMutation = Effect.fn("runProjectMutation")(function* (
382 flags: CliAuthLocationFlags,
383 run: (input: {
384 readonly snapshot: ProjectSnapshot;
385 readonly dispatch: (
386 command: ProjectCliDispatchCommand,
387 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
388 readonly mode: ProjectCommandExecutionMode;
389 }) => Effect.Effect<
390 string,
391 Error,
392 | Crypto.Crypto
393 | FileSystem.FileSystem
394 | HttpClient.HttpClient
395 | Path.Path
396 | WorkspacePaths.WorkspacePaths
397 >,
398) {
399 const logLevel = yield* GlobalFlag.LogLevel;
400 const config = yield* resolveCliAuthConfig(flags, logLevel);
401 const minimumLogLevel = config.logLevel;
402
403 return yield* Effect.gen(function* () {
404 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
405 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
406
407 if (Option.isSome(liveMode)) {
408 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
409 Effect.gen(function* () {
410 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
411 const output = yield* run({
412 snapshot,
413 dispatch: (command) =>
414 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
415 mode: "live",
416 });
417 yield* Console.log(output);
418 }),
419 );
420 }
421
422 const layerOfflineRuntime = layerProjectCliRuntime.pipe(
423 Layer.provide(ServerConfig.layer(config)),
424 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
425 );
426
427 return yield* Effect.gen(function* () {
428 const snapshot = yield* getOfflineSnapshot();
429 const projects = yield* ProjectService.ProjectService;
430 const output = yield* run({
431 snapshot,
432 dispatch: (command) => projectMutationOperation(projects, command).pipe(Effect.asVoid),
433 mode: "offline",
434 });
435 yield* Console.log(output);
436 }).pipe(Effect.provide(layerOfflineRuntime));
437 }).pipe(
438 Effect.provide(
439 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
440 Layer.provideMerge(FetchHttpClient.layer),
441 Layer.provide(ServerConfig.layer(config)),
442 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
443 ),
444 ),
445 );
446});
447
448const projectAddCommand = Command.make("add", {
449 ...projectLocationFlags,
450 workspaceRoot: Argument.String("path").pipe(
451 Argument.withDescription("Workspace root to add as a project."),
452 ),
453 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
454}).pipe(
455 Command.withDescription("Add a project."),
456 Command.withHandler((flags) =>
457 runProjectMutation(
458 flags,
459 Effect.fn("projectAddMutation")(function* ({
460 snapshot,
461 dispatch,
462 }: {
463 readonly snapshot: ProjectSnapshot;
464 readonly dispatch: (
465 command: ProjectCliDispatchCommand,
466 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
467 }) {
468 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
469 const existingProject = snapshot.projects.find(
470 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
471 );
472 if (existingProject) {
473 return yield* new ProjectAlreadyExistsError({
474 operation: "addProject",
475 projectId: existingProject.id,
476 workspaceRoot,
477 });
478 }
479
480 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
481 const projectId = ProjectId.make(yield* projectCommandUuid);
482 yield* dispatch({
483 type: "project.create",
484 commandId: CommandId.make(yield* projectCommandUuid),
485 projectId,
486 title,
487 workspaceRoot,
488 });
489 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
490 }),
491 ),
492 ),
493);
494
495const projectRemoveCommand = Command.make("remove", {
496 ...projectLocationFlags,
497 project: Argument.String("project").pipe(
498 Argument.withDescription("Project id or workspace root to remove."),
499 ),
500 force: Flag.Boolean("force").pipe(
501 Flag.withDescription("Delete the project and all of its threads."),
502 Flag.withDefault(false),
503 ),
504}).pipe(
505 Command.withDescription("Remove a project."),
506 Command.withHandler((flags) =>
507 runProjectMutation(
508 flags,
509 Effect.fn("projectRemoveMutation")(function* ({
510 snapshot,
511 dispatch,
512 }: {
513 readonly snapshot: ProjectSnapshot;
514 readonly dispatch: (
515 command: ProjectCliDispatchCommand,
516 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
517 }) {
518 const project = yield* findActiveProjectTarget({
519 snapshot,
520 identifier: flags.project,
521 });
522 yield* dispatch({
523 type: "project.delete",
524 commandId: CommandId.make(yield* projectCommandUuid),
525 projectId: project.id,
526 force: flags.force,
527 });
528 return `Removed project ${project.id} (${project.title}).`;
529 }),
530 ),
531 ),
532);
533
534const projectRenameCommand = Command.make("rename", {
535 ...projectLocationFlags,
536 project: Argument.String("project").pipe(
537 Argument.withDescription("Project id or workspace root to rename."),
538 ),
539 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
540}).pipe(
541 Command.withDescription("Rename a project."),
542 Command.withHandler((flags) =>
543 runProjectMutation(
544 flags,
545 Effect.fn("projectRenameMutation")(function* ({
546 snapshot,
547 dispatch,
548 }: {
549 readonly snapshot: ProjectSnapshot;
550 readonly dispatch: (
551 command: ProjectCliDispatchCommand,
552 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
553 }) {
554 const project = yield* findActiveProjectTarget({
555 snapshot,
556 identifier: flags.project,
557 });
558 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
559 if (nextTitle === project.title) {
560 return `Project ${project.id} is already named ${nextTitle}.`;
561 }
562
563 yield* dispatch({
564 type: "project.update",
565 commandId: CommandId.make(yield* projectCommandUuid),
566 projectId: project.id,
567 title: nextTitle,
568 });
569 return `Renamed project ${project.id} to ${nextTitle}.`;
570 }),
571 ),
572 ),
573);
574
575export const projectCommand = Command.make("project").pipe(
576 Command.withDescription("Manage projects."),
577 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
578);